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: mongodb FindAndModify - update data I have this already in the MongoDB collections. { "_id" : ObjectId("4e677efce88c7f0718000000"), "ptbn" : "indl000000001", "tbucode" : "5649", "district" : "west", "dcode" : "110048", "tbu" : "super clinic", "state" : "delhi" } I am unable to understand how to work with FindAnd...
mongodb FindAndModify - update data
I have this already in the MongoDB collections. { "_id" : ObjectId("4e677efce88c7f0718000000"), "ptbn" : "indl000000001", "tbucode" : "5649", "district" : "west", "dcode" : "110048", "tbu" : "super clinic", "state" : "delhi" } I am unable to understand how to work with FindAndModify from MongoDb I am working on Mongo...
[ "You don't actually need findAndModify for this. A simple update() will do the trick.\ndb.tc_basic.update({'_id':ObjectId(\"...\")}, {'$set': {'state': 'goa', 'district': 'north'}})\n\nFor more details on what you can do with update() see: http://www.mongodb.org/display/DOCS/Updating\n" ]
[ 4 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0007338806_mongodb_python.txt
Q: How to convert a list of dictionaries to CSV format in Python, assuming the dictionaries can have different keys? I have a list of dictionaries like that : [ {'item1':'bla', 'item2':'bli', 'item3':'blu'}, {'item1':'love', 'item3':'python'} ] Notice that dict 2 doesn't have key 'item2'. I want to produce a csv out...
How to convert a list of dictionaries to CSV format in Python, assuming the dictionaries can have different keys?
I have a list of dictionaries like that : [ {'item1':'bla', 'item2':'bli', 'item3':'blu'}, {'item1':'love', 'item3':'python'} ] Notice that dict 2 doesn't have key 'item2'. I want to produce a csv output as such, so I can insert everything into a SQL table: item1,item2,item3 bla,bli,blu love,,python I found an easy w...
[ "Use csv.DictWriter with the fieldnames and restval arguments.\n", "Something like\n#Create a master list of keys\nallKeys = ()\nfor row in YourListHere:\n allKeys.union(row.keys())\n\n#Sort the keys\nallKeys = list(allKeys).sorted()\n\n#Go through printing the rows\nfor row in YourListHere:\n values = []\n...
[ 2, 0 ]
[]
[]
[ "csv", "dictionary", "key", "python", "sql" ]
stackoverflow_0007338836_csv_dictionary_key_python_sql.txt
Q: Django HttpRequest problem I'm trying to gat the value of a form field in django, now xxx = request.POST[u'a1'] gives me a value, but xxx = request.POST.get(u'a1') gives me nothing what am I doing wrong? Update: Using the first method, request.method = POST, using the second method changes it to GET, all I am d...
Django HttpRequest problem
I'm trying to gat the value of a form field in django, now xxx = request.POST[u'a1'] gives me a value, but xxx = request.POST.get(u'a1') gives me nothing what am I doing wrong? Update: Using the first method, request.method = POST, using the second method changes it to GET, all I am doing is replacing one line of co...
[ "The get method takes two parameters: key and a return value for where there's no match for the key (defaults to None).\nMaybe the first example worked only in cases where the form had a value in the field 'a1'.\nEither set a return value for the get method (e.g. xxx = request.POST.get(u'a1', 'something')) or check...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007197534_django_python.txt
Q: autodetect proxy setting linux I am writing a python app that needs to send and retrieve some information from Internet. I would like to auto-detect the proxy setting (to avoid asking the user to set up the proxy configuration). It seems that urllib can do this on Windows and Mac OsX and not on Unix/Linux. I need/...
autodetect proxy setting linux
I am writing a python app that needs to send and retrieve some information from Internet. I would like to auto-detect the proxy setting (to avoid asking the user to set up the proxy configuration). It seems that urllib can do this on Windows and Mac OsX and not on Unix/Linux. I need/prefer to use the mechanize module, ...
[ "One way is to check the HTTP_PROXY environment variable (that's the way wget checks if it has to use a proxy). The code could look like this for example:\nimport os\nimport mechanize\n\nbr = mechanize.Browser()\n\nproxy = os.environ.get('HTTP_PROXY')\nif proxy is not None:\n br.set_proxies({'http': proxy})\n\nb...
[ 0 ]
[]
[]
[ "mechanize", "proxy", "python" ]
stackoverflow_0007338837_mechanize_proxy_python.txt
Q: Cython callback works correctly for function, but not for bound method I am implementing a cython-based interface to a C++ library. I implemented a callback system that works with normal functions but fails strangely when passing in bound methods. Here is a portion of my cython code: cdef extern from "VolumeHapt...
Cython callback works correctly for function, but not for bound method
I am implementing a cython-based interface to a C++ library. I implemented a callback system that works with normal functions but fails strangely when passing in bound methods. Here is a portion of my cython code: cdef extern from "VolumeHapticTool.h": cdef cppclass HDButtonEvent: bool isPressed() ...
[ "Thanks to comments by Stefan Behnel and Mark Florisson on the cython discussion group, the problem is that the reference to my bound method was going out of scope and getting garbage collected. \nThe solution was to do this:\ncdef class pyScene:\n cdef Scene * m_scene\n cdef object drill_button_func\n\n ...
[ 3 ]
[]
[]
[ "callback", "cython", "python" ]
stackoverflow_0007326762_callback_cython_python.txt
Q: Printing the line above the current executing line Is there a way for a line of code in a Python script to print the line above it? UPDATE: Motivations It's an intriguing problem. I was wondering if Python's strong introspection goes that far. I was saving this for a follow up question - I actually don't want to...
Printing the line above the current executing line
Is there a way for a line of code in a Python script to print the line above it? UPDATE: Motivations It's an intriguing problem. I was wondering if Python's strong introspection goes that far. I was saving this for a follow up question - I actually don't want to "print the line above", but rather to grab a certain li...
[ "To read (with your eyes) you can use PDB\nJust import pdb and then you can do this:\ncode:\na = 'test'\nimport pdb; pdb.set_trace()\n\nAfter running a code you will get stopped in shell like enviroment and you will be able to do this:\n-> import pdb; pdb.set_trace()\n(Pdb) print a\ntest\n(Pdb) l\n 1 a = 'test...
[ 2, 0 ]
[ "Depending on the complexity, and this is probably ill advised, you can read in your python file w/ readlines(), print them, and then call exec() on them in a looping structure.\nexample for those dumb enough to suggest that this isn't possible in the limited scope i was referring to.\n>>> a = [\"a=1+1\",\"b=a\",\"...
[ -2 ]
[ "python" ]
stackoverflow_0007338456_python.txt
Q: Parsing a text file with a special markup I need to parse a DSL file using Python. A DSL file is a text file with a text having a special markup with tags used by ABBYY Lingvo. It looks like: activate [m0][b]ac·ti·vate[/b] {{id=000000367}} [c rosybrown]\[[/c][c darkslategray][b]activate[/b][/c] [c darkslategra...
Parsing a text file with a special markup
I need to parse a DSL file using Python. A DSL file is a text file with a text having a special markup with tags used by ABBYY Lingvo. It looks like: activate [m0][b]ac·ti·vate[/b] {{id=000000367}} [c rosybrown]\[[/c][c darkslategray][b]activate[/b][/c] [c darkslategray][b]activates[/b][/c] [c darkslategray][b]acti...
[ "Using RegExp for this for something other than trivial use will give heartache and pain.\nIf you insist on using a RegEx (NOT RECOMMENDED), look at the methods used HERE on XML\nIf by \".dsl\" you mean the ABBRY or Lingvo dict format, you may want to look at stardict. It can read the ABBRY dsl format. \n", "\n\"...
[ 1, 1 ]
[]
[]
[ "markup", "parsing", "python", "tags" ]
stackoverflow_0007339446_markup_parsing_python_tags.txt
Q: Python, strings, unicode characters comp/INFO_MAP_ECE/101102.1.119 This string is the output of a CPU but there are always special/non-printable characters after the number and my aim is to obtain the number excluding the text before it and special/non-printable after it. I am trying the split method but am not su...
Python, strings, unicode characters
comp/INFO_MAP_ECE/101102.1.119 This string is the output of a CPU but there are always special/non-printable characters after the number and my aim is to obtain the number excluding the text before it and special/non-printable after it. I am trying the split method but am not sure what to use for special/non-printable ...
[ "Assuming your output always looks something like what you showed, you can use a regular expression:\nnumPattern = r'/([\\d.]+)'\noutput = 'comp/INFO_MAP_ECE/101102.1.119'\n\nm = re.search(numPattern, output)\n\nif m: #If a match was found\n numString = m.group(1) #Extracts the first group surrounded by ()\n #et...
[ 3, 1 ]
[]
[]
[ "character", "python", "regex", "string", "unicode" ]
stackoverflow_0007334341_character_python_regex_string_unicode.txt
Q: python HTMLParser to replace some strings in the data of the html file I need to replace some strings in the data content of my html page. I can't use replace function directly because I need to change only the data section. It shouldn't modify any of the tags or attributes. I used HTMLParser for this. But I am st...
python HTMLParser to replace some strings in the data of the html file
I need to replace some strings in the data content of my html page. I can't use replace function directly because I need to change only the data section. It shouldn't modify any of the tags or attributes. I used HTMLParser for this. But I am stuck on writing it back to file. Using HTMLParser I can parse and get data co...
[ "HTMLParser doesn't construct any representation in memory of your html file. You could do it yourself in handle_*() methods but a simpler way would be to use BeautifulSoup:\n>>> import re\n>>> from BeautifulSoup import BeautifulSoup\n>>> soup = BeautifulSoup('<a title=,>,</a>')\n>>> print soup\n<a title=\",\">,</a...
[ 3 ]
[]
[]
[ "html_parsing", "python" ]
stackoverflow_0007339042_html_parsing_python.txt
Q: Calling Google's Custom Search API via Python I am writing in Python a module that will query Google's Custom Search API and return all listings of domain 'example.com' I Have been reading instructions at https://code.google.com/apis/customsearch/v1/getting_started.html and am a little stumped at the moment. Are m...
Calling Google's Custom Search API via Python
I am writing in Python a module that will query Google's Custom Search API and return all listings of domain 'example.com' I Have been reading instructions at https://code.google.com/apis/customsearch/v1/getting_started.html and am a little stumped at the moment. Are my assumptions listed below correct? For example, to...
[ "Though this question is quite old and the author doesn't seem to be too responsive, Google still highly ranks this page and many people may come here, so I post my answer. \nSearching with Google Custom Search is described in this answer to similar question. \nParameters are as follows:\nkey - yes, it is API key f...
[ 5 ]
[]
[]
[ "google_search_api", "python" ]
stackoverflow_0004504717_google_search_api_python.txt
Q: Unable to retrieve NTLM authenticated webpage with Python because of HTTP 302 Can anyone help me with the python code that I have below? It is some open source that I've slightly modified for my own use. I am attempting to access a webpage from a Windows server that is running NTLM authentication. At first my prob...
Unable to retrieve NTLM authenticated webpage with Python because of HTTP 302
Can anyone help me with the python code that I have below? It is some open source that I've slightly modified for my own use. I am attempting to access a webpage from a Windows server that is running NTLM authentication. At first my problem was keeping a persistent connection so that I wouldn't get the http 401 error. ...
[ "once you get the response from the server, check if it is a 302 status. If it is a 302 status get the coookies and make another request with the cookie information\nif(response.code==302):\n header={'Cookie':response.headers['Set-Cookie']}\n req=urllib2.Request(thesameurl,None,header)\n respon...
[ 5 ]
[]
[]
[ "authentication", "http_status_code_302", "ntlm", "python", "redirect" ]
stackoverflow_0006460494_authentication_http_status_code_302_ntlm_python_redirect.txt
Q: sort values and return list of keys from dict python Possible Duplicate: Python: Sort a dictionary by value I have a dictionary like this: A = {'Name1':34, 'Name2': 12, 'Name6': 46,....} I want a list of keys sorted by the values, i.e. [Name2, Name1, Name6....] Thanks!!! A: Use sorted with the get method as a...
sort values and return list of keys from dict python
Possible Duplicate: Python: Sort a dictionary by value I have a dictionary like this: A = {'Name1':34, 'Name2': 12, 'Name6': 46,....} I want a list of keys sorted by the values, i.e. [Name2, Name1, Name6....] Thanks!!!
[ "Use sorted with the get method as a key (dictionary keys can be accessed by iterating):\nsorted(A, key=A.get)\n\n", "Use sorted's key argument\nsorted(d, key=d.get)\n\n", "sorted(a.keys(), key=a.get)\nThis sorts the keys, and for each key, uses a.get to find the value to use as its sort value.\n", "I'd use:\...
[ 72, 6, 4, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007340019_dictionary_python.txt
Q: Exception logging in Pylons Is there a way to create a middleware that will catch every raised exception and print the stacktrace both to log and stdout (possibly with some additional information) in Pylons framework? A: Standard paste.exceptions.errormiddleware.ErrorMiddleware already does this, and even a lit...
Exception logging in Pylons
Is there a way to create a middleware that will catch every raised exception and print the stacktrace both to log and stdout (possibly with some additional information) in Pylons framework?
[ "Standard paste.exceptions.errormiddleware.ErrorMiddleware already does this, and even a little more.\n" ]
[ 2 ]
[]
[]
[ "exception", "middleware", "pylons", "python" ]
stackoverflow_0007337189_exception_middleware_pylons_python.txt
Q: Does a generator decorator exist? I just got through tracking down a random bug while using Twisted: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/twisted/spread/pb.py", line 826, in proto_message self._recvMessage(self.localObjectForID, requestID, objectID, message, answerRequire...
Does a generator decorator exist?
I just got through tracking down a random bug while using Twisted: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/twisted/spread/pb.py", line 826, in proto_message self._recvMessage(self.localObjectForID, requestID, objectID, message, answerRequired, netArgs, netKw) File "/usr/lib/pyt...
[ "As others have noted, this likely makes no sense. But for completeness and to answer the question:\nNo, you have to use a yield to make it a generator, except of course if you create a decorator that's a generator (by including the yield keyword) itself but doesn't actually yield anything and just calls the decora...
[ 6, 1, 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0007339577_python_twisted.txt
Q: Help interpreting Python code snippet I found the below on the web, however from my little exposure with Python I am aware that one can attach functions to object in the fly. I am also aware that everything in Python is object. I am yet to understand what one intend to achieve with the below and its use case. This...
Help interpreting Python code snippet
I found the below on the web, however from my little exposure with Python I am aware that one can attach functions to object in the fly. I am also aware that everything in Python is object. I am yet to understand what one intend to achieve with the below and its use case. This is the part I need help: run_sql_command.c...
[ "The idea here (I believe) is that someone is creating a placeholder object that keeps reference to a cursor c so that it may be used to execute queries later. Proposed usage is probably something like this:\nc = DBConnectionObject.cursor()\n\nmyExecutor = get_sql_object(c)\n\n# some amount of code later\nrows = m...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007340169_python.txt
Q: Detecting overlapping date recurrence rules I'm working in a application that looks like Google Calendar, but with one main difference: events shouldn't have intersections with other events. This means that no two events may share common time, even in minutes granularity. This is specially useful for a calendar th...
Detecting overlapping date recurrence rules
I'm working in a application that looks like Google Calendar, but with one main difference: events shouldn't have intersections with other events. This means that no two events may share common time, even in minutes granularity. This is specially useful for a calendar that only store meetings, since it is impossible to...
[ "No, I don't believe it's possible to analyse a rrule to see if it can intersect another one without creating the datetime objects.\nEssentially you're asking for the output of an algorithm without running the algorithm, and I think that's non-computable.\nHowever, for certain types of rrule it is possible - e.g. a...
[ 5 ]
[]
[]
[ "intersection", "interval_intersection", "python", "python_datetime", "python_dateutil" ]
stackoverflow_0007264302_intersection_interval_intersection_python_python_datetime_python_dateutil.txt
Q: Does SQLAlchemy support "closure tables?" I've been reading about closure tables as a way of modeling hierarchies over SQL. Does [SQLAlchemy] have any built-in support for creating and traversing hierarchical collections of object instances (tree structured collections) using closure tables? A: I've recently blo...
Does SQLAlchemy support "closure tables?"
I've been reading about closure tables as a way of modeling hierarchies over SQL. Does [SQLAlchemy] have any built-in support for creating and traversing hierarchical collections of object instances (tree structured collections) using closure tables?
[ "I've recently blogged on this matter.\nFor the most part, sqlalchemy doesn't do anything that SQL also doesn't do; sqlalchemy really only provides ways of generating sql, and turning the result sets into nice python objects. \nIf your database provides some useful tools for working with recurrence relations, such...
[ 7 ]
[]
[]
[ "python", "sql", "sqlalchemy", "transitive_closure_table" ]
stackoverflow_0007340320_python_sql_sqlalchemy_transitive_closure_table.txt
Q: how to sort a scipy array with order attribute when it does not have the field names? I have a 2d scipy array(The oigion is the one color channel of an rgb image). I want to find the specific occurance of an element. I can use np.argsort(arr) to do the job. But the problem is that I want to do it in a specifi...
how to sort a scipy array with order attribute when it does not have the field names?
I have a 2d scipy array(The oigion is the one color channel of an rgb image). I want to find the specific occurance of an element. I can use np.argsort(arr) to do the job. But the problem is that I want to do it in a specific order along axis. The scipy example for doing this is as follows x = np.array([(1, 0),...
[ "Okay, suppose you have an ordinary numpy array:\nIn [34]: x = np.array([(1, 0), (0, 1)])\n\nYou can view it as a so-called structured array by using view:\nIn [35]: y = x.ravel().view(dtype=[('x', x.dtype), ('y', x.dtype)])\n\nNow you can use np.argsort on y with the order parameter:\nIn [36]: np.argsort(y, order=...
[ 4 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0007340212_numpy_python_scipy.txt
Q: Tail recursive function fails to return a value (Python 3) I've created a tail recursive function to solve an optimization problem: def optimize(current_price = 0.1, last_profit = 0.0): current_profit = profit(current_price) if (last_profit > current_profit) and (current_profit > 0.0): return {'bes...
Tail recursive function fails to return a value (Python 3)
I've created a tail recursive function to solve an optimization problem: def optimize(current_price = 0.1, last_profit = 0.0): current_profit = profit(current_price) if (last_profit > current_profit) and (current_profit > 0.0): return {'best_price': current_price - 0.1, 'best_profit': last_profit} ...
[ "Even a tail-recursive function needs a return in Python:\ndef optimize(current_price = 0.1, last_profit = 0.0):\n current_profit = profit(current_price)\n if (last_profit > current_profit) and (current_profit > 0.0):\n return {'best_price': current_price - 0.1, 'best_profit': last_profit}\n else: #...
[ 5 ]
[]
[]
[ "python", "python_3.x", "recursion", "return_value" ]
stackoverflow_0007340616_python_python_3.x_recursion_return_value.txt
Q: Problem with the __str__ method This is my script: import math class Vector: def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def ___str___(self): return "{0}, {1}".format(self.x, self.y) @classmethod def vectorPoints(cls, p1, p2): a = p2[0] - p1[0] ...
Problem with the __str__ method
This is my script: import math class Vector: def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def ___str___(self): return "{0}, {1}".format(self.x, self.y) @classmethod def vectorPoints(cls, p1, p2): a = p2[0] - p1[0] b = p2[1] - p1[1] return Vect...
[ "The method name should be __str__ (2 underscores surrounding), not ___str___ (3 underscores surrounding).\n", "You are using three underscores (_) instead of the normal two.\n" ]
[ 10, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007340786_python.txt
Q: Creating an object with an external form I have a upload form that is going to S3 -- <form action="https://test.s3.amazonaws.com/" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="id_file" /> <input type="submit" value="Upload to Amazon S3" name="upload"> </form> When the f...
Creating an object with an external form
I have a upload form that is going to S3 -- <form action="https://test.s3.amazonaws.com/" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="id_file" /> <input type="submit" value="Upload to Amazon S3" name="upload"> </form> When the form is submitted to S3, I also need to create ...
[ "You could use an iframe to send the form and js to search for the id you are looking for in the retrieved page.\nYou could also use another script to perform the post method like php with the curl library. You could grab all the data retrieved from there, search for what you are looking for and add what you need t...
[ 0 ]
[]
[]
[ "ajax", "forms", "python" ]
stackoverflow_0007340870_ajax_forms_python.txt
Q: Multiple data set plotting with matplotlib.pyplot.plot_date this might be really a simple question for most of you guys using matplotlib. Please help me out. I want to plot two array like [1,2,3,4] and [4,5,6,7] versus time in a same plot. I am trying to use matplotlib.pyplot.plot_date but couldn't figure out how ...
Multiple data set plotting with matplotlib.pyplot.plot_date
this might be really a simple question for most of you guys using matplotlib. Please help me out. I want to plot two array like [1,2,3,4] and [4,5,6,7] versus time in a same plot. I am trying to use matplotlib.pyplot.plot_date but couldn't figure out how to do it. It seems to me that only one trend can be plotted with ...
[ "To use plot date with multiple trends, it's easiest to call it multiple times. For example:\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\n# Generate Data\ntime = mdates.drange(datetime.datetime(2010, 1, 1), \n datetime.datetime(2011,...
[ 13 ]
[]
[]
[ "matplotlib", "numpy", "python", "scipy" ]
stackoverflow_0007340547_matplotlib_numpy_python_scipy.txt
Q: Python open() with minimal fluff variables The intent is to look in a json file in the directory above the script and load up what it finds in that file. This is what I've got: import os import json settings_file = '/home/me/foo/bar.txt' root = os.path.dirname(os.path.dirname(os.path.abspath(settings_file))) # '/...
Python open() with minimal fluff variables
The intent is to look in a json file in the directory above the script and load up what it finds in that file. This is what I've got: import os import json settings_file = '/home/me/foo/bar.txt' root = os.path.dirname(os.path.dirname(os.path.abspath(settings_file))) # '/home/me' target = os.path.join(root,'.extras.txt...
[ "Code looks fine, make sure referenced files are in the appropriate places. Given your code that includes target/file variable assignment, full path to .extras.txt is \n\n/home/me/.extras.txt\n\n", "You need to do:\nfile = open(target, 'w')\n\nbecause by default open will try to open the file in read mode (r) but...
[ 0, 0 ]
[]
[]
[ "file_io", "json", "python" ]
stackoverflow_0007340509_file_io_json_python.txt
Q: reading, grouping, finding average I am new dummy to python...please help me in the following problem I have a data in *.txt format as 4 colums name|items| a1| a2|, here I am interested only in 3rd and 4th column. Items column goes like a set [1,1], [12,12,2] etc., I need to open the text file, read the file and g...
reading, grouping, finding average
I am new dummy to python...please help me in the following problem I have a data in *.txt format as 4 colums name|items| a1| a2|, here I am interested only in 3rd and 4th column. Items column goes like a set [1,1], [12,12,2] etc., I need to open the text file, read the file and group all similar items colums in one arr...
[ "Here are some sections from the Python tutorial you may find helpful:\n\nReading and writing files\nUsing python as a calculator\nData structures\n\n", "f = open(\"...\")\n\nd = {}\n\nfor line in f:\n x = line.split()\n if len(x) == 4: #skip empty lines\n k = x[1]\n v = float(x[3])\n i...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007339339_python.txt
Q: Python logging issues from multiple modules I have 3 python modules. LogManager.py Runner.py Other.py Runner.py is the first main module in the chain of events, and from that module functions inside Other.py are called. So, inside Runner.py I have a function call to the LogManager.py logger = LogManager.get_log(...
Python logging issues from multiple modules
I have 3 python modules. LogManager.py Runner.py Other.py Runner.py is the first main module in the chain of events, and from that module functions inside Other.py are called. So, inside Runner.py I have a function call to the LogManager.py logger = LogManager.get_log() and from there, I can make simple logs, e.g. l...
[ "The logging module already implements a singleton pattern for you - when you call logger.getLogger(name), it will create the logger if it hasn't done so already and return it. Although it's not exactly what you're asking for, I would suggest just renaming get_log() to setup_log(), since that's what it does. Then y...
[ 16 ]
[]
[]
[ "logging", "python", "singleton" ]
stackoverflow_0007341538_logging_python_singleton.txt
Q: how to get the first occurring of an element from every row in a 2D numpy array? I have a 2d numpy array. I am looking for the indices of the first occurance of a specific element in each row. The output will be an (n x 2) array, where n is the number of rows and every entry contains the x and y coordinate of the ...
how to get the first occurring of an element from every row in a 2D numpy array?
I have a 2d numpy array. I am looking for the indices of the first occurance of a specific element in each row. The output will be an (n x 2) array, where n is the number of rows and every entry contains the x and y coordinate of the first occurance of that specific element. Thanks a lot.
[ "If I understand the question correctly, you want something like this:\nimport numpy as N\n#\nnrows=5\nncols=10 \n#\na=N.random.random((nrows,ncols))\nb=-99*N.ones((nrows,2))\n#\nfor j in range(nrows):\n for i in range(ncols):\n if(a[j,i]<0.5):\n b[j,0]=i\n b[j,1]=j\n cont...
[ 2, 2, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007341592_numpy_python.txt
Q: Logger Entity in App engine Is it viable to have a logger entity in app engine for writing logs? I'll have an app with ~1500req/sec and am thinking about doing it with a taskqueue. Whenever I receive a request, I would create a task and put it in a queue to write something to a log entity (with a date and string p...
Logger Entity in App engine
Is it viable to have a logger entity in app engine for writing logs? I'll have an app with ~1500req/sec and am thinking about doing it with a taskqueue. Whenever I receive a request, I would create a task and put it in a queue to write something to a log entity (with a date and string properties). I need this because ...
[ "There are a few ways to do this:\n\nAccumulate logs and write them in a single datastore put at the end of the request. This is the highest latency option, but only slightly - datastore puts are fairly fast. This solution also consumes the least resources of all the options.\nAccumulate logs and enqueue a task que...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "nosql", "python" ]
stackoverflow_0007274049_google_app_engine_google_cloud_datastore_nosql_python.txt
Q: GeoModel with Google App Engine - queries I'm trying to use GeoModel python module to quickly access geospatial data for my Google App Engine app. I just have a few general questions for issues I'm running into. There's two main methods, proximity_fetch and bounding_box_fetch, that you can use to return queries. ...
GeoModel with Google App Engine - queries
I'm trying to use GeoModel python module to quickly access geospatial data for my Google App Engine app. I just have a few general questions for issues I'm running into. There's two main methods, proximity_fetch and bounding_box_fetch, that you can use to return queries. They actually return a result set, not a filter...
[ "You can also work directly with the location_geocells of your model.\nfrom geospatial import geomodel, geocell, geomath\n\n# query is a db.GqlQuery\n# location is a db.GeoPt\n\n# A resolution of 4 is box of environs 150km\nbbox = geocell.compute_box(geocell.compute(geo_point.location, resolution=4))\ncell = geocel...
[ 2, 1 ]
[]
[]
[ "geolocation", "geospatial", "google_app_engine", "python" ]
stackoverflow_0002248341_geolocation_geospatial_google_app_engine_python.txt
Q: How to properly query Datastore with Python? - issue with the basics As a beginner in Python and App Engine I once again have to ask for your assistance. For some time I've been working with the book "Code in the Cloud" to learn the very basics of using App Engine. The thing is I have not been very successful so f...
How to properly query Datastore with Python? - issue with the basics
As a beginner in Python and App Engine I once again have to ask for your assistance. For some time I've been working with the book "Code in the Cloud" to learn the very basics of using App Engine. The thing is I have not been very successful so far. While most of the issues I have had stemmed from UTF-8 encoding/decodi...
[ "Your query is:\n messages = db.GqlQuery(\"SELECT * From ChatMessage ORDER BY time\")\n\nbut your datastore model doesn't have a time property, it has a timestamp property. Attempting to order by a property that isn't on any entities will always return an empty resultset.\n", "In your for loop over the message...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007331932_google_app_engine_google_cloud_datastore_python.txt
Q: Set QGraphicsTextItem origin in PyQt If I want to place one letter (a QGraphicsTextItem) in a QGraphicsView, is there any way I can set the text to display in the middle of the coordinates I specify? If I use QGraphicsTextItem.setPos(x,y), it treats the (x,y) as the top-left corner. I still want the top-left of th...
Set QGraphicsTextItem origin in PyQt
If I want to place one letter (a QGraphicsTextItem) in a QGraphicsView, is there any way I can set the text to display in the middle of the coordinates I specify? If I use QGraphicsTextItem.setPos(x,y), it treats the (x,y) as the top-left corner. I still want the top-left of the QGraphicsScene to remain as (0, 0), thou...
[ "I believe you should be able to use the boundingRect method of your QGraphicsTextItem to calculate the height and width of your letter and then shift position of the QGraphicsTextItem to make it look like it's centered around x,y coordinates. Smth like this:\nQGraphicsTextItem* textItem0 = new QGraphicsTextItem(\"...
[ 1 ]
[]
[]
[ "pyqt", "python", "qgraphicsscene", "qgraphicsview", "qt" ]
stackoverflow_0007341635_pyqt_python_qgraphicsscene_qgraphicsview_qt.txt
Q: Help, In the middle of translating Python script to Scala I'm trying to translate: http://thinkstats.com/survey.py this script. So here's what I'm translating right now (Python): """This file contains code for use with "Think Stats", by Allen B. Downey, available from greenteapress.com Copyright 2010 Allen B. Dow...
Help, In the middle of translating Python script to Scala
I'm trying to translate: http://thinkstats.com/survey.py this script. So here's what I'm translating right now (Python): """This file contains code for use with "Think Stats", by Allen B. Downey, available from greenteapress.com Copyright 2010 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """...
[ "As I recall, the Python syntax you're showing is for class extension (inheritance). The equivalent Scala would be\n/** Represents a record.\n */\nclass Record\n\n/** Represents a respondent.\n */\nclass Respondent extends Record\n\n/** Represents a pregnancy.\n */\nclass Pregnancy extends Record\n\nScala comments ...
[ 5 ]
[]
[]
[ "python", "scala" ]
stackoverflow_0007342249_python_scala.txt
Q: django-keyedcache: NameError: global name 'tid' is not defined Can't put my finger on this error. In other parts of the application it works fine, but not in this one, the only thing that is different that this code runs in threaded server while the other runs in preforked. On the other hand, on another production...
django-keyedcache: NameError: global name 'tid' is not defined
Can't put my finger on this error. In other parts of the application it works fine, but not in this one, the only thing that is different that this code runs in threaded server while the other runs in preforked. On the other hand, on another production server it works fine in threaded server too. File "/usr/lib/python2...
[ "It appears my setup was invalid. Old .pyc files etc. In fact it was a little more complex than that but nevertheless, it works now. Sorry for the possible confusion.\n" ]
[ 0 ]
[]
[]
[ "caching", "django", "python" ]
stackoverflow_0007234009_caching_django_python.txt
Q: How to subclass a subclass of numpy.ndarray I'm struggling to subclass my own subclass of numpy.ndarray. I don't really understand what the problem is and would like someone to explain what goes wrong in the following cases and how to do what I'm trying to do. What I'm trying to achieve: I have a subclass of numpy...
How to subclass a subclass of numpy.ndarray
I'm struggling to subclass my own subclass of numpy.ndarray. I don't really understand what the problem is and would like someone to explain what goes wrong in the following cases and how to do what I'm trying to do. What I'm trying to achieve: I have a subclass of numpy.ndarry that behaves as I want (class A in the co...
[ "For Case 1, the simplest way is:\nclass B(A):\n def __new__(cls,data,name):\n obj = A.__new__(cls, data)\n obj.name = name\n return obj\n\n__new__ is actually a static method that takes a class as the first argument, not a class method, so you can call it directly with the class of which yo...
[ 4 ]
[]
[]
[ "numpy", "python", "subclassing" ]
stackoverflow_0007342637_numpy_python_subclassing.txt
Q: Mapping a 'fake' object in SQLAlchemy I'm not sure what this is called since it is new to me, but here is what I want to do: I have two tables in my database: TableA and TableB. TableA has pk a_id and another field called a_code. TableB has pk b_id and another field called b_code. I have these tables mapped in m...
Mapping a 'fake' object in SQLAlchemy
I'm not sure what this is called since it is new to me, but here is what I want to do: I have two tables in my database: TableA and TableB. TableA has pk a_id and another field called a_code. TableB has pk b_id and another field called b_code. I have these tables mapped in my sqlalchemy code and they work fine. I wa...
[ "I don't really have a complete understanding of the query you are trying to express, weather it's a union or a join or some third thing, but that aside, it certainly is possible to map an arbitrary selectable (anything you can pass to a database that returns rows).\nI'll start with the assumption that you want som...
[ 8, 1, 1 ]
[]
[]
[ "mapping", "orm", "python", "sqlalchemy" ]
stackoverflow_0005637451_mapping_orm_python_sqlalchemy.txt
Q: Python comparing strings to their equivalent integers effeciently What's the most efficient way to compare two python values both of which are probably strings, but might be integers. So far I'm using str(x)==str(y) but that feels inefficient and (more importantly) ugly: >>> a = 1.0 >>> b = 1 >>> c = '1' >>> a ==...
Python comparing strings to their equivalent integers effeciently
What's the most efficient way to compare two python values both of which are probably strings, but might be integers. So far I'm using str(x)==str(y) but that feels inefficient and (more importantly) ugly: >>> a = 1.0 >>> b = 1 >>> c = '1' >>> a == b True >>> b == c False # here I wanted this to be true >>> str(b)==s...
[ "Test it out. I like using %timeit in ipython:\n\nIn [1]: %timeit str(\"1\") == str(1)\n1000000 loops, best of 3: 702 ns per loop\n\nIn [2]: %timeit \"1\" == str(1)\n1000000 loops, best of 3: 412 ns per loop\n\nIn [3]: %timeit int(\"1\") == 1\n1000000 loops, best of 3: 906 ns per loop\n\nApart from that, though, i...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007343130_python.txt
Q: Using python regex to extract addresses from Craigslist rss feed I'm pulling my hair out trying to parse out a craigslist rss feed to extract location information. I used feedparser to parse the script into into entries and entry descriptions. Unfortunately the address information is contained in irregular tags wi...
Using python regex to extract addresses from Craigslist rss feed
I'm pulling my hair out trying to parse out a craigslist rss feed to extract location information. I used feedparser to parse the script into into entries and entry descriptions. Unfortunately the address information is contained in irregular tags within the description section. the addresses are contained in a section...
[ "That's some invalid syntax. You cannot concatenate/format strings unless the strings are quoted. Try:\naddressStart = r'!-- CLTAG xstreet0='\naddressEnd = r'-->'\n\nprog = re.compile(addressStart + r'(.*?)' + addressEnd)\nresult = prog.match(string)\n\n", "Try search instead of match (The reason is that the li...
[ 2, 2 ]
[]
[]
[ "craigslist", "python", "regex", "rss" ]
stackoverflow_0007343290_craigslist_python_regex_rss.txt
Q: Problem updating fields in Django app I am trying to create a new website with Django. I am only just starting out with web development however and am new to many bits and pieces e.g. SQL. I defined a model with various fields and then went ahead and created an instance of it etc in the Django shell. Later I cha...
Problem updating fields in Django app
I am trying to create a new website with Django. I am only just starting out with web development however and am new to many bits and pieces e.g. SQL. I defined a model with various fields and then went ahead and created an instance of it etc in the Django shell. Later I changed the name of a few of the fields, now w...
[ "You added new attribute with name \"body\" to your model \"Post\" of your application \"posts\". Django cant't automatically create database column for this new field (it can only create database table for new model). So you need to create all new fields manually. Alter your table in database:\nALTER TABLE `posts...
[ 2, 2, 0, 0 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0007336815_django_python_sql.txt
Q: Open PDF with default program in Windows 7 I have a program in which the help documentation is in a .pdf in the same folder as the .py module. I need the program to open the .pdf with the system's default PDF reader. I am using this code in my program: if sys.platform.startswith('darwin'): os.system("SlannanHe...
Open PDF with default program in Windows 7
I have a program in which the help documentation is in a .pdf in the same folder as the .py module. I need the program to open the .pdf with the system's default PDF reader. I am using this code in my program: if sys.platform.startswith('darwin'): os.system("SlannanHelp.pdf") elif sys.platform.startswith('linux'): ...
[ "The problem is os.filestart does not exist at all.\nYou problably want os.startfile\nYou should also take a look at:\nOpen document with default application in Python\nand How to open a file with the standard application? which recommend system('open', filepath) on mac and system('xdg-open', filepath) on linux\n" ...
[ 6 ]
[]
[]
[ "file", "python", "sys" ]
stackoverflow_0007343388_file_python_sys.txt
Q: How to convert python tuple into a two dimentional table? a flat (one dimension) tuple on input: data = ('a','b','c'.....'z'); output: table (two dimensions) that has n (say 9) columns table = ?what code here? so print table ( ('a','b','c'...), ('k','l','m','n'...), ....) which is the shortest way to do so? ...
How to convert python tuple into a two dimentional table?
a flat (one dimension) tuple on input: data = ('a','b','c'.....'z'); output: table (two dimensions) that has n (say 9) columns table = ?what code here? so print table ( ('a','b','c'...), ('k','l','m','n'...), ....) which is the shortest way to do so?
[ "Here's the short version if you find the rest of this too wordy:\nn = 9\ntable = zip(*[iter(data)]*n)\n\nLet's say you start with a list:\n>>> data = range(1,101)\n>>> data\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,\n19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,\n35, 36, 37,...
[ 7, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007342054_python.txt
Q: How to reformat a string in python? Right now I have a string in the form xxx@yyy.com@zzz.com and I want to strip off the @zzz.com so that it comes out as xxx@yyy.com. A: You can use: "xxx@yyy.com@zzz.com".replace("@zzz.com", "") If you know it will always be "@zzz.com". Otherwise, you could try: data = "xxx@y...
How to reformat a string in python?
Right now I have a string in the form xxx@yyy.com@zzz.com and I want to strip off the @zzz.com so that it comes out as xxx@yyy.com.
[ "You can use:\n\"xxx@yyy.com@zzz.com\".replace(\"@zzz.com\", \"\")\n\nIf you know it will always be \"@zzz.com\".\nOtherwise, you could try:\ndata = \"xxx@yyy.com@zzz.com\"\nif data.count(\"@\") == 2:\n data = data.rsplit('@', 1)[0]\n\nOr, more generally:\ndata = \"xxx@yyy.com@zzz.com@___.com\"\nif data.count(\"...
[ 3, 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007343810_python.txt
Q: How to efficiently split a pair of arrays based on a condition on one of them I have two 2D numpy arrays - real r, which contains points in space, given by their Cartesian coordinates, and v, a complex vector defined at each of these points. I would like to split both of these arrays, based on some condition on r....
How to efficiently split a pair of arrays based on a condition on one of them
I have two 2D numpy arrays - real r, which contains points in space, given by their Cartesian coordinates, and v, a complex vector defined at each of these points. I would like to split both of these arrays, based on some condition on r. e.g., r1 contains all points with the first cartesian coordinate is positive, and ...
[ "you can use bool array as index to filter out values:\ncreate some random test data first:\nimport numpy as np\nnp.random.seed(0)\nr = np.random.rand(10,2)-0.5\nv = np.random.rand(10) + np.random.rand(10)*1j\n\nthen:\nidx = r[:,0] > 0 # idx is a bool array \nr1 = r[idx]\nv1 = v[idx]\n\nr2 = r[~idx] # ~idx compute ...
[ 3, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007343782_numpy_python.txt
Q: Python standard library function for rearranging a list I am wondering if there is a standard library function in Python which will rearrange the elements of a list like below: a = [1,2,3,4,5,6,7] function(a) print a a = [1,7,2,6,3,5,4] It should get one element from beginning of original list, then one from e...
Python standard library function for rearranging a list
I am wondering if there is a standard library function in Python which will rearrange the elements of a list like below: a = [1,2,3,4,5,6,7] function(a) print a a = [1,7,2,6,3,5,4] It should get one element from beginning of original list, then one from end, then second from beginning and so on. Then rearrange the ...
[ "You could build a fast, memory efficient generator using itertools which does what you want:\nfrom itertools import chain, izip\n\ndef reorder(a):\n gen = chain.from_iterable(izip(a, reversed(a)))\n for _ in a:\n yield next(gen)\n\n>>> list(reorder(a))\n<<< [1, 7, 2, 6, 3, 5, 4]\n\nYou'll find that it...
[ 9, 3, 2, 2, 1 ]
[]
[]
[ "function", "list", "python", "standards" ]
stackoverflow_0007141577_function_list_python_standards.txt
Q: Alternative to PycURL? Here's a bit of code that is uploading a file: file_size = os.path.getsize('Tea.rdf') f = file('Tea.rdf') c = pycurl.Curl() c.setopt(pycurl.URL, 'http://localhost:8080/openrdf-sesame/repositories/rep/statements') c.setopt(pycurl.HTTPHEADER, ["Content-Type: application/rdf+xml;chars...
Alternative to PycURL?
Here's a bit of code that is uploading a file: file_size = os.path.getsize('Tea.rdf') f = file('Tea.rdf') c = pycurl.Curl() c.setopt(pycurl.URL, 'http://localhost:8080/openrdf-sesame/repositories/rep/statements') c.setopt(pycurl.HTTPHEADER, ["Content-Type: application/rdf+xml;charset=UTF-8"]) c.setopt(pycur...
[ "Yes, pycurl have a bad API design, cURL is powerful. It have more futures, then urllib/urllib2.\nMaybe you want to try to use human_curl. It's python curl wrapper. You can install it from sources https://github.com/lispython/human_curl or by pip: pip install human_curl.\nExample:\n>>> import human_curl as hurl\n>>...
[ 4, 1, 0 ]
[]
[]
[ "pycurl", "python" ]
stackoverflow_0001683103_pycurl_python.txt
Q: Installing and including envisage plugin I just installed the envisagecore and envisageplugin in Ubuntu 10.04. I'm using Eclipse SDK and PyDev plugin. How can I import this plugin in Eclipse? A: I don't have access to the Envisage plugins documentation, so I'm not sure how these are installed. In general what yo...
Installing and including envisage plugin
I just installed the envisagecore and envisageplugin in Ubuntu 10.04. I'm using Eclipse SDK and PyDev plugin. How can I import this plugin in Eclipse?
[ "I don't have access to the Envisage plugins documentation, so I'm not sure how these are installed. In general what you need to do is open Windows -> Preferences -> PyDev -> Interpreter - Python and check that the package directory is present in the System PYTHONPATH window. If it isn't add it and press Apply.\nIf...
[ 1 ]
[]
[]
[ "plugins", "python" ]
stackoverflow_0007344835_plugins_python.txt
Q: No errors shown rendering an included file in Django/GAE Usually an error message is shown in browser if any error occured processing a Django/GAE template. But once such error is contained in an included file, then none message is shown - the "include" tag produces just blank output making development difficult. ...
No errors shown rendering an included file in Django/GAE
Usually an error message is shown in browser if any error occured processing a Django/GAE template. But once such error is contained in an included file, then none message is shown - the "include" tag produces just blank output making development difficult. Is there a way to show all errors?
[ "Write a unit test in tests.py, where you render the template using django.templates.Template. Check there whether it renders to something else than None or \"\" or white space.\nOnce that unit test succeeds, you can proceed with the next one:\nUse self.client to render the template using the full stack. If the pro...
[ 0 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0006888622_django_templates_google_app_engine_python.txt
Q: python QT underlying object deleted when import code I have a simple program which create a QGraphicsScene / View then execute a given file (via the exec statement of python) with some globals function export. My aim is to only define code of the scene in new files, with some helpers function already defined. I al...
python QT underlying object deleted when import code
I have a simple program which create a QGraphicsScene / View then execute a given file (via the exec statement of python) with some globals function export. My aim is to only define code of the scene in new files, with some helpers function already defined. I also have in my main program a thread which deliver callback...
[ "Thanks to your comments alexisdm and varela, i found the problem.\nI was doing something like this:\nclass Synoptique:\n def __init__(self, w, h):\n self.view = QGraphicsView()\n self.scene = SynopScene()\n # some initialization ...\n\ndef openSynop(buApp, fname, w, h):\n synop = Synopt...
[ 1 ]
[]
[]
[ "exec", "python", "qt" ]
stackoverflow_0007281243_exec_python_qt.txt
Q: Python RegEx, match words in string and get count I want to match a list of words with an string and get how many of the words are matched. Now I have this: import re words = ["red", "blue"] exactMatch = re.compile(r'\b%s\b' % '\\b|\\b'.join(words), flags=re.IGNORECASE) print exactMatch.search("my blue cat") prin...
Python RegEx, match words in string and get count
I want to match a list of words with an string and get how many of the words are matched. Now I have this: import re words = ["red", "blue"] exactMatch = re.compile(r'\b%s\b' % '\\b|\\b'.join(words), flags=re.IGNORECASE) print exactMatch.search("my blue cat") print exactMatch.search("my red car") print exactMatch.sear...
[ "If you use findall instead of search, then you get a tuple as result containing all the matched words.\nprint exactMatch.findall(\"my blue cat\")\nprint exactMatch.findall(\"my red car\")\nprint exactMatch.findall(\"my red and blue monkey\")\nprint exactMatch.findall(\"my yellow dog\")\n\nwill result in\n\n['blue'...
[ 11, 3, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007345252_python_regex.txt
Q: Regular expression in python I have text file (seq.fasta) which contains sequence as follows M1 MPMILGYWNVRGLTHPIRMLLEYTDSSYDEKRYTMGDAPDFDRSQWLNEKFKLGLDFPNL PYLIDGSHKITQSNAILRYLARKHHLDGETEEERIRADIVENQVMDTRMQLIMLCYNPDF EKQKPEFLKTIPEKMKLYSEFLGKRPWFAGDKVTYVDFLAYDILDQYRMFEPKCLDAFPN LRDFLARFEGLKKISAYMKSSRYIATPIFSKMAHW...
Regular expression in python
I have text file (seq.fasta) which contains sequence as follows M1 MPMILGYWNVRGLTHPIRMLLEYTDSSYDEKRYTMGDAPDFDRSQWLNEKFKLGLDFPNL PYLIDGSHKITQSNAILRYLARKHHLDGETEEERIRADIVENQVMDTRMQLIMLCYNPDF EKQKPEFLKTIPEKMKLYSEFLGKRPWFAGDKVTYVDFLAYDILDQYRMFEPKCLDAFPN LRDFLARFEGLKKISAYMKSSRYIATPIFSKMAHWSNK I have to extract motif PXXP ...
[ "Try with this one:\n re.compile(r\"(P..P)\")\n\n. means any character.\n{2} means that the last token must be repeated twice times (in your regex, this means PP.\n\\b matches word boundaries\n", "You can use this:\nre.compile( r\"(P[\\w]{2}P)\" )\n\nor\nre.compile( r\"(P[A-Z]{2}P)\" )\n\nMeta \\w - means alphanu...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007346129_python.txt
Q: Django referrer question I want to know who refers my webpage, so in my models I have:referrer = models.CharField(max_length=30, default='google', verbose_name=_('referrer'), help_text=_('Referrer')) This are the URL's for my page:url(r'^$', app_views.index, name='index_default') and url(r'^(\w+)/$', app_v...
Django referrer question
I want to know who refers my webpage, so in my models I have:referrer = models.CharField(max_length=30, default='google', verbose_name=_('referrer'), help_text=_('Referrer')) This are the URL's for my page:url(r'^$', app_views.index, name='index_default') and url(r'^(\w+)/$', app_views.index, name='index_defaul...
[ "in the meta dictionary of request there is a HTTP_REFERER value .. I think that can help you\n" ]
[ 5 ]
[]
[]
[ "django", "python", "referrer", "regex" ]
stackoverflow_0007346342_django_python_referrer_regex.txt
Q: How python can help me to make my website? i want to develop a website in Python. Can someone tell me how I can do this. currently I am using ASP.NET MVC for web development. I want to make just the Hello world sample. It should print dynamically. A: Here is a solution using string Templates: #!/usr/bin/env pyt...
How python can help me to make my website?
i want to develop a website in Python. Can someone tell me how I can do this. currently I am using ASP.NET MVC for web development. I want to make just the Hello world sample. It should print dynamically.
[ "Here is a solution using string Templates:\n#!/usr/bin/env python\n\nimport string\n\ns=string.Template(\"\"\"\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n\n \"http://www.w3.org/TR/html4/loose.dtd\">\n<html lang=\"en\">\n<head>\n <meta http-equiv=\"content-type\" content=\"text/htm...
[ 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0007346368_html_python.txt
Q: Should I use class as a container for global variable I were making a simple game in pygame and I realized I need a bunch of markers, counts and all sorts of global staff. So I decided to define a class and use it like this: class Staff(): def __init__(self): self.modes={'menu':True,'spawning':False,'s...
Should I use class as a container for global variable
I were making a simple game in pygame and I realized I need a bunch of markers, counts and all sorts of global staff. So I decided to define a class and use it like this: class Staff(): def __init__(self): self.modes={'menu':True,'spawning':False,'sprite_change':False} self.timer=pygame.time.Clock()...
[ "Please, do yourself a favour and rethink your design.\nFirstly you might think that is easier for you to use global variables. You can pass around values and you can access them from every function without passing it to them using parameters. But when it comes to debugging or finding errors or just looking into yo...
[ 2, 1 ]
[]
[]
[ "global_variables", "memory", "python" ]
stackoverflow_0007345907_global_variables_memory_python.txt
Q: Expanding a tree-like data structure I am attempting to use Python to alter some text strings using the re module (i.e., re.sub). However, I think that my question is applicable to other languages that have regex implementations. I have a number of strings that represent tree-like data structures. They look someth...
Expanding a tree-like data structure
I am attempting to use Python to alter some text strings using the re module (i.e., re.sub). However, I think that my question is applicable to other languages that have regex implementations. I have a number of strings that represent tree-like data structures. They look something like this: (A,B)-C-D A-B-(C,D) A-(B,C,...
[ "You could not do this with regular expressions, because you have to deal with nested structures. Instead you could use pyparsing's nestedExpr\n", "The problem you are describing is one of enumerating paths within a graph.\nYou describe three graphs\nA B\n \\ /\n C\n |\n D\n\n A\n |\n B\n / \\\nC D\n\n ...
[ 3, 2, 1 ]
[]
[]
[ "graph_theory", "python", "tree" ]
stackoverflow_0007336985_graph_theory_python_tree.txt
Q: libspotify Python package for calling Spotify api? I'm building an app that needs to get artwork information out of the libspotify Spotify API. I'm building the app in python on google appengine. Does anyone know of a package that will enable me to access the libspotify API? The official page is C and I've googled...
libspotify Python package for calling Spotify api?
I'm building an app that needs to get artwork information out of the libspotify Spotify API. I'm building the app in python on google appengine. Does anyone know of a package that will enable me to access the libspotify API? The official page is C and I've googled around to try and find a suitable wrapper but can't see...
[ "There is also https://github.com/mopidy/pyspotify which is actively used in some applications and up to date.\n", "I don't think you will be able to call libspotify at all. From the docs: \n\"The Python interpreter runs in a secured \"sandbox\" environment to isolate your application for service and security. Th...
[ 3, 2, 0 ]
[]
[]
[ "google_app_engine", "python", "spotify" ]
stackoverflow_0005281492_google_app_engine_python_spotify.txt
Q: $PYTHONSTARTUP with python 2.7 and python 3.2 I finally started using python 3 alongside python 2.7 on Linux. I setup my python shell using a startup-script defined by $PYTHONSTARTUP. Due to incompatibilities I am unable to use the same script for both versions. What is the easiest way to get one script for python...
$PYTHONSTARTUP with python 2.7 and python 3.2
I finally started using python 3 alongside python 2.7 on Linux. I setup my python shell using a startup-script defined by $PYTHONSTARTUP. Due to incompatibilities I am unable to use the same script for both versions. What is the easiest way to get one script for python 2.7, and another for python 3.2?
[ "If you use Python 2 for some projects and Python 3 for others, then change the environment variable when you change projects.\nOr, have your startup script look like this:\nimport sys\nif sys.version_info[0] == 2:\n import startup2\nelse:\n import startup3\n\nand split your real startup code into startup2.py...
[ 14, 7, 2 ]
[]
[]
[ "python", "python_3.x", "startupscript" ]
stackoverflow_0007346984_python_python_3.x_startupscript.txt
Q: Dynamically resizing and adding widgets to Tkinter window I have a Python Tkinter GUI which solicits file names from the user. I would like to add an Entry() box elsewhere in the window when each file is selected -- is it possible to do this in Tkinter? Thanks Mark A: Yes, it is possible. You do it like you add...
Dynamically resizing and adding widgets to Tkinter window
I have a Python Tkinter GUI which solicits file names from the user. I would like to add an Entry() box elsewhere in the window when each file is selected -- is it possible to do this in Tkinter? Thanks Mark
[ "Yes, it is possible. You do it like you add any other widget -- call Entry(...) and then use its grid, pack or place method to have it show up visually. \nHere's a contrived example:\nimport Tkinter as tk\nimport tkFileDialog\n\nclass SampleApp(tk.Tk):\n def __init__(self, *args, **kwargs):\n tk.Tk.__ini...
[ 5 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0007339647_python_tkinter_user_interface.txt
Q: Remove a '\n' list item from a python list I have a list which contains an item '\n' in it. I want to remove it. however, the remove command is not working for it. Can anyone tell me what I am doing wrong? def main(): list1 = ['\ng,g\ng,g,g\n', '\n', '\ns\ns,s\n', '\nd,d\nd\nd,d,d,d\n\n'] print list1 ...
Remove a '\n' list item from a python list
I have a list which contains an item '\n' in it. I want to remove it. however, the remove command is not working for it. Can anyone tell me what I am doing wrong? def main(): list1 = ['\ng,g\ng,g,g\n', '\n', '\ns\ns,s\n', '\nd,d\nd\nd,d,d,d\n\n'] print list1 print list1.remove('\n') if __name__ == '__mai...
[ "The remove method modifies the list in-place and returns None. Thus, when you use print list1.remove('\\n'), the list is modified, but None is printed. Do it in two steps, instead:\nlist1.remove('\\n')\nprint list1\n\nTo remove all occurrences, most natural would be to construct a new list while excluding the newl...
[ 6, 5, 3, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007347063_list_python.txt
Q: What is the difference between gtk builder file and libglade file when using Glade designer? I'm using glade interface designer for developing a simple application. I was actually following a tutorial which was based on libglade format. But I want to use the gtkbuilder format. So I switched to the gtkbuilder forma...
What is the difference between gtk builder file and libglade file when using Glade designer?
I'm using glade interface designer for developing a simple application. I was actually following a tutorial which was based on libglade format. But I want to use the gtkbuilder format. So I switched to the gtkbuilder format. But I just want to know what is the exact difference between libglade format and gtkbuilder fo...
[ "Libglade was a separate library. It since has been deprecated, and the functionnalities have been integrated in GTK, which uses the GTK builder format which is a bit different. Both formats allow almost the same things, but the GtkBuilder one is prefered.\n" ]
[ 3 ]
[]
[]
[ "glade", "gtk", "linux", "python" ]
stackoverflow_0007343714_glade_gtk_linux_python.txt
Q: Pip package install with preinstalled dependencies I would like to install some python packages from local directories (downloaded from GitHub) specified in requirements.txt -e ./src/django-django-eca4737 -e ./src/divio-django-appmedia-55835b6 -e ./src/ojii-django-sekizai-25c64f4 -e ./src/ojii-django-classy-tags-f...
Pip package install with preinstalled dependencies
I would like to install some python packages from local directories (downloaded from GitHub) specified in requirements.txt -e ./src/django-django-eca4737 -e ./src/divio-django-appmedia-55835b6 -e ./src/ojii-django-sekizai-25c64f4 -e ./src/ojii-django-classy-tags-f2076f6 -e ./src/theatlantic-django-south-471b16b -e ./sr...
[ "use --no-dependencies or just --no-deps option\npip install --no-dependencies -r requirements.txt\n\n" ]
[ 5 ]
[]
[]
[ "django", "django_cms", "pip", "python" ]
stackoverflow_0007344650_django_django_cms_pip_python.txt
Q: how to get the upper-left and bottom right coordinates of the box around a certain value in a matrix using python? I have a 2D numpy array. Lets consider the following example [[0,6,89,255,1,6,7] [0,255,89,255,1,1,7] [255,255,255,255,255,255,255] [1,2,3,4,5,6,7] [1,1,255,5,7,3,255]] We need th...
how to get the upper-left and bottom right coordinates of the box around a certain value in a matrix using python?
I have a 2D numpy array. Lets consider the following example [[0,6,89,255,1,6,7] [0,255,89,255,1,1,7] [255,255,255,255,255,255,255] [1,2,3,4,5,6,7] [1,1,255,5,7,3,255]] We need the coordinates of the box around a certain value. For example for value 255 the coordinates of the box around the value 2...
[ "The answer is very similar to: Is there a \"bounding box\" function (slice with non-zero values) for a ndarray in NumPy?\nfrom numpy import array, argwhere\n\nA = array([[0 ,6 ,89 ,255,1 ,6 ,7 ],\n [0 ,255,89 ,255,1 ,1 ,7 ],\n [255,255,255,255,255,255,255],\n [1 ,2 ,3 ,4 ...
[ 4 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007347101_numpy_python.txt
Q: How do I check if a file on http exists, using Python/django? How do I check if a file on http exists, using Python/Django? I try to check if file in http://hostname/directory/file.jpg exist A: Try urllib2.urlopen: import urllib2 ret = urllib2.urlopen('http://hostname/directory/file.jpg') if ret.code == 200: ...
How do I check if a file on http exists, using Python/django?
How do I check if a file on http exists, using Python/Django? I try to check if file in http://hostname/directory/file.jpg exist
[ "Try urllib2.urlopen:\nimport urllib2\nret = urllib2.urlopen('http://hostname/directory/file.jpg')\nif ret.code == 200:\n print \"Exists!\"\n\nNote that you don't check if file exists - you check if resource exists\nEDIT: The other answer by user Geo is better in that HEAD request can be much more efficient as i...
[ 14, 7 ]
[]
[]
[ "python" ]
stackoverflow_0007347888_python.txt
Q: Show directories and files using GtkTreeView Having the following base code for walking a directory I would like to fill a GtkTreeView with the directory and files information to the user: import os for (path, dirs, files) in os.walk("/etc"): print path, dirs, files C code is also welcome since it is easy to ...
Show directories and files using GtkTreeView
Having the following base code for walking a directory I would like to fill a GtkTreeView with the directory and files information to the user: import os for (path, dirs, files) in os.walk("/etc"): print path, dirs, files C code is also welcome since it is easy to translate to pygtk.
[ "Look at this question.\nThe question was funnily the other way around: how to get the directory structure which can then be filled into the TreeView.\n" ]
[ 0 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0007348231_gtk_gtktreeview_pygtk_python.txt
Q: py2exe cannot find a module I have a Python app that works fine. Now I use py2exe to create a windows executable of this app, however the resulting exe fails with complain that it lacks the configobj module Traceback (most recent call last): File "file1.py", line 1, in <module> File "file2.pyc", line 10, in <m...
py2exe cannot find a module
I have a Python app that works fine. Now I use py2exe to create a windows executable of this app, however the resulting exe fails with complain that it lacks the configobj module Traceback (most recent call last): File "file1.py", line 1, in <module> File "file2.pyc", line 10, in <module> ImportError: No module nam...
[ "Reinstalling configobj from source fixed the problem. Damn me if I know why\n" ]
[ 1 ]
[]
[]
[ "configobj", "py2exe", "python" ]
stackoverflow_0007298937_configobj_py2exe_python.txt
Q: conversion float to long in python I have a function fac(n) which return n!, and I am comparing it to gamma(n+1) >>> from math import gamma >>> gamma(101)-fac(100) 0.0 >>> math.floor(gamma(101))-fac(100) 0.0 >>> long(gamma(101))-fac(100) -1716052534060312817912314997891197522637580074354635372754659484313875350886...
conversion float to long in python
I have a function fac(n) which return n!, and I am comparing it to gamma(n+1) >>> from math import gamma >>> gamma(101)-fac(100) 0.0 >>> math.floor(gamma(101))-fac(100) 0.0 >>> long(gamma(101))-fac(100) -17160525340603128179123149978911975226375800743546353727546594843138753508868681910084278482568206994876966492346271...
[ "The results are different because of the limited precision of the floating point type, and because of the way the subtraction operator coerces its operands to be the same type. The gamma function returns a float, so it cannot return an accurate answer for numbers this large. This page gives a good description of...
[ 6, 2 ]
[]
[]
[ "integer", "long_integer", "python" ]
stackoverflow_0007348212_integer_long_integer_python.txt
Q: Array storage in python I want to store a bunch of arrays for future use, how can I do this in python? I usually use append() method for element storage but this doesn't work with arrays. Thanks. A: Why are you using arrays? Do you mean lists? if your using lists then you can append lists (objects) anything to ...
Array storage in python
I want to store a bunch of arrays for future use, how can I do this in python? I usually use append() method for element storage but this doesn't work with arrays. Thanks.
[ "Why are you using arrays? Do you mean lists? if your using lists then you can append lists (objects) anything to other lists.\n", "If you talk about numpy arrays: either you append the elements to a list and construct an array from this list via numpy.array(li) or you use numpys hstack() resp. vstack().\n", "N...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007348144_python.txt
Q: No module named backends.default.urls So I've installed django-registration through easy_install. I'm following a quick start guide and I'm trying to setup my urlConf, however it says module named backends.defauls.urls is not found. What might be the problem ? import registration (r'^accounts/', include('registrat...
No module named backends.default.urls
So I've installed django-registration through easy_install. I'm following a quick start guide and I'm trying to setup my urlConf, however it says module named backends.defauls.urls is not found. What might be the problem ? import registration (r'^accounts/', include('registration.backends.default.urls')),
[ "(not my solution, but since it was hidden in a comment)\nYou need to use use include('registration.urls'),\ninstead of include('registration.backends.default.urls')\n", "Is the registration module in your PYTHONPATH?\n", "I'd suggest always getting django-registration from Bitbucket: https://bitbucket.org/uber...
[ 27, 4, 2, 1 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0004259497_django_django_urls_python.txt
Q: Wildcards in a Search and Replace Dictionary I am fairly new to Python so if my terminology is wrong I apologize. I am running Python 2.6.5, I am not sure about updating to 3.0 since Python was initially downloaded with my spatial analysis software. I am writing a program to search and replace column headers in mu...
Wildcards in a Search and Replace Dictionary
I am fairly new to Python so if my terminology is wrong I apologize. I am running Python 2.6.5, I am not sure about updating to 3.0 since Python was initially downloaded with my spatial analysis software. I am writing a program to search and replace column headers in multiple comma delimited text files. Since there ar...
[ "\nUse the csv module to parse and write your comma-separated data.\nUse the string strip() method to remove unwanted spaces and tabs.\nDo not include * in your dict key names. They will not glob as you\nhope. They just represent literal *s there.\nIt is probably better to use json instead of pickle. JSON is\nhuman...
[ 1 ]
[]
[]
[ "dictionary", "pickle", "python", "wildcard" ]
stackoverflow_0007349074_dictionary_pickle_python_wildcard.txt
Q: Learn Python the Hard Way ex41 Extra Credit working my way through LPTHW and am stuck on the extra credit for exercise 41: Extra Credit: Add cheat codes to the game so you can get past the more difficult rooms. Instead of having each function print itself, learn about “doc string” style comments. Write the r...
Learn Python the Hard Way ex41 Extra Credit
working my way through LPTHW and am stuck on the extra credit for exercise 41: Extra Credit: Add cheat codes to the game so you can get past the more difficult rooms. Instead of having each function print itself, learn about “doc string” style comments. Write the room description as doc comments, and change the...
[ "death has no doc string. if room==death then print room.__doc__ prints None. in the following if/elifs you return from the function runnner which results in the programs end.\nYour program will work if you add the missing doc string and if you replace return \"death\" in runner() by a simple \"pass\", or by ommit...
[ 3 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0007349097_python_python_2.7.txt
Q: deque creation from vector class in python I define a deque and insert a vector in it in python.My goal was define a deque from vectors. But when I iterate on this queue,python returns first argument of this vector. How can I define a deque from vector? A: I'm not sure what you mean by vector, but, as with about...
deque creation from vector class in python
I define a deque and insert a vector in it in python.My goal was define a deque from vectors. But when I iterate on this queue,python returns first argument of this vector. How can I define a deque from vector?
[ "I'm not sure what you mean by vector, but, as with about any sequence in Python you are able to store any type of object in it. Unlike C++, where the type of the stored objects needs to be known at compile time.\nHere is an example:\nclass vector(object):\n def __str__(self):\n return \"I'm a vector, for...
[ 1 ]
[]
[]
[ "deque", "python" ]
stackoverflow_0007349224_deque_python.txt
Q: Parsing an escape character Using Python, I'm trying to parse a string like this: "hello" "I am an example" "the man said:\"hello!\"" into these tokens: 1) hello 2) I am an example 3) the man said: "hello!" Something like re.findall(r'"[^"]*"', str) comes close, but cannot handle the escape char (\). I'm curious...
Parsing an escape character
Using Python, I'm trying to parse a string like this: "hello" "I am an example" "the man said:\"hello!\"" into these tokens: 1) hello 2) I am an example 3) the man said: "hello!" Something like re.findall(r'"[^"]*"', str) comes close, but cannot handle the escape char (\). I'm curious what kind of pythonic ways there...
[ "This is a good fit for regex:\nre.findall(r'\"(?:\\\\.|[^\"\\\\])*\"', str)\n\nExplanation:\n\" # Match a \"\n(?: # Match either...\n \\\\. # an escaped character (\\\\, \\\" etc.)\n| # or\n [^\"\\\\] # any character except \" or \\\n)* # any number of times\n\" # Match a \"\n\...
[ 5, 5 ]
[ "You could replace the '\\' tokens in the original string before rexing them:\ninput_string = '\"hello\" \"I am an example\" \"the man said:\\\"hello!\\\"\"'\ninput_string.replace('\\', '')\n\nEDIT: I'm not sure if you have to escape the '\\' sign. maybe you have to write:\ninput_string.replace('\\\\', '')\n\n" ]
[ -1 ]
[ "parsing", "python" ]
stackoverflow_0007349411_parsing_python.txt
Q: Using an MFC .dll file with Python 3.2 I am currently planning to access my MFC Dialog based application's .dll file using Python. I am new to Python and have the latest version of Python installed i.e. 3.2. I have installed PythonWin as well, but not really sure if it would be useful or not. I have understood lik...
Using an MFC .dll file with Python 3.2
I am currently planning to access my MFC Dialog based application's .dll file using Python. I am new to Python and have the latest version of Python installed i.e. 3.2. I have installed PythonWin as well, but not really sure if it would be useful or not. I have understood like the basics of using python with the help o...
[ "I think this should give you some idea on what you are trying to do. Hope this helps.\n", "MFC isn't just a library, it's a platform. It's going to depend on certain assumptions, such as proper initialization being done at program startup and that an MFC message pump will be called periodically among others. Tho...
[ 2, 1 ]
[]
[]
[ "dll", "mfc", "python", "scripting", "visual_c++" ]
stackoverflow_0007346140_dll_mfc_python_scripting_visual_c++.txt
Q: What is the most efficient way to match list items to lines in a large file in Python? I have a large file (5Gb) called my_file. I have a list called my_list. What is the most efficient way to read each line in the file and, if an item from my_list matches an item from a line in my_file, create a new list called m...
What is the most efficient way to match list items to lines in a large file in Python?
I have a large file (5Gb) called my_file. I have a list called my_list. What is the most efficient way to read each line in the file and, if an item from my_list matches an item from a line in my_file, create a new list called matches that contains items from the lines in my_file AND items from my_list where a match oc...
[ "You could build a dictonary for looking up v. I added further little optimizations:\ndef calc(my_file, my_list)\n\n vd = dict( (v[1],v[0]) for v in my_list)\n\n my_file.seek(0,0)\n for line in my_file:\n f0, f1, f2, f3 = line[:-1].split('\\t')\n v0 = vd.get(f2)\n if v0 is not None:\n ...
[ 3, 0, 0, 0 ]
[]
[]
[ "list", "match", "python" ]
stackoverflow_0007346770_list_match_python.txt
Q: How to access the specific locations of an integer list in Python? I have an integer list which should be used as indices of another list to retrieve a value. Lets say we have following array a = [1,2,3,4,5,6,7,8,9] We can get the specific elements using following code import operator operator.itemge...
How to access the specific locations of an integer list in Python?
I have an integer list which should be used as indices of another list to retrieve a value. Lets say we have following array a = [1,2,3,4,5,6,7,8,9] We can get the specific elements using following code import operator operator.itemgetter(1,2,3)(a) It will return the 2nd, 3rd and 4th item. Lets say i hav...
[ "Use *:\noperator.itemgetter(*b)(a)\n\nThe * in a function call means, unpack this value, and use its elements as the arguments to the function.\n", "Since you have tagged your question with the numpy tag, you could also consider making a an array so this works:\nfrom numpy import array\na = array([1,2,3,4,5,6,7,...
[ 8, 3, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007350301_numpy_python.txt
Q: How to place a combobox in wxgrid (python)? I can't find any good information on how to place a combobox inside a cell in a wxgrid. I tried Google, but maybe I'm blind. Anyone have a simple sample to share? A: Take a look at GridChoiceCellEditor. You can use it as follows: choice_editor = wx.grid.GridCellCho...
How to place a combobox in wxgrid (python)?
I can't find any good information on how to place a combobox inside a cell in a wxgrid. I tried Google, but maybe I'm blind. Anyone have a simple sample to share?
[ "Take a look at GridChoiceCellEditor. You can use it as follows:\n choice_editor = wx.grid.GridCellChoiceEditor(choices_list, True) \n grid.SetCellEditor(row, col, choice_editor)\n\n", "The wxPython demo has an example that shows how this is done in the GridStdEdRend.py file itself or from within the demo i...
[ 5, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007348431_python_wxpython.txt
Q: How to calculate slope in numpy If I have an array of 50 elements, how would I calculate a 3 period slope and a 5 period slope? The docs dont add much..... >>> from scipy import stats >>> import numpy as np >>> x = np.random.random(10) >>> y = np.random.random(10) >>> slope, intercept, r_value, p_value, std_err ...
How to calculate slope in numpy
If I have an array of 50 elements, how would I calculate a 3 period slope and a 5 period slope? The docs dont add much..... >>> from scipy import stats >>> import numpy as np >>> x = np.random.random(10) >>> y = np.random.random(10) >>> slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) Would this w...
[ "I'm assuming you mean the slope calculated on every 3rd and 5th element so that you have a series of (exact, not least-squares) slopes?\nIf so, you'd just do something along the lines of:\nthird_period_slope = np.diff(y[::3]) / np.diff(x[::3])\nfifth_period_slope = np.diff(y[::5]) / np.diff(x[::5])\n\nI'm probably...
[ 7, 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007350588_numpy_python.txt
Q: Comparison: Pycharm vs WingIDE Which one do you prefer? Which features does one have that the other doesn't (in their latest versions, of course)? Both IDEs have trial versions at their respective websites: http://wingware.com/ http://www.jetbrains.com/pycharm/ A: I don't think this is the kind of question some...
Comparison: Pycharm vs WingIDE
Which one do you prefer? Which features does one have that the other doesn't (in their latest versions, of course)? Both IDEs have trial versions at their respective websites: http://wingware.com/ http://www.jetbrains.com/pycharm/
[ "I don't think this is the kind of question someone could answer for you. As they both provide trial licenses, you really should try each one for your everyday coding, and you'll then know which one fits best your needs.\n" ]
[ 3 ]
[]
[]
[ "comparison", "pycharm", "python", "wing_ide" ]
stackoverflow_0007349397_comparison_pycharm_python_wing_ide.txt
Q: Regular expression optimization - C enum typedef For a certain project of mine I need to parse enum typedefs from an .h file. For example lets take the next simple case: typedef enum { data1, /*aaagege*/ data2, data3 }ESample; This is a very simple declaration (without assigns or anything a bit more ...
Regular expression optimization - C enum typedef
For a certain project of mine I need to parse enum typedefs from an .h file. For example lets take the next simple case: typedef enum { data1, /*aaagege*/ data2, data3 }ESample; This is a very simple declaration (without assigns or anything a bit more complex) and yet the regular expression that I wrote s...
[ "The reason it's slow is because of your nested repeats (marked with ^):\n(?:\\s+(\\w+)[^\\n]*)+\n ^ ^\n\nThis causes nested backtracking, which leads to exponential running times.\nBut you have a larger problem which is that putting a group inside a repeat means that only the last match of the group...
[ 3, 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007350655_python_regex.txt
Q: Need to do a math operation on every line in several CSV files in Python I have about 100 CSV files I have to operate on once a month and I was trying to wrap my head around this but I'm running into a wall. I'm starting to understand some things about Python, but combining several things is still giving me issue...
Need to do a math operation on every line in several CSV files in Python
I have about 100 CSV files I have to operate on once a month and I was trying to wrap my head around this but I'm running into a wall. I'm starting to understand some things about Python, but combining several things is still giving me issues, so I can't figure this out. Here's my problem: I have many CSV files, and h...
[ "There's a tool in the standard library for each of these tasks:\nTo iterate over all CSV files in a directory, use the glob module:\nimport glob\nfor csvfilename in glob.glob(r\"C:\\mydirectory\\*.csv\"):\n #do_something\n\nTo parse a CSV file, use the csv module:\nimport csv\nwith open(csvfilename, \"rb\") as ...
[ 7, 0 ]
[]
[]
[ "csv", "datestamp", "python" ]
stackoverflow_0007350851_csv_datestamp_python.txt
Q: Comparing 2 model entities Is there an easy way to compare to entities to to check for property value differences? I want something like this: me = User.get_by_id( 28 ) cloned_me = me cloned_me.first_name = 'Tom' if me != cloned_me: self.response.out.write( 'These 2 objects have different property values' ) ...
Comparing 2 model entities
Is there an easy way to compare to entities to to check for property value differences? I want something like this: me = User.get_by_id( 28 ) cloned_me = me cloned_me.first_name = 'Tom' if me != cloned_me: self.response.out.write( 'These 2 objects have different property values' )
[ "For simplest scenario you can compare objects field by field e.g.\nfrom django.contrib.auth.models import User\n\ndef compare(user1, user2):\n for field in user1._meta.fields: \n val1 = getattr(user1, field.name)\n val2 = getattr(user2, field.name)\n if val1 != val2:\n print \"%s...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007350852_google_app_engine_python.txt
Q: Python: Nested Dictionary duplicate values I am not that experienced in python so it might be the case that I am missing something which is already there.. But it would be great if anyone can help me sort this out. I have a nested dictionary which is something of the following form: Main dictionary has key: userid...
Python: Nested Dictionary duplicate values
I am not that experienced in python so it might be the case that I am missing something which is already there.. But it would be great if anyone can help me sort this out. I have a nested dictionary which is something of the following form: Main dictionary has key: userid then in this the particular user has rated (may...
[ "Here you need to add a new inner dict to the outer dict only if it doesn't exist yet, right? Then you need to use setdefault:\ndataDict={}\nfor line in myFile:\n words = line.strip().split()\n userId = words[0]\n movieId = words[1]\n rating = words[2]\n innerDict = dataDict.setde...
[ 2, 0 ]
[]
[]
[ "dictionary", "nested", "python" ]
stackoverflow_0007351472_dictionary_nested_python.txt
Q: split string in to 2 based on last occurrence of a separator I would like to know if there is any built in function in python to break the string in to 2 parts, based on the last occurrence of a separator. for eg: consider the string "a b c,d,e,f" , after the split over separator ",", i want the output as "a b c,d...
split string in to 2 based on last occurrence of a separator
I would like to know if there is any built in function in python to break the string in to 2 parts, based on the last occurrence of a separator. for eg: consider the string "a b c,d,e,f" , after the split over separator ",", i want the output as "a b c,d,e" and "f". I know how to manipulate the string to get the desir...
[ "Use rpartition(s). It does exactly that.\nYou can also use rsplit(s, 1).\n", ">>> \"a b c,d,e,f\".rsplit(',',1)\n['a b c,d,e', 'f']\n\n", "You can split a string by the last occurrence of a separator with rsplit:\n\nReturns a list of the words in the string, separated by the delimiter string (starting from rig...
[ 122, 74, 55 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007351744_python_string.txt
Q: Special considerations when performing file I/O on an NFS share via a Python-based daemon? I have a python-based daemon that provides a REST-like interface over HTTP to some command line tools. The general nature of the tool is to take in a request, perform some command-line action, store a pickled data structure ...
Special considerations when performing file I/O on an NFS share via a Python-based daemon?
I have a python-based daemon that provides a REST-like interface over HTTP to some command line tools. The general nature of the tool is to take in a request, perform some command-line action, store a pickled data structure to disk, and return some data to the caller. There's a secondary thread spawned on daemon startu...
[ "I have the answer to my problem and it had nothing to with the fact that I was doing file I/O on an NFS share. It turns out the problem just showed up faster if the I/O was over an NFS mount versus local disk.\nA key piece of information is that the code was running threaded via the SocketServer.ThreadingMixIn and...
[ 6, 2 ]
[]
[]
[ "daemon", "nfs", "python" ]
stackoverflow_0007084194_daemon_nfs_python.txt
Q: python: deleting numbers in a file I need to delete numbers from a text file on windows XP. I am new to python and just installed it for data scrubbing. I have stored the test file in C:\folder1\test1.txt The contexts on test1.txt is just 1 line: This must not b3 delet3d, but the number at the end yes 134411 I w...
python: deleting numbers in a file
I need to delete numbers from a text file on windows XP. I am new to python and just installed it for data scrubbing. I have stored the test file in C:\folder1\test1.txt The contexts on test1.txt is just 1 line: This must not b3 delet3d, but the number at the end yes 134411 I want to created a file result1.txt which ...
[ "You're using open() in the os module, which takes a numeric file mode. You want instead the builtin open() function. Also, backslashes in strings take on a special meaning in Python; you need to double them up if you really mean backslashes. Try:\nfin = open('C:\\\\folder1\\\\test1.txt','r')\n\n", "according to ...
[ 8, 2, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0007351939_file_python.txt
Q: Sorting a dictionary of tuples in Python I know there's tonnes of questions on python sorting lists/dictionaries already, but I can't seem to find one which helps in my case, and i'm looking for the most efficient solution as I'm going to be sorting a rather large dataset. My data basically looks like this at the ...
Sorting a dictionary of tuples in Python
I know there's tonnes of questions on python sorting lists/dictionaries already, but I can't seem to find one which helps in my case, and i'm looking for the most efficient solution as I'm going to be sorting a rather large dataset. My data basically looks like this at the moment: a = {'a': (1, 2, 3), 'b': (3, 2, 1)} ...
[ "Something like this?\n>>> a = {'a': (1, 2, 3), 'b': (3, 2, 1)}\n>>> b = a.items()\n>>> b\n[('a', (1, 2, 3)), ('b', (3, 2, 1))]\n>>> b.sort(key=lambda x:x[1][2]) # sorting by the third item in the tuple\n>>> b\n[('b', (3, 2, 1)), ('a', (1, 2, 3))]\n\n", "Names are easier to work with and remember that indices, s...
[ 9, 1 ]
[]
[]
[ "dictionary", "python", "sorting", "tuples" ]
stackoverflow_0007349646_dictionary_python_sorting_tuples.txt
Q: pyside-uic/pyuic4: command not found I'm running Python 2.7 on OS X Snow Leopard. I installed Python using Macports. Then, I installed py27-pyqt4 and py27-pyside, and I can't get them to work. Python doesn't give errors when I import, but I get the following errors in the terminal when I test either: pyside-uic :...
pyside-uic/pyuic4: command not found
I'm running Python 2.7 on OS X Snow Leopard. I installed Python using Macports. Then, I installed py27-pyqt4 and py27-pyside, and I can't get them to work. Python doesn't give errors when I import, but I get the following errors in the terminal when I test either: pyside-uic : command not found pyuic4 : command not fo...
[ "You are still using the default Mac OS Python and not using the new installed one.\n\nCheck the python version: python must be 2.7. \nfind the new\nversion (should be inside /usr/local/bin ) \nupdate your\n.bash_profile PATH=/usr/local/bin/:$PATH \nTry again and try to\nimport PyQt4\n\n" ]
[ 1 ]
[]
[]
[ "macos", "pyqt4", "pyside", "python" ]
stackoverflow_0007211672_macos_pyqt4_pyside_python.txt
Q: Why can't I use app.MainLoop() with iPython? I'd like a rectangle to appear every time the user clicks on the line. I've gotten this to work procedurally like in this example: http://www.daniweb.com/software-development/python/code/216648 but once I implemented iPython compatibility and started using classes, I co...
Why can't I use app.MainLoop() with iPython?
I'd like a rectangle to appear every time the user clicks on the line. I've gotten this to work procedurally like in this example: http://www.daniweb.com/software-development/python/code/216648 but once I implemented iPython compatibility and started using classes, I could no longer use the app.MainLoop() without the p...
[ "It seems likely that matplotlib is set to use a backend other than wx. Try either setting this in the matplotlibrc file, or it can be set in the program (but it must be set before matplotlib is imported). Instructions are here.\n" ]
[ 1 ]
[]
[]
[ "ipython", "matplotlib", "python", "wxpython" ]
stackoverflow_0007339761_ipython_matplotlib_python_wxpython.txt
Q: Question about "Python GTK adding signal to a combo box" / answered Apr 24 '10 at 18:21 I'm very new to Python and pygtk , I want to use the changed value of the combo in the main window , but I can't ! I need some help Thanks in advance Best regards A: Without code, it is rather difficult to help for sure, bu...
Question about "Python GTK adding signal to a combo box" / answered Apr 24 '10 at 18:21
I'm very new to Python and pygtk , I want to use the changed value of the combo in the main window , but I can't ! I need some help Thanks in advance Best regards
[ "Without code, it is rather difficult to help for sure, but I'll take a stab at this...\nFrom your question, I am guessing that you're wanting to retrieve the value of the combo box once the user changes it.\nYou're going to need to create a new event handler to retrieve the value upon the user changing. In order t...
[ 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0005588345_pygtk_python.txt
Q: Have a sentence printed in Python without ' or ", using the print function Below is my code, I am working with Python2.7 #list of angle couples phipsi=[[48.6,53.4],[-124.9,156.7],[-66.2,-30.8],[-58.8,-43.1], \ [-73.9,-40.6],[-53.7,-37.5],[-80.6,-16.0],[-68.5,135.0], \ [-64.9,-23.5],[-66.9,-45.5],[-69.6,-41.0],[-62...
Have a sentence printed in Python without ' or ", using the print function
Below is my code, I am working with Python2.7 #list of angle couples phipsi=[[48.6,53.4],[-124.9,156.7],[-66.2,-30.8],[-58.8,-43.1], \ [-73.9,-40.6],[-53.7,-37.5],[-80.6,-16.0],[-68.5,135.0], \ [-64.9,-23.5],[-66.9,-45.5],[-69.6,-41.0],[-62.7,-37.5], \ [-68.2,-38.3],[-61.2,-49.1],[-59.7,-41.1],[-63.2,-48.5], \ [-65.5,-...
[ "In Python 2.x print is not a function, but a statement, and it doesn't include parens around the list of printed objects. In Python 3.x print was changed to a function. You're using the Python 3.x syntax.\nYou have two options:\n\nUse the Python 2.x syntax instead, skipping the parens: print a, b, c\nAdd from __fu...
[ 6, 1 ]
[]
[]
[ "printing", "python", "python_2.7" ]
stackoverflow_0007352353_printing_python_python_2.7.txt
Q: C++ API in Python - SWIG, Redesign, or Message Passing Ok, quick, and hopefully easy question here... I have a large C++ API that is basically a sockets API with a top level XML type protocol. This is a distributed source package from a company. All of the source code is written into header files (including func...
C++ API in Python - SWIG, Redesign, or Message Passing
Ok, quick, and hopefully easy question here... I have a large C++ API that is basically a sockets API with a top level XML type protocol. This is a distributed source package from a company. All of the source code is written into header files (including function implementations) for some odd reason (I guess they figu...
[ "SWIG would usually be my preferred solution for problems like this. \"Custom typed\" structures can be wrapped perfectly sensibly. The thing you will need to watch out for though is the limitations of the SWIG parser if you've got everything in the header files.\n", "You should consider boost_python. It gives y...
[ 4, 3 ]
[]
[]
[ "api", "c++", "python", "swig" ]
stackoverflow_0007352345_api_c++_python_swig.txt
Q: Efficient Array replacement in Python I'm wondering what is the most efficient way to replace elements in an array with other random elements in the array given some criteria. More specifically, I need to replace each element which doesn't meet a given criteria with another random value from that row. For exampl...
Efficient Array replacement in Python
I'm wondering what is the most efficient way to replace elements in an array with other random elements in the array given some criteria. More specifically, I need to replace each element which doesn't meet a given criteria with another random value from that row. For example, I want to replace each row of data as a ...
[ "I think it would be faster to pull out all the good values, then use random.choice() to pick one whenever you need it. Something like this:\nimport numpy as np\nimport random\nfrom itertools import izip\n\ndata = np.random.normal(0, 1, (10, 100))\nfor row in data:\n good_ones = np.logical_and(row >= -0.8, row ...
[ 4 ]
[]
[]
[ "arrays", "numpy", "python", "replace" ]
stackoverflow_0007352847_arrays_numpy_python_replace.txt
Q: What's the best way to get a number as input from python while maintaining type I'm trying to get a number as CLI input from python. Valid input should be either an int or a float and I need to maintain type. So validating an int and returning a float wouldn't work. This is the best thing I've been able to come up...
What's the best way to get a number as input from python while maintaining type
I'm trying to get a number as CLI input from python. Valid input should be either an int or a float and I need to maintain type. So validating an int and returning a float wouldn't work. This is the best thing I've been able to come up with and it's not all that good. def is_valid(n): try: if '.' in n: ret...
[ "use a for loop to try all the conversions, I added complex type for demonstration:\ndef is_valid(n):\n for t in (int, float, complex):\n try:\n return t(n)\n except ValueError:\n pass\n raise ValueError(\"invalid number %s\" % n)\n\nprint is_valid(\"10\")\nprint is_valid(\...
[ 8, 1, 1, 1 ]
[]
[]
[ "command_line_interface", "input", "python", "shell" ]
stackoverflow_0007342103_command_line_interface_input_python_shell.txt
Q: Why str can't get a second parameter,when __str__ can? I decided to use str for printing the contents of a tree in tree-like structure,using something like print tree The nodes of the tree are all objects of user-created classes and I overload their __str__ magic method in order to use the child nodes' str after...
Why str can't get a second parameter,when __str__ can?
I decided to use str for printing the contents of a tree in tree-like structure,using something like print tree The nodes of the tree are all objects of user-created classes and I overload their __str__ magic method in order to use the child nodes' str after indent t tabs like that def __str__ (self,t=0) :` retu...
[ "Imagine it this way.\ndef str(obj):\n try:\n return obj.__str__()\n except ...:\n ...\n\nJust because __str__ can take more parameters, doesn't mean that str is configured to pass those parameters through.\n", "If you have a Class C with a method __str__(self, t=0), str(c) will call C.__str__...
[ 12, 3 ]
[]
[]
[ "methods", "operator_overloading", "python", "string", "tree" ]
stackoverflow_0007353486_methods_operator_overloading_python_string_tree.txt
Q: Python: how to launch scp with pexpect without OpenSSH GUI Password Prompt on Ubuntu? I'm attempting to automate scp commands with pexpect on Ubuntu. However, I keep getting a password GUI prompt with title "OpenSSH". How can I disable this behavior and use command line prompts instead? A: See the DISPLAY and SS...
Python: how to launch scp with pexpect without OpenSSH GUI Password Prompt on Ubuntu?
I'm attempting to automate scp commands with pexpect on Ubuntu. However, I keep getting a password GUI prompt with title "OpenSSH". How can I disable this behavior and use command line prompts instead?
[ "See the DISPLAY and SSH_ASKPASS section of man ssh-add.\n" ]
[ 1 ]
[]
[]
[ "pexpect", "python" ]
stackoverflow_0007352021_pexpect_python.txt
Q: Trying to Split One List into Multiple Lists Inside of a Main List - Python For some reason I get this traceback when trying to split comma delimited items into a new list and then inserting them into a higher list: Traceback (most recent call last): File "S:/Personal Folders/Andy/Python Projects/People Cancelle...
Trying to Split One List into Multiple Lists Inside of a Main List - Python
For some reason I get this traceback when trying to split comma delimited items into a new list and then inserting them into a higher list: Traceback (most recent call last): File "S:/Personal Folders/Andy/Python Projects/People Cancelled/Analyze Customers Test.py", line 15, in <module> text[x] = textnew TypeErro...
[ "this...\nfor x in text:\n textnew = x.split(\",\")\n text[x] = textnew\n\nshould probably be this...\nfor index, line in enumerate(text):\n text[index] = line.split(',')\n\nThe problem in the first example is that you are using x as an index into text, but text is an array of strings, so x is always a str...
[ 4, 3, 0, 0, 0 ]
[]
[]
[ "iteration", "list", "python", "string" ]
stackoverflow_0007353353_iteration_list_python_string.txt
Q: mongodb FindAndModify - update data I am using MongoDB 1.8 with python 2.6 and want to modify a 'value' ... dynamically ... with reference to this link mongodb FindAndModify - update data the solution did not work for me. The following is the line within my python script, to insert into MongoDb collections. basic...
mongodb FindAndModify - update data
I am using MongoDB 1.8 with python 2.6 and want to modify a 'value' ... dynamically ... with reference to this link mongodb FindAndModify - update data the solution did not work for me. The following is the line within my python script, to insert into MongoDb collections. basic = {'state' : state, 'district' : distric...
[ "Well, if it's a new object then you have to insert.\nIf the object already exists and the user modifies it then you've already retrieved the object(s) from the collection so you knew its ObjectId. Put it in the HTML form as hidden field so you will know which object to update.\n" ]
[ 0 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0007349372_mongodb_python.txt
Q: UnicodeDecodeError in SUDS but only in the .exe generated by py2exe I have a Python 2.7 script SendPreord.py which communicates with web services using SUDS. In the script I call a web service method passing some parameters as strings (runJob(par1, par2, par3)). It works well with western european characters in th...
UnicodeDecodeError in SUDS but only in the .exe generated by py2exe
I have a Python 2.7 script SendPreord.py which communicates with web services using SUDS. In the script I call a web service method passing some parameters as strings (runJob(par1, par2, par3)). It works well with western european characters in the strings. I run it in Eclipse with PyDev. Then I generate the .exe using...
[ "You've been bitten by Python's guessing on encoding conversions. The first part you tried is right: decode first with the (hopefully correct) encoding. Before you send it out, you have to\nencode it again, preferrably using something like UTF-8, or else Python tries the \"default\" encoding (which is in most insta...
[ 0 ]
[]
[]
[ "ascii", "character_encoding", "py2exe", "python", "suds" ]
stackoverflow_0007350115_ascii_character_encoding_py2exe_python_suds.txt
Q: graphing multiple types of plots (line, scatter, bar etc) in the same window I'm trying to graph two types of plots in the same window (i.e. a line plot, and a scatter plot). The data being plotted in the line graph (first plot) are floating numerical values representing climate indices (Y) vs. decimal years (X). ...
graphing multiple types of plots (line, scatter, bar etc) in the same window
I'm trying to graph two types of plots in the same window (i.e. a line plot, and a scatter plot). The data being plotted in the line graph (first plot) are floating numerical values representing climate indices (Y) vs. decimal years (X). The second plot that I would like to be a 'scatter'ed is much the same, but with ...
[ "Why not just use plot in both cases?\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\n# Generate some random data\ntime = mdates.drange(datetime.datetime(2010, 1, 1), \n datetime.datetime(2011, 1, 1),\n datetime.time...
[ 5, 1 ]
[]
[]
[ "matplotlib", "python", "scatter" ]
stackoverflow_0007352900_matplotlib_python_scatter.txt
Q: Python: can I modify a Tuple? I have a 2 D tuple (Actually I thought, it was a list.. but the error says its a tuple) But anyways.. The tuple is of form: (floatnumber_val, prod_id) now I have a dictionary which contains key-> prod_id and value prod_name now.. i want to change the prod_id in tuple to prod_name So ...
Python: can I modify a Tuple?
I have a 2 D tuple (Actually I thought, it was a list.. but the error says its a tuple) But anyways.. The tuple is of form: (floatnumber_val, prod_id) now I have a dictionary which contains key-> prod_id and value prod_name now.. i want to change the prod_id in tuple to prod_name So this is waht I did #if prodName is ...
[ "Tuples are not mutable, you cannot change them. \nThe thing to do is probably to find out why you are creating tuples instead of the list you expected.\n", "If prodName is a list of tuples and you want to create a new list of tuples like you explained, you have to create new tuples since a tuple is immutable (i....
[ 9, 7, 5, 4, 2 ]
[]
[]
[ "immutability", "list", "python", "tuples" ]
stackoverflow_0007353589_immutability_list_python_tuples.txt
Q: make dictionary from csv file columns i am new to the concept of dictionaries in python. I have a csv file with multiple columns and i want to create a dictionary such that keys are taken from 1st column and values from the second and a key:value pair is made for all rows of those two columns. The code is as foll...
make dictionary from csv file columns
i am new to the concept of dictionaries in python. I have a csv file with multiple columns and i want to create a dictionary such that keys are taken from 1st column and values from the second and a key:value pair is made for all rows of those two columns. The code is as follows: if __name__=="__main__": reader = ...
[ "if __name__==\"__main__\":\n mydict = {}\n reader = csv.reader(open(\"file.csv\", \"rb\"))\n for rows in reader:\n k = rows[0]\n v = rows[1]\n mydict[k] = v\n print mydict\n\nHere:\nmydict = {k:v}\n\nYou were making new dictionary in every iteration, and the previous data has been ...
[ 6, 5 ]
[]
[]
[ "python" ]
stackoverflow_0007353743_python.txt
Q: Grouping Elements of a List based on attributes of the elements I have the following list List=[ ('G1', 'CFS', 'FCL', 'R1'), ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9'), ('G4', 'CFS', 'FCL', 'R10'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), ('G1', 'CFS', 'FCL', 'R2'), ('G2', 'LOOSEFREIGHT', 'LCL', ...
Grouping Elements of a List based on attributes of the elements
I have the following list List=[ ('G1', 'CFS', 'FCL', 'R1'), ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9'), ('G4', 'CFS', 'FCL', 'R10'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), ('G1', 'CFS', 'FCL', 'R2'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5'), ] Now I want to group this elements of List first by inde...
[ "If this is a one-off task list-comprehensions are probably the simplest solution:\n>>> new_list = []\n>>> new_list.append([i for i in L if i[1] == 'CFS']) # where L is your original list\n>>> new_list.append([i for i in L if i[1] == 'LOOSEFREIGHT' and i[2] == 'LCL'])\n>>> new_list.append([i for i in L if i[1] == '...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005478272_python.txt
Q: autofilling location search box I'm learning web design using django as a starting point. I would like a search box with a drop down auto completing location e.g as here. Can I use a Google API for this? A: Here is the main plugin you want: jqueryui See the source code section for how to implement. This google ...
autofilling location search box
I'm learning web design using django as a starting point. I would like a search box with a drop down auto completing location e.g as here. Can I use a Google API for this?
[ "Here is the main plugin you want:\njqueryui\nSee the source code section for how to implement.\nThis google code addon to the above also looks helpful:\ndjango-ajax-selects\nIt uses django 1.0 or greater and jquery 1.26 or greater.\n" ]
[ 1 ]
[]
[]
[ "django", "google_maps", "python" ]
stackoverflow_0007353555_django_google_maps_python.txt