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: Creating Dependency Graphs in Python I have inherited a huge codebase that I need to make some small changes into. I was wondering if there are utilities that would parse python code and give dependencies between functions, as in if I make changes to a function I want to be sure that I dont break other functions, so if I could see in a graph like diagram it would make my life easier. A: Usually "dependency" is defined for module / package import. What you are looking for is a visualizing call flow. http://pycallgraph.slowchop.com/ You can still not guarantee that you will not break functionality :) My experience and solution: Many a times, I found the call flow data overwhelming and the diagram too complex. So what i usually do is trace call flow partially for the function, I am interested in. This is done by utilizing the sys.settrace(...) function. After generating the call flows as textual data, I generate a call graph using graphviz. http://docs.python.org/library/sys.html On call tracing For generating graphs, use graphviz solutions from networkX. [Edit: based on comments] Then my piecemeal solution works better. Just insert the code and use the decorator on a function that you want to trace. You will see gaps where deferred comes into picture but that can be worked out. You will not get the complete picture directly. I have been trying to do that and made a few post that works on that understanding.
Creating Dependency Graphs in Python
I have inherited a huge codebase that I need to make some small changes into. I was wondering if there are utilities that would parse python code and give dependencies between functions, as in if I make changes to a function I want to be sure that I dont break other functions, so if I could see in a graph like diagram it would make my life easier.
[ "\nUsually \"dependency\" is defined for module / package import.\nWhat you are looking for is a visualizing call flow.\n\nhttp://pycallgraph.slowchop.com/\n\nYou can still not guarantee that you will not break functionality :)\nMy experience and solution:\nMany a times, I found the call flow data overwhelming and ...
[ 35 ]
[]
[]
[ "call_flow", "dependency_management", "python" ]
stackoverflow_0004160746_call_flow_dependency_management_python.txt
Q: How badly should I avoid surrogate primary keys in SQL? Short story I have a technical problem with a third-party library at my hands that I seem to be unable to easily solve in a way other than creating a surrogate key (despite the fact that I'll never need it). I've read a number of articles on the Net discouraging the use of surrogate keys, and I'm a bit at a loss if it is okay to do what I intend to do. Long story I need to specify a primary key, because I use SQLAlchemy ORM (which requires one), and I cannot just set it in __mapper_args__, since the class is being built with classobj, and I have yet to find a way to reference the field of a not-yet-existing class in the appropriate PK definition argument. Another problem is that the natural equivalent of the PK is a composite key that is too long for the version of MySQL I use (and it's generally a bad idea to use such long primary keys anyway). A: I always make surrogate keys when using ORMs (or rather, I let the ORMs make them for me). They solve a number of problems, and don't introduce any (major) problems. So, you've done your job by acknowledging that there are "papers on the net" with valid reasons to avoid surrogate keys, and that there's probably a better way to do it. Now, write "# TODO: find a way to avoid surrogate keys" somewhere in your source code and go get some work done. A: "Using a surrogate key allows duplicates to be created when using a natural key would have prevented such problems" Exactly, so you should have both keys, not just a surrogate. The error you seem to be making is not that you are using a surrogate, it's that you are assuming the table only needs one key. Make sure you create all the keys you need to ensure the integrity of your data. Having said that, in this case it seems like a deficiency of the ORM software (apparently not being able to use a composite key) is the real cause of your problems. It's unfortunate that a software limitation like that should force you to create keys you don't otherwise need. Maybe you could consider using different software. A: I use surrogate keys in a db that I use reflection on with sqlalchemy. The pro is that you can more easily manage the foreign keys / relationships that exists in your tables / models. Also, the rdbms is managing the data more efficiently. The con is the data inconsistency: duplicates. To avoid this - always use the unique constraint on your natural key. Now, I understand from your long story that you can't enforce this uniqueness because of your mysql limitations. For long composite keys mysql causes problems. I suggest you move to postgresql.
How badly should I avoid surrogate primary keys in SQL?
Short story I have a technical problem with a third-party library at my hands that I seem to be unable to easily solve in a way other than creating a surrogate key (despite the fact that I'll never need it). I've read a number of articles on the Net discouraging the use of surrogate keys, and I'm a bit at a loss if it is okay to do what I intend to do. Long story I need to specify a primary key, because I use SQLAlchemy ORM (which requires one), and I cannot just set it in __mapper_args__, since the class is being built with classobj, and I have yet to find a way to reference the field of a not-yet-existing class in the appropriate PK definition argument. Another problem is that the natural equivalent of the PK is a composite key that is too long for the version of MySQL I use (and it's generally a bad idea to use such long primary keys anyway).
[ "I always make surrogate keys when using ORMs (or rather, I let the ORMs make them for me). They solve a number of problems, and don't introduce any (major) problems.\nSo, you've done your job by acknowledging that there are \"papers on the net\" with valid reasons to avoid surrogate keys, and that there's probably...
[ 2, 0, 0 ]
[]
[]
[ "primary_key", "python", "sqlalchemy" ]
stackoverflow_0003712949_primary_key_python_sqlalchemy.txt
Q: Algorithm Python uses to decide between >>> and ... prompt in interactive console? I'm implementing a custom (Iron)Python console. I need to display a >>> prompt in general, but when a statement is incomplete, I need to change the prompt to ... and gather more lines before executing them. How do I know if a line entered by a user is complete or if I need to read more lines? A simple way seems to be checking if : is present. But I'm not sure if I'm not missing other cases where : is not present. I looked into the IronPython source code to figure how it does this, but there are many steps involved and my simple reproduction failed to completely work. A: It's impractical to try to guess from just looking at the code string for colons and brackets. You would end up needing to implement half the Python parser to get that right. The standard library code module reproduces the behaviour of the interactive Python interpreter, and I believe it is this module that IronPython uses to implement its console. (The CPython one isn't implemented in Python itself.) The line-continuation logic you're interested in comes from the codeop.compile_command function. It's a bit of a hack. Essentially it tries to compile() the given code using the obscure PyCF_DONT_IMPLY_DEDENT flag, which means it doesn't assume that any open indents are closed automatically at the end of the block. It then tries to compile it again with newlines added (causing explicit DEDENTs). If the second works but the first doesn't, you've got a potential continuation, more can be typed into the block. A: There are a few different ways I can think of to get the ... prompt. Starting (or continuing) a block def foo(): Unclosed parenthesis, brace, square bracket (and watch out for nesting) x = ( x = { x = [ Unclosed triple quoted string x = ''' Backslash at end of line: x = \ A: The repl loop has full knowledge and access to the parser. If the parser state is such that it expects anything other than a statement, then the repl loop produces a .... In the case of unclosed parentheses, a statement would be illegal on the next line, because there's no possible subexpression which can contain a statement. Following a :, the next expected token is always an indent, once again a statement would always be illegal. Thats why it's always necessary to type a blank line at the end of an indented block at the repl loop, because you must provide the closing dedent for a statement to become the next expected production rule. A: Did you use a : or a \ (or an unclosed delimiter, like brackets or parens)? The interactive interpreter shows a .... The actual logic might be a bit more complicated, but that's the basic rule.
Algorithm Python uses to decide between >>> and ... prompt in interactive console?
I'm implementing a custom (Iron)Python console. I need to display a >>> prompt in general, but when a statement is incomplete, I need to change the prompt to ... and gather more lines before executing them. How do I know if a line entered by a user is complete or if I need to read more lines? A simple way seems to be checking if : is present. But I'm not sure if I'm not missing other cases where : is not present. I looked into the IronPython source code to figure how it does this, but there are many steps involved and my simple reproduction failed to completely work.
[ "It's impractical to try to guess from just looking at the code string for colons and brackets. You would end up needing to implement half the Python parser to get that right.\nThe standard library code module reproduces the behaviour of the interactive Python interpreter, and I believe it is this module that IronP...
[ 5, 3, 3, 1 ]
[]
[]
[ "console", "interactive", "ironpython", "python", "read_eval_print_loop" ]
stackoverflow_0004160534_console_interactive_ironpython_python_read_eval_print_loop.txt
Q: Caught TypeError while rendering: 'BoundField' object is not iterable I am trying to display a list of tags as the tag.name (instead of the list). However when I try and run a for-loop over the list, it throws the "Caught TypeError while rendering: 'BoundField' object is not iterable." <dd>{% for tag in form.tags %}{{tag.name}}{% endfor %}</dd> Iterating through .all will load the page, but doesn't show the Tags field. <dd>{% for tag in form.tags.all %}{{tag.name}}{% endfor %}</dd> class Profile(models.Model): user = models.ForeignKey(User) tagging.register(Profile) form = ProfileForm(initial={ "fullname":fullname, "location":request.user.get_profile().location, "website":request.user.get_profile().website, "twitter_account":request.user.get_profile().twitter_account, "email":request.user.email, "bio":request.user.get_profile().bio, "tags":request.user.get_profile().tags }) class ProfileForm(forms.Form): fullname = forms.CharField( label=_("Full Name"), widget=forms.TextInput(), required=False) location = forms.CharField( label=_("Location"), widget=forms.TextInput(), required=False) website = forms.CharField( label=_("Website"), widget=forms.TextInput(), required=False) twitter_account = forms.CharField( label=_("Twitter"), widget=forms.TextInput(), required=False) bio = forms.CharField( label=_("Bio"), widget=forms.Textarea(), required=False) tags = forms.CharField( label=_("Keywords"), widget=forms.Textarea(), required=False) Many thanks in advance! A: Code from a Howto Post Template: {% for tag in blogpost.get_tags %} <a href="/blog/tag/{{tag}}" alt="{{tag}}" title="{{tag}}">{{tag}}</a> {%endfor%} Model: from django.db import models from tagging.fields import TagField from tagging.models import Tag class BlogPost(models.Model): title = models.CharField(max_length=30) body = models.TextField() date_posted = models.DateField(auto_now_add=True) tags = TagField() def set_tags(self, tags): Tag.objects.update_tags(self, tags) def get_tags(self, tags): return Tag.objects.get_for_object(self) A: {% for tag in form.tags.choices %}{{tag.1}}{% endfor %} A: form.tags is defined in your form as a CharField with a TextArea widget. So when you access form.tags you are accessing that field, not the underlying tags model attribute (which I assume is some sort of m2m). Without seeing your models it's impossible to tell you exactly how to achieve what you're trying to do, but the general idea is that you need to iterate over the tag objects, not the form field.
Caught TypeError while rendering: 'BoundField' object is not iterable
I am trying to display a list of tags as the tag.name (instead of the list). However when I try and run a for-loop over the list, it throws the "Caught TypeError while rendering: 'BoundField' object is not iterable." <dd>{% for tag in form.tags %}{{tag.name}}{% endfor %}</dd> Iterating through .all will load the page, but doesn't show the Tags field. <dd>{% for tag in form.tags.all %}{{tag.name}}{% endfor %}</dd> class Profile(models.Model): user = models.ForeignKey(User) tagging.register(Profile) form = ProfileForm(initial={ "fullname":fullname, "location":request.user.get_profile().location, "website":request.user.get_profile().website, "twitter_account":request.user.get_profile().twitter_account, "email":request.user.email, "bio":request.user.get_profile().bio, "tags":request.user.get_profile().tags }) class ProfileForm(forms.Form): fullname = forms.CharField( label=_("Full Name"), widget=forms.TextInput(), required=False) location = forms.CharField( label=_("Location"), widget=forms.TextInput(), required=False) website = forms.CharField( label=_("Website"), widget=forms.TextInput(), required=False) twitter_account = forms.CharField( label=_("Twitter"), widget=forms.TextInput(), required=False) bio = forms.CharField( label=_("Bio"), widget=forms.Textarea(), required=False) tags = forms.CharField( label=_("Keywords"), widget=forms.Textarea(), required=False) Many thanks in advance!
[ "Code from a Howto Post\n\nTemplate:\n{% for tag in blogpost.get_tags %}\n <a href=\"/blog/tag/{{tag}}\" alt=\"{{tag}}\" title=\"{{tag}}\">{{tag}}</a>\n{%endfor%}\n\n\n\nModel:\nfrom django.db import models\nfrom tagging.fields import TagField\nfrom tagging.models import Tag\n\nclass BlogPost(models.Model):\n\n ...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_forms", "django_views", "python" ]
stackoverflow_0004159400_django_django_forms_django_views_python.txt
Q: Unable to close a stream opened with pycurl I am working on a client for a web service using pycurl. The client opens a connection to a stream service and spawns it into a separate thread. Here's a stripped down version of how the connection is set up: def _setup_connection(self): self.conn = pycurl.Curl() self.conn.setopt(pycurl.URL, FILTER_URL) self.conn.setopt(pycurl.POST, 1) . . . self.conn.setopt(pycurl.HTTPHEADER, headers_list) self.conn.setopt(pycurl.WRITEFUNCTION, self.local_callback) def up(self): if self.conn is None: self._setup_connection() self.perform() Now, when i want to shut the connection down, if I call self.conn.close() I get the following exception: error: cannot invoke close() - perform() is currently running Which, in some way makes sense, the connection is constantly open. I've been hunting around and cant seem to find any way to circumvent this problem and close the connection cleanly. A: It sounds like you are invoking close() in one thread while another thread is executing perform(). Luckily, the library warns you rather than descending into unknown behavior-ville. You should only use the curl session from one thread - or have the perform() thread somehow communicate when the call to perform() is complete. A: You obviously showed some methods from a curl wrapper class, what you need to do is to let the object handles itself. def __del__(self): self.conn.close() and don't call the closing explicitly. When the object finishes its job and all the references to it are removed, the curl connection will be closed.
Unable to close a stream opened with pycurl
I am working on a client for a web service using pycurl. The client opens a connection to a stream service and spawns it into a separate thread. Here's a stripped down version of how the connection is set up: def _setup_connection(self): self.conn = pycurl.Curl() self.conn.setopt(pycurl.URL, FILTER_URL) self.conn.setopt(pycurl.POST, 1) . . . self.conn.setopt(pycurl.HTTPHEADER, headers_list) self.conn.setopt(pycurl.WRITEFUNCTION, self.local_callback) def up(self): if self.conn is None: self._setup_connection() self.perform() Now, when i want to shut the connection down, if I call self.conn.close() I get the following exception: error: cannot invoke close() - perform() is currently running Which, in some way makes sense, the connection is constantly open. I've been hunting around and cant seem to find any way to circumvent this problem and close the connection cleanly.
[ "It sounds like you are invoking close() in one thread while another thread is executing perform(). Luckily, the library warns you rather than descending into unknown behavior-ville.\nYou should only use the curl session from one thread - or have the perform() thread somehow communicate when the call to perform() ...
[ 1, 0 ]
[]
[]
[ "multithreading", "pycurl", "python" ]
stackoverflow_0003788463_multithreading_pycurl_python.txt
Q: How to override the `is` operator Possible Duplicate: python: class override “is” behavior I am trying to override the is operator, so that I could do something like if tom is writer: print 'tom is writing' elif tom is programmer: print 'tom is programming' Is this possible in python? A: As far as I know, you can't override 'is' because it tests whether two objects are the same object by comparing their memory addresses (i.e. pointer comparison). You probably want to override '==' by implementing tom's __eq__ method. A: The Python way to test for the type of an object is to use isinstance, as in isinstance(tom,Writer). But whenever you start to write code that reads like your example, think about using polymorphism instead. Here is a simple class hierarchy that does what you want, without a single call to isinstance: class Worker(object): def __init__(self, name): self.name = name def is_doing(self): return "working" class Writer(Worker): def is_doing(self): return "writing" class Programmer(Worker): def is_doing(self): return "programming" workers = [ Writer("Tom"), Programmer("Dick"), ] for w in workers: print "%s is %s" % (w.name, w.is_doing()) Prints: Tom is writing Dick is programming Now you can just add new subclasses to Worker and implement is_doing, and you don't have to maintain some table of type-to-activity values. This pattern of polymorphism is traditional O-O, but in Python, you aren't even restricted to subclasses of Worker - any object that implements is_doing and has a name attribute will work: class Fish(object): def __init__(self, n): self.name = n def is_doing(self): return "swimming" workers.append(Fish("Wanda")) for w in workers: print "%s is %s" % (w.name, w.is_doing()) will print: Tom is writing Dick is programming Wanda is swimming
How to override the `is` operator
Possible Duplicate: python: class override “is” behavior I am trying to override the is operator, so that I could do something like if tom is writer: print 'tom is writing' elif tom is programmer: print 'tom is programming' Is this possible in python?
[ "As far as I know, you can't override 'is' because it tests whether two objects are the same object by comparing their memory addresses (i.e. pointer comparison). You probably want to override '==' by implementing tom's __eq__ method.\n", "The Python way to test for the type of an object is to use isinstance, as ...
[ 5, 3 ]
[]
[]
[ "operators", "python" ]
stackoverflow_0004160876_operators_python.txt
Q: problem with email parsing with python and multiple Received records I am trying to parse emails with python email.parser. When my email contains multiple Received records, email.parser seems like ignoring those records. Fore example, for input : ... Received: from localhost (jalapeno [127.0.0.1]) by jmason.org (Postfix) with ESMTP id 5C4E816F6D for <jm@localhost>; Sun, 6 Oct 2002 22:54:39 +0100 (IST) Received: from jalapeno [127.0.0.1] by localhost with IMAP (fetchmail-5.9.0) for jm@localhost (single-drop); Sun, 06 Oct 2002 22:54:39 +0100 (IST) ... the output is : ... Received ::: from localhost (jalapeno [127.0.0.1]) by jmason.org (Postfix) with ESMTP id 5C4E816F6D for <jm@localhost>; Sun, 6 Oct 2002 22:54:39 +0100 (IST) Received ::: from localhost (jalapeno [127.0.0.1]) by jmason.org (Postfix) with ESMTP id 5C4E816F6D for <jm@localhost>; Sun, 6 Oct 2002 22:54:39 +0100 (IST) ... I am using the following python code import email f = open('email.txt', 'r') data = f.read() e = email.message_from_string(data) for i in e.keys(): print i, ':::', e[i] Is this a bug of email.parser? Do you suggest any other email parsing python library? A: The python doc for email.__getitem__() says: Note that if the named field appears more than once in the message’s headers, exactly which of those field values will be returned is undefined. Use the get_all() method to get the values of all the extant named headers. so, use e.get_all(i) instead of e[i] to get all values of the Received: header.
problem with email parsing with python and multiple Received records
I am trying to parse emails with python email.parser. When my email contains multiple Received records, email.parser seems like ignoring those records. Fore example, for input : ... Received: from localhost (jalapeno [127.0.0.1]) by jmason.org (Postfix) with ESMTP id 5C4E816F6D for <jm@localhost>; Sun, 6 Oct 2002 22:54:39 +0100 (IST) Received: from jalapeno [127.0.0.1] by localhost with IMAP (fetchmail-5.9.0) for jm@localhost (single-drop); Sun, 06 Oct 2002 22:54:39 +0100 (IST) ... the output is : ... Received ::: from localhost (jalapeno [127.0.0.1]) by jmason.org (Postfix) with ESMTP id 5C4E816F6D for <jm@localhost>; Sun, 6 Oct 2002 22:54:39 +0100 (IST) Received ::: from localhost (jalapeno [127.0.0.1]) by jmason.org (Postfix) with ESMTP id 5C4E816F6D for <jm@localhost>; Sun, 6 Oct 2002 22:54:39 +0100 (IST) ... I am using the following python code import email f = open('email.txt', 'r') data = f.read() e = email.message_from_string(data) for i in e.keys(): print i, ':::', e[i] Is this a bug of email.parser? Do you suggest any other email parsing python library?
[ "The python doc for email.__getitem__() says:\n\nNote that if the named field appears\n more than once in the message’s\n headers, exactly which of those field\n values will be returned is undefined.\n Use the get_all() method to get the\n values of all the extant named\n headers.\n\nso, use e.get_all(i) inst...
[ 2 ]
[]
[]
[ "email", "parsing", "python" ]
stackoverflow_0004161122_email_parsing_python.txt
Q: Python "Value Error: cannot delete array elements" -- Why am I getting this? I haven't been able to find anything about this value error online and I am at a complete loss as to why my code is eliciting this response. I have a large dictionary of around 50 keys. The value associated with each key is a 2D array of many elements of the form [datetime object, some other info]. A sample would look like this: {'some_random_key': array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 14.1], [datetime(2010, 10, 26, 11, 5, 38, 613066), 17.2]], dtype=object), 'some_other_key': array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 'true'], [datetime(2010, 10, 26, 11, 5, 38, 613066), 'false']], dtype=object)} What I want my code to do is to allow a user to select a start and stop date and remove all of the array elements (for all of the keys) that are not within that range. Placing print statements throughout the code I was able to deduce that it can find the dates that are out of range, but for some reason, the error occurs when it attempts to remove the element from the array. Here is my code: def selectDateRange(dictionary, start, stop): #Make a clone dictionary to delete values from theClone = dict(dictionary) starting = datetime.strptime(start, '%d-%m-%Y') #put in datetime format ending = datetime.strptime(stop+' '+ '23:59', '%d-%m-%Y %H:%M') #put in datetime format #Get a list of all the keys in the dictionary listOfKeys = theClone.keys() #Go through each key in the list for key in listOfKeys: print key #The value associate with each key is an array innerAry = theClone[key] #Loop through the array and . . . for j, value in enumerate(reversed(innerAry)): if (value[0] <= starting) or (value[0] >= ending): #. . . delete anything that is not in the specified dateRange del innerAry[j] return theClone This is the error message that I get: ValueError: cannot delete array elements and it occurs at the line: del innerAry[j] Please help - perhaps you have the eye to see the problem where I cannot. Thanks! A: If you use numpy arrays, then use them as arrays and not as lists numpy does comparison elementwise for the entire array, which can then be used to select the relevant subarray. This also removes the need for the inner loop. >>> a = np.array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 14.1], [datetime(2010, 10, 26, 11, 5, 30, 613066), 17.2], [datetime(2010, 10, 26, 11, 5, 31, 613066), 17.2], [datetime(2010, 10, 26, 11, 5, 32, 613066), 17.2], [datetime(2010, 10, 26, 11, 5, 33, 613066), 17.2], [datetime(2010, 10, 26, 11, 5, 38, 613066), 17.2]], dtype=object) >>> start = datetime(2010, 10, 26, 11, 5, 28, 157405) >>> end = datetime(2010, 10, 26, 11, 5, 33, 613066) >>> (a[:,0] > start)&(a[:,0] < end) array([False, True, True, True, False, False], dtype=bool) >>> a[(a[:,0] > start)&(a[:,0] < end)] array([[2010-10-26 11:05:30.613066, 17.2], [2010-10-26 11:05:31.613066, 17.2], [2010-10-26 11:05:32.613066, 17.2]], dtype=object) just to make sure we still have datetimes in there: >>> b = a[(a[:,0] > start)&(a[:,0] < end)] >>> b[0,0] datetime.datetime(2010, 10, 26, 11, 5, 30, 613066) A: NumPy arrays are fixed in size. Use lists instead.
Python "Value Error: cannot delete array elements" -- Why am I getting this?
I haven't been able to find anything about this value error online and I am at a complete loss as to why my code is eliciting this response. I have a large dictionary of around 50 keys. The value associated with each key is a 2D array of many elements of the form [datetime object, some other info]. A sample would look like this: {'some_random_key': array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 14.1], [datetime(2010, 10, 26, 11, 5, 38, 613066), 17.2]], dtype=object), 'some_other_key': array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 'true'], [datetime(2010, 10, 26, 11, 5, 38, 613066), 'false']], dtype=object)} What I want my code to do is to allow a user to select a start and stop date and remove all of the array elements (for all of the keys) that are not within that range. Placing print statements throughout the code I was able to deduce that it can find the dates that are out of range, but for some reason, the error occurs when it attempts to remove the element from the array. Here is my code: def selectDateRange(dictionary, start, stop): #Make a clone dictionary to delete values from theClone = dict(dictionary) starting = datetime.strptime(start, '%d-%m-%Y') #put in datetime format ending = datetime.strptime(stop+' '+ '23:59', '%d-%m-%Y %H:%M') #put in datetime format #Get a list of all the keys in the dictionary listOfKeys = theClone.keys() #Go through each key in the list for key in listOfKeys: print key #The value associate with each key is an array innerAry = theClone[key] #Loop through the array and . . . for j, value in enumerate(reversed(innerAry)): if (value[0] <= starting) or (value[0] >= ending): #. . . delete anything that is not in the specified dateRange del innerAry[j] return theClone This is the error message that I get: ValueError: cannot delete array elements and it occurs at the line: del innerAry[j] Please help - perhaps you have the eye to see the problem where I cannot. Thanks!
[ "If you use numpy arrays, then use them as arrays and not as lists\nnumpy does comparison elementwise for the entire array, which can then be used to select the relevant subarray. This also removes the need for the inner loop.\n>>> a = np.array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 14.1],\n ...
[ 6, 3 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0004048011_arrays_numpy_python.txt
Q: regular expression to filter out part of key value in a json string I have the following JSON string as part of a log line. cells : {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"} I want to filter out to the following format: {"Lac":"7824","Cid":"11983"}. How can do this using regular expression ? in Javascript or Python ? the keys are constant strings(Lac, CntryISO, ...), but the value strings are varying. A: Why don't you just delete them in JavaScript? var myJson = {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"}; delete myJson.Lac; delete myJson.cId; A: To expand and explain @alex answer: JSON is a nested multi dimensional structure. Simply filtering the "string-ifiyed form of a Javascript object" (aka JSON) will work in very simple cases, but will rapidly fail when the structure is no longer flat or it starts to get complex with escaped fields, etc. At that point you will need proper parsing logic. This is nicely supplied by Javascript itself, to quote @alexes code: var myJson = {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"}; delete myJson.Lac; delete myJson.cId; Or, if you want to use python, the json module will work just fine: http://docs.python.org/library/json.html Good luck! :) A: Why would you want to use regex for this when you can just use a JSON parser/serializer? Try cjson in Python if you are concerned about speed, it is faster than 'json' module in the Python standard library.
regular expression to filter out part of key value in a json string
I have the following JSON string as part of a log line. cells : {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"} I want to filter out to the following format: {"Lac":"7824","Cid":"11983"}. How can do this using regular expression ? in Javascript or Python ? the keys are constant strings(Lac, CntryISO, ...), but the value strings are varying.
[ "Why don't you just delete them in JavaScript?\nvar myJson = {\"Lac\":\"7824\",\"CntryISO\":\"us\",\"NetTyp\":\"GSM\",\"NetOp\":\"310260\",\"Cid\":\"11983\"};\n\ndelete myJson.Lac;\ndelete myJson.cId;\n\n", "To expand and explain @alex answer:\nJSON is a nested multi dimensional structure. Simply filtering the \...
[ 5, 1, 0 ]
[]
[]
[ "javascript", "python", "regex" ]
stackoverflow_0004160997_javascript_python_regex.txt
Q: Union of two iterators Consider the iterators count(3,3) and count(5,5). How can I create a iterator that outputs only the numbers that occur in either count(3,3) and count(5,5)? A: For the sake of having an answer to this question, OP accepted (x for x in count(3) if not x%3 or not x%5) as a solution in the comments. What follows below should work for the general case so long as duplicates are acceptable. If duplicates aren't acceptable, it could be wrapped in a function that stored its output in a set for further reference but now we're making assumptions on the total size that it will end up being. one way would just be to interleave the two. This assumes that they both have the same cardnality. This will also create duplicates as pointed out in the comments. import itertools def union(it1, it2): return (item for pair in itertools.izip(it1, it2) for item in pair) If they have different cardnalities, then you'll end up truncating one of the two. Here's a more general solution import itertools def union(it1, it2): it1, it2 = iter(it1), iter(it2) for item in (item for pair in itertools.izip(it1, it2) for item in pair): yield item for it in (it1, it2): for item in it: yield item
Union of two iterators
Consider the iterators count(3,3) and count(5,5). How can I create a iterator that outputs only the numbers that occur in either count(3,3) and count(5,5)?
[ "For the sake of having an answer to this question, OP accepted (x for x in count(3) if not x%3 or not x%5) as a solution in the comments. What follows below should work for the general case so long as duplicates are acceptable. If duplicates aren't acceptable, it could be wrapped in a function that stored its outp...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004161318_python.txt
Q: Pass in variable to Mako template In Perl, by using Template Toolkit, here is what I do Perl my $vars = { name => 'Count Edward van Halen', }; $tt->process('letters/overdrawn', $vars) || die $tt->error(), "\n"; HTML Dear [% name %], In Mako template, how can I do so? Check through their render function, doesn't get much hint. A: Use named arguments mytemplate.render(myvar1="var1", mydict=dict()) In the mako side you'd do ${myvar1} % for val in mydict: ${val} % endfor
Pass in variable to Mako template
In Perl, by using Template Toolkit, here is what I do Perl my $vars = { name => 'Count Edward van Halen', }; $tt->process('letters/overdrawn', $vars) || die $tt->error(), "\n"; HTML Dear [% name %], In Mako template, how can I do so? Check through their render function, doesn't get much hint.
[ "Use named arguments\nmytemplate.render(myvar1=\"var1\", mydict=dict())\n\nIn the mako side you'd do\n${myvar1}\n% for val in mydict:\n ${val}\n% endfor\n\n" ]
[ 7 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0004161464_mako_python.txt
Q: Pattern for a background Twisted server that fills an incoming message queue and empties an outgoing message queue? I'd like to do something like this: twistedServer.start() # This would be a nonblocking call while True: while twistedServer.haveMessage(): message = twistedServer.getMessage() response = handleMessage(message) twistedServer.sendResponse(response) doSomeOtherLogic() The key thing I want to do is run the server in a background thread. I'm hoping to do this with a thread instead of through multiprocessing/queue because I already have one layer of messaging for my app and I'd like to avoid two. I'm bringing this up because I can already see how to do this in a separate process, but what I'd like to know is how to do it in a thread, or if I can. Or if perhaps there is some other pattern I can use that accomplishes this same thing, like perhaps writing my own reactor.run method. Thanks for any help. :) A: The key thing I want to do is run the server in a background thread. You don't explain why this is key, though. Generally, things like "use threads" are implementation details. Perhaps threads are appropriate, perhaps not, but the actual goal is agnostic on the point. What is your goal? To handle multiple clients concurrently? To handle messages of this sort simultaneously with events from another source (for example, a web server)? Without knowing the ultimate goal, there's no way to know if an implementation strategy I suggest will work or not. With that in mind, here are two possibilities. First, you could forget about threads. This would entail defining your event handling logic above as only the event handling parts. The part that tries to get an event would be delegated to another part of the application, probably something ultimately based on one of the reactor APIs (for example, you might set up a TCP server which accepts messages and turns them into the events you're processing, in which case you would start off with a call to reactor.listenTCP of some sort). So your example might turn into something like this (with some added specificity to try to increase the instructive value): from twisted.internet import reactor class MessageReverser(object): """ Accept messages, reverse them, and send them onwards. """ def __init__(self, server): self.server = server def messageReceived(self, message): """ Callback invoked whenever a message is received. This implementation will reverse and re-send the message. """ self.server.sendMessage(message[::-1]) doSomeOtherLogic() def main(): twistedServer = ... twistedServer.start(MessageReverser(twistedServer)) reactor.run() main() Several points to note about this example: I'm not sure how your twistedServer is defined. I'm imagining that it interfaces with the network in some way. Your version of the code would have had it receiving messages and buffering them until they were removed from the buffer by your loop for processing. This version would probably have no buffer, but instead just call the messageReceived method of the object passed to start as soon as a message arrives. You could still add buffering of some sort if you want, by putting it into the messageReceived method. There is now a call to reactor.run which will block. You might instead write this code as a twistd plugin or a .tac file, in which case you wouldn't be directly responsible for starting the reactor. However, someone must start the reactor, or most APIs from Twisted won't do anything. reactor.run blocks, of course, until someone calls reactor.stop. There are no threads used by this approach. Twisted's cooperative multitasking approach to concurrency means you can still do multiple things at once, as long as you're mindful to cooperate (which usually means returning to the reactor once in a while). The exact times the doSomeOtherLogic function is called is changed slightly, because there's no notion of "the buffer is empty for now" separate from "I just handled a message". You could change this so that the function is installed called once a second, or after every N messages, or whatever is appropriate. The second possibility would be to really use threads. This might look very similar to the previous example, but you would call reactor.run in another thread, rather than the main thread. For example, from Queue import Queue from threading import Thread class MessageQueuer(object): def __init__(self, queue): self.queue = queue def messageReceived(self, message): self.queue.put(message) def main(): queue = Queue() twistedServer = ... twistedServer.start(MessageQueuer(queue)) Thread(target=reactor.run, args=(False,)).start() while True: message = queue.get() response = handleMessage(message) reactor.callFromThread(twistedServer.sendResponse, response) main() This version assumes a twistedServer which works similarly, but uses a thread to let you have the while True: loop. Note: You must invoke reactor.run(False) if you use a thread, to prevent Twisted from trying to install any signal handlers, which Python only allows to be installed in the main thread. This means the Ctrl-C handling will be disabled and reactor.spawnProcess won't work reliably. MessageQueuer has the same interface as MessageReverser, only its implementation of messageReceived is different. It uses the threadsafe Queue object to communicate between the reactor thread (in which it will be called) and your main thread where the while True: loop is running. You must use reactor.callFromThread to send the message back to the reactor thread (assuming twistedServer.sendResponse is actually based on Twisted APIs). Twisted APIs are typically not threadsafe and must be called in the reactor thread. This is what reactor.callFromThread does for you. You'll want to implement some way to stop the loop and the reactor, one supposes. The python process won't exit cleanly until after you call reactor.stop. Note that while the threaded version gives you the familiar, desired while True loop, it doesn't actually do anything much better than the non-threaded version. It's just more complicated. So, consider whether you actually need threads, or if they're merely an implementation technique that can be exchanged for something else.
Pattern for a background Twisted server that fills an incoming message queue and empties an outgoing message queue?
I'd like to do something like this: twistedServer.start() # This would be a nonblocking call while True: while twistedServer.haveMessage(): message = twistedServer.getMessage() response = handleMessage(message) twistedServer.sendResponse(response) doSomeOtherLogic() The key thing I want to do is run the server in a background thread. I'm hoping to do this with a thread instead of through multiprocessing/queue because I already have one layer of messaging for my app and I'd like to avoid two. I'm bringing this up because I can already see how to do this in a separate process, but what I'd like to know is how to do it in a thread, or if I can. Or if perhaps there is some other pattern I can use that accomplishes this same thing, like perhaps writing my own reactor.run method. Thanks for any help. :)
[ "\nThe key thing I want to do is run the server in a background thread.\n\nYou don't explain why this is key, though. Generally, things like \"use threads\" are implementation details. Perhaps threads are appropriate, perhaps not, but the actual goal is agnostic on the point. What is your goal? To handle multip...
[ 10 ]
[]
[]
[ "background", "client", "nonblocking", "python", "twisted" ]
stackoverflow_0004161403_background_client_nonblocking_python_twisted.txt
Q: Error installing virtualenv on Mac OS 10.6 When I try to install virtualenv on my local machine running OS 10.6.4, I get the following: Searching for virtualenv Reading http://pypi.python.org/simple/virtualenv/ Reading http://virtualenv.openplans.org Best match: virtualenv 1.5.1 Downloading http://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.5.1.tar.gz#md5=3daa1f449d5d2ee03099484cecb1c2b7 Processing virtualenv-1.5.1.tar.gz Running virtualenv-1.5.1/setup.py -q bdist_egg --dist-dir /var/folders/Ej/EjJBMhPjFSWPq+RuE6ubhE+++TI/-Tmp-/easy_install-lZp_Mm/virtualenv-1.5.1/egg-dist-tmp-vC_6xR warning: no previously-included files matching '*.*' found under directory 'docs/_templates' Adding virtualenv 1.5.1 to easy-install.pth file Installing virtualenv script to /usr/local/bin error: /usr/local/bin: Permission denied Any thoughts on how I can remedy the error at the end? error: /usr/local/bin: Permission denied Looking at my /usr/local directory, there is no /bin subdirectory. Any help would be great appreciated, thanks! A: You need to have root permission to install into /usr/local/bin. If you are using the easy_install command, do: $ sudo easy_install virtualenv
Error installing virtualenv on Mac OS 10.6
When I try to install virtualenv on my local machine running OS 10.6.4, I get the following: Searching for virtualenv Reading http://pypi.python.org/simple/virtualenv/ Reading http://virtualenv.openplans.org Best match: virtualenv 1.5.1 Downloading http://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.5.1.tar.gz#md5=3daa1f449d5d2ee03099484cecb1c2b7 Processing virtualenv-1.5.1.tar.gz Running virtualenv-1.5.1/setup.py -q bdist_egg --dist-dir /var/folders/Ej/EjJBMhPjFSWPq+RuE6ubhE+++TI/-Tmp-/easy_install-lZp_Mm/virtualenv-1.5.1/egg-dist-tmp-vC_6xR warning: no previously-included files matching '*.*' found under directory 'docs/_templates' Adding virtualenv 1.5.1 to easy-install.pth file Installing virtualenv script to /usr/local/bin error: /usr/local/bin: Permission denied Any thoughts on how I can remedy the error at the end? error: /usr/local/bin: Permission denied Looking at my /usr/local directory, there is no /bin subdirectory. Any help would be great appreciated, thanks!
[ "You need to have root permission to install into /usr/local/bin. If you are using the easy_install command, do:\n$ sudo easy_install virtualenv\n\n" ]
[ 5 ]
[]
[]
[ "command_line", "python", "terminal", "virtualenv" ]
stackoverflow_0004162196_command_line_python_terminal_virtualenv.txt
Q: Uploading a video to google app engine blobstore I'm trying to associate a video file to a record with a bunch of properties, but can't seem to allow the user to do everything in one form - name the video, provide description and answer some question, AND upload the file. Here are the steps I'd like to perform: User is served with a page containing a form with the following fields: Name, Description, File selector. The file gets stored as a blob and the id gets recorded together with name and description. Does anyone have any examples of doing this I could learn from or a tutorial you could point me to? The one from google only shows uploading the file and getting redirected to it. Thanks and sorry for a newbish question! A: http://demofileuploadgae.appspot.com/ - My demo uploader to the blobstore. My code for the upload: http://code.google.com/p/gwt-examples/source/browse/trunk/DemoUpload/src/org/gonevertical/upload/#upload/server%3Fstate%3Dclosed A: Here's the code I'm using to upload images and associate them with articles. The toughest bit was getting the article id to get to the upload handler, I solved it by setting the file name as the article id to get around the problem. from lib import urllib2_file from lib.urllib2_file import UploadFile # this view serves a task in a queue def article(request): article = Article.objects.get(id=form.cleaned_data['article']) try: image = StringIO(urllib2.urlopen(image_url).read()) except (urllib2.HTTPError, DownloadError): article.parsed = True article.save() else: image = UploadFile(image, '.'.join([str(article.id), image_url.rsplit('.', 1)[1][:4]])) upload_url = blobstore.create_upload_url(reverse('Articles.views.upload')) try: urllib2.urlopen(upload_url, {'file': image}) except (DownloadError, RequestTooLargeError): pass return HttpResponse(json.dumps({'status': 'OK'})) def upload(request): if request.method == 'POST': blobs = get_uploads(request, field_name='file', populate_post=True) article = Article.objects.get(id=int(blobs[0].filename.split('.')[0])) article.media = blobs[0].filename article.parsed = True article.save() return HttpResponseRedirect(reverse('Articles.views.upload')) else: return HttpResponse('meow') def upload(request): if request.method == 'POST': blobs = get_uploads(request, field_name='file', populate_post=True) article = Article.objects.get(id=int(blobs[0].filename.split('.')[0])) article.media = blobs[0].filename article.parsed = True article.save() return HttpResponseRedirect(reverse('Articles.views.upload')) else: return HttpResponse('meow') # this serves the image def image(request): blob = BlobInfo.gql("WHERE filename='%s' LIMIT 1" % request.form.cleaned_data['id'])[0] return HttpResponse(BlobReader(blob.key()).read(), content_type=blob.content_type) Also you'll need this http://fabien.seisen.org/python/urllib2_file/ A: Here is how I did it. It is more straight forward than you think. Note the following taken from Blobstore overview. "When the Blobstore rewrites the user's request, the MIME parts of the uploaded files have their bodies emptied, and the blob key is added as a MIME part header. All other form fields and parts are preserved and passed to the upload handler." In the upload handler is where you can do whatever it is you want with the other form fields. class Topic(db.Model): title = db.StringProperty(multiline=False) blob = blobstore.BlobReferenceProperty() imageurl = db.LinkProperty() class MainHandler(webapp.RequestHandler): def get(self): upload_url = blobstore.create_upload_url('/upload') self.response.out.write('<html><body>') self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url) self.response.out.write("""Upload File: <input type="file" name="file"><br> <div><label>Title:</label></div> <div><textarea name="title" rows="1" cols="25"></textarea></div><input type="submit" name="submit" value="Submit"> </form>""") self.response.out.write('<br><br><h2>TOPIC LIST</h2><table border="1"><tr><td>') for topic in Topic.all(): self.response.out.write('<div><img src="%s=s48"/>' % topic.imageurl) self.response.out.write('<div><b>Image URL: </b><i>%s</i></div>' % topic.imageurl) self.response.out.write('<div><b>Title: </b><i>%s</i></div>' % topic.title) self.response.out.write('</td></tr></table><br>') self.response.out.write('</body></html>') class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): upload_files = self.get_uploads('file') # 'file' is file upload field in the form blob_info = upload_files[0] topic = Topic() topic.title = self.request.get("title") topic.blob = blob_info.key() topic.imageurl = images.get_serving_url(str(blob_info.key())) topic.put() self.redirect('/') def main(): application = webapp.WSGIApplication( [('/', MainHandler), ('/upload', UploadHandler), ], debug=True) run_wsgi_app(application)
Uploading a video to google app engine blobstore
I'm trying to associate a video file to a record with a bunch of properties, but can't seem to allow the user to do everything in one form - name the video, provide description and answer some question, AND upload the file. Here are the steps I'd like to perform: User is served with a page containing a form with the following fields: Name, Description, File selector. The file gets stored as a blob and the id gets recorded together with name and description. Does anyone have any examples of doing this I could learn from or a tutorial you could point me to? The one from google only shows uploading the file and getting redirected to it. Thanks and sorry for a newbish question!
[ "http://demofileuploadgae.appspot.com/ - My demo uploader to the blobstore.\nMy code for the upload: http://code.google.com/p/gwt-examples/source/browse/trunk/DemoUpload/src/org/gonevertical/upload/#upload/server%3Fstate%3Dclosed\n", "Here's the code I'm using to upload images and associate them with articles. Th...
[ 5, 3, 1 ]
[]
[]
[ "blobstore", "google_app_engine", "python" ]
stackoverflow_0003409375_blobstore_google_app_engine_python.txt
Q: jquery: post with json will actually post array I have a python as CGI and the POST from jquery will transform json object to array, so when I see the POST from jquery, I actually see: login_user[username]=dfdsfdsf&login_user[password]=dsfsdf (the [ and ] already escaped) My question is how I can convert this string back to JSON in python? Or, how can I convert this string to python array/dict structure so that I can process it easier? [edit] My jquery is posting: {'login_user': {'username':username, 'password':password}} A: If what you want to accomplish is to send structured data from the browser and then unpack it in your Python backend and keep the same structure, I suggest the following: Create JavaScript objects in the browser to hold your data: var d = {} d['login_user'] = { 'username': 'foo', 'password': 'bar' } Serialize to JSON, with https://github.com/douglascrockford/JSON-js POST to your backend doing something like this: $.post(url, {'data': encoded_json_data}, ...) In your Python code, parse the JSON, POST in my example is where you get your POST data in your CGI script: data = json.loads(POST['data']) data['login_user'] A: import re thestring = "login_user[username]=dfdsfdsf&login_user[password]=dafef" pattern = re.compile(r'^login_user\[username\]=(.*)&login_user\[password\]=(.*)') match = pattern.search(thestring) print match.groups() Output: >>> ('dfdsfdsf', 'dafef') Thus, lp = match.groups() print "{'login_user': {'username':"+lp[0]+", 'password':"+lp[1]+"}}" shall bear: >>> {'login_user': {'username':dfdsfdsf, 'password':dafef}} A: >>> import json >>> data = {'login_user':{'username':'dfdsfdsf', 'password':'dsfsdf'}} >>> json.dumps(data) '{"login_user": {"username": "dfdsfdsf", "password": "dsfsdf"}}' I suspect that data would already be contained in a GET var if that's coming from the URL...
jquery: post with json will actually post array
I have a python as CGI and the POST from jquery will transform json object to array, so when I see the POST from jquery, I actually see: login_user[username]=dfdsfdsf&login_user[password]=dsfsdf (the [ and ] already escaped) My question is how I can convert this string back to JSON in python? Or, how can I convert this string to python array/dict structure so that I can process it easier? [edit] My jquery is posting: {'login_user': {'username':username, 'password':password}}
[ "If what you want to accomplish is to send structured data from the browser and then unpack it in your Python backend and keep the same structure, I suggest the following:\n\nCreate JavaScript objects in the browser to hold your data:\nvar d = {} \nd['login_user'] = { 'username': 'foo', 'password': 'bar' }\n\nSeria...
[ 5, 1, 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0004162339_json_python.txt
Q: How can you POST JSON? I have a python FastCGI server which accepts POST from client, I want to use JSON as the format to communicate between the client and server, but it really confuse me how it works. The JSON representation in javascript is: {'login_user': {'username':username, 'password':password}} When I post this JSON object, the jquery will re-encode it to dict and convert it to string, encode it and send it out: login_user[username] = "kajjd"&loginuser[password] = "kdjfdj" #it's unescaped query string My python server will receive this string. I also want to use JSON in the server side, what I can do to convert this query string back to JSON in python? Is it any fast way? I don't know my usage of JSON is good way, but I can't see any good side of JSON, why not XML? I am asking myself. A: XML for communication for a web-app? Take a deep breath and think about it. If you have doubts about it, then it means you really have no need for it. You rely on XML for fairly complex data sets with potential heavy modifications to the format of a protocol to be foreseen over time. By nature XML would make this OK: morphing the data, producing different versions, allowing for self-describing formats to be parsed by code who wouldn't need to detect this itself and know what to do about it. Otherwise prefer something more lightweight (and that could still achieve pretty much the same thing). That's why JSON is a good alternative: it's still more compact, and relatively easy to manipulate both by a human and a machine. If you were to need to reduce bandwidth a lot, then look at binary formats. Now moving on to the real question: See this answer for JSON usage in JavaScript and Java. They're all bi-directional libraries supporting decoding and encoding. Now regarding your form: if you want to use JSON, why do you transform the string this dict format? To get data from the server, either do a normal AJAX request and parse or eval your returned value (parsing preferred, if possible with native APIs), or use something like jQuery.getJSON. Or jquery-json. To send the request to the server, lookup jQuery.ajax() or jQuery.post(). You may also want to look at these questions: Formalize Form to JSON with jQuery Serializing to JSON in jQuery
How can you POST JSON?
I have a python FastCGI server which accepts POST from client, I want to use JSON as the format to communicate between the client and server, but it really confuse me how it works. The JSON representation in javascript is: {'login_user': {'username':username, 'password':password}} When I post this JSON object, the jquery will re-encode it to dict and convert it to string, encode it and send it out: login_user[username] = "kajjd"&loginuser[password] = "kdjfdj" #it's unescaped query string My python server will receive this string. I also want to use JSON in the server side, what I can do to convert this query string back to JSON in python? Is it any fast way? I don't know my usage of JSON is good way, but I can't see any good side of JSON, why not XML? I am asking myself.
[ "XML for communication for a web-app? Take a deep breath and think about it. If you have doubts about it, then it means you really have no need for it. You rely on XML for fairly complex data sets with potential heavy modifications to the format of a protocol to be foreseen over time. By nature XML would make this ...
[ 2 ]
[]
[]
[ "jquery", "json", "python" ]
stackoverflow_0004162500_jquery_json_python.txt
Q: How to unescape a query string I have a query string as follows: cmd%5Blogin_user%5D%5Busername%5D=dfdsfdsf&cmd%5Blogin_user%5D%5Bpassword%5D=dsfsdf How do I unescape it in python? A: import urllib print urllib.unquote("cmd%5Blogin_user%5D%5Busername%5D=dfdsfdsf&cmd%5Blogin_user%5D%5Bpassword%5D=dsfsdf") A: Another way is to use the following function: xml.sax.saxutils.unescape()
How to unescape a query string
I have a query string as follows: cmd%5Blogin_user%5D%5Busername%5D=dfdsfdsf&cmd%5Blogin_user%5D%5Bpassword%5D=dsfsdf How do I unescape it in python?
[ "import urllib\n\nprint urllib.unquote(\"cmd%5Blogin_user%5D%5Busername%5D=dfdsfdsf&cmd%5Blogin_user%5D%5Bpassword%5D=dsfsdf\")\n\n", "Another way is to use the following function:\nxml.sax.saxutils.unescape()\n" ]
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004162179_python.txt
Q: Django request get parameters In a Django request I have the following: POST:<QueryDict: {u'section': [u'39'], u'MAINS': [u'137']}> How do I get the values of section and MAINS? if request.method == 'GET': qd = request.GET elif request.method == 'POST': qd = request.POST section_id = qd.__getitem__('section') or getlist.... A: You may also use: request.POST.get('section','') # => [39] request.POST.get('MAINS','') # => [137] request.GET.get('section','') # => [39] request.GET.get('MAINS','') # => [137] Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used). A: You can use [] to extract values from a QueryDict object like you would any ordinary dictionary. # HTTP POST variables request.POST['section'] # => [39] request.POST['MAINS'] # => [137] # HTTP GET variables request.GET['section'] # => [39] request.GET['MAINS'] # => [137] # HTTP POST and HTTP GET variables (Deprecated since Django 1.7) request.REQUEST['section'] # => [39] request.REQUEST['MAINS'] # => [137]
Django request get parameters
In a Django request I have the following: POST:<QueryDict: {u'section': [u'39'], u'MAINS': [u'137']}> How do I get the values of section and MAINS? if request.method == 'GET': qd = request.GET elif request.method == 'POST': qd = request.POST section_id = qd.__getitem__('section') or getlist....
[ "You may also use:\nrequest.POST.get('section','') # => [39]\nrequest.POST.get('MAINS','') # => [137] \nrequest.GET.get('section','') # => [39]\nrequest.GET.get('MAINS','') # => [137]\n\nUsing this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an excep...
[ 223, 108 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0004162625_django_django_models_django_views_python.txt
Q: Stack performance in programming languages Just for fun, I tried to compare the stack performance of a couple of programming languages calculating the Fibonacci series using the naive recursive algorithm. The code is mainly the same in all languages, i'll post a java version: public class Fib { public static int fib(int n) { if (n < 2) return 1; return fib(n-1) + fib(n-2); } public static void main(String[] args) { System.out.println(fib(Integer.valueOf(args[0]))); } } Ok so the point is that using this algorithm with input 40 I got these timings: C: 2.796s Ocaml: 2.372s Python: 106.407s Java: 1.336s C#(mono): 2.956s They are taken in a Ubuntu 10.04 box using the versions of each language available in the official repositories, on a dual core intel machine. I know that functional languages like ocaml have the slowdown that comes from treating functions as first order citizens and have no problem to explain CPython's running time because of the fact that it's the only interpreted language in this test, but I was impressed by the java running time which is half of the c for the same algorithm! Would you attribute this to the JIT compilation? How would you explain these results? EDIT: thank you for the interesting replies! I recognize that this is not a proper benchmark (never said it was :P) and maybe I can make a better one and post it to you next time, in the light of what we've discussed :) EDIT 2: I updated the runtime of the ocaml implementation, using the optimizing compiler ocamlopt. Also I published the testbed at https://github.com/hoheinzollern/fib-test. Feel free to make additions to it if you want :) A: You might want to crank up the optimisation level of your C compiler. With gcc -O3, that makes a big difference, a drop from 2.015 seconds to 0.766 seconds, a reduction of about 62%. Beyond that, you need to ensure you've tested correctly. You should run each program ten times, remove the outliers (fastest and slowest), then average the other eight. In addition, make sure you're measuring CPU time rather than clock time. Anything less than that, I would not consider a decent statistical analysis and it may well be subject to noise, rendering your results useless. For what it's worth, those C timings above were for seven runs with the outliers taken out before averaging. In fact, this question shows how important algorithm selection is when aiming for high performance. Although recursive solutions are usually elegant, this one suffers from the fault that you duplicate a lot of calculations. The iterative version: int fib(unsigned int n) { int t, a, b; if (n < 2) return 1; a = b = 1; while (n-- >= 2) { t = a + b; a = b; b = t; } return b; } further drops the time taken, from 0.766 seconds to 0.078 seconds, a further reduction of 89% and a whopping reduction of 96% from the original code. And, as a final attempt, you should try out the following, which combines a lookup table with calculations beyond a certain point: static int fib(unsigned int n) { static int lookup[] = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141 }; int t, a, b; if (n < sizeof(lookup)/sizeof(*lookup)) return lookup[n]; a = lookup[sizeof(lookup)/sizeof(*lookup)-2]; b = lookup[sizeof(lookup)/sizeof(*lookup)-1]; while (n-- >= sizeof(lookup)/sizeof(*lookup)) { t = a + b; a = b; b = t; } return b; } That reduces the time yet again but I suspect we're hitting the point of diminishing returns here. A: You say very little about your configuration (in benchmarking, details are everything: commandlines, computer used, ...) When I try to reproduce for OCaml I get: let rec f n = if n < 2 then 1 else (f (n-1)) + (f (n-2)) let () = Format.printf "%d@." (f 40) $ ocamlopt fib.ml $ time ./a.out 165580141 real 0m1.643s This is on an Intel Xeon 5150 (Core 2) at 2.66GHz. If I use the bytecode OCaml compiler ocamlc on the other hand, I get a time similar to your result (11s). But of course, for running a speed comparison, there is no reason to use the bytecode compiler, unless you want to benchmark the speed of compilation itself (ocamlc is amazing for speed of compilation). A: One possibility is that the C compiler is optimizing on the guess that the first branch (n < 2) is the one more frequently taken. It has to do that purely at compile time: make a guess and stick with it. Hotspot gets to run the code, see what actually happens more often, and reoptimize based on that data. You may be able to see a difference by inverting the logic of the if: public static int fib(int n) { if (n >= 2) return fib(n-1) + fib(n-2); return 1; } It's worth a try, anyway :) As always, check the optimization settings for all platforms, too. Obviously the compiler settings for C - and on Java, try using the client version of Hotspot vs the server version. (Note that you need to run for longer than a second or so to really get the full benefit of Hotspot... it might be interesting to put the outer call in a loop to get runs of a minute or so.) A: I can explain the Python performance. Python's performance for recursion is abysmal at best, and it should be avoided like the plague when coding in it. Especially since stack overflow occurs by default at a recursion depth of only 1000... As for Java's performance, that's amazing. It's rare that Java beats C (even with very little compiler optimization on the C side)... what the JIT might be doing is memoization or tail recursion... A: Note that if the Java Hotspot VM is smart enough to memoise fib() calls, it can cut down the exponentional cost of the algorithm to something nearer to linear cost. A: With C, you should either declare the fibonacci function "inline", or, using gcc, add the -finline-functions argument to the compile options. That will allow the compiler to do recursive inlining. That's also the reason why with -O3 you get better performance, it activates -finline-functions. Edit You need to at least specify -O/-O1 to have recursive inlining, also if the function is declared inline. Actually, testing myself I found that declaring the function inline and using -O as compilation flag, or just using -O -finline-functions, my recursive fibonacci code was faster than with -O2 or -O2 -finline-functions. A: I wrote a C version of the naive Fibonacci function and compiled it to assembler in gcc (4.3.2 Linux). I then compiled it with gcc -O3. The unoptimised version was 34 lines long and looked like a straight translation of the C code. The optimised version was 190 lines long and (it was difficult to tell but) it appeared to inline at least the calls for values up to about 5. A: One C trick which you can try is to disable the stack checking (i e built-in code which makes sure that the stack is large enough to permit the additional allocation of the current function's local variables). This could be dicey for a recursive function and indeed could be the reason behind the slow C times: the executing program might well have run out of stack space which forces the stack-checking to reallocate the entire stack several times during the actual run. Try to approximate the stack size you need and force the linker to allocate that much stack space. Then disable stack-checking and re-make the program.
Stack performance in programming languages
Just for fun, I tried to compare the stack performance of a couple of programming languages calculating the Fibonacci series using the naive recursive algorithm. The code is mainly the same in all languages, i'll post a java version: public class Fib { public static int fib(int n) { if (n < 2) return 1; return fib(n-1) + fib(n-2); } public static void main(String[] args) { System.out.println(fib(Integer.valueOf(args[0]))); } } Ok so the point is that using this algorithm with input 40 I got these timings: C: 2.796s Ocaml: 2.372s Python: 106.407s Java: 1.336s C#(mono): 2.956s They are taken in a Ubuntu 10.04 box using the versions of each language available in the official repositories, on a dual core intel machine. I know that functional languages like ocaml have the slowdown that comes from treating functions as first order citizens and have no problem to explain CPython's running time because of the fact that it's the only interpreted language in this test, but I was impressed by the java running time which is half of the c for the same algorithm! Would you attribute this to the JIT compilation? How would you explain these results? EDIT: thank you for the interesting replies! I recognize that this is not a proper benchmark (never said it was :P) and maybe I can make a better one and post it to you next time, in the light of what we've discussed :) EDIT 2: I updated the runtime of the ocaml implementation, using the optimizing compiler ocamlopt. Also I published the testbed at https://github.com/hoheinzollern/fib-test. Feel free to make additions to it if you want :)
[ "You might want to crank up the optimisation level of your C compiler. With gcc -O3, that makes a big difference, a drop from 2.015 seconds to 0.766 seconds, a reduction of about 62%.\nBeyond that, you need to ensure you've tested correctly. You should run each program ten times, remove the outliers (fastest and sl...
[ 17, 11, 4, 4, 2, 1, 1, 0 ]
[]
[]
[ "c", "java", "ocaml", "performance", "python" ]
stackoverflow_0004121790_c_java_ocaml_performance_python.txt
Q: Two Zope/Plone machines and SSO I'm installing an environment where I had two Zope/Plone servers: plone1 -> for web content & user authentication plone2 -> for web applications I want to implement SSO around both servers but I don't know how to do it. I try to modify login_next and setAuthCookie(..) to share the __ac cookie in the domain, but didn't work. Anyone know the best way to achieve it! Thanks in advance, Oscar Sánchez. A: I haven't done this yet, but may need to do so. So this is what I've gathered so far. CAS Plone as CAS server and as CAS client. PubCookie See the Pubcookie documentation. Here's a writeup of setting it up with Plone: Single Sign On with Pubcookie More on pubcookie and plone: Setting up Apache, Plone, and Pubcookie -- but there are some crucial gaps. In this case, the authentication provider is something called UWNetID, but they don't talk about configuring that. In your case, that would be a Plone instance. mod_auth_tkt See the mod_auth_tkt documentation. It works with plone.session. A: If both sites are on the same domain (but different subdomain), you can try to set the cookie on ".domain.tld". But I'm not sure if that will work - sending the original credentials as cookies is highly insecure, a session should be used in stead, and you can't share this session between two different instances. Have you considered something like openid, possibly with your own private OpenID provider? That basically implements simple SSO out of the box.
Two Zope/Plone machines and SSO
I'm installing an environment where I had two Zope/Plone servers: plone1 -> for web content & user authentication plone2 -> for web applications I want to implement SSO around both servers but I don't know how to do it. I try to modify login_next and setAuthCookie(..) to share the __ac cookie in the domain, but didn't work. Anyone know the best way to achieve it! Thanks in advance, Oscar Sánchez.
[ "I haven't done this yet, but may need to do so. So this is what I've gathered so far.\nCAS\nPlone as CAS server and as CAS client. \nPubCookie\nSee the Pubcookie documentation.\nHere's a writeup of setting it up with Plone: Single Sign On with Pubcookie\nMore on pubcookie and plone: Setting up Apache, Plone, and P...
[ 1, 0 ]
[]
[]
[ "plone", "python", "single_sign_on", "zope" ]
stackoverflow_0003666676_plone_python_single_sign_on_zope.txt
Q: Create an object using Python's C API Say I have my object layout defined as: typedef struct { PyObject_HEAD // Other stuff... } pyfoo; ...and my type definition: static PyTypeObject pyfoo_T = { PyObject_HEAD_INIT(NULL) // ... pyfoo_new, }; How do I create a new instance of pyfoo somewhere within my C extension? A: Call PyObject_New(), followed by PyObject_Init(). EDIT: The best way is to call the class object, just like in Python itself: /* Pass two arguments, a string and an int. */ PyObject *argList = Py_BuildValue("si", "hello", 42); /* Call the class object. */ PyObject *obj = PyObject_CallObject((PyObject *) &pyfoo_T, argList); /* Release the argument list. */ Py_DECREF(argList);
Create an object using Python's C API
Say I have my object layout defined as: typedef struct { PyObject_HEAD // Other stuff... } pyfoo; ...and my type definition: static PyTypeObject pyfoo_T = { PyObject_HEAD_INIT(NULL) // ... pyfoo_new, }; How do I create a new instance of pyfoo somewhere within my C extension?
[ "Call PyObject_New(), followed by PyObject_Init().\nEDIT: The best way is to call the class object, just like in Python itself:\n/* Pass two arguments, a string and an int. */\nPyObject *argList = Py_BuildValue(\"si\", \"hello\", 42);\n\n/* Call the class object. */\nPyObject *obj = PyObject_CallObject((PyObject *)...
[ 55 ]
[]
[]
[ "c", "python", "python_c_api", "python_embedding", "python_extensions" ]
stackoverflow_0004163018_c_python_python_c_api_python_embedding_python_extensions.txt
Q: Is there a working rc-script for Celery on FreeBSD? I have hacked together an rc script for celeryd on FreeBSD, but I can't help but think that there must be a better way. celeryd does not daemonize itself, and it seems to have a hard time responding to sigterm as well, so it might be complicated to get to work. Is this a problem that someone else has solved before? A: There's an experimental init.d script here: https://github.com/ask/celery/tree/master/contrib/generic-init.d/ I don't know if it has been tested on FreeBSD, but it should definitely be made to work there. What do you mean celeryd isn't responding to TERM? This is the recommended signal to use for a clean shutdown as it will finish any currently running tasks. (there's no time out, so it doesn't help if you have a task in deadlock, for that you may use the --time-limit argument) Here's the /etc/default/celeryd file I use (it's for a Django project, for others just replace manage.py celeryd with celeryd): http://pastie.org/1216111 celerybeat/celeryevcam is using the scripts from contrib/debian/init.d, there are no generic versions of these yet.
Is there a working rc-script for Celery on FreeBSD?
I have hacked together an rc script for celeryd on FreeBSD, but I can't help but think that there must be a better way. celeryd does not daemonize itself, and it seems to have a hard time responding to sigterm as well, so it might be complicated to get to work. Is this a problem that someone else has solved before?
[ "There's an experimental init.d script here:\nhttps://github.com/ask/celery/tree/master/contrib/generic-init.d/\nI don't know if it has been tested on FreeBSD, but it should definitely be made\nto work there.\nWhat do you mean celeryd isn't responding to TERM? This is the recommended signal\nto use for a clean shu...
[ 1 ]
[]
[]
[ "celery", "freebsd", "python", "startup", "startupscript" ]
stackoverflow_0004162303_celery_freebsd_python_startup_startupscript.txt
Q: AJAX and browser GET calls appear to have different cookies I have 2 pages, a static html page and a python script - hosted on [local] google app engine. /html/hello.html define as login: required /broadcast which is a python script when I access hello.html for the first time I am redirected to login page, I sign in, and then redirected back to hello.html. inside hello.html - an AJAX call with jQuery is executed to load data from '/broadcast', this call errors saying 'you're not logged in'! BUT - the same call to '/broadcast' through the browser address field succeeds as if I AM signed in! as if the ajax and the browser callers have different cookies!?? HELP, am I going bananas? A: Stupid me... The ajax call was to localhost/broadcast and the browser address field was 127.0.0.1/broadcast ... the cookies for "different" domains ('127.0.0.1' != 'localhost') are not shared ofcourse... Then I haven't gone mad...
AJAX and browser GET calls appear to have different cookies
I have 2 pages, a static html page and a python script - hosted on [local] google app engine. /html/hello.html define as login: required /broadcast which is a python script when I access hello.html for the first time I am redirected to login page, I sign in, and then redirected back to hello.html. inside hello.html - an AJAX call with jQuery is executed to load data from '/broadcast', this call errors saying 'you're not logged in'! BUT - the same call to '/broadcast' through the browser address field succeeds as if I AM signed in! as if the ajax and the browser callers have different cookies!?? HELP, am I going bananas?
[ "Stupid me... \nThe ajax call was to localhost/broadcast\nand the browser address field was 127.0.0.1/broadcast\n...\nthe cookies for \"different\" domains ('127.0.0.1' != 'localhost') are not shared ofcourse...\nThen I haven't gone mad... \n" ]
[ 2 ]
[]
[]
[ "ajax", "google_app_engine", "javascript", "jquery", "python" ]
stackoverflow_0004163748_ajax_google_app_engine_javascript_jquery_python.txt
Q: Not root user, how to kill subprocess in python 2.4 I want to kill a subprocess if the time of executing is too long. I know I have to use os.kill or os.killpg. However, the problems comes out when if I am not a root user. For example, in my designed GUI, I want to call subprocess, and os.kill or os.killpg to kill the subprocess. But my GUI is owned by apache. So when it comes to the command os.kill, I will get error: [type: exceptions.OSError value: [Errno 1] Operation not permitted And besides, the version of my python is 2.4.3. so terminate()...can't be used. Could anyone give me some ideas? Thanks a lot! P.S. Related part of my code: timeout=4 subp = subprocess.Popen('sudo %s'%commandtosend, shell=True,preexec_fn=os.setsid, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while subp.poll() is None: time.sleep(0.1) now = datetime.datetime.now() if (now - start).seconds > timeout: os.kill(subp.pid, signal.SIGKILL) #os.killpg(subp.pid, signal.SIGKILL) break A: Remove sudo from the subprocess command if it's possible which you should do because you shouldn't run a subprocess in a sudo user from your GUI , it's definitely a security breach: subprocess.Popen(commandtosend, shell=True,preexec_fn=os ^^ Here don't put sudo Like this your subprocess will be launch with the www-data user(Apache user), and you can kill it with os.kill(subp.pid, signal.SIGKILL). If it's not possible to remove the sudo (which is bad) from the subprocess you will have to execute the kill like this : os.system("sudo kill %s" % (subp.pid, )) Hope this can help :) A: Your subprocess is running with superuser privileges (because you're starting it with sudo). To kill it, you need to be superuser. One option would be to not use os.kill but run 'sudo kill 5858' where 5858 would be the PID of the process spawned by subprocess.Popen. It's also worth noting that if your program allows the user to control commandtosend you will give the user superuser rights to the entire machine.
Not root user, how to kill subprocess in python 2.4
I want to kill a subprocess if the time of executing is too long. I know I have to use os.kill or os.killpg. However, the problems comes out when if I am not a root user. For example, in my designed GUI, I want to call subprocess, and os.kill or os.killpg to kill the subprocess. But my GUI is owned by apache. So when it comes to the command os.kill, I will get error: [type: exceptions.OSError value: [Errno 1] Operation not permitted And besides, the version of my python is 2.4.3. so terminate()...can't be used. Could anyone give me some ideas? Thanks a lot! P.S. Related part of my code: timeout=4 subp = subprocess.Popen('sudo %s'%commandtosend, shell=True,preexec_fn=os.setsid, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while subp.poll() is None: time.sleep(0.1) now = datetime.datetime.now() if (now - start).seconds > timeout: os.kill(subp.pid, signal.SIGKILL) #os.killpg(subp.pid, signal.SIGKILL) break
[ "Remove sudo from the subprocess command if it's possible which you should do because you shouldn't run a subprocess in a sudo user from your GUI , it's definitely a security breach:\nsubprocess.Popen(commandtosend, shell=True,preexec_fn=os\n ^^\n Here don't put sudo\n\nLike this you...
[ 5, 3 ]
[]
[]
[ "apache", "python", "subprocess", "user_interface" ]
stackoverflow_0004163200_apache_python_subprocess_user_interface.txt
Q: writing python script on windows I am new to python scripts . I have few repetative testing tasks such logging to various IM's ex (OCS,different public messengers) etc . Is it possible to automate these tasks using python . If so from where do I start with ? Working on windows 2003 server . I know the basics of python. want to enhance the skills . Thanks, Tazim A: Not quite a duplicate question, but the answers to "How can we use ms office communicator client exposed APIs in python, is that possible ?" should prove valuable. If you are new to Python, you'll want to check out the Python Tutorial. You may also wish to consider something a bit more Windows-oriented like VBScript or PowerShell, however. A: OCS For OCS, you should be able to use COM scripting to do most but not all[1] things. The code should look a bit like this: import win32com.client def get_contact(signin_uri, communicator): c = communicator.GetContact(signin_uri, communicator.MyServiceId) return c comm = win32com.client.Dispatch('Communicator.UIAutomation') contact = get_contact("jaya@contoso.com", comm) You should be able to translate the documentation from the API fairly easily, especially if you focus on the JScript examples. MSN/Live, AIM, ICQ, and IRC For MSN/Live Messenger, the excellent twisted library contains an rudimentary implementation of a multiprotocol IM client (and server). To get started, check out some code samples. [1] From the documentation: For reasons of security, not all methods or properties can be called using JavaScript or another scripting language. Such restrictions are documented in Office Communicator Automation API Reference.
writing python script on windows
I am new to python scripts . I have few repetative testing tasks such logging to various IM's ex (OCS,different public messengers) etc . Is it possible to automate these tasks using python . If so from where do I start with ? Working on windows 2003 server . I know the basics of python. want to enhance the skills . Thanks, Tazim
[ "Not quite a duplicate question, but the answers to \"How can we use ms office communicator client exposed APIs in python, is that possible ?\" should prove valuable.\nIf you are new to Python, you'll want to check out the Python Tutorial. \nYou may also wish to consider something a bit more Windows-oriented like V...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004164000_python.txt
Q: Stylesheet parsing error for [dir=rtl] when using cssutils python module I'm parsing a css stylesheet with cssutils python module. The parser emits an error when reaching the "[dir=ltr] div.row div.label" selector. I would like to find a way to modify the CSS to make the parser happy and maintain the same functionality. What would be the standard way for this: div.row div.label { float: left; width: 18%; text-align: right; } div.row div.formw { width: 80%; } [dir=ltr] div.row div.label, [dir=rtl] div.row div.formw { float: left; text-align: right; } [dir=rtl] div.row div.label, [dir=ltr] div.row div.formw { float: right; text-align: left; } Note: "dir" is used to control the direction of the text for languages like hebrew or arabic. http://www.unics.uni-hannover.de/nhtcapri/bidirectional-text.html A: it's a bit slower but *[dir=ltr] div.row div.label, *[dir=rtl] div.row div.formw { float: left; text-align: right; } *[dir=rtl] div.row div.label, *[dir=ltr] div.row div.formw { float: right; text-align: left; } should work. Obviously change * with the element with this attribute if is possible
Stylesheet parsing error for [dir=rtl] when using cssutils python module
I'm parsing a css stylesheet with cssutils python module. The parser emits an error when reaching the "[dir=ltr] div.row div.label" selector. I would like to find a way to modify the CSS to make the parser happy and maintain the same functionality. What would be the standard way for this: div.row div.label { float: left; width: 18%; text-align: right; } div.row div.formw { width: 80%; } [dir=ltr] div.row div.label, [dir=rtl] div.row div.formw { float: left; text-align: right; } [dir=rtl] div.row div.label, [dir=ltr] div.row div.formw { float: right; text-align: left; } Note: "dir" is used to control the direction of the text for languages like hebrew or arabic. http://www.unics.uni-hannover.de/nhtcapri/bidirectional-text.html
[ "it's a bit slower but\n*[dir=ltr] div.row div.label, *[dir=rtl] div.row div.formw {\n float: left;\n text-align: right;\n}\n*[dir=rtl] div.row div.label, *[dir=ltr] div.row div.formw {\n float: right;\n text-align: left;\n}\n\nshould work. Obviously change * with the element with this attribute if is possible\n" ]
[ 3 ]
[]
[]
[ "css", "css_parsing", "css_selectors", "html", "python" ]
stackoverflow_0004164049_css_css_parsing_css_selectors_html_python.txt
Q: How do I add a factory created type as a header in suds? I can't seem to get suds working with my setup. I have to pass a context, with a remote user set before I can use any of the functions in the API. What I tried to do was this: client = Client(url, username=userid, password=password) apiContext = client.factory.create("apiCallContext") # This is listed in the types apiContext.remoteUser = "serviceAccount" # when I print the client client.set_options(soapheaders=apiContext) client.service.getActiveIPs() Throughout the process, everything seems to be getting created correctly (if I print the client, I see all the functions and types, if I print apiContext, I see everything set correctly), but the headers don't actually seem to be getting set: ... DEBUG:suds.client:sending to ($URL) message: <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:ns0=$NS xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <ns1:Body> <ns0:getActiveIPs/> </ns1:Body> </SOAP-ENV:Envelope> DEBUG:suds.client:headers = {'SOAPAction': u'""', 'Content-Type': 'text/xml; charset=utf-8'} DEBUG:suds.transport.http:sending: URL:$URL HEADERS: {'SOAPAction': u'""', 'Content-Type': 'text/xml; charset=utf-8', 'Content-type': 'text/xml; charset=utf-8', 'Soapaction': u'""'} ... I'm not seeing the context anywhere in the headers, and the server is erroring out that there's no remote user set. What am I doing wrong? A: Without knowing the exact spec of the webservice you are working with, I can only hazard a guess at this answer, but the header looks similar to a web service I have used in the past. Have you tried creating the elements directly and passing them into the header thus?: from suds.sax.element import Element ... NS = ('h', SOME_NAMESPACE) apiContext = Element('apiContext') authcred = Element('authenticationCredential', ns=NS) username = Element(userid, ns=NS).setText('USERNAME') passw = Element(password, ns=NS).setText('PASSWORD') authcred.append(username) authcred.append(passw) apiContext.append(authcred) client.set_options(soapheaders=apiContext) i.e. is the authentication part of the context object?
How do I add a factory created type as a header in suds?
I can't seem to get suds working with my setup. I have to pass a context, with a remote user set before I can use any of the functions in the API. What I tried to do was this: client = Client(url, username=userid, password=password) apiContext = client.factory.create("apiCallContext") # This is listed in the types apiContext.remoteUser = "serviceAccount" # when I print the client client.set_options(soapheaders=apiContext) client.service.getActiveIPs() Throughout the process, everything seems to be getting created correctly (if I print the client, I see all the functions and types, if I print apiContext, I see everything set correctly), but the headers don't actually seem to be getting set: ... DEBUG:suds.client:sending to ($URL) message: <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:ns0=$NS xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <ns1:Body> <ns0:getActiveIPs/> </ns1:Body> </SOAP-ENV:Envelope> DEBUG:suds.client:headers = {'SOAPAction': u'""', 'Content-Type': 'text/xml; charset=utf-8'} DEBUG:suds.transport.http:sending: URL:$URL HEADERS: {'SOAPAction': u'""', 'Content-Type': 'text/xml; charset=utf-8', 'Content-type': 'text/xml; charset=utf-8', 'Soapaction': u'""'} ... I'm not seeing the context anywhere in the headers, and the server is erroring out that there's no remote user set. What am I doing wrong?
[ "Without knowing the exact spec of the webservice you are working with, I can only hazard a guess at this answer, but the header looks similar to a web service I have used in the past. Have you tried creating the elements directly and passing them into the header thus?: \nfrom suds.sax.element import Element\n...\...
[ 1 ]
[]
[]
[ "header", "python", "soap", "suds" ]
stackoverflow_0004107978_header_python_soap_suds.txt
Q: Most appropriate data structure (Python) I'm new to Python and have what is probably a very basic question about the 'best' way to store data in my code. Any advice much appreciated! I have a long .csv file in the following format: Scenario,Year,Month,Value 1,1961,1,0.5 1,1961,2,0.7 1,1961,3,0.2 etc. My scenario values run from 1 to 100, year goes from 1961 to 1990 and month goes from 1 to 12. My file therefore has 100*29*12 = 34800 rows, each with an associated value. I'd like to read this file into some kind of Python data structure so that I can access a 'Value' by specifying the 'Scenario', 'Year' and 'Month'. What's the best way to do this please (or what are the various options)? In my head I think of this data as a kind of 'number cuboid' with axes for Scenario, Year and Month, so that each Value is located at co-ordinates (Scenario, Year, Month). For this reason, I'm tempted to try to read these values into a 3D numpy array and use Scenario, Year and Month as indices. Is this a sensible thing to do? I guess I could also make a dictionary where the keys are something like str(Scenario)+str(Year)+str(Month) Would this be better? Are there other options? (By 'better' I suppose I mean 'faster to access', although if one method is much less memory intensive than another it'd be good to know about that too). Thanks very much! A: I'd use a dict of tuples. Simple, fast, and a hash-table look-up to retrieve a single value: import csv reader = csv.reader(open('data.csv', 'rb')) header = reader.next() data = {} for row in reader: key = tuple([int(v) for v in row[:-1]]) val = row[-1] data[key] = float(val) # Retrieve a value print data[1, 1961, 3] A: I would use sqlite3 for storing the data to disk. You'll be able to read in the full data set or subsets through SQL queries. You can then load that data into a numpy array or other Python data structure -- whatever is most convenient for the task. If you do choose to use sqlite, also note that sqlite has a TIMESTAMP data type. It may be a good idea to combine the year and month into one TIMESTAMP. When you read TIMESTAMPs into Python, sqlite3 can be told to automatically convert the TIMESTAMPs into datetime.datetime objects, which would reduce some of the boilerplate code you'd otherwise have to write. It will also make it easier to form SQL queries which ask for all the rows between two dates. A: sqlite is a nice option if you're going to access your values by different parameters each time. If that's not the case, and you'll always access by this triplet (scenario, year, month), you can use a Tuple (immutable list) as your key, and the value as your value. In code it would look like: d = {} d[1, 1961, 12] = 0.5 or in more generic loop code: d[scenario, year, month] = value later on you can just access it with: print d[scenario, year, month] Python will automatically create the Tuple for you. A: Make a dictionary of dictionaries of dictionaries like you described. If you need data as numbers, convert them to numbers once when your read them and stores numbers in the dicts. It will be faster then using strings as keys. Let me know if need a help with the code.
Most appropriate data structure (Python)
I'm new to Python and have what is probably a very basic question about the 'best' way to store data in my code. Any advice much appreciated! I have a long .csv file in the following format: Scenario,Year,Month,Value 1,1961,1,0.5 1,1961,2,0.7 1,1961,3,0.2 etc. My scenario values run from 1 to 100, year goes from 1961 to 1990 and month goes from 1 to 12. My file therefore has 100*29*12 = 34800 rows, each with an associated value. I'd like to read this file into some kind of Python data structure so that I can access a 'Value' by specifying the 'Scenario', 'Year' and 'Month'. What's the best way to do this please (or what are the various options)? In my head I think of this data as a kind of 'number cuboid' with axes for Scenario, Year and Month, so that each Value is located at co-ordinates (Scenario, Year, Month). For this reason, I'm tempted to try to read these values into a 3D numpy array and use Scenario, Year and Month as indices. Is this a sensible thing to do? I guess I could also make a dictionary where the keys are something like str(Scenario)+str(Year)+str(Month) Would this be better? Are there other options? (By 'better' I suppose I mean 'faster to access', although if one method is much less memory intensive than another it'd be good to know about that too). Thanks very much!
[ "I'd use a dict of tuples. Simple, fast, and a hash-table look-up to retrieve a single value:\nimport csv\n\nreader = csv.reader(open('data.csv', 'rb'))\nheader = reader.next()\ndata = {}\n\nfor row in reader:\n key = tuple([int(v) for v in row[:-1]])\n val = row[-1]\n data[key] = float(val)\n\n# Retrieve...
[ 7, 4, 2, 0 ]
[]
[]
[ "arrays", "data_structures", "dictionary", "python" ]
stackoverflow_0004164303_arrays_data_structures_dictionary_python.txt
Q: Python - how to read path file/folder from server Using Python, how might one read a file's path from a remote server? This is a bit more clear to me on my local PC. A: See Reading and Writing Files in the Python Tutorial, which is a great place to start for a newbie. Be sure to escape your backslashes on Windows, viz: f=open('\\\\SERVER\\share\\file.ext', 'r') or use "raw" strings: f=open(r'\\SERVER\share\file.ext', 'r') A: use the os.path module to manipulate path string (you need to import os) the current directory is os.path.abspath(os.curdir) join 2 parts of a path with os.path.join(dirname, filename): this will take care of inserting the right path separator ('\' or '/', depending on the operating system) for building the path
Python - how to read path file/folder from server
Using Python, how might one read a file's path from a remote server? This is a bit more clear to me on my local PC.
[ "See Reading and Writing Files in the Python Tutorial, which is a great place to start for a newbie.\nBe sure to escape your backslashes on Windows, viz:\nf=open('\\\\\\\\SERVER\\\\share\\\\file.ext', 'r')\n\nor use \"raw\" strings: \nf=open(r'\\\\SERVER\\share\\file.ext', 'r')\n\n", "use the os.path module to ma...
[ 8, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004163456_python.txt
Q: youtube data api comment paging I'm struggling a little bit with the syntax for iterating through all comments on a youtube video. I'm using the python and have found little documentation on the GetYouTubeVideoCommentFeed() function. What I'm really trying to do is search all comments of a video for an instance of a word and increase a counter (eventually the comment will be printed out). It functions for the 25 results returned, but I need to access the rest of the comments. import gdata.youtube import gdata.youtube.service video_id = 'hMnk7lh9M3o' yt_service = gdata.youtube.service.YouTubeService() comment_feed = yt_service.GetYouTubeVideoCommentFeed(video_id=video_id) for comment_entry in comment_feed.entry: comment = comment_entry.content.text if comment.find('hi') != -1: counter = counter + 1 print "hi: " print counter I tried to set the start_index of GetYouTubeVideoCommentFeed() in addition to the video_id but it didn't like that. Is there something I'm missing? Thanks! Steve A: Here's the code snippet for the same: # Comment feed URL comment_feed_url = "http://gdata.youtube.com/feeds/api/videos/%s/comments" ''' Get the comment feed of a video given a video_id''' def WriteCommentFeed(video_id, data_file): url = comment_feed_url % video_id comment_feed = yt_service.GetYouTubeVideoCommentFeed(uri=url) try: while comment_feed: for comment_entry in comment_feed.entry: print comment_entry.id.text print comment_entry.author[0].name.text print comment_entry.title.text print comment_entry.published.text print comment_entry.updated.text print comment_entry.content.text comment_feed = yt_service.Query(comment_feed.GetNextLink().href) except: pass A: Found out how to do it. Instead of passing a video_id to the GetYouTubeVideoCommentFeed function, you can pass it a URL. You can iterate through the comments by changing the URL parameters. There must be an API limitation though; I can only access the last 1000 comments on the video.
youtube data api comment paging
I'm struggling a little bit with the syntax for iterating through all comments on a youtube video. I'm using the python and have found little documentation on the GetYouTubeVideoCommentFeed() function. What I'm really trying to do is search all comments of a video for an instance of a word and increase a counter (eventually the comment will be printed out). It functions for the 25 results returned, but I need to access the rest of the comments. import gdata.youtube import gdata.youtube.service video_id = 'hMnk7lh9M3o' yt_service = gdata.youtube.service.YouTubeService() comment_feed = yt_service.GetYouTubeVideoCommentFeed(video_id=video_id) for comment_entry in comment_feed.entry: comment = comment_entry.content.text if comment.find('hi') != -1: counter = counter + 1 print "hi: " print counter I tried to set the start_index of GetYouTubeVideoCommentFeed() in addition to the video_id but it didn't like that. Is there something I'm missing? Thanks! Steve
[ "Here's the code snippet for the same: \n# Comment feed URL\ncomment_feed_url = \"http://gdata.youtube.com/feeds/api/videos/%s/comments\"\n\n''' Get the comment feed of a video given a video_id''' \ndef WriteCommentFeed(video_id, data_file): \n url = comment_feed_url % video_id\n comment_feed = yt_se...
[ 5, 1 ]
[]
[]
[ "python", "youtube", "youtube_api" ]
stackoverflow_0001901487_python_youtube_youtube_api.txt
Q: Datetime to Second Conversion i have two datetime string like this '2010-08-31 04:35:50.176725' and '2010-09-05 04:35:50.176725' . now my question is how calculate seconds between two dates. i used time delta but its return in hour, minute formate. i want compltely in seconds. A: import datetime as dt import time now=dt.datetime.now() The Epoch is defined as 1970-01-01 00:00:00 GMT. You can find the number of seconds between now and the Epoch this way: print(time.mktime(now.timetuple())) # 1289565310.0 Or, if you wish to find the number of seconds between two dt.datetime objects: now2=dt.datetime(2010,11,12,12,0,0) def timestamp(date): return time.mktime(date.timetuple()) print(timestamp(now2)-timestamp(now)) # 15890.0 A: I'm guessing you want to find a difference between two dates in seconds? If it's the case, then first get a timedelta (by simply subracting any two datetime objects with - operator). Then read the seconds field of the resulting object.
Datetime to Second Conversion
i have two datetime string like this '2010-08-31 04:35:50.176725' and '2010-09-05 04:35:50.176725' . now my question is how calculate seconds between two dates. i used time delta but its return in hour, minute formate. i want compltely in seconds.
[ "import datetime as dt\nimport time\n\nnow=dt.datetime.now()\n\nThe Epoch is defined as 1970-01-01 00:00:00 GMT.\nYou can find the number of seconds between now and the Epoch this way:\nprint(time.mktime(now.timetuple()))\n# 1289565310.0\n\nOr, if you wish to find the number of seconds between two dt.datetime objec...
[ 14, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004164518_python.txt
Q: Use ssh key to encrypt and decrypt a password My python-script (Python 2.6, on Debian Linux) asks the user for a password, wich is then saved in the users home directory. Because i don't want to safe the password as plain text, i want to encrypt it somehow. So i thought that maybe i could use the (private) ssh-key of the user to encrypt and decrypt the password thats saved in the file, so that only one with access to the private ssh key can decrypt the saved password. Is it a good idea to use the private ssh key for this? How can i use the key to encrypt a string in python? (btw i don't want to use keyring and stuff like that) EDIT Okay i understand its a bad idea to use the users ssh key for stuff like that. Instead i'm now just using base64 encoding, like described here: How does one encode and decode a string with Python for use in a URL? of course its not save, when someone reads my python script. But its enough for me, not having to save the password as plain text. A: The only thing that's definitely worth doing is storing the file that only the user can read. Your argument for using the ssh key seems to be something like the following: I need to store a password, so I'll encrypt it If I use the user's ssh key to do the encryption this will prevent someone decrypting the password even if they have the source of my script because only the user can read their ssh key. If you store the encrypted password in a file only the user can read you get the same benefit as using the ssh key without having to bother with reading the users ssh keys at all. I agree there's some benefit to not storing the password in plain text to prevent someone logged in as root just doing: cat secret-password to get the password but remember it would be easy to find the line in your Python script which said: password = decrypt-password(data) and add the following line: print "The user's password is",password Something like os.fchown() would do the trick to protect the file, as would just creating the file with the correct permissions in the first place. You could base64 encode the password so it is not plain text, but if we assume an attacker can read and edit your script the only thing which will protect the user is the attacker not being able to read the file containing the encrypted password. If you're really worried about this, just prompt the user for the password each time they run the script. A: Is it a good idea to use the private ssh key for this? No: The private key could be password protected itself. It's poor form to go reading user's secret keys. It can be changed without regard to your script. You also seem to be mixing up your terminology. You've used encoding, decoding and hashing when I'd assume you'd mean encrypting and decrypting. As Dave Webb points out, your premise that the private key file is read-only to the user and not itself encrypted. You'd be going from "protected by filesystem user-read-only" to "protected by a different file that is user-read-only".
Use ssh key to encrypt and decrypt a password
My python-script (Python 2.6, on Debian Linux) asks the user for a password, wich is then saved in the users home directory. Because i don't want to safe the password as plain text, i want to encrypt it somehow. So i thought that maybe i could use the (private) ssh-key of the user to encrypt and decrypt the password thats saved in the file, so that only one with access to the private ssh key can decrypt the saved password. Is it a good idea to use the private ssh key for this? How can i use the key to encrypt a string in python? (btw i don't want to use keyring and stuff like that) EDIT Okay i understand its a bad idea to use the users ssh key for stuff like that. Instead i'm now just using base64 encoding, like described here: How does one encode and decode a string with Python for use in a URL? of course its not save, when someone reads my python script. But its enough for me, not having to save the password as plain text.
[ "The only thing that's definitely worth doing is storing the file that only the user can read.\nYour argument for using the ssh key seems to be something like the following:\n\nI need to store a password, so I'll encrypt it\nIf I use the user's ssh key to do the encryption this will prevent someone decrypting the p...
[ 5, 2 ]
[]
[]
[ "python", "ssh_keys" ]
stackoverflow_0004165042_python_ssh_keys.txt
Q: On-value-change type of event for widgets or use .trace_variable() technique? Is there an on-value-change type of event for data input widgets like Entry, Text, Spinner, Checkbutton, Radiobutton? By on-value-change, I mean the ability to detect when the value of a widget has changed due to keyboard input or cut/delete/paste (and Text edit_undo/edit_redo) activity? I see no such event described in the Tkinter event documentation [1]. Is the proper technique to link Tkinter variables to widget values I want to monitor and use these variables' .trace_variable( 'w', ... ) methods to bind to value changes? This seems like the right approach, but I haven't seen a lot of trace_variable() use in the Tkinter application source code that I've studied ... leading me to be cautious about using this approach. [1] http://infohost.nmt.edu/tcc/help/pubs/tkinter/events.html A: Different widgets call for different solutions. For example, check buttons and radio buttons have a command option, and with an entry widget you can use the built-in validation features. For all the widgets that can be tied to a variable, doing a variable trace is a common solution. The text widget is one exception since you can't associate it with a variable without a lot of effort. In the tcl/tk world I associate all my widgets to a single array (tcl's name for a hash map / dictionary) and then put a single trace on the array. Unfortunately tkinter doesn't directly support tcl arrays. However, support is somewhat easy to hack in. For more information see my response to this question: How to run a code whenever a Tkinter widget value changes?
On-value-change type of event for widgets or use .trace_variable() technique?
Is there an on-value-change type of event for data input widgets like Entry, Text, Spinner, Checkbutton, Radiobutton? By on-value-change, I mean the ability to detect when the value of a widget has changed due to keyboard input or cut/delete/paste (and Text edit_undo/edit_redo) activity? I see no such event described in the Tkinter event documentation [1]. Is the proper technique to link Tkinter variables to widget values I want to monitor and use these variables' .trace_variable( 'w', ... ) methods to bind to value changes? This seems like the right approach, but I haven't seen a lot of trace_variable() use in the Tkinter application source code that I've studied ... leading me to be cautious about using this approach. [1] http://infohost.nmt.edu/tcc/help/pubs/tkinter/events.html
[ "Different widgets call for different solutions. For example, check buttons and radio buttons have a command option, and with an entry widget you can use the built-in validation features. \nFor all the widgets that can be tied to a variable, doing a variable trace is a common solution. The text widget is one except...
[ 1 ]
[]
[]
[ "events", "python", "tkinter", "ttk", "user_interface" ]
stackoverflow_0004165164_events_python_tkinter_ttk_user_interface.txt
Q: Gedit not getting views on window creation (Plugin development) I am developing a plugin for Gedit. import gedit class ReloadOnSave(gedit.Plugin): def __init__(self): gedit.Plugin.__init__(self) def activate(self, window): for view in window.get_views(): self.connect_handlers(view) def connect_handlers(self, view): print 'Reached here' // This doesnt happen on Gedit startup. What happens is, when i open up gedit(with any number of tabs open), i don't see 'Reached here'. But if i go to the plugins menu, and disabled and renable my plugin, i will print 'Reached here' (as many times as however many tabs are open) I also do need get_views(), as i need to use the 'saved' event handler. (ultimately I am trying to do something when a document is saved) So, why isn't window.get_views() returning any views when Gedit is first opened? (and is only doing so if i disable and renable the plugin) Also, if i do 'print window.get_views(), same thing will happen. It will print an empty list, but if it disable/re-enable the plugin, i get a list with all the views. A: That happens because when your plugin is activated, you don't have any tabs yet. Tabs are created after plugin activation. You might want to listen to the "tab-added" and "tab-removed" signals to fix that.
Gedit not getting views on window creation (Plugin development)
I am developing a plugin for Gedit. import gedit class ReloadOnSave(gedit.Plugin): def __init__(self): gedit.Plugin.__init__(self) def activate(self, window): for view in window.get_views(): self.connect_handlers(view) def connect_handlers(self, view): print 'Reached here' // This doesnt happen on Gedit startup. What happens is, when i open up gedit(with any number of tabs open), i don't see 'Reached here'. But if i go to the plugins menu, and disabled and renable my plugin, i will print 'Reached here' (as many times as however many tabs are open) I also do need get_views(), as i need to use the 'saved' event handler. (ultimately I am trying to do something when a document is saved) So, why isn't window.get_views() returning any views when Gedit is first opened? (and is only doing so if i disable and renable the plugin) Also, if i do 'print window.get_views(), same thing will happen. It will print an empty list, but if it disable/re-enable the plugin, i get a list with all the views.
[ "That happens because when your plugin is activated, you don't have any tabs yet. Tabs are created after plugin activation. You might want to listen to the \"tab-added\" and \"tab-removed\" signals to fix that.\n" ]
[ 4 ]
[]
[]
[ "gedit", "plugins", "python" ]
stackoverflow_0004164078_gedit_plugins_python.txt
Q: problem with arrays in python ,help! I am making a program in python and I am having an error that I cannot solve. This is the problem: I have a set to points in 3D space, and I am storing it in a vector(rake). My point is to build a stream surface. So I am appending those points to another list so that I can have all the points from the "line" before. The rake list has this format: [[60, 0, 50], [63, 3, 50], [66, 6, 50], [69, 9, 50], [72, 12, 50], [75, 15, 50], [78, 18, 50], [81, 21, 50], [84, 24, 50], [87, 27, 50], [90, 30, 50], [93, 33, 50], [96, 36, 50], [99, 39, 50], [102, 42, 50]] Then when I append the points to the other list(points_list) is like this: [[[60, 0, 50], [63, 3, 50], [66, 6, 50], [69, 9, 50], [72, 12, 50], [75, 15, 50], [78, 18, 50], [81, 21, 50], [84, 24, 50], [87, 27, 50], [90, 30, 50], [93, 33, 50], [96, 36, 50], [99, 39, 50], [102, 42, 50]]] My point is that with the points_list I can know in witch iteration level I am dealing with, so that I could render the surface in the end. When I try to get, for instance, one element from the points_arrays I have and index error. this is the code: points_arrays.append(rake) for i in range(iterations): for j in range(rlength): print points_arrays[i][j][0],points_arrays[i][j][1],points_arrays[i][j][1] When I run this part of the code I am able to get the points but in the end I get an index error. (IndexError: list index out of range) Can anyone help me to solve this?? A: Your main problem is that you should use extend instead of append: points_list.extend(rake) This is because append adds a single object to the end of the list. In this case it means that the entire second list is appended as a single element. append - append object to end extend - extend list by appending elements from the iterable You should also be aware of the following points that are not directly related to your problem: In Python the object created when you write [1, 2, 3] is called a list, not an array. Your print statement is wrong. The second occurrence of points_arrays[i][j][1] should be points_arrays[i][j][2] A: for rake in points_list: for point in rake: print point[0], point[1], point[2] If you want to use numbers as indexes: for npoint in xrange(len(points_list)) for nrake in xrange(len(points_list[npoint])) print points_list[npoint][nrake][0], points_list[npoint][nrake][1], points_list[npoint][nrake][2]
problem with arrays in python ,help!
I am making a program in python and I am having an error that I cannot solve. This is the problem: I have a set to points in 3D space, and I am storing it in a vector(rake). My point is to build a stream surface. So I am appending those points to another list so that I can have all the points from the "line" before. The rake list has this format: [[60, 0, 50], [63, 3, 50], [66, 6, 50], [69, 9, 50], [72, 12, 50], [75, 15, 50], [78, 18, 50], [81, 21, 50], [84, 24, 50], [87, 27, 50], [90, 30, 50], [93, 33, 50], [96, 36, 50], [99, 39, 50], [102, 42, 50]] Then when I append the points to the other list(points_list) is like this: [[[60, 0, 50], [63, 3, 50], [66, 6, 50], [69, 9, 50], [72, 12, 50], [75, 15, 50], [78, 18, 50], [81, 21, 50], [84, 24, 50], [87, 27, 50], [90, 30, 50], [93, 33, 50], [96, 36, 50], [99, 39, 50], [102, 42, 50]]] My point is that with the points_list I can know in witch iteration level I am dealing with, so that I could render the surface in the end. When I try to get, for instance, one element from the points_arrays I have and index error. this is the code: points_arrays.append(rake) for i in range(iterations): for j in range(rlength): print points_arrays[i][j][0],points_arrays[i][j][1],points_arrays[i][j][1] When I run this part of the code I am able to get the points but in the end I get an index error. (IndexError: list index out of range) Can anyone help me to solve this??
[ "Your main problem is that you should use extend instead of append:\npoints_list.extend(rake)\n\nThis is because append adds a single object to the end of the list. In this case it means that the entire second list is appended as a single element.\n\nappend - append object to end\n extend - extend list by appendin...
[ 3, 1 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0004165626_arrays_python.txt
Q: Building a custom ZIP file in Django I'm working on a webapp that uses SCORM so it can be included in our clients' learning management systems. This works by building a zip file that contains several files. Two of the files depend on the particular resource they want to include and the client themselves. I'd therefore like to generate these zip files automatically, on demand. So imagine I have a "template" version of the ZIP, extracted to a directory: /zipdir/fileA.html /zipdir/fileB.xml /zipdir/static-file.jpg Let's imagine I use Django's template sytax in fileA and fileB. I know how to run a file through the template loader and render it, but how do I add that file to a ZIP file? Could I create a base zip file (that doesn't have fileA and fileB in) and add the two renders to it? Otherwise, how would you go about cloning the zipdir to a temporary location and then rendering those two files to it before zipping it? A: Using zipfile with StringIO will allow you to create a zip file in memory that you can later send to the client.
Building a custom ZIP file in Django
I'm working on a webapp that uses SCORM so it can be included in our clients' learning management systems. This works by building a zip file that contains several files. Two of the files depend on the particular resource they want to include and the client themselves. I'd therefore like to generate these zip files automatically, on demand. So imagine I have a "template" version of the ZIP, extracted to a directory: /zipdir/fileA.html /zipdir/fileB.xml /zipdir/static-file.jpg Let's imagine I use Django's template sytax in fileA and fileB. I know how to run a file through the template loader and render it, but how do I add that file to a ZIP file? Could I create a base zip file (that doesn't have fileA and fileB in) and add the two renders to it? Otherwise, how would you go about cloning the zipdir to a temporary location and then rendering those two files to it before zipping it?
[ "Using zipfile with StringIO will allow you to create a zip file in memory that you can later send to the client.\n" ]
[ 5 ]
[]
[]
[ "django", "python", "zip" ]
stackoverflow_0004165661_django_python_zip.txt
Q: Using PyQt4 - QTableView with SQLAlchemy using QSqlTableModel (or not) i'm starting to learn Qt for python and as i was wondering after reading this post : qt - pyqt QTableView not populating when changing databases. if there was a way to use SQLAlchemy sessions instead of (re-)opening a database connection as a Table Model with Qt's QTableView widget. Something that would work a little bit like that : databasePath = "base.sqlite" # used for production engine = create_engine('sqlite:///' + databasePath, echo=True) # initializing session : Session = sessionmaker(bind=engine) session = Session() # Set up the user interface from Designer. self.setupUi(self) self.model = QSqlTableModel(self) self.model.setTable("records") self.model.setSort(FILEORDER, Qt.AscendingOrder) self.model.setHeaderData(ID, Qt.Horizontal, QVariant("ID")) self.model.setHeaderData(NAME, Qt.Horizontal, QVariant("Name")) self.model.select() self.tableView.setModel(self.model) Any help would be greatly appreciated, as well as new ways to think about this problem. Thank you A: Take a look at Camelot . It does much more:) I happily found it when the frustration and angst, generated by Q*View and Q*Model experience forced me to start implementing my own ones on the basis of SqlAlchemy. And it was half implemented, when I found the instrument, that does much more, than I've even dream of, struggling with QSqlRelationalTableModel.
Using PyQt4 - QTableView with SQLAlchemy using QSqlTableModel (or not)
i'm starting to learn Qt for python and as i was wondering after reading this post : qt - pyqt QTableView not populating when changing databases. if there was a way to use SQLAlchemy sessions instead of (re-)opening a database connection as a Table Model with Qt's QTableView widget. Something that would work a little bit like that : databasePath = "base.sqlite" # used for production engine = create_engine('sqlite:///' + databasePath, echo=True) # initializing session : Session = sessionmaker(bind=engine) session = Session() # Set up the user interface from Designer. self.setupUi(self) self.model = QSqlTableModel(self) self.model.setTable("records") self.model.setSort(FILEORDER, Qt.AscendingOrder) self.model.setHeaderData(ID, Qt.Horizontal, QVariant("ID")) self.model.setHeaderData(NAME, Qt.Horizontal, QVariant("Name")) self.model.select() self.tableView.setModel(self.model) Any help would be greatly appreciated, as well as new ways to think about this problem. Thank you
[ "Take a look at Camelot . It does much more:)\nI happily found it when the frustration and angst, generated by Q*View and Q*Model experience forced me to start implementing my own ones on the basis of SqlAlchemy. And it was half implemented, when I found the instrument, that does much more, than I've even dream of,...
[ 5 ]
[]
[]
[ "pyqt4", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0002397987_pyqt4_python_sqlalchemy_sqlite.txt
Q: how do you radially 'sweep out' a 1D array to plot 3d figure in python? (to represent a wavefunction) effectively I have a large 1D array of heights. As a small example consider: u=array([0,1,2,1,0,2,4,6,4,2,1]) and a 1D array, the same size as u, of radial values which the heights correspond to, e.g.: r=array([0,1,2,3,4,5,6,7,8,9,10]) Obviously plotting these with: pylab.plot(r,u) gives a nice 2D plot. How can one sweep this out around 360 degrees, to give a 3D contour/surface plot? If you can imagine it should look like a series of concentric, circular ridges, like for the wavefunction of an atom. any help would be much appreciated! A: You're better off with something more 3D oriented than matplotlib, in this case... Here's a quick example using mayavi: from enthought.mayavi import mlab import numpy as np # Generate some random data along a straight line in the x-direction num = 100 x = np.arange(num) y, z = np.ones(num), np.ones(num) s = np.cumsum(np.random.random(num) - 0.5) # Plot using mayavi's mlab api fig = mlab.figure() # First we need to make a line source from our data line = mlab.pipeline.line_source(x,y,z,s) # Then we apply the "tube" filter to it, and vary the radius by "s" tube = mlab.pipeline.tube(line, tube_sides=20, tube_radius=1.0) tube.filter.vary_radius = 'vary_radius_by_scalar' # Now we display the tube as a surface mlab.pipeline.surface(tube) # And finally visualize the result mlab.show() A: #!/usr/bin/python from mpl_toolkits.mplot3d import Axes3D import matplotlib import numpy as np from scipy.interpolate import interp1d from matplotlib import cm from matplotlib import pyplot as plt step = 0.04 maxval = 1.0 fig = plt.figure() ax = Axes3D(fig) u=np.array([0,1,2,1,0,2,4,6,4,2,1]) r=np.array([0,1,2,3,4,5,6,7,8,9,10]) f=interp1d(r,u) # walk along the circle p = np.linspace(0,2*np.pi,50) R,P = np.meshgrid(r,p) # transform them to cartesian system X,Y = R*np.cos(P),R*np.sin(P) Z=f(R) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet) ax.set_xticks([]) plt.show()
how do you radially 'sweep out' a 1D array to plot 3d figure in python? (to represent a wavefunction)
effectively I have a large 1D array of heights. As a small example consider: u=array([0,1,2,1,0,2,4,6,4,2,1]) and a 1D array, the same size as u, of radial values which the heights correspond to, e.g.: r=array([0,1,2,3,4,5,6,7,8,9,10]) Obviously plotting these with: pylab.plot(r,u) gives a nice 2D plot. How can one sweep this out around 360 degrees, to give a 3D contour/surface plot? If you can imagine it should look like a series of concentric, circular ridges, like for the wavefunction of an atom. any help would be much appreciated!
[ "You're better off with something more 3D oriented than matplotlib, in this case...\nHere's a quick example using mayavi:\n\nfrom enthought.mayavi import mlab\nimport numpy as np\n\n# Generate some random data along a straight line in the x-direction\nnum = 100\nx = np.arange(num)\ny, z = np.ones(num), np.ones(num)...
[ 2, 2 ]
[]
[]
[ "3d", "matplotlib", "python" ]
stackoverflow_0004159942_3d_matplotlib_python.txt
Q: Blender3d vs 3DS max; which one is better suited for automation in python? I am getting started with the development of 3d environments for using in panda3d. As I am new to this, I need to choose a modelling software to create basic geometries, etc. Therefore, which one is better suited for automation through python? 3DS Max or Blender3D? I would like to automate generating basic geometries, the export process and some basic animations. Blender has the benefit of being free, but my office will provide me the licenses for 3DS if I request, so that is not a problem. A: From a python automation point of view, blender itself is written largely in python, and the source is available which allows a level of automation not possible if you can't change the source. To me, having the source available in that situation is more of a benefit than the price tag. If you do go with blender, definitely grab the 2.5 beta. They made some huge UI and scripting improvements. In my opinion, most of the complaints about it being difficult to learn compared to commercial packages are no longer valid for 2.5, especially if you don't have the mental burden of already having learned another software's interface. A: Actually the poster Karl Bielefldt is wrong. Blender is not written in python is written in C. What is written in python is some script tools, python is used as blender's script engine , but in the end what is triggered are C libraries. That is not big deal though since python itself is written in C. However all this is totally unrelated to your question. Since the engine you are going to use is third party and not the game engine of blender, there is no reason for you to consider Blender as a mandatory choice. Any 3d package can serve you well. This is because as other kind of software, 3d software has several formats that are common ammong 3d apps. Like *.3ds and *.obj . So that means that you can use anything you wish like Maya, XSi, Ciname 4d , anything. As almost 3d software saves to these common file formats. However I would strongly advice to take a look at blender game engine. The blender game engine automates alot of things and has a gui inside blender that minimises coding unlike Panda 3d which requires everything to be coded regarding the engine. You can save loads of time with blender's game engine. There is even a blender game that was developed using solely with the blender game engine , its called project apricot or Yo Fankie. Apricot Project You can download it for free and see the source to help you learn loads of things for Blender Game engine. Good luck.
Blender3d vs 3DS max; which one is better suited for automation in python?
I am getting started with the development of 3d environments for using in panda3d. As I am new to this, I need to choose a modelling software to create basic geometries, etc. Therefore, which one is better suited for automation through python? 3DS Max or Blender3D? I would like to automate generating basic geometries, the export process and some basic animations. Blender has the benefit of being free, but my office will provide me the licenses for 3DS if I request, so that is not a problem.
[ "From a python automation point of view, blender itself is written largely in python, and the source is available which allows a level of automation not possible if you can't change the source. To me, having the source available in that situation is more of a benefit than the price tag.\nIf you do go with blender,...
[ 4, 3 ]
[]
[]
[ "blender", "panda3d", "python" ]
stackoverflow_0003896087_blender_panda3d_python.txt
Q: How to detect if the values in array are in a certain range and return a binary array in Python? So I am trying to detect if the values in an array is in a certain range and then return a binary logical array i.e. one for true and zero for false. I have this but iPython keeps complaining D = ( 1 < X[0,:] + X[1,:]) < 2 ).astype(int) the interesting thing is that just checking one way works totally ok D = ( X[0,:] + X[1,:]) < 2 ).astype(int) which I find a bit perplexing. A: Y=X[0,:]+X[1,:] D = ((1<Y) & (Y<2)).astype(int) A: array = (1, 2, 3, 4, 5) bit_array = map(lambda x: 1 < x < 5 and 1 or 0, array) bit_array is [0, 1, 1, 1, 0] after that. Is that what you wanted? A: unutbu's is shorter, this is more explicit >>> import numpy >>> numpy.logical_and(1 < np.arange(5), np.arange(5)< 4).astype(int) array([0, 0, 1, 1, 0]) A: This? bits = [ bool(low <= value < high) for value in some_list ] A: Try using all (edited to return int): D = numpy.all([1 < x, x < 2], axis=0).astype(int)
How to detect if the values in array are in a certain range and return a binary array in Python?
So I am trying to detect if the values in an array is in a certain range and then return a binary logical array i.e. one for true and zero for false. I have this but iPython keeps complaining D = ( 1 < X[0,:] + X[1,:]) < 2 ).astype(int) the interesting thing is that just checking one way works totally ok D = ( X[0,:] + X[1,:]) < 2 ).astype(int) which I find a bit perplexing.
[ "Y=X[0,:]+X[1,:]\nD = ((1<Y) & (Y<2)).astype(int)\n\n", "array = (1, 2, 3, 4, 5)\nbit_array = map(lambda x: 1 < x < 5 and 1 or 0, array)\n\nbit_array is [0, 1, 1, 1, 0] after that. Is that what you wanted?\n", "unutbu's is shorter, this is more explicit\n>>> import numpy\n>>> numpy.logical_and(1 < np.arange(5),...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "arrays", "ipython", "numpy", "python", "range" ]
stackoverflow_0004164862_arrays_ipython_numpy_python_range.txt
Q: Can Java and Python coexist in the same app? I need to have a Java instance fetching data directly from the Python's instance datastore. I don't know if that's possible at all. Is the datastore transparent/unique, or each instance (if they can indeed coexist) has its separate datastore? Suming it up: how can a Java app fetch data from the datastore of a Python app, and vice-versa? A: Different versions of an app share a datastore, and AFAIK you can still have a Java version of your app, and Python version, at the same time. It used to be a necessary hack to use features that were implemented in Python but not (yet) in Java, and quite possibly still is. Of course only one of those versions can be the default, but other versions are accessible. A: You could use jython. It's a python implementation written in java. You can call java functions/classes from python that way. That would allow you to run python code in the java instance. I don't know of anything to do the opposite (run java inside a python process).
Can Java and Python coexist in the same app?
I need to have a Java instance fetching data directly from the Python's instance datastore. I don't know if that's possible at all. Is the datastore transparent/unique, or each instance (if they can indeed coexist) has its separate datastore? Suming it up: how can a Java app fetch data from the datastore of a Python app, and vice-versa?
[ "Different versions of an app share a datastore, and AFAIK you can still have a Java version of your app, and Python version, at the same time. It used to be a necessary hack to use features that were implemented in Python but not (yet) in Java, and quite possibly still is.\nOf course only one of those versions can...
[ 9, 6 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "integration", "java", "python" ]
stackoverflow_0004165824_google_app_engine_google_cloud_datastore_integration_java_python.txt
Q: Django Evolution: How do I add a new field at a specific position? Is there a way to tell Django Evolution to add a new field to a database table at a specific position, similar to the AFTER statement of (My)SQL? I have a table with some columns and I want to add new_column after column1. Using SQL directly I would do this: ALTER TABLE `db_table` ADD `new_column` DATETIME NULL DEFAULT NULL AFTER `column1` For Django Evolution this translates to: MUTATIONS = [ AddField('DbTable', 'new_column', models.DateTimeField, null=True, ...) ] However, this would add new_column to the end of the table, is there something I can pass in for the dots in the above statement giving more control over the order? A: Django does not depend or care about the column position in the database. My guess is that Django Evolution works the same way. So you shouldn't depend or care too much about database internals either, in the end that is why you are using the ORM, right? If you really have to do it, I suggest subclassing django_evolution.mutations.AddField and overwriting the add_column method to integrate the AFTER statement in the list of SQL statements this method returns. There might be better places, this would be a hack.
Django Evolution: How do I add a new field at a specific position?
Is there a way to tell Django Evolution to add a new field to a database table at a specific position, similar to the AFTER statement of (My)SQL? I have a table with some columns and I want to add new_column after column1. Using SQL directly I would do this: ALTER TABLE `db_table` ADD `new_column` DATETIME NULL DEFAULT NULL AFTER `column1` For Django Evolution this translates to: MUTATIONS = [ AddField('DbTable', 'new_column', models.DateTimeField, null=True, ...) ] However, this would add new_column to the end of the table, is there something I can pass in for the dots in the above statement giving more control over the order?
[ "Django does not depend or care about the column position in the database. My guess is that Django Evolution works the same way.\nSo you shouldn't depend or care too much about database internals either, in the end that is why you are using the ORM, right?\nIf you really have to do it, I suggest subclassing django_...
[ 1 ]
[]
[]
[ "django", "django_evolution", "django_models", "python" ]
stackoverflow_0004166220_django_django_evolution_django_models_python.txt
Q: Why do I have to use .wait() with python's subprocess module? I'm running a Perl script through the subprocess module in Python on Linux. The function that runs the script is called several times with variable input. def script_runner(variable_input): out_file = open('out_' + variable_input, 'wt') error_file = open('error_' + variable_input, 'wt') process = subprocess.Popen(['perl', 'script', 'options'], shell=False, stdout=out_file, stderr=error_file) However, if I run this function, say, twice, the execution of the first process will stop when the second process starts. I can get my desired behavior by adding process.wait() after calling the script, so I'm not really stuck. However, I want find out why I cannot run the script using subprocess as many times as I want, and have the script make these computations in parallel, without having to wait for it to finish between each run. UPDATE The culprit was not so exciting: the perl script used a common file that was rewritten for each execution. However, the lesson I learned from this was that the garbage collector does not delete the process once it starts running, because this had no influence on my script once I got it sorted out. A: If you are using Unix, and wish to run many processes in the background, you could use subprocess.Popen this way: x_fork_many.py: import subprocess import os import sys import time import random import gc # This is just to test the hypothesis that garbage collection of p=Popen() causing the problem. # This spawns many (3) children in quick succession # and then reports as each child finishes. if __name__=='__main__': N=3 if len(sys.argv)>1: x=random.randint(1,10) print('{p} sleeping for {x} sec'.format(p=os.getpid(),x=x)) time.sleep(x) else: for script in xrange(N): args=['test.py','sleep'] p = subprocess.Popen(args) gc.collect() for i in range(N): pid,retval=os.wait() print('{p} finished'.format(p=pid)) The output looks something like this: % x_fork_many.py 15562 sleeping for 10 sec 15563 sleeping for 5 sec 15564 sleeping for 6 sec 15563 finished 15564 finished 15562 finished I'm not sure why you are getting the strange behavior when not calling .wait(). However, the script above suggests (at least on unix) that saving subprocess.Popen(...) processes in a list or set is not necessary. Whatever the problem is, I don't think it has to do with garbage collection. PS. Maybe your perl scripts are conflicting in some way, which causes one to end with an error when another one is running. Have you tried starting multiple calls to the perl script from the command line? A: You have to call wait() in order to ask to "wait" the ending of your popen. As popen execute in background the perl script, if you do not wait(), it will be stopped at the object "process" 's end of life... that is at the end of script_runner. A: As said by ericdupo, the task is killed because you overwrite your process variable with a new Popen object, and since there are no more references to your previous Popen object, it is destroyed by the garbage collector. You can prevent this by keeping a reference to your objects somewhere, like a list: processes = [] def script_runner(variable_input): out_file = open('out_' + variable_input, 'wt') error_file = open('error_' + variable_input, 'wt') process = subprocess.Popen(['perl', 'script', 'options'], shell=False, stdout=out_file, stderr=error_file) processes.append(process) This should be enough to prevent your previous Popen object from being destroyed A: I think you want to do list_process = [] def script_runner(variable_input): out_file = open('out_' + variable_input, 'wt') error_file = open('error_' + variable_input, 'wt') process = subprocess.Popen(['perl', 'script', 'options'], shell=False, stdout=out_file, stderr=error_file) list_process.append(process) #call several times script_runner for process in list_process: process.wait() so your process will be run in parallel
Why do I have to use .wait() with python's subprocess module?
I'm running a Perl script through the subprocess module in Python on Linux. The function that runs the script is called several times with variable input. def script_runner(variable_input): out_file = open('out_' + variable_input, 'wt') error_file = open('error_' + variable_input, 'wt') process = subprocess.Popen(['perl', 'script', 'options'], shell=False, stdout=out_file, stderr=error_file) However, if I run this function, say, twice, the execution of the first process will stop when the second process starts. I can get my desired behavior by adding process.wait() after calling the script, so I'm not really stuck. However, I want find out why I cannot run the script using subprocess as many times as I want, and have the script make these computations in parallel, without having to wait for it to finish between each run. UPDATE The culprit was not so exciting: the perl script used a common file that was rewritten for each execution. However, the lesson I learned from this was that the garbage collector does not delete the process once it starts running, because this had no influence on my script once I got it sorted out.
[ "If you are using Unix, and wish to run many processes in the background, you could use subprocess.Popen this way:\nx_fork_many.py: \nimport subprocess\nimport os\nimport sys\nimport time\nimport random\nimport gc # This is just to test the hypothesis that garbage collection of p=Popen() causing the problem.\n\n# ...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0004165145_python_subprocess.txt
Q: Is this a bug? Variables are identical references to the same string in this example (Python) This is for Python 2.6. I could not figure out why a and b are identical: >>> a = "some_string" >>> b = "some_string" >>> a is b True But if there is a space in the string, they are not: >>> a = "some string" >>> b = "some string" >>> a is b False If this is normal behavior, could someone please explain what is going on. Edit: Disclaimer ! This is not being used to check for equality. I actually wanted to explain to someone else that "is" is only to check identity, not equality. And from the documentation I had understood that references created in this way will be different, that a new string will be created each time. The very first example I gave threw me off when I couldn't prove my own point! Edit: I understand that this is not a bug, and interning was a new concept for me. This seems to be a good explanation. A: Python may or may not automatically intern strings, which determines whether future instances of the string will share a reference. If it decides to intern a string, then both will refer to the same string instance. If it doesn't, it'll create two separate strings that happen to have the same contents. In general, you don't need to worry about whether this is happening or not; you usually want to check equality, a == b, not whether they're the same object, a is b. A: TIM PETERS SAID: Sorry, the only bug I see here is in the code you posted using "is" to try to determine whether two strings are equal. "is" tests for object identity, not for equality, and whether two immutable objects are really the same object isn't in general defined by Python. You should use "==" to check two strings for equality. The only time it's reliable to use "is" for that purpose is when you've explicitly interned all strings being compared (via using the intern() builtin function). from here: http://mail.python.org/pipermail/python-bugs-list/2004-December/026772.html A: This should actually be more of a comment to Gleen's answer but I can not do comments yet. I've run some tests directly on the Python interpreter and I saw some interesting behavior. According to Glenn, the interpreter treats entries as separate "files" and they don't share a string table when stored for future reference. Here is what I run: >>> a="some_string" >>> b="some_string" >>> id(a) 2146597048 >>> id(b) 2146597048 >>> a="some string" >>> b="some string" >>> id(a) 2146597128 >>> id(b) 2146597088 >>> c="some string" <-----(1) >>> d="some string" >>> id(c) 2146597208 <-----(1) >>> a="some_string" >>> b="some_string" >>> id(a) 2146597248 <---- waited a few minutes >>> c="some_string" >>> d="some_string" >>> id(d) 2146597248 <---- still same id after a few min >>> b="some string" >>> id(b) 2146597288 >>> b="some_string" <---(2) >>> id(b) 2146597248 <---(2) >>> a="some" >>> b="some" >>> c="some" >>> d="some" <---(2) lost all references >>> id(a) 2146601728 >>> a="some_string" <---(2) >>> id(a) 2146597248 <---(2) returns same old one after mere seconds >>> a="some" >>> id(a) 2146601728 <---(2) Waited a few minutes >>> a="some_string" <---- (1) >>> id(a) 2146597208 <---- (1) Reused a "different" id after a few minutes It seems that some of the id references might be reused after the initial references are lost and no longer "in use" (1), but it might also be related to the time those id references are not being used, as you can see in what i have marked as number (2), giving different id references depending on how long that id has not been used. I just find it curious and thought of posting it.
Is this a bug? Variables are identical references to the same string in this example (Python)
This is for Python 2.6. I could not figure out why a and b are identical: >>> a = "some_string" >>> b = "some_string" >>> a is b True But if there is a space in the string, they are not: >>> a = "some string" >>> b = "some string" >>> a is b False If this is normal behavior, could someone please explain what is going on. Edit: Disclaimer ! This is not being used to check for equality. I actually wanted to explain to someone else that "is" is only to check identity, not equality. And from the documentation I had understood that references created in this way will be different, that a new string will be created each time. The very first example I gave threw me off when I couldn't prove my own point! Edit: I understand that this is not a bug, and interning was a new concept for me. This seems to be a good explanation.
[ "Python may or may not automatically intern strings, which determines whether future instances of the string will share a reference.\nIf it decides to intern a string, then both will refer to the same string instance. If it doesn't, it'll create two separate strings that happen to have the same contents.\nIn gener...
[ 10, 1, 0 ]
[]
[]
[ "python", "reference", "string" ]
stackoverflow_0004165688_python_reference_string.txt
Q: Assigning variables from XML returned from an API call I need to pull some data from the API. It returns the GET in XML and I have having some issues trying to figure out how to assign some of the data from the API to fields in my model in django/python. The API for activeCollab does not allow me to create my own projectID number, it automatically generates the number for me. So I would like to take that number, then assign it to my API_id field in my project model. Could someone help me figure out how to take the XML that the GET returns and assign it to one of my fields. ActiveCollab API Documentation for projects: http://www.activecollab.com/docs/manuals/developers/api/projects Here is my models.py class Project(models.Model): client = models.ForeignKey(Clients, related_name='projects') created_by = models.ForeignKey(User, related_name='created_by') #general information API_id = models.IntegerField(max_length=10, verbose_name='aC ProjectID', null=True, blank=True) proj_name = models.CharField(max_length=255, verbose_name='Project Name') pre_quote = models.CharField(max_length=3) quote = models.IntegerField(max_length=10, verbose_name='Quote #', unique=True) estimator = models.ForeignKey(User, related_name='Estimator', null=True) desc = models.TextField(verbose_name='Description', null=True, blank=True) starts_on = models.DateField(verbose_name='Start Date') due_date = models.DateField(verbose_name='Due Date', null=True, blank=True) completed_on = models.DateField(verbose_name='Finished On', null=True, blank=True) notes = models.TextField(verbose_name='Notes', null=True, blank=True) Views.py def addProject(request): if request.method == 'POST': form = AddSingleProjectForm(request.POST) if form.is_valid(): project = form.save(commit=False) project.created_by = request.user today = datetime.date.today() project.pre_quote = "%s-" % (str(today.year)[2:4]) project.quote = Project.objects.latest().quote+1 project.save() project.status.create( value = form.cleaned_data.get('status', None) ) #API activeCollab params = urllib.urlencode({ 'format':'xml', 'submitted':'submitted', 'project[name]': project.proj_name, 'project[overview]': project.desc, 'project[starts_on]': project.starts_on, 'project[leader_id]': 10, }) req = urllib2.Request("web_url/public/api.php?path_info=/projects/add&token=####################", params) f = urllib2.urlopen(req) print f.read() return HttpResponseRedirect('/project/') else: form = AddSingleProjectForm() return render_to_response('project/addProject.html', { 'form': form, 'user':request.user}, context_instance=RequestContext(request)) Any suggestions will be appreciated. Steve Ps. The api call that I have shown is to create a new project A: Having looked at the link you posted... something like this might get you started, using lxml and xpath: >>> from lxml import etree >>> doc = etree.XML("""<projects> ... <project> ... <id>1</id> ... <name> ... <![CDATA[First Project]]> ... </name> ... <overview> ... <![CDATA[<p>This is overview of the first project</p>]]> ... </overview> ... <status> ... <![CDATA[active]]> ... </status> ... <type>...</type> ... <permalink>...</permalink> ... <leader_id>...</leader_id> ... <company_id>...</company_id> ... <group_id>...</group_id> ... </project> ... </projects>""") >>> data = {} >>> for a in doc.xpath('/projects/project/*'): ... data[a.tag] = str(a.text).strip() ... >>> data {'company_id': '...', 'group_id': '...', 'id': '1', 'leader_id': '...', 'name': 'First Project', 'overview': '<p>This is overview of the first project</p>', 'permalink': '...', 'status': 'active', 'type': '...'} Update Slightly more explicit help: Assuming you have an from lxml import etree in your file. here's a snippet for your addProject function: req = urllib2.Request("web_url/public/api.php?path_info=/projects/add&token=####################", params) resp = urllib2.urlopen(req) resp_data = f.read() if not resp.code == 200 and resp.headers.get('content-type') == 'text/xml': # Do your error handling. raise Exception('Unexpected response',req,resp) data = etree.XML(resp_data) api_id = int(data.xpath('/project/id/text()')[0]) project.API_id = api_id project.save()
Assigning variables from XML returned from an API call
I need to pull some data from the API. It returns the GET in XML and I have having some issues trying to figure out how to assign some of the data from the API to fields in my model in django/python. The API for activeCollab does not allow me to create my own projectID number, it automatically generates the number for me. So I would like to take that number, then assign it to my API_id field in my project model. Could someone help me figure out how to take the XML that the GET returns and assign it to one of my fields. ActiveCollab API Documentation for projects: http://www.activecollab.com/docs/manuals/developers/api/projects Here is my models.py class Project(models.Model): client = models.ForeignKey(Clients, related_name='projects') created_by = models.ForeignKey(User, related_name='created_by') #general information API_id = models.IntegerField(max_length=10, verbose_name='aC ProjectID', null=True, blank=True) proj_name = models.CharField(max_length=255, verbose_name='Project Name') pre_quote = models.CharField(max_length=3) quote = models.IntegerField(max_length=10, verbose_name='Quote #', unique=True) estimator = models.ForeignKey(User, related_name='Estimator', null=True) desc = models.TextField(verbose_name='Description', null=True, blank=True) starts_on = models.DateField(verbose_name='Start Date') due_date = models.DateField(verbose_name='Due Date', null=True, blank=True) completed_on = models.DateField(verbose_name='Finished On', null=True, blank=True) notes = models.TextField(verbose_name='Notes', null=True, blank=True) Views.py def addProject(request): if request.method == 'POST': form = AddSingleProjectForm(request.POST) if form.is_valid(): project = form.save(commit=False) project.created_by = request.user today = datetime.date.today() project.pre_quote = "%s-" % (str(today.year)[2:4]) project.quote = Project.objects.latest().quote+1 project.save() project.status.create( value = form.cleaned_data.get('status', None) ) #API activeCollab params = urllib.urlencode({ 'format':'xml', 'submitted':'submitted', 'project[name]': project.proj_name, 'project[overview]': project.desc, 'project[starts_on]': project.starts_on, 'project[leader_id]': 10, }) req = urllib2.Request("web_url/public/api.php?path_info=/projects/add&token=####################", params) f = urllib2.urlopen(req) print f.read() return HttpResponseRedirect('/project/') else: form = AddSingleProjectForm() return render_to_response('project/addProject.html', { 'form': form, 'user':request.user}, context_instance=RequestContext(request)) Any suggestions will be appreciated. Steve Ps. The api call that I have shown is to create a new project
[ "Having looked at the link you posted... something like this might get you started, using lxml and xpath:\n>>> from lxml import etree\n>>> doc = etree.XML(\"\"\"<projects>\n... <project>\n... <id>1</id>\n... <name>\n... <![CDATA[First Project]]>\n... </name>\n... <overview>\n... <![CDA...
[ 1 ]
[]
[]
[ "activecollab", "api", "django", "python", "xml" ]
stackoverflow_0004166291_activecollab_api_django_python_xml.txt
Q: How can I optimally concat a list of chars to a string? The data: list = ['a','b','x','d','s'] I want to create a string str = "abxds". How can I do that? Right now I am doing something like: str = "" for i in list: str = str + i print(str) I know strings are immutable in Python and this will create 7 string object. And this goes out of my memory when I do thousands of times. Is there a more efficient way of doing this? A: >>> theListOfChars = ['a', 'b', 'x', 'd', 's'] >>> ''.join(theListOfChars) 'abxds' BTW, don't use list or str as variable names as they are names of built-in functions already. (Also, there is no char in Python. A "character" is just a string of length 1. So the ''.join method works for list of strings as well.) A: KennyTM's answer is great. Also, if you wanted to make them comma separated or something, it'd be: ",".join(characterlist) This would result in "a,b,x,d,s" A: The thing you're looking for is str.join(): >>> L = ['a','b','x','d','s'] >>> ''.join(L) 'abxds' (Don't name your variable list, it's a builtin name.)
How can I optimally concat a list of chars to a string?
The data: list = ['a','b','x','d','s'] I want to create a string str = "abxds". How can I do that? Right now I am doing something like: str = "" for i in list: str = str + i print(str) I know strings are immutable in Python and this will create 7 string object. And this goes out of my memory when I do thousands of times. Is there a more efficient way of doing this?
[ ">>> theListOfChars = ['a', 'b', 'x', 'd', 's']\n>>> ''.join(theListOfChars)\n'abxds'\n\nBTW, don't use list or str as variable names as they are names of built-in functions already.\n(Also, there is no char in Python. A \"character\" is just a string of length 1. So the ''.join method works for list of strings as ...
[ 13, 4, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0004166641_python_string.txt
Q: why just one name could taken def path(request, mypath): mypath = request.path_info _listdir = os.listdir(mypath) # ['folder1', 'folder2', 'folder3', 'folder4'] mess = _listdir a = ' ' x=0 scope = vars() for i in mess: scope['x']+=1 a += mess[x] a += '\n' return HttpResponse(a) I hope the output is like this: folder1 folder2 folder3 folder4 but why the output just like this: folder1 folder1 folder1 folder1 any help? A: There are huge swathes of unnecessary code in that function. def path(request): return HttpResponse('\n'.join(os.listdir(request.path_info))) Job done! A: From the docs: Note: The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined. So, don't do that. A: You probably want a += mess[i] instead of a += mess[x] A: I hope the output is like this: folder1 folder2 folder3 folder4 Thus shall you have your output... for i in os.listdir(mypath): print i You can return the i in the loop with HttpResponse there should be no problem, do this returnString = "" for i in os.listdir(mypath): returnString = returnString + i + "\n" return returnString A: Most of what you have is unneccesary. You just want to loop through the return values. Not modify them, nor play around with a variable indirectly via scope. def path(request, mypath): mypath = request.path_info dirs = os.listdir(mypath) # ['folder1', 'folder2', 'folder3', 'folder4'] a = '' for i in dirs: a += dirs a += '\n' return HttpResponse(a)
why just one name could taken
def path(request, mypath): mypath = request.path_info _listdir = os.listdir(mypath) # ['folder1', 'folder2', 'folder3', 'folder4'] mess = _listdir a = ' ' x=0 scope = vars() for i in mess: scope['x']+=1 a += mess[x] a += '\n' return HttpResponse(a) I hope the output is like this: folder1 folder2 folder3 folder4 but why the output just like this: folder1 folder1 folder1 folder1 any help?
[ "There are huge swathes of unnecessary code in that function.\ndef path(request):\n return HttpResponse('\\n'.join(os.listdir(request.path_info)))\n\nJob done!\n", "From the docs:\n\nNote: The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.\n\nSo, don't ...
[ 4, 3, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004162248_python.txt
Q: How can I read a python pickle database/file from C? I am working on integrating with several music players. At the moment my favorite is exaile. In the new version they are migrating the database format from SQLite3 to an internal Pickle format. I wanted to know if there is a way to access pickle format files without having to reverse engineer the format by hand. I know there is the cPickle python module, but I am unaware if it is callable directly from C. A: http://www.picklingtools.com/ There is a library called the PicklingTools which I help maintain which might be useful: it allows you to form data structures in C++ that you can then pickle/unpickle ... it is C++, not C, but that shouldn't be a problem these days (assuming you are using the gcc/g++ suite). The library is a plain C++ library (there are examples of C++ and Python within the distribution showing how to use the library over sockets and files from both C++ and Python), but in general, the basics of pickling to files is available. The basic idea is that the PicklingTools library gives you "python-like" data structures from C++ so that you can then serialize and deserialize to/from Python/C++. All (?) the basic types: int, long int,string, None, complex, dictionarys, lists, ordered dictionaries and tuples are supported. There are few hooks to do custom classes, but that part is a bit immature: the rest of the library is pretty stable and has been active for 8 (?) years. Simple example: #include "chooseser.h" int main() { Val a_dict = Tab("{ 'a':1, 'b':[1,2.2,'three'], 'c':None }"); cout << a_dict["b"][0]; // value of 1 // Dump to a file DumpValToFile(a_dict, "example.p0", SERIALIZE_P0); // .. from Python, can load the dictionary with pickle.load(file('example.p0')) // Get the result back Val result; LoadValFromFile(result, "example.p0", SERIALIZE_P0); cout << result << endl; } There is further documentation (FAQ and User's Guide) on the web site. Hope this is useful: Gooday, Richie http://www.picklingtools.com/ A: Like Cristian told, you can rather easily embed python code in your C code, see the example here. Using cPickle is dead easy as well on python you could use something like: import cPickle f = open('dbfile', 'rb') db = cPickle.load(f) f.close() # handle db integration f = open('dbfile', 'wb') cPickle.dump(db, f) f.close() A: You can embed a Python interpreter in a C program, but I think that the easiest solution is to write a Python script that converts "pickles" in another format, e.g. an SQLite database.
How can I read a python pickle database/file from C?
I am working on integrating with several music players. At the moment my favorite is exaile. In the new version they are migrating the database format from SQLite3 to an internal Pickle format. I wanted to know if there is a way to access pickle format files without having to reverse engineer the format by hand. I know there is the cPickle python module, but I am unaware if it is callable directly from C.
[ "http://www.picklingtools.com/\nThere is a library called the PicklingTools which I help maintain which might be useful: it allows you to form data structures in C++ that you can then pickle/unpickle ... it is C++, not C, but that shouldn't be a problem these days (assuming you are using the gcc/g++ suite). \nThe ...
[ 31, 5, 3 ]
[]
[]
[ "c", "python" ]
stackoverflow_0001296162_c_python.txt
Q: how to parse table inside table using beautiful soup? I tried this: s = soup.findAll("table", {"class": "view"}) But it is giving me the table. But I need the table inside table. <table class="view" > <tr> <td width="46%" valign="top"> <table> <tr> <td> <div style="adasdasd"> <div class="abc">dasdsadasdasdas</div> </div> <div> <span><span class="aaaaaaa " title="aaaaaaaaaaa"><span>aaaaaaaaaaaaa</span></span> </span> <b>My Face</b><br /> Hello This is me, </div> <div class="abc""> Dec 6, 2010 by Alis </div> </td> </tr> </table> </tr> </table> The things I want to scrap is: Hello This is me, My Face Dec 6, 2010 by Alis A: s = soup.findAll("table", {"class": "view"})[0].find("table") If there's just the one table, you could use .find for the first one too, and drop the [0]. A: Heres some better formatted html: <table class="view" > <tr> <td width="46%" valign="top"> <table> <tr> <td> <div style="adasdasd"> <div class="abc">dasdsadasdasdas</div> </div> <div> <span> <span class="aaaaaaa " title="aaaaaaaaaaa"> <span>aaaaaaaaaaaaa</span> </span> </span> <b>My Face</b> <br /> Hello This is me, </div> <div class="abc"> Dec 6, 2010 by Alis </div> </td> </tr> </table> </td> </tr> </table> Note: I actually added a tag because it was missing one. innerTable = soup.find("table", {"class": "view"}).tr.td.table ##Gets the table in the first cell of the first row innerDiv = innerTable.find("div", {"style": "adasdasd"}).nextSibling #this gets the div in which all of you content resides So that will get you to that that holds all of your content. From there it's just a little bit of parsing to get the content you actually need.
how to parse table inside table using beautiful soup?
I tried this: s = soup.findAll("table", {"class": "view"}) But it is giving me the table. But I need the table inside table. <table class="view" > <tr> <td width="46%" valign="top"> <table> <tr> <td> <div style="adasdasd"> <div class="abc">dasdsadasdasdas</div> </div> <div> <span><span class="aaaaaaa " title="aaaaaaaaaaa"><span>aaaaaaaaaaaaa</span></span> </span> <b>My Face</b><br /> Hello This is me, </div> <div class="abc""> Dec 6, 2010 by Alis </div> </td> </tr> </table> </tr> </table> The things I want to scrap is: Hello This is me, My Face Dec 6, 2010 by Alis
[ "s = soup.findAll(\"table\", {\"class\": \"view\"})[0].find(\"table\")\n\nIf there's just the one table, you could use .find for the first one too, and drop the [0].\n", "Heres some better formatted html:\n<table class=\"view\" >\n <tr>\n <td width=\"46%\" valign=\"top\">\n <table>\n ...
[ 2, 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0004164301_beautifulsoup_python.txt
Q: A cleaner/shorter way to solve this problem? This exercise is taken from Google's Python Class: D. Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list. Here's my solution so far: def remove_adjacent(nums): if not nums: return nums list = [nums[0]] for num in nums[1:]: if num != list[-1]: list.append(num) return list But this looks more like a C program than a Python script, and I have a feeling this can be done much more elegant. EDIT So [1, 2, 2, 3] should give [1, 2, 3] and [1, 2, 3, 3, 2] should give [1, 2, 3, 2] A: There is function in itertools that works here: import itertools [key for key,seq in itertools.groupby([1,1,1,2,2,3,4,4])] You can also write a generator: def remove_adjacent(items): # iterate the items it = iter(items) # get the first one last = next(it) # yield it in any case yield last for current in it: # if the next item is different yield it if current != last: yield current last = current # else: its a duplicate, do nothing with it print list(remove_adjacent([1,1,1,2,2,3,4,4])) A: itertools to the rescue. import itertools def remove_adjacent(lst): i = iter(lst) yield next(i) for x, y in itertools.izip(lst, i): if x != y: yield y L = [1, 2, 2, 3] print list(remove_adjacent(L)) A: Solution using list comprehensions, zipping then iterating through a twice. Inefficient, but short and sweet. It also has the problem of extending a[1:] with something. a = [ 1,2,2,2,3,4,4,5,3,3 ] b = [ i for i,j in zip(a,a[1:] + [None]) if not i == j ] A: This works, but I'm not quite happy with it yet because of the +[None] bit to ensure that the last element is also returned... >>> mylist=[1,2,2,3,3,3,3,4,5,5,5] >>> [x for x, y in zip(mylist, mylist[1:]+[None]) if x != y] [1, 2, 3, 4, 5] The most Pythonic way is probably to go the path of least resistance and use itertools.groupby() as suggested by THC4K and be done with it. A: >>> def collapse( data ): ... return list(sorted(set(data))) ... >>> collapse([1,2,2,3]) [1, 2, 3] Second attempt after the additional requirment was added: >>> def remove_adjacent( data ): ... last = None ... for datum in data: ... if datum != last: ... last = datum ... yield datum ... >>> list( remove_adjacent( [1,2,2,3,2] ) ) [1, 2, 3, 2] A: You may want to look at itertools. Also, here's a tutorial on Python iterators and generators (pdf). A: This is also somewhat functional; it could be written as a one-liner using lambdas but that would just make it more confusing. In Python 3 you'd need to import reduce from functools. def remove_adjacent(nums): def maybe_append(l, x): return l + ([] if len(l) and l[-1] == x else [x]) return reduce(maybe_append, nums, [])
A cleaner/shorter way to solve this problem?
This exercise is taken from Google's Python Class: D. Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list. Here's my solution so far: def remove_adjacent(nums): if not nums: return nums list = [nums[0]] for num in nums[1:]: if num != list[-1]: list.append(num) return list But this looks more like a C program than a Python script, and I have a feeling this can be done much more elegant. EDIT So [1, 2, 2, 3] should give [1, 2, 3] and [1, 2, 3, 3, 2] should give [1, 2, 3, 2]
[ "There is function in itertools that works here:\nimport itertools\n[key for key,seq in itertools.groupby([1,1,1,2,2,3,4,4])]\n\nYou can also write a generator:\ndef remove_adjacent(items):\n # iterate the items\n it = iter(items)\n # get the first one\n last = next(it)\n # yield it in any case\n ...
[ 9, 3, 3, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004167009_python.txt
Q: Python/Tkinter: Trap text selection via keyboard/mouse as an event? Is it possible to trap text selection via the keyboard AND mouse as a selection/selection_change type of event? (I know I can trap selection via the keyboard by watching every keypress and comparing selection range - but I see no way to detect selection via the mouse or as a discrete event by itself) I've looked at the following Tkinter event documentation and don't see a selection/selection_changed type of event. http://infohost.nmt.edu/tcc/help/pubs/tkinter/events.html Perhaps some of you Tkinter/Tk veterans might have some clever ideas? Thank you, Malcolm A: The text widget generates a <<Selection>> event, and the listbox generates a <<ListboxSelect>> event. Do either of those meet your needs?
Python/Tkinter: Trap text selection via keyboard/mouse as an event?
Is it possible to trap text selection via the keyboard AND mouse as a selection/selection_change type of event? (I know I can trap selection via the keyboard by watching every keypress and comparing selection range - but I see no way to detect selection via the mouse or as a discrete event by itself) I've looked at the following Tkinter event documentation and don't see a selection/selection_changed type of event. http://infohost.nmt.edu/tcc/help/pubs/tkinter/events.html Perhaps some of you Tkinter/Tk veterans might have some clever ideas? Thank you, Malcolm
[ "The text widget generates a <<Selection>> event, and the listbox generates a <<ListboxSelect>> event. Do either of those meet your needs?\n" ]
[ 1 ]
[]
[]
[ "events", "python", "tkinter", "user_interface", "windows" ]
stackoverflow_0004165045_events_python_tkinter_user_interface_windows.txt
Q: Sorting datastore item by auto_now=True and auto_now_add=True I am trying to sort an item in datastore by age by using auto_now=True and auto_now_add=True. I managed to solve datetime problems but I am unable to sort correctly by age. I appreciate any suggestions. (Sorry for the capitalized variables, I will fix them eventually.) My model is: class Rep(db.Model): mAUTHOR = db.UserProperty(auto_current_user=True) mUNIQUE = db.StringProperty() mCOUNT = db.IntegerProperty() mDATE = db.DateTimeProperty(auto_now=True) mDATE0 = db.DateTimeProperty(auto_now_add=True) mWEIGHT = db.IntegerProperty() mAGE = db.IntegerProperty() Query is: QUERY3 = Rep.all() QUERY3.filter("mAUTHOR =", user) QUERY3.order("mAGE") RESULTS3 = QUERY3.fetch(7) And this is what I use in Mako template: % for result in RESULTS3: <% result.mAGE = int((result.mDATE - result.mDATE0).seconds) %> <p>${result.mUNIQUE} (${result.mCOUNT}) (${result.mAGE})</p> % endfor And here's an example of output with bad sort: mUNIQUE mCOUNT mAGE A (11) (38604) C (19) (5319) D (10) (1797) E (17) (2735) F (16) (871) Thanks! A: Off the top of my head, it looks like you're only calculating mAGE when you retrieve the records, i.e. after doing the query. Shouldn't you calculate it whenever you modify an object, before putting it into the datastore? Before that, though, are you sure that it's what you want to do? mAGE will be the time between when you last modified each record, and when the record was created. That seems like an odd thing to sort on. If you want to sort by the actual age of the record (time since creation), use mDATE0 to sort. Or if you want to sort by most recent changes, use mDATE. To sort in reverse, use QUERY3.order("-mDATE") (note the hyphen).
Sorting datastore item by auto_now=True and auto_now_add=True
I am trying to sort an item in datastore by age by using auto_now=True and auto_now_add=True. I managed to solve datetime problems but I am unable to sort correctly by age. I appreciate any suggestions. (Sorry for the capitalized variables, I will fix them eventually.) My model is: class Rep(db.Model): mAUTHOR = db.UserProperty(auto_current_user=True) mUNIQUE = db.StringProperty() mCOUNT = db.IntegerProperty() mDATE = db.DateTimeProperty(auto_now=True) mDATE0 = db.DateTimeProperty(auto_now_add=True) mWEIGHT = db.IntegerProperty() mAGE = db.IntegerProperty() Query is: QUERY3 = Rep.all() QUERY3.filter("mAUTHOR =", user) QUERY3.order("mAGE") RESULTS3 = QUERY3.fetch(7) And this is what I use in Mako template: % for result in RESULTS3: <% result.mAGE = int((result.mDATE - result.mDATE0).seconds) %> <p>${result.mUNIQUE} (${result.mCOUNT}) (${result.mAGE})</p> % endfor And here's an example of output with bad sort: mUNIQUE mCOUNT mAGE A (11) (38604) C (19) (5319) D (10) (1797) E (17) (2735) F (16) (871) Thanks!
[ "Off the top of my head, it looks like you're only calculating mAGE when you retrieve the records, i.e. after doing the query. Shouldn't you calculate it whenever you modify an object, before putting it into the datastore?\nBefore that, though, are you sure that it's what you want to do? mAGE will be the time betwe...
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "mako", "python" ]
stackoverflow_0004167468_google_app_engine_google_cloud_datastore_mako_python.txt
Q: how to configure Sweave it's work and recognize for Rpy2? how to configure Sweave it's work and recognize for Rpy2? I use this import rpy2.robjects as robjects R["library"]("utils") R["library"]("tools") R['sweave("/var/www/tmp/pywps/central.Rnw")'] R['texi2dvi("/var/www/tmp/pywps/central.tex", pdf=TRUE)'] but I get these errors [File "/usr/lib/python2.6/dist-packages/rpy2/robjects/__init__.py", line 241, in __getitem__ res = rinterface.globalenv.get(item) LookupError: 'Sweave("/var/www/tmp/pywps/central.Rnw")' not found Traceback (most recent call last):] thanks for your answers and help A: Use square brackets to get an R object, then call it from Python. Or use () brackets to pass a line to R: R["Sweave"]("/var/www/tmp/pywps/central.Rnw") R('Sweave("/var/www/tmp/pywps/central.Rnw")') Sweave needs a capital S (in my tests). A: Uh, does this work? You're not doing all the R[] invocations the same way. import rpy2.robjects as robjects R["library"]("utils") R["library"]("tools") R["sweave"]("/var/www/tmp/pywps/central.Rnw") R["texi2dvi"]("/var/www/tmp/pywps/central.tex", "pdf=TRUE") (I've never used Rpy2 so this is totally guessing.) A: Using the R package importer would let you use autocompletion in your IDE or interactive shell and make the code more Python-like. from rpy2.robjects.packages import importr utils = importr('utils') utils.Sweave("/var/www/tmp/pywps/central.Rnw")
how to configure Sweave it's work and recognize for Rpy2?
how to configure Sweave it's work and recognize for Rpy2? I use this import rpy2.robjects as robjects R["library"]("utils") R["library"]("tools") R['sweave("/var/www/tmp/pywps/central.Rnw")'] R['texi2dvi("/var/www/tmp/pywps/central.tex", pdf=TRUE)'] but I get these errors [File "/usr/lib/python2.6/dist-packages/rpy2/robjects/__init__.py", line 241, in __getitem__ res = rinterface.globalenv.get(item) LookupError: 'Sweave("/var/www/tmp/pywps/central.Rnw")' not found Traceback (most recent call last):] thanks for your answers and help
[ "Use square brackets to get an R object, then call it from Python. Or use () brackets to pass a line to R:\nR[\"Sweave\"](\"/var/www/tmp/pywps/central.Rnw\")\nR('Sweave(\"/var/www/tmp/pywps/central.Rnw\")')\n\nSweave needs a capital S (in my tests).\n", "Uh, does this work? You're not doing all the R[] invocatio...
[ 2, 1, 1 ]
[]
[]
[ "python", "r", "rpy2", "sweave" ]
stackoverflow_0004160318_python_r_rpy2_sweave.txt
Q: Alternatives to ApacheBench for profiling my code speed I've done some experiments using Apache Bench to profile my code response times, and it doesn't quite generate the right kind of data for me. I hope the good people here have ideas. Specifically, I need a tool that Does HTTP requests over the network (it doesn't need to do anything very fancy) Records response times as accurately as possible (at least to a few milliseconds) Writes the response time data to a file without further processing (or provides it to my code, if a library) I know about ab -e, which prints data to a file. The problem is that this prints only the quantile data, which is useful, but not what I need. The ab -g option would work, except that it doesn't print sub-second data, meaning I don't have the resolution I need. I wrote a few lines of Python to do it, but the httplib is horribly inefficient and so the results were useless. In general, I need better precision than pure Python is likely to provide. If anyone has suggestions for a library usable from Python, I'm all ears. I need something that is high performance, repeatable, and reliable. I know that half my responses are going to be along the lines of "internet latency makes that kind of detailed measurements meaningless." In my particular use case, this is not true. I need high resolution timing details. Something that actually used my HPET hardware would be awesome. Throwing a bounty on here because of the low number of answers and views. A: I have done this in two ways. With "loadrunner" which is a wonderful but pretty expensive product (from I think HP these days). With combination perl/php and the Curl package. I found the CURL api slightly easier to use from php. Its pretty easy to roll your own GET and PUT requests. I would also recommend manually running through some sample requests with Firefox and the LiveHttpHeaders add on to captute the exact format of the http requests you need. A: JMeter is pretty handy. It has a GUI from which you can set up your requests and threadpools and it also can be run from the command line. A: If you can code in Java, you can look at the combination of JUnitPerf + HttpUnit. The downside is that you will have to do more things yourself. But at the price of this you will get unlimited flexibility and arguably more preciseness than with GUI tools, not to mention HTML parsing, JavaScript execution, etc. There's also another project called Grinder which seems to be purposed for a similar task but I don't have any experience with it. A: A good reference of opensource perfomance testing tools: http://www.opensourcetesting.org/performance.php You will find descriptions and a "most popular" list A: httperf is very powerful. A: I've used a script to drive 10 boxes on the same switch to generate load by "replaying" requests to 1 server. I had my web app logging response time (server only) to the granularity I needed, but I didn't care about the response time to the client. I'm not sure you care to include the trip to and from the client in your calculations, but if you did it shouldn't be to difficult to code up. I then processed my log with a script which extracted the times per url and did scatter plot graphs, and trend graphs based on load. This satisfied my requirements which were: Real world distribution of calls to different urls. Trending performance based on load. Not influencing the web app by running other intensive ops on the same box. I did controller as a shell script that foreach server started a process in the background to loop over all the urls in a file calling curl on each one. I wrote the log processor in Perl since I was doing more Perl at that time.
Alternatives to ApacheBench for profiling my code speed
I've done some experiments using Apache Bench to profile my code response times, and it doesn't quite generate the right kind of data for me. I hope the good people here have ideas. Specifically, I need a tool that Does HTTP requests over the network (it doesn't need to do anything very fancy) Records response times as accurately as possible (at least to a few milliseconds) Writes the response time data to a file without further processing (or provides it to my code, if a library) I know about ab -e, which prints data to a file. The problem is that this prints only the quantile data, which is useful, but not what I need. The ab -g option would work, except that it doesn't print sub-second data, meaning I don't have the resolution I need. I wrote a few lines of Python to do it, but the httplib is horribly inefficient and so the results were useless. In general, I need better precision than pure Python is likely to provide. If anyone has suggestions for a library usable from Python, I'm all ears. I need something that is high performance, repeatable, and reliable. I know that half my responses are going to be along the lines of "internet latency makes that kind of detailed measurements meaningless." In my particular use case, this is not true. I need high resolution timing details. Something that actually used my HPET hardware would be awesome. Throwing a bounty on here because of the low number of answers and views.
[ "I have done this in two ways.\nWith \"loadrunner\" which is a wonderful but pretty expensive product (from I think HP these days).\nWith combination perl/php and the Curl package. I found the CURL api slightly easier to use from php. Its pretty easy to roll your own GET and PUT requests. I would also recommend man...
[ 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "apachebench", "benchmarking", "latency", "profiling", "python" ]
stackoverflow_0004083523_apachebench_benchmarking_latency_profiling_python.txt
Q: How to do atomic increment/decrement with Elixir/SQLAlchemy I'd like to increment (or decrement) a score field in an Elixir entity: class Posting(Entity): score = Field(Integer, PassiveDefault(text('0'))) def upvote(self): self.score = self.score + 1 However, this doesn't work reliably with concurrent calls to upvote. The best I could come up with is this ugly mess (basically constructing an SQL UPDATE statement with SQLAlchemy): def upvote(self): # sqlalchemy atomic increment; is there a cleaner way? update = self.table.update().where(self.table.c.id==self.id) update = update.values({Posting.score: Posting.score + 1}) update.execute() Do you see any problems with this solution? Are there cleaner ways to achieve the same? I'd like to avoid using DB locks here. I'm using Elixir, SQLAlchemy, Postgres. Update Here is a variant which is derived from vonPetrushev's solution: def upvote(self): Posting.query.filter_by(id=self.id).update( {Posting.score: Posting.score + 1} ) This is somewhat nicer than my first solution but still requires to filter for the current entity. Unfortunately, this does not work if the Entity is spread over multiple tables. A: I'll try, but I'm not sure if this meets your needs: session.query(Posting).\ .filter(Posting.id==self.id)\ .update({'score':self.score+1}) You might wanna do session.commit() right after it? EDIT: [concerning the question's update] If the Posting is derived from Entity which is class mapped to multiple tables, the solution above still stands, but the meaning of Posting.id attribute is changed, that is, it is no longer mapped to some table's column, but to a different composition. Here: http://docs.sqlalchemy.org/en/latest/orm/nonstandard_mappings.html#mapping-a-class-against-multiple-tables you can see how to define it. I suggest it will be like: j = join(entity_table_1, entity_table_2) mapper(Entity, j, properties={ 'id': column_property(entity_table_1.c.id, entity_table_2.c.user_id) <... some other properties ...> })
How to do atomic increment/decrement with Elixir/SQLAlchemy
I'd like to increment (or decrement) a score field in an Elixir entity: class Posting(Entity): score = Field(Integer, PassiveDefault(text('0'))) def upvote(self): self.score = self.score + 1 However, this doesn't work reliably with concurrent calls to upvote. The best I could come up with is this ugly mess (basically constructing an SQL UPDATE statement with SQLAlchemy): def upvote(self): # sqlalchemy atomic increment; is there a cleaner way? update = self.table.update().where(self.table.c.id==self.id) update = update.values({Posting.score: Posting.score + 1}) update.execute() Do you see any problems with this solution? Are there cleaner ways to achieve the same? I'd like to avoid using DB locks here. I'm using Elixir, SQLAlchemy, Postgres. Update Here is a variant which is derived from vonPetrushev's solution: def upvote(self): Posting.query.filter_by(id=self.id).update( {Posting.score: Posting.score + 1} ) This is somewhat nicer than my first solution but still requires to filter for the current entity. Unfortunately, this does not work if the Entity is spread over multiple tables.
[ "I'll try, but I'm not sure if this meets your needs:\nsession.query(Posting).\\\n .filter(Posting.id==self.id)\\\n .update({'score':self.score+1})\n\nYou might wanna do session.commit() right after it?\nEDIT: [concerning the question's update]\nIf the Posting is derived from Entity which is class mapped to m...
[ 2 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0004167568_python_python_elixir_sqlalchemy.txt
Q: How can I get the port number of the newly accepted connection in python? When I create a socket on a server and the accept an incoming connection: conn, addr = s.accept() Both print conn.getsockname() and print s.getsockname() print out the same port number. I thought 'conn' was supposed to represent a NEW socket. How do I get the port number of this new socket? Thanks! A: The local port remains the same. What you want is the remote side's port. You can use getpeername for this (or the second element of accept's return value). A: It is a new socket, but it has the same local port as the original listening socket.
How can I get the port number of the newly accepted connection in python?
When I create a socket on a server and the accept an incoming connection: conn, addr = s.accept() Both print conn.getsockname() and print s.getsockname() print out the same port number. I thought 'conn' was supposed to represent a NEW socket. How do I get the port number of this new socket? Thanks!
[ "The local port remains the same. What you want is the remote side's port. You can use getpeername for this (or the second element of accept's return value).\n", "It is a new socket, but it has the same local port as the original listening socket.\n" ]
[ 6, 0 ]
[]
[]
[ "python", "sockets", "tcp" ]
stackoverflow_0004168191_python_sockets_tcp.txt
Q: Python: Problems mocking an instance I am having problem mocking an object to test a descriptor. This is the code of the descriptor: class Text(object): def __init__(self, default_value=u'', validators=[]): self.validators = validators self._value = default_value def __set__(self, instance, value): for validator in self.validators: validator(value).validate() this is the test: def test_text_validator_raises_exception(self): validator = Mock() validator.validate.side_effect = ValidationError() text = Text(validators=[validator]) self.assertRaises( ValidationError, text__set__, (text, '') ) Edit: The function has () in the code I did a typo when copying the code. The error I got was that set() takes exactly 3 arguments. But I noticed in the answers that I shouldn't pass a tuple as a last argument. But It also isn't working when I called validator('').validate() inside the test function. A: validator in Text is an object factory e.g., class object validator in the test_.. function is used as a concrete instance -- the product of an object factory. You should give to Text() something that returns objects with .validate method not the objects themselves: def test_text_validator_raises_exception(self): validator = Mock() validator.validate.side_effect = ValidationError() text = Text(validators=[Mock(return_value=validator)]) self.assertRaises(ValidationError, text.__set__, text, '') A: I guess you need to put () after function name A: Maybe the best way to mock an instance is just "You call yourself an instance?" Seriously, though, def test_text_validator_raises_exception: should be def test_text_validator_raises_exception(): But what problem are you having with it, as the first commenter asked?
Python: Problems mocking an instance
I am having problem mocking an object to test a descriptor. This is the code of the descriptor: class Text(object): def __init__(self, default_value=u'', validators=[]): self.validators = validators self._value = default_value def __set__(self, instance, value): for validator in self.validators: validator(value).validate() this is the test: def test_text_validator_raises_exception(self): validator = Mock() validator.validate.side_effect = ValidationError() text = Text(validators=[validator]) self.assertRaises( ValidationError, text__set__, (text, '') ) Edit: The function has () in the code I did a typo when copying the code. The error I got was that set() takes exactly 3 arguments. But I noticed in the answers that I shouldn't pass a tuple as a last argument. But It also isn't working when I called validator('').validate() inside the test function.
[ "\nvalidator in Text is an object factory e.g., class object\nvalidator in the test_.. function is used as a concrete instance -- the product of an object factory. \n\nYou should give to Text() something that returns objects with .validate method not the objects themselves:\ndef test_text_validator_raises_exception...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004168301_python.txt
Q: best algorithm to combine multiple RSS feeds using Python I am writing a python script to combine about 20+ RSS feeds. I would like to use a custom solution instead of feedjack or planetfeed. I use feedparser to parse the feeds and mysql to cache them. The problem I am running into is determining which feeds have already been cached and which haven't. Some pseudo code for what I have tried: create a list of all feed items get the date of last item cached from db check which items in my list have a date greater than my item from the db and return this filtered list sort the returned filtered list by date the item was created add new items to the db I feel like this would work, but my problem is that not all of the dates on the RSS feeds I am using are correct. Sometimes a publisher, for whatever reason, will have feed items with dates in the future. If this future date gets added to the db, then it will always be greater than the date of the items in my list. So, the comparison stops working and no new items get added to the db. I would like to come up with another solution and not rely on the publishers dates. How would some of you pros do this? Assuming you have to combine multiple rss feeds, save them to a mysql db and then return them in ordered by date. I'm just looking for pseudo code to give me an idea of the best way to do this. Thanks for your help. A: Depending on how often the feeds are updated and how often you check, you could simply fix broken dates (if it's in the future, reset it to today), before adding them to the database. Other than that, you'd have to use some sort of ID—I think RSS has an ID field on each item. If your feeds are kept in order, you can get the most recent cached ID, find that in the feed items list, and then add everything newer. If they're out of order, you'd have to check each one against your cache, and add it if it's missing.
best algorithm to combine multiple RSS feeds using Python
I am writing a python script to combine about 20+ RSS feeds. I would like to use a custom solution instead of feedjack or planetfeed. I use feedparser to parse the feeds and mysql to cache them. The problem I am running into is determining which feeds have already been cached and which haven't. Some pseudo code for what I have tried: create a list of all feed items get the date of last item cached from db check which items in my list have a date greater than my item from the db and return this filtered list sort the returned filtered list by date the item was created add new items to the db I feel like this would work, but my problem is that not all of the dates on the RSS feeds I am using are correct. Sometimes a publisher, for whatever reason, will have feed items with dates in the future. If this future date gets added to the db, then it will always be greater than the date of the items in my list. So, the comparison stops working and no new items get added to the db. I would like to come up with another solution and not rely on the publishers dates. How would some of you pros do this? Assuming you have to combine multiple rss feeds, save them to a mysql db and then return them in ordered by date. I'm just looking for pseudo code to give me an idea of the best way to do this. Thanks for your help.
[ "Depending on how often the feeds are updated and how often you check, you could simply fix broken dates (if it's in the future, reset it to today), before adding them to the database.\nOther than that, you'd have to use some sort of ID—I think RSS has an ID field on each item. If your feeds are kept in order, you ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004167863_python.txt
Q: find string with format '[number]' using regex I have a string in a django/python app and need to search it for every instance of [x]. This includes the brackets and x, where x is any number between 1 and several million. I then need to replace x with my own string. ie, 'Some string [3423] of words and numbers like 9898' would turn into 'Some string [mycustomtext] of words and numbers like 9898' Note only the bracketed number was affected. I am not familiar with regex but think this will do it for me? A: Regex is precisely what you want. It's the re module in Python, you'll want to use re.sub, and it will look something like: newstring = re.sub(r'\[\d+\]', replacement, yourstring) If you need to do a lot of it, consider compiling the regex: myre = re.compile(r'\[\d+\]') newstring = myre.sub(replacement, yourstring) Edit: To reuse the number, use a regex group: newstring = re.sub(r'\[(\d+)\]',r'[mytext, \1]', yourstring) Compilation is still possible too. A: Use re.sub: import re input = 'Some string [3423] of words and numbers like 9898' output = re.sub(r'\[[0-9]+]', '[mycustomtext]', input) # output is now 'Some string [mycustomtext] of words and numbers like 9898' A: Since no one else is jumping in here I'll give you my non-Python version of the regex \[(\d{1,8})\] Now in the replacement part you can use the 'passive group' $n to replace (where n = the number corresponding to the part in parentheses). This one would be $1
find string with format '[number]' using regex
I have a string in a django/python app and need to search it for every instance of [x]. This includes the brackets and x, where x is any number between 1 and several million. I then need to replace x with my own string. ie, 'Some string [3423] of words and numbers like 9898' would turn into 'Some string [mycustomtext] of words and numbers like 9898' Note only the bracketed number was affected. I am not familiar with regex but think this will do it for me?
[ "Regex is precisely what you want. It's the re module in Python, you'll want to use re.sub, and it will look something like:\nnewstring = re.sub(r'\\[\\d+\\]', replacement, yourstring)\n\nIf you need to do a lot of it, consider compiling the regex:\nmyre = re.compile(r'\\[\\d+\\]')\nnewstring = myre.sub(replacement...
[ 4, 1, 0 ]
[]
[]
[ "python", "regex", "replace", "string" ]
stackoverflow_0004168729_python_regex_replace_string.txt
Q: Is there any data structure which can avoid duplication, preserve order and random access Previously, while I am looking for the data structure with the following characteristic. Avoid duplication Iteration order will be same as insertion order In Java, I use LinkHashSet, In Python, I use OrderedDict Now, on the top of 2 requirements, I would like to have an additional requirement Able to random access through indexing, means I can access through data[123] Is there any data structure available? Or I need to fall back to use List? List able to full fill 2nd and 3rd requirement, but not 1st. I may need to perform manual (and slow check) during insertion, to avoid duplication? A: A simple approach in Java would be to create a wrapper class that implements both the Set and List interfaces, and that contained both a HashSet and ArrayList. Update operations would need to update both internal collections, and read operations would be mapped to whichever internal collection gives the correct semantics and best performance. The only slightly tricky method is iterator() where you need to arrange that remove updates both collections. This approach will give you the "best of both worlds" performance for read operations, but updates will necessarily be slower. In particular, insert at a given position and remove will be O(N) operations. (I'd note that LinkedHashSet is not a direct solution since it does not provide a get(int) method. You could implement this method via the LinkedHashSet iterator, by that makes it an O(N) operation. Probably not what you want.) FOLLOW UP I've not been able to find a general purpose implementation class that implements both the Set and List interfaces. I think that the reason is that there are semantic anomalies when you combine the interfaces. For example, (as @ColinD notes) if you call E set(int, E) with an element that it already in the list, it is not clear what the result should be. Dealing with this in a way that satisfies everyone is probably impossible, and I can understand why they might have decided not to go swimming in the tarpit. However, I don't see this as a major problem if you are creating a Set + List class for your application's internal use. You either pick a semantic for that suits your application, code your application to not use the method at all, or code your application to avoid being bitten by the anomaly. (For instance, you might code it to either ignore result of the set method, to throw an unchecked exception if there is a duplicate, or return null or some distinguished object if there is a duplicate.) For the record, it is not unforgivable for a custom collection class to violate the interface contract. Indeed, even the Java designers do it - see IdentityHashMap. What is unforgivable is not documenting the contract violations in the javadocs. A: If you can use an immutable collection, use an ImmutableSet from Guava, which has an asList() view to provide indexed access. A: java.util.Set doesn't provide random access methods like get() and set(), so most/all of its implementations don't either. You could create your own implementation of Set that will provide this, maybe with an ArrayList to hold the data. A: The LinkedHashSet class provides the toArray-Method, which should fit your needs. A: You're not going to find a basic data structure that does this; the goals you're looking for rule out all of them. You might find an more esoteric one that'll do it, but the easiest approach is to use a compound data structure, maintaining two data structures in parallel. That's what collections.OrderedDict does under the hood, in fact. That's not what you want, though: since it's not designed to support indexing, it uses a linked list under the hood for preserving order. Linked lists can't do indexing--short of a slow, linear scan, which you usually want to avoid since it tends to turn O(n^2) on you if used in a loop. Here's a simple implementation. It maintains two data structures: a list, preserving the order of items as they're set, and a dict, for quick lookup by key. Both hold the value, and both hold the other's key: the dict holds the index within the list, and the list holds the key within the dict. This makes it easy to reference each data structure from the other, so it can handle both assignment and iteration efficiently. Note that this doesn't implement every operation, just the basic ones: dict-style assignment a['x'] = 1, dict-style lookup a['x'], list-style assignment a.set_value_by_index(0, 1) and list-style lookup a.get_value_by_index(0). Also note carefully: this doesn't use the same syntax for dict-style and list-style operations. That's confusing and evil, and will bite you badly sooner or later. This doesn't turn a[0] into a list-style lookup; if that's what you want, be explicit and use get_value_by_index. Don't be magic and try to guess based on the parameter type. Finally, it provides simple dict-style iteration, yielding the keys as a dict does. Implementing things like iteritems and itervalues or Python3 views are obvious extensions. class IndexableUniqueList(object): """ >>> a = IndexableUniqueList() >>> a['x'] = 1 >>> a['x'] 1 >>> a['y'] = 2 >>> a['y'] 2 >>> a.get_key_by_index(0) 'x' >>> a.get_value_by_index(0) 1 >>> a.get_key_by_index(1) 'y' >>> a.get_value_by_index(1) 2 >>> a['x'] = 3 >>> a.get_key_by_index(0) 'x' >>> a.get_value_by_index(0) 3 >>> a.set_value_by_index(0, 4) >>> a['x'] 4 >>> [val for val in a] ['x', 'y'] """ def __init__(self): self.items_by_index = [] self.items_by_key = {} def __getitem__(self, key): return self.items_by_key[key][1] def __setitem__(self, key, value): if key in self.items_by_key: idx, old_value = self.items_by_key[key] self.items_by_key[key] = (idx, value) self.items_by_index[idx] = (key, value) return idx = len(self.items_by_index) self.items_by_key[key] = (idx, value) self.items_by_index.append((key, value)) def get_key_by_index(self, idx): return self.items_by_index[idx][0] def get_value_by_index(self, idx): key = self.get_key_by_index(idx) return self.items_by_key[key][1] def set_value_by_index(self, idx, value): key = self.items_by_index[idx][0] self[key] = value def __iter__(self): for key, value in self.items_by_index: yield key
Is there any data structure which can avoid duplication, preserve order and random access
Previously, while I am looking for the data structure with the following characteristic. Avoid duplication Iteration order will be same as insertion order In Java, I use LinkHashSet, In Python, I use OrderedDict Now, on the top of 2 requirements, I would like to have an additional requirement Able to random access through indexing, means I can access through data[123] Is there any data structure available? Or I need to fall back to use List? List able to full fill 2nd and 3rd requirement, but not 1st. I may need to perform manual (and slow check) during insertion, to avoid duplication?
[ "A simple approach in Java would be to create a wrapper class that implements both the Set and List interfaces, and that contained both a HashSet and ArrayList. Update operations would need to update both internal collections, and read operations would be mapped to whichever internal collection gives the correct s...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "collections", "java", "python" ]
stackoverflow_0004160929_collections_java_python.txt
Q: twisted+gtk gui crashing very rarely I'm using twisted with gtk (and gtk2reactor). My application crashes in a strange way. So far this is the second time it's crashed in this way. The previous time was about a month ago. These are the errors Python was able to capture in my log file: 2010-11-12 05:23:10,497 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkgc-win32.c:823: SaveDC failed: The operation completed successfully. 2010-11-12 05:23:10,499 ERROR stderr: gtk.main() 2010-11-12 05:23:10,500 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkgc-win32.c:963: RestoreDC failed: The operation completed successfully. 2010-11-12 05:23:10,503 ERROR stderr: gtk.main() 2010-11-12 05:23:10,515 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkdrawable-win32.c:1259: LineTo failed: The operation completed successfully. 2010-11-12 05:23:10,515 ERROR stderr: gtk.main() 2010-11-12 05:23:10,519 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkdrawable-win32.c:1800: GetDC failed: The operation completed successfully. 2010-11-12 05:23:10,519 ERROR stderr: gtk.main() 2010-11-12 05:23:10,519 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkgc-win32.c:961: GetCurrentObject failed: The handle is invalid. 2010-11-12 05:23:10,520 ERROR stderr: gtk.main() 2010-11-12 05:23:10,522 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkgc-win32.c:963: RestoreDC failed: The handle is invalid. 2010-11-12 05:23:10,523 ERROR stderr: gtk.main() 2010-11-12 05:23:10,523 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: _gdk_win32_drawable_release_dc: assertion `impl->hdc_count > 0' failed 2010-11-12 05:23:10,523 ERROR stderr: gtk.main() 2010-11-12 05:23:39,522 DEBUG BHGUIController: Received message 2010-11-12 05:23:39,762 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: PangoWarning: failed to create cairo scaled font, expect ugly output. the offending font is 'Segoe UI Bold 9' 2010-11-12 05:23:39,762 ERROR stderr: gtk.main() 2010-11-12 05:23:39,792 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkpixmap-win32.c:302: CreateDIBSection failed: The parameter is incorrect. 2010-11-12 05:23:39,792 ERROR stderr: gtk.main() 2010-11-12 05:23:39,792 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkpixmap-win32.c:114: DeleteObject failed: The operation completed successfully. 2010-11-12 05:23:39,793 ERROR stderr: gtk.main() 2010-11-12 05:23:39,793 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: _gdk_drawable_ref_cairo_surface: assertion `GDK_IS_DRAWABLE (drawable)' failed 2010-11-12 05:23:39,795 ERROR stderr: gtk.main() Last time a similar series of errors appeared, followed by a segmentation fault. I can't be sure it was the same errors, but something along the lines. I'm using Python 2.5.2, gtk 2.14.1, twisted 8.1.0 . A: These are all very old versions of the software involved. Please upgrade to at least Python 2.6 and Twisted 10.1. I am not sure what the status of GTK+ on Windows is, but I know that there were some bugfixes a couple of years ago, so you should upgrade that as much as possible too.
twisted+gtk gui crashing very rarely
I'm using twisted with gtk (and gtk2reactor). My application crashes in a strange way. So far this is the second time it's crashed in this way. The previous time was about a month ago. These are the errors Python was able to capture in my log file: 2010-11-12 05:23:10,497 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkgc-win32.c:823: SaveDC failed: The operation completed successfully. 2010-11-12 05:23:10,499 ERROR stderr: gtk.main() 2010-11-12 05:23:10,500 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkgc-win32.c:963: RestoreDC failed: The operation completed successfully. 2010-11-12 05:23:10,503 ERROR stderr: gtk.main() 2010-11-12 05:23:10,515 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkdrawable-win32.c:1259: LineTo failed: The operation completed successfully. 2010-11-12 05:23:10,515 ERROR stderr: gtk.main() 2010-11-12 05:23:10,519 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkdrawable-win32.c:1800: GetDC failed: The operation completed successfully. 2010-11-12 05:23:10,519 ERROR stderr: gtk.main() 2010-11-12 05:23:10,519 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkgc-win32.c:961: GetCurrentObject failed: The handle is invalid. 2010-11-12 05:23:10,520 ERROR stderr: gtk.main() 2010-11-12 05:23:10,522 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkgc-win32.c:963: RestoreDC failed: The handle is invalid. 2010-11-12 05:23:10,523 ERROR stderr: gtk.main() 2010-11-12 05:23:10,523 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: _gdk_win32_drawable_release_dc: assertion `impl->hdc_count > 0' failed 2010-11-12 05:23:10,523 ERROR stderr: gtk.main() 2010-11-12 05:23:39,522 DEBUG BHGUIController: Received message 2010-11-12 05:23:39,762 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: PangoWarning: failed to create cairo scaled font, expect ugly output. the offending font is 'Segoe UI Bold 9' 2010-11-12 05:23:39,762 ERROR stderr: gtk.main() 2010-11-12 05:23:39,792 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkpixmap-win32.c:302: CreateDIBSection failed: The parameter is incorrect. 2010-11-12 05:23:39,792 ERROR stderr: gtk.main() 2010-11-12 05:23:39,792 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: gdkpixmap-win32.c:114: DeleteObject failed: The operation completed successfully. 2010-11-12 05:23:39,793 ERROR stderr: gtk.main() 2010-11-12 05:23:39,793 ERROR stderr: C:\Python25\lib\site-packages\twisted\internet\gtk2reactor.py:255: GtkWarning: _gdk_drawable_ref_cairo_surface: assertion `GDK_IS_DRAWABLE (drawable)' failed 2010-11-12 05:23:39,795 ERROR stderr: gtk.main() Last time a similar series of errors appeared, followed by a segmentation fault. I can't be sure it was the same errors, but something along the lines. I'm using Python 2.5.2, gtk 2.14.1, twisted 8.1.0 .
[ "These are all very old versions of the software involved. Please upgrade to at least Python 2.6 and Twisted 10.1. I am not sure what the status of GTK+ on Windows is, but I know that there were some bugfixes a couple of years ago, so you should upgrade that as much as possible too.\n" ]
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python", "segmentation_fault", "twisted" ]
stackoverflow_0004168947_gtk_pygtk_python_segmentation_fault_twisted.txt
Q: Using the argparse output to call functions Currently my code looks like this. It allows me to parse multiple parameters my program script gets. Is there a different way that is closer to 'best practices'? I haven't seen code actually using the output of argparse, only how to set it up. def useArguments(): x = 0 while x <= 5: if x == 0: if args.getweather != None: getWeather(args.getweather) if x == 1: if args.post != None: post(args.post) if x == 2: if args.custompost != None: custompost(args.custompost) if x == 3: if args.list != None: listAccounts(args.list) if x == 4: if args.add != None: addAccount(args.add[0]) if x == 5: if args.edit != None: editAccount(args.edit[0]) x = x + 1 if __name__ == '__main__': updateConfig() parser = argparse.ArgumentParser(description='Post Yahoo weather to Twitter.', epilog="Report any bugs to example@email.com", prog='Program') parser.add_argument('-a', '--add', nargs=1, help='Add a new account. Use the desired account name as an argument.') parser.add_argument('-e', '--edit', nargs=1, choices=accountListSTR[:-1], help='Edit an account. Use the desired account name as an argument.') parser.add_argument('-g', '--getweather', nargs='*', choices=accountListSTR, help='Get weather and post here. Specify account(s) as argument. Use "all" for all accounts. If you specify multiple accounts, separate by a space NOT a comma.') parser.add_argument('-p', '--post', nargs='*', choices=accountListSTR, help='Post weather to Twitter. Specify account(s) as argument. Use "all" for all accounts. If you specify multiple accounts, separate by a space NOT a comma.') parser.add_argument('-c', '--custompost', nargs=2, help='Post a custom message. Specify an account then type the message. Make sure you use "" around the message. Use "all" for all accounts.') parser.add_argument('-l', '--list', action='store_const', const='all', help='List all accounts.') parser.add_argument('--version', action='version', version='%(prog)s 0.3.3') args = parser.parse_args() useArguments() A: You could supply a custom action for an argument by, and I quote: passing an object that implements the Action API. The easiest way to do this is to extend argparse.Action, supplying an appropriate __call__ method. The __call__ method should accept four parameters: parser: The ArgumentParser object which contains this action. namespace: The namespace object that will be returned by parse_args(). Most actions add an attribute to this object. values: The associated command-line args, with any type-conversions applied.(Type-conversions are specified with the type keyword argument to add_argument(). option_string: The option string that was used to invoke this action. The option_string argument is optional, and will be absent if the action is associated with a positional argument. A: See http://docs.python.org/library/argparse.html#sub-commands: One particularly effective way of handling sub-commands is to combine the use of the add_subparsers() method with calls to set_defaults() so that each subparser knows which Python function it should execute. In a nutshell: parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() weather_parser = subparsers.add_parser('get-weather') weather_parser.add_argument('--bar') weather_parser.set_defaults(function=get_weather) # ! args = parser.parse_args(['get-weather', '--bar', 'quux']) print args.function(args) Here we create a subparser for the command get-weather and assign the function get_weather to it. Note that the documentation says that the keyword/attribute is named func but it's definitely function as of argparse 1.1. The resulting code is a bit too wordy so I've published a small package "argh" that makes things simpler, e.g.: parser = argparse.ArgumentParser() add_commands(parser, [get_weather]) print dispatch(parser, ['get-weather', '--bar', 'quux']) "Argh" can do more but I'll let stack overflow answer that. :-) A: With the exception of --version, which is very commonly an option, the actions you've provided are better off treated as "subcommands". I'm unaware of the argparse specifics, as I have yet to try Python 2.7, but you might take a look at the svn command as an example, here's some pseudocode for the command line: myprog [--version] <command> [<command opts>...] Where <command> in: add|edit|getweather|post|custompost|list And <command opts> are options specific to that command. Using optparse (which is similar), this would mean that your command would be returned in args, when calling parse_args, allowing you to do something like this: opts, args = parser.parse_args() if opts.version: ... else: getattr("do_" + args[0])(*args[1:]) I find this pattern particularly useful for debugging, where I'd provide access to internal functions from the command line, and pass various arguments for testing. Adjust the selection of the command handler as appropriate for your own project.
Using the argparse output to call functions
Currently my code looks like this. It allows me to parse multiple parameters my program script gets. Is there a different way that is closer to 'best practices'? I haven't seen code actually using the output of argparse, only how to set it up. def useArguments(): x = 0 while x <= 5: if x == 0: if args.getweather != None: getWeather(args.getweather) if x == 1: if args.post != None: post(args.post) if x == 2: if args.custompost != None: custompost(args.custompost) if x == 3: if args.list != None: listAccounts(args.list) if x == 4: if args.add != None: addAccount(args.add[0]) if x == 5: if args.edit != None: editAccount(args.edit[0]) x = x + 1 if __name__ == '__main__': updateConfig() parser = argparse.ArgumentParser(description='Post Yahoo weather to Twitter.', epilog="Report any bugs to example@email.com", prog='Program') parser.add_argument('-a', '--add', nargs=1, help='Add a new account. Use the desired account name as an argument.') parser.add_argument('-e', '--edit', nargs=1, choices=accountListSTR[:-1], help='Edit an account. Use the desired account name as an argument.') parser.add_argument('-g', '--getweather', nargs='*', choices=accountListSTR, help='Get weather and post here. Specify account(s) as argument. Use "all" for all accounts. If you specify multiple accounts, separate by a space NOT a comma.') parser.add_argument('-p', '--post', nargs='*', choices=accountListSTR, help='Post weather to Twitter. Specify account(s) as argument. Use "all" for all accounts. If you specify multiple accounts, separate by a space NOT a comma.') parser.add_argument('-c', '--custompost', nargs=2, help='Post a custom message. Specify an account then type the message. Make sure you use "" around the message. Use "all" for all accounts.') parser.add_argument('-l', '--list', action='store_const', const='all', help='List all accounts.') parser.add_argument('--version', action='version', version='%(prog)s 0.3.3') args = parser.parse_args() useArguments()
[ "You could supply a custom action for an argument by, and I quote:\n\npassing an object that implements the\n Action API. The easiest way to do this\n is to extend argparse.Action,\n supplying an appropriate __call__\n method. The __call__ method should\n accept four parameters:\n\nparser: The ArgumentParser o...
[ 11, 6, 4 ]
[]
[]
[ "argparse", "arguments", "command_line", "parameters", "python" ]
stackoverflow_0003454934_argparse_arguments_command_line_parameters_python.txt
Q: Where are the layman non-prerequisite introductory materials for everything-testing in Python? This question has been modified If I had to really pick the kind of testing I would like to learn (I have no idea which way this translates to Python) is found here http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd. I don't know if this is agile, extreme or if it's just called TDD. Is this unit testing, doc testing a combination of both or am I missing something? Is there something even better, similar or is this style simply not applicable? I am looking for extreme beginners material on how to do testing (specifically for Python) as described in my link. I am open to ideas and all Python resources. Thanks! I pasted the original message here for reference http://dpaste.com/274603/plain/ A: The simplest thing to start with is Python's unittest module. There are frameworks to do things more automatically later on, but unittest works fine for simple cases. The basic idea is that you have a class for a particular test suite. You define a set of test methods, and optional setUp and tearDown methods to be executed before and after each test in that suite. Within each test, you can use various assert* methods to check that things work. Finally, you call unittest.main() to run all the tests you've defined. Have a look at this example: http://docs.python.org/library/unittest#basic-example A: What resources do you fellas have for starting out in testing in particular to Python? ... What are the most excellent places to start out at, anybody? Step 1. Write less. Step 2. Focus. Step 3. Identify in clear, simple sentences what you are testing. Is it software? What does it do? What architecture does it run on? Specifically list the specific things you're actually going to test. Specific. Focused. Step 4. For one thing you're going to test. One thing. Pick a requirement it must meet. One requirement. I.e., "Given x and y as input, computes z." Looking at your question, I feel you might find this to be very, very hard. But it's central to testing. Indeed, this is all that testing is. You must have something to test. (A "fixture".) You must have requirements against which to test it. (A "TestCase".) You have have measurable pass/fail criteria. (An "assertion".) If you don't have that, you can't test. It helps to write it down in words. Short, focused lists of fixtures, cases and assertions. Short. Focused. Once you've got one requirement, testing is just coding the requirements into a language that asserts the results of each test case. Nothing more. Your unittest.TestCase uses setUp to create a fixture. A TestCase can have one or more test methods to exercise the fixture in different ways. Each test method has one or more assertions about the fixture. Once you have a test case which passes, you can move back to Step 4 and do one more requirement. Once you have all the requirements for a fixture, you go back to Step 3 and do one more fixture. Build up your tests slowly. In pieces. Write less. Focus. A: I like this one and this one too A: Testing is more of an art, and you get better through practice. For myself, I have read this book Pragmatic Unit Testing in C# with NUnit, and I'll really recommend it to you. Although its about .Net and C# and not about Python, you can skip the exact code, but try to understand the principles being taught. It contains good examples about what one should look out for when designing tests. And also, what kind of code should be written that supports the tests-first paradigm. A: Here's a link to C. Titus Brown's Software Carpentry notes on testing: http://ivory.idyll.org/articles/advanced-swc/#testing-your-software It talks basics about testing, including ideas of how to test your code (and retrofitting tests onto existing code). Seems up your alley.
Where are the layman non-prerequisite introductory materials for everything-testing in Python?
This question has been modified If I had to really pick the kind of testing I would like to learn (I have no idea which way this translates to Python) is found here http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd. I don't know if this is agile, extreme or if it's just called TDD. Is this unit testing, doc testing a combination of both or am I missing something? Is there something even better, similar or is this style simply not applicable? I am looking for extreme beginners material on how to do testing (specifically for Python) as described in my link. I am open to ideas and all Python resources. Thanks! I pasted the original message here for reference http://dpaste.com/274603/plain/
[ "The simplest thing to start with is Python's unittest module. There are frameworks to do things more automatically later on, but unittest works fine for simple cases.\nThe basic idea is that you have a class for a particular test suite. You define a set of test methods, and optional setUp and tearDown methods to b...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "testing", "unit_testing" ]
stackoverflow_0004168401_python_testing_unit_testing.txt
Q: Possible to add an object to SQLAlchemy session without explicit session.add()? I have a number of classes that are mapped to tables with SQLAlchemy (non-declaratively if that matters). Because I'd like the application to be unit-testable, all SQLAlchemy session interaction is isolated into a single class. Using the app goes something like this: m = Model("mysql://localhost/mydb") s1 = Service("somename") m.session.add(s1) s1 is m.get_service("somename") # True It's actually more streamlined than that, but work with me here. Is it possible to skip the session.add() step? In other words, if I instantiate a mapped class, is it possible for that be automatically added to the active SQLAlchemy session (if any)? A: In SQLAlchemy you can only do this with tables by binding their metadata to an engine. This does not work with the ORM part of SQLALchemy. http://www.sqlalchemy.org/docs/core/schema.html?highlight=metadata#binding-metadata-to-an-engine-or-connection One approach to this sort of thing is to use a scoped session that can be accessed anywhere. http://www.sqlalchemy.org/docs/orm/session.html?highlight=scoped%20session#sqlalchemy.orm.scoped_session A: Actually, not all the time. If you have defined relationship between child and parent models, or many-to-many relationship, you only have to .add the parent objects explicitly. The child objects are added automatically when assigned the attribute parent, which is always already in db/session. Example: a1 = Author(name='Pynchon') # out of session session.add(a1) # in session b1 = Book(name='Gravity`s Rainbow') # out of session b1.author = a1 #in session a2 = session.query(Author).filter(name='Eco').one() # in session b2 = Book(name='Baudolino') # out of session b2.author = a2 # in session Of course, you need to specify the 'author' relationship between the mappers beforehand.
Possible to add an object to SQLAlchemy session without explicit session.add()?
I have a number of classes that are mapped to tables with SQLAlchemy (non-declaratively if that matters). Because I'd like the application to be unit-testable, all SQLAlchemy session interaction is isolated into a single class. Using the app goes something like this: m = Model("mysql://localhost/mydb") s1 = Service("somename") m.session.add(s1) s1 is m.get_service("somename") # True It's actually more streamlined than that, but work with me here. Is it possible to skip the session.add() step? In other words, if I instantiate a mapped class, is it possible for that be automatically added to the active SQLAlchemy session (if any)?
[ "In SQLAlchemy you can only do this with tables by binding their metadata to an engine. This does not work with the ORM part of SQLALchemy.\nhttp://www.sqlalchemy.org/docs/core/schema.html?highlight=metadata#binding-metadata-to-an-engine-or-connection\nOne approach to this sort of thing is to use a scoped session t...
[ 6, 3 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0004115818_python_sqlalchemy.txt
Q: Install Apache with mod_wsgi to use Python for RESTful web services and Apache for web pages Can anyone help me install Apache with mod_wsgi to run Python for implementation of RESTful Web services. We're trying to get rid of our existing Java REST services with Apache Tomcat. The installation platform is SUSE Linux Enterprise. Please provide a step by step installation procedure with required modules, as I tried it and everytime was missinhg one module or other either in Python installation or Apache installation. I followed the standard Installation steps for all 3, Apache, Python and mod_wsgi, but didn't work out for me. Would this work at all? Do you have any other suggestions? A: Check if mod_wsgi is loaded as a module into the httpd.conf Add apache host that points to a python/wsgi module which contains the 'def application' definition for your web-service. Resolve any path issues that maybe arise from your import handling. If this doesn't work, drop some error-dump here and we'll check. A: Found the solution to the specific thing I was trying: Install apache & apr using YaST2, not by downloading the package from apache.org Install python & python-devel using YaST2, not by downloading the package from python.org Download the rpm package from http://software.opensuse.org/search?lang=en&p=2&q=mod_wsgi for your version of SLES. rpm -i <"packagename">.rpm restart apache : apachetl restart .
Install Apache with mod_wsgi to use Python for RESTful web services and Apache for web pages
Can anyone help me install Apache with mod_wsgi to run Python for implementation of RESTful Web services. We're trying to get rid of our existing Java REST services with Apache Tomcat. The installation platform is SUSE Linux Enterprise. Please provide a step by step installation procedure with required modules, as I tried it and everytime was missinhg one module or other either in Python installation or Apache installation. I followed the standard Installation steps for all 3, Apache, Python and mod_wsgi, but didn't work out for me. Would this work at all? Do you have any other suggestions?
[ "\nCheck if mod_wsgi is loaded as a module into the httpd.conf\nAdd apache host that points to a python/wsgi module which contains the 'def application' definition for your web-service. \nResolve any path issues that maybe arise from your import handling.\n\nIf this doesn't work, drop some error-dump here and we'll...
[ 0, 0 ]
[]
[]
[ "apache", "mod_python", "mod_wsgi", "python", "rest" ]
stackoverflow_0004167684_apache_mod_python_mod_wsgi_python_rest.txt
Q: Writing metadata to a pdf using pyobjc I'm trying to write metadata to a pdf file using the following python code: from Foundation import * from Quartz import * url = NSURL.fileURLWithPath_("test.pdf") pdfdoc = PDFDocument.alloc().initWithURL_(url) assert pdfdoc, "failed to create document" print "reading pdf file" attrs = {} attrs[PDFDocumentTitleAttribute] = "THIS IS THE TITLE" attrs[PDFDocumentAuthorAttribute] = "A. Author and B. Author" PDFDocumentTitleAttribute = "test" pdfdoc.setDocumentAttributes_(attrs) pdfdoc.writeToFile_("mynewfile.pdf") print "pdf made" This appears to work fine (no errors to the consoled), however when I examine the metadata of the file it is as follows: PdfID0: 242b7e252f1d3fdd89b35751b3f72d3 PdfID1: 242b7e252f1d3fdd89b35751b3f72d3 NumberOfPages: 4 and the original file had the following metadata: InfoKey: Creator InfoValue: PScript5.dll Version 5.2.2 InfoKey: Title InfoValue: Microsoft Word - PROGRESS ON THE GABION HOUSE Compressed.doc InfoKey: Producer InfoValue: GPL Ghostscript 8.15 InfoKey: Author InfoValue: PWK InfoKey: ModDate InfoValue: D:20101021193627-05'00' InfoKey: CreationDate InfoValue: D:20101008152350Z PdfID0: d5fd6d3960122ba72117db6c4d46cefa PdfID1: 24bade63285c641b11a8248ada9f19 NumberOfPages: 4 So the problems are, it is not appending the metadata, and it is clearing the previous metadata structure. What do I need to do to get this to work? My objective is to append metadata that reference management systems can import. A: Mark is on the right track, but there are a few peculiarities that should be accounted for. First, he is correct that pdfdoc.documentAttributes is an NSDictionary that contains the document metadata. You would like to modify that, but note that documentAttributes gives you an NSDictionary, which is immutable. You have to convert it to an NSMutableDictionary as follows: attrs = NSMutableDictionary.alloc().initWithDictionary_(pdfDoc.documentAttributes()) Now you can modify attrs as you did. There is no need to write PDFDocument.PDFDocumentTitleAttribute as Mark suggested, that one won't work, PDFDocumentTitleAttribute is declared as a module-level constant, so just do as you did in your own code. Here is the full code that works for me: from Foundation import * from Quartz import * url = NSURL.fileURLWithPath_("test.pdf") pdfdoc = PDFDocument.alloc().initWithURL_(url) attrs = NSMutableDictionary.alloc().initWithDictionary_(pdfdoc.documentAttributes()) attrs[PDFDocumentTitleAttribute] = "THIS IS THE TITLE" attrs[PDFDocumentAuthorAttribute] = "A. Author and B. Author" pdfdoc.setDocumentAttributes_(attrs) pdfdoc.writeToFile_("mynewfile.pdf") A: DISCLAIMER: I'm utterly new to Python, but an old hand at PDF. To avoid smashing all the existing attributes, you need to start attrs with pdfDoc.documentAttributes, not {}. setDocumentAttributes is almost certainly an overwrite rather than a merge (given your output here). Second, all the PDFDocument*Attribute constants are part of PDFDocument. My Python ignorance is undoubtedly showing, but shouldn't you be referencing them as attributes rather than as bare variables? Like this: attrs[PDFDocument.PDFDocumentTitleAttribute] = "THIS IS THE TITLE" That you can assign to PDFDocumentTitleAttribute leads me to believe it's not a constant. If I'm right, your attrs will have tried to assign numerous values to a null key. My Python is weak, so I don't know how you'd check that. Examining attrs prior to calling pdfDoc.setDocumentAttributes_() should be revealing.
Writing metadata to a pdf using pyobjc
I'm trying to write metadata to a pdf file using the following python code: from Foundation import * from Quartz import * url = NSURL.fileURLWithPath_("test.pdf") pdfdoc = PDFDocument.alloc().initWithURL_(url) assert pdfdoc, "failed to create document" print "reading pdf file" attrs = {} attrs[PDFDocumentTitleAttribute] = "THIS IS THE TITLE" attrs[PDFDocumentAuthorAttribute] = "A. Author and B. Author" PDFDocumentTitleAttribute = "test" pdfdoc.setDocumentAttributes_(attrs) pdfdoc.writeToFile_("mynewfile.pdf") print "pdf made" This appears to work fine (no errors to the consoled), however when I examine the metadata of the file it is as follows: PdfID0: 242b7e252f1d3fdd89b35751b3f72d3 PdfID1: 242b7e252f1d3fdd89b35751b3f72d3 NumberOfPages: 4 and the original file had the following metadata: InfoKey: Creator InfoValue: PScript5.dll Version 5.2.2 InfoKey: Title InfoValue: Microsoft Word - PROGRESS ON THE GABION HOUSE Compressed.doc InfoKey: Producer InfoValue: GPL Ghostscript 8.15 InfoKey: Author InfoValue: PWK InfoKey: ModDate InfoValue: D:20101021193627-05'00' InfoKey: CreationDate InfoValue: D:20101008152350Z PdfID0: d5fd6d3960122ba72117db6c4d46cefa PdfID1: 24bade63285c641b11a8248ada9f19 NumberOfPages: 4 So the problems are, it is not appending the metadata, and it is clearing the previous metadata structure. What do I need to do to get this to work? My objective is to append metadata that reference management systems can import.
[ "Mark is on the right track, but there are a few peculiarities that should be accounted for.\nFirst, he is correct that pdfdoc.documentAttributes is an NSDictionary that contains the document metadata. You would like to modify that, but note that documentAttributes gives you an NSDictionary, which is immutable. You...
[ 6, 2 ]
[]
[]
[ "cocoa", "pdf", "pdfkit", "pyobjc", "python" ]
stackoverflow_0004100405_cocoa_pdf_pdfkit_pyobjc_python.txt
Q: How do you do a "hidden" field in Django's forms.Form models? lat = forms.FloatField() How do you make this hidden? A: lat = forms.FloatField(widget=forms.HiddenInput())
How do you do a "hidden" field in Django's forms.Form models?
lat = forms.FloatField() How do you make this hidden?
[ "lat = forms.FloatField(widget=forms.HiddenInput())\n\n" ]
[ 4 ]
[]
[]
[ "django", "forms", "hidden", "python" ]
stackoverflow_0004170031_django_forms_hidden_python.txt
Q: Optimizing python for loops Here are two programs that naively calculate the number of prime numbers <= n. One is in Python and the other is in Java. public class prime{ public static void main(String args[]){ int n = Integer.parseInt(args[0]); int nps = 0; boolean isp; for(int i = 1; i <= n; i++){ isp = true; for(int k = 2; k < i; k++){ if( (i*1.0 / k) == (i/k) ) isp = false; } if(isp){nps++;} } System.out.println(nps); } } `#!/usr/bin/python` import sys n = int(sys.argv[1]) nps = 0 for i in range(1,n+1): isp = True for k in range(2,i): if( (i*1.0 / k) == (i/k) ): isp = False if isp == True: nps = nps + 1 print nps Running them on n=10000 I get the following timings. shell:~$ time python prime.py 10000 && time java prime 10000 1230 real 0m49.833s user 0m49.815s sys 0m0.012s 1230 real 0m1.491s user 0m1.468s sys 0m0.016s Am I using for loops in python in an incorrect manner here or is python actually just this much slower? I'm not looking for an answer that is specifically crafted for calculating primes but rather I am wondering if python code is typically utilized in a smarter fashion. The Java code was compiled with javac 1.6.0_20 Run with java version "1.6.0_18" OpenJDK Runtime Environment (IcedTea6 1.8.1) (6b18-1.8.1-0ubuntu1~9.10.1) OpenJDK Client VM (build 16.0-b13, mixed mode, sharing) Python is: Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) A: As has been pointed out, straight Python really isn't made for this sort of thing. That the prime checking algorithm is naive is also not the point. However, with two simple things I was able to greatly reduce the time in Python while using the original algorithm. First, put everything inside of a function, call it main() or something. This decreased the time on my machine in Python from 20.6 seconds to 14.54 seconds. Doing things globally is slower than doing them in a function. Second, use Psyco, a JIT compiler. This requires adding two lines to the top of the file (and of course having psyco installed): import psyco psyco.full() This brought the final time to 2.77 seconds. One last note. I decided for kicks to use Cython on this and got the time down to 0.8533. However, knowing how to make the few changes to make it fast Cython code isn't something that I recommend for the casual user. A: Yes, Python is slow, about a hundred times slower than C. You can use xrange instead of range for a small speedup, but other than that it's fine. Ultimately what you're doing wrong is that you do this in plain Python, instead of using optimized libraries such as Numpy or Psyco. Java comes with a jit compiler that makes a big difference where you're just crunching numbers. A: You can make your Python about twice as fast by replacing that complicated test with if i % k == 0: isp = False You can also make it about eight times faster (for n=10000) than that by adding a break after that isp = False. Also, do yourself a favor and skip the even numbers (adding one to nps to start to include 2). Finally, you only need k to go up to sqrt(i). Of course, if you make the same changes in the Java, it's still about 10x faster than the optimized Python. A: Boy, when you said it was a naive implementation, you sure weren't joking! But yes, a one to two order of magnitude difference in performance is not unexpected when comparing JIT-compiled, optimized machine code with an interpreted language. An alternative Python implementation such as Jython, which runs on the Java VM, may well be faster for this task; you could give it a whirl. Cython, which allows you to add static typing to Python and get C-like performance in some cases, may be worth investigating as well. Even when considering the standard Python interpreter, CPython, though, the question is: is Python fast enough for the task at hand? Will the time you save writing the code in a dynamic language like Python make up for the extra time spent running it? If you had to write a given program in Java, would it seem like too much work to be worth the trouble? Consider, for example, that a Python program running on a modern computer will be about as fast as a Java program running on a 10-year-old computer. The computer you had ten years ago was fast enough for many things, wasn't it? Python does have a number of features that make it great for numerical work. These include an integer type that supports an unlimited number of digits, a decimal type with unlimited precision, and an optional library called NumPy specifically for calculations. Speed of execution, however, is not generally one of its major claims to fame. Where it excels is in getting the computer to do what you want with minimal cognitive friction. A: If you're looking to do it fast, Python probably isn't the way forward, but you could speed it up a bit. First, you're using quite a slow way to test for divisibility. Modulo is quicker. You can also stop the inner loop (with k) as soon as it detects a match. I'd do something like this: nps = 0 for i in range(1, n+1): if all(i % k for k in range(2, i)): # i.e. if divisible by none of them nps += 1 That brings it down from 25 s to 1.5 s for me. Using xrange brings it down to 0.9 s. You could speed it up further by keeping a list of primes you've already found, and only testing those, rather than every number up to i (if i isn't divisible by 2, it won't be divisible by 4, 6, 8...). A: Why don't you post something about the memory usage - and not just the speed? Trying to get a simple servlet on tomcat is wasting 3GB on my server. What you did with the examples up there is not very good. You need to use numpy. Replace for/range with while loops, thus avoiding the list creation. At last, python is quite suitable for number crunching, at least by people that do it the right way, and know what Sieve of Eratosthenes is, or mod operation is. A: There are lots of things you can do to this algorithm to speed it up, but most of them would also speed up the Java version as well. Some of those will speed up the Python more than the Java, so they're worth testing. Here's just a couple of changes that speed it up from 11.4 to 2.8 seconds on my system: nps = 0 for i in range(1,n+1): isp = True for k in range(2,i): isp = isp and (i % k != 0) if isp: nps = nps + 1 print nps A: Python is a language which, ironically, is well-suited for developing algorithms. Even a modified algorithm like this: # See Thomas K for use of all(), many posters for sqrt optimization nps = 0 for i in xrange(1, n+1): if all(i % k for k in xrange(2, 1 + int(i ** 0.5))): nps += 1 runs in significantly under one second. Code like this: def eras(n): last = n + 1 sieve = [0,0] + range(2, last) sqn = int(round(n ** 0.5)) it = (i for i in xrange(2, sqn + 1) if sieve[i]) for i in it: sieve[i*i:last:i] = [0] * (n//i - i + 1) return filter(None, sieve) is faster still. Or try out these. The thing is, python is usually fast enough for designing your solution. If it is not fast enough for production, use numpy or Jython to goose more performance out of it. Or move it to a compiled language, taking your algorithm observations learned in python with you.
Optimizing python for loops
Here are two programs that naively calculate the number of prime numbers <= n. One is in Python and the other is in Java. public class prime{ public static void main(String args[]){ int n = Integer.parseInt(args[0]); int nps = 0; boolean isp; for(int i = 1; i <= n; i++){ isp = true; for(int k = 2; k < i; k++){ if( (i*1.0 / k) == (i/k) ) isp = false; } if(isp){nps++;} } System.out.println(nps); } } `#!/usr/bin/python` import sys n = int(sys.argv[1]) nps = 0 for i in range(1,n+1): isp = True for k in range(2,i): if( (i*1.0 / k) == (i/k) ): isp = False if isp == True: nps = nps + 1 print nps Running them on n=10000 I get the following timings. shell:~$ time python prime.py 10000 && time java prime 10000 1230 real 0m49.833s user 0m49.815s sys 0m0.012s 1230 real 0m1.491s user 0m1.468s sys 0m0.016s Am I using for loops in python in an incorrect manner here or is python actually just this much slower? I'm not looking for an answer that is specifically crafted for calculating primes but rather I am wondering if python code is typically utilized in a smarter fashion. The Java code was compiled with javac 1.6.0_20 Run with java version "1.6.0_18" OpenJDK Runtime Environment (IcedTea6 1.8.1) (6b18-1.8.1-0ubuntu1~9.10.1) OpenJDK Client VM (build 16.0-b13, mixed mode, sharing) Python is: Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[ "As has been pointed out, straight Python really isn't made for this sort of thing. That the prime checking algorithm is naive is also not the point. However, with two simple things I was able to greatly reduce the time in Python while using the original algorithm.\nFirst, put everything inside of a function, call ...
[ 11, 4, 2, 2, 0, 0, 0, 0 ]
[ "Yes, Python is one of the slowest practical languages you'll encounter. While loops are marginally faster than for i in xrange(), but ultimately Python will always be much, much slower than anything else.\nPython has its place: Prototyping theory and ideas, or in any situation where the ability to produce code fas...
[ -5 ]
[ "python" ]
stackoverflow_0004169828_python.txt
Q: How can I implement encryption between server side in (php/python) and C++ (Win32/Native Windows)? How can I implement encryption between server side in (php/python) and C++ (Win32/Native Windows)? I have to transfer data between server side (using php or python) and client side (C++ using Win32 APIs). I am not sure that what functions/APIs or Libs I can use on the both sides so that both sides should be able to communicate. I am not looking for some complicated public/private key or using https but a simple encryption method. Any help in this regards would be of great help. Thanks in advance! A: Use OpenSSL on client side and OpenSSL on server side. In other way you writing "I am not looking for some complicated" but if you don't want use some complicated then you don't have encryption. Easiest way is use cleartext transmission without encryption, if you searching something like this use for example ROT13 (str_rot13) but this is not give you any encryption.
How can I implement encryption between server side in (php/python) and C++ (Win32/Native Windows)?
How can I implement encryption between server side in (php/python) and C++ (Win32/Native Windows)? I have to transfer data between server side (using php or python) and client side (C++ using Win32 APIs). I am not sure that what functions/APIs or Libs I can use on the both sides so that both sides should be able to communicate. I am not looking for some complicated public/private key or using https but a simple encryption method. Any help in this regards would be of great help. Thanks in advance!
[ "Use OpenSSL on client side and OpenSSL on server side. In other way you writing \"I am not looking for some complicated\" but if you don't want use some complicated then you don't have encryption. Easiest way is use cleartext transmission without encryption, if you searching something like this use for example ROT...
[ 3 ]
[]
[]
[ "c++", "cryptography", "encryption", "php", "python" ]
stackoverflow_0004170135_c++_cryptography_encryption_php_python.txt
Q: git error: cannot spawn .git/hooks/post-commit: No such file or directory I'm trying to write a post-commit hook, I have a Git repository on a mapped drive (V:), msysgit installed in C:\Git, and Python in C:\Python26. I'm running TortoiseGit on Windows 7 64 Bit. The script is: #!C:/Python26/python import sys from subprocess import Popen, PIPE, call GIT_PATH = 'C:\Git\bin\git.exe' BRANCHES = ['master'] TRAC_ENV = 'C:\TRAC_ENV' REPO_NAME = 'core' def call_git(command, args): return Popen([GIT_PATH, command] + args, stdout=PIPE).communicate()[0] def handle_ref(old, new, ref): # If something else than the master branch (or whatever is contained by the # constant BRANCHES) was pushed, skip this ref. if not ref.startswith('refs/heads/') or ref[11:] not in BRANCHES: return # Get the list of hashs for commits in the changeset. args = (old == '0' * 40) and [new] or [new, '^' + old] pending_commits = call_git('rev-list', args).splitlines()[::-1] call(["trac-admin", TRAC_ENV, "changeset", "added", REPO_NAME] + pending_commits) if __name__ == '__main__': for line in sys.stdin: handle_ref(*line.split()) If I run the "git commit..." command from command line, it doesn't seem to even run the hook script at all. A: According to the githooks man page, [The post-commit hook] is invoked by git-commit. It takes no parameter, and is invoked after a commit is made. It takes no parameters. In Python, that means sys.argv[1:] will be an empty list. The man page doesn't say what, if anything, is sent to stdin, but presumably nothing. Let's check that. I made a little git directory and put this in .git/hooks/post-commit: #!/usr/bin/env python import sys def handle_ref(old, new, ref): with open('/tmp/out','w') as f: f.write(old,new,ref) if __name__ == '__main__': with open('/tmp/out','w') as f: f.write('post-commit running') for line in sys.stdin: handle_ref(*line.split()) with open('/tmp/out','w') as f: f.write('Got here') and made it executable. When I make a commit I see the /tmp/out file has been created, but its only contents are post-commit running So the script ran, but the for line in sys.stdin: loop does nothing since nothing is sent to sys.stdin. You're going to need to generate the arguments to send to handle_ref in some other way, perhaps through a subprocess call to some git command.
git error: cannot spawn .git/hooks/post-commit: No such file or directory
I'm trying to write a post-commit hook, I have a Git repository on a mapped drive (V:), msysgit installed in C:\Git, and Python in C:\Python26. I'm running TortoiseGit on Windows 7 64 Bit. The script is: #!C:/Python26/python import sys from subprocess import Popen, PIPE, call GIT_PATH = 'C:\Git\bin\git.exe' BRANCHES = ['master'] TRAC_ENV = 'C:\TRAC_ENV' REPO_NAME = 'core' def call_git(command, args): return Popen([GIT_PATH, command] + args, stdout=PIPE).communicate()[0] def handle_ref(old, new, ref): # If something else than the master branch (or whatever is contained by the # constant BRANCHES) was pushed, skip this ref. if not ref.startswith('refs/heads/') or ref[11:] not in BRANCHES: return # Get the list of hashs for commits in the changeset. args = (old == '0' * 40) and [new] or [new, '^' + old] pending_commits = call_git('rev-list', args).splitlines()[::-1] call(["trac-admin", TRAC_ENV, "changeset", "added", REPO_NAME] + pending_commits) if __name__ == '__main__': for line in sys.stdin: handle_ref(*line.split()) If I run the "git commit..." command from command line, it doesn't seem to even run the hook script at all.
[ "According to the githooks man page,\n\n[The post-commit hook] is invoked by git-commit.\n It takes no parameter, and is invoked\n after a commit is made.\n\nIt takes no parameters. In Python, that means sys.argv[1:] will be an empty list.\nThe man page doesn't say what, if anything, is sent to stdin, but pres...
[ 2 ]
[]
[]
[ "git", "python", "shebang", "tortoisegit", "trac" ]
stackoverflow_0004168739_git_python_shebang_tortoisegit_trac.txt
Q: Django project (apache, mod_wsgi) can't import namespace packages When installing django-piston from the bitbucket repo with pip, I noticed something weird (first indented line of the output): $ pip install hg+http://bitbucket.org/jespern/django-piston Downloading/unpacking hg+http://bitbucket.org/jespern/django-piston Cloning Mercurial repository http://bitbucket.org/jespern/django-piston to /tmp/pip-v1h8Sh-build Running setup.py egg_info for package from hg+http://bitbucket.org/jespern/django-piston Installing collected packages: django-piston Running setup.py install for django-piston Skipping installation of [venv]/lib/python2.6/site-packages/piston/__init__.py (namespace package) Installing [venv]/lib/python2.6/site-packages/django_piston-0.2.3rc1-py2.6-nspkg.pth Successfully installed django-piston Cleaning up Pip won't install piston's __init__.py, indicating that this is because 'piston' is specified as one of the namespace_packages in the setup.py. Further, when I looked inside the "django_piston-0.2.3rc1-nspkg.pth" file, I find this, what seems to be an attempt at "virtual packages": # File: [virtualenv]/lib/python2.6/site-packages/django_piston-0.2.3rc1-py2.6-nspkg.pth # Originally all on one line; broken apart here for readability. import sys,new,os; p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('piston',)); ie = os.path.exists(os.path.join(p,'__init__.py')); m = not ie and sys.modules.setdefault('piston',new.module('piston')); mp = (m or []) and m.__dict__.setdefault('__path__',[]); (p not in mp) and mp.append(p) I can see what it's doing here; it's basically creating a "fake module", where piston should be, which essentially aggregates all of piston's sub-modules. This seems to work fine for command-line work (I can import piston from the django shell [though its repr is <module 'piston' (built-in)>], and things seem to work fine from runserver.), but my project, running on apache mod_wsgi, throws a 500 error on every page, because there's "No module named piston.handler". I've ruled out python path issues; the site-packages dir is in the path for all attempts. I don't know any other reasons why it would behave like this, any ideas? A: After looking some more, I discovered the answer in the docs for mod_wsgi: As an additional step however, the WSGI script file described in the instructions would be modified to overlay the virtual environment for the application on top of the baseline environment. This would be done by adding at the very start of the WSGI script file the following: import site site.addsitedir('/usr/local/pythonenv/PYLONS-1/lib/python2.5/site-packages') Note that in this case the full path to the 'site-packages' directory for the virtual environment needs to be specified and not just the root of the virtual environment. Using 'site.addsitedir()' is a bit different to simply adding the directory to 'sys.path' as the function will open up any '.pth' files located in the directory and process them. This is necessary to ensure that any special directories related to Python eggs are automatically added to 'sys.path'. Adding the site.addsitedir call to my wsgi script (in place of appending to sys.path, as I had been doing) cleared up all the issues.
Django project (apache, mod_wsgi) can't import namespace packages
When installing django-piston from the bitbucket repo with pip, I noticed something weird (first indented line of the output): $ pip install hg+http://bitbucket.org/jespern/django-piston Downloading/unpacking hg+http://bitbucket.org/jespern/django-piston Cloning Mercurial repository http://bitbucket.org/jespern/django-piston to /tmp/pip-v1h8Sh-build Running setup.py egg_info for package from hg+http://bitbucket.org/jespern/django-piston Installing collected packages: django-piston Running setup.py install for django-piston Skipping installation of [venv]/lib/python2.6/site-packages/piston/__init__.py (namespace package) Installing [venv]/lib/python2.6/site-packages/django_piston-0.2.3rc1-py2.6-nspkg.pth Successfully installed django-piston Cleaning up Pip won't install piston's __init__.py, indicating that this is because 'piston' is specified as one of the namespace_packages in the setup.py. Further, when I looked inside the "django_piston-0.2.3rc1-nspkg.pth" file, I find this, what seems to be an attempt at "virtual packages": # File: [virtualenv]/lib/python2.6/site-packages/django_piston-0.2.3rc1-py2.6-nspkg.pth # Originally all on one line; broken apart here for readability. import sys,new,os; p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('piston',)); ie = os.path.exists(os.path.join(p,'__init__.py')); m = not ie and sys.modules.setdefault('piston',new.module('piston')); mp = (m or []) and m.__dict__.setdefault('__path__',[]); (p not in mp) and mp.append(p) I can see what it's doing here; it's basically creating a "fake module", where piston should be, which essentially aggregates all of piston's sub-modules. This seems to work fine for command-line work (I can import piston from the django shell [though its repr is <module 'piston' (built-in)>], and things seem to work fine from runserver.), but my project, running on apache mod_wsgi, throws a 500 error on every page, because there's "No module named piston.handler". I've ruled out python path issues; the site-packages dir is in the path for all attempts. I don't know any other reasons why it would behave like this, any ideas?
[ "After looking some more, I discovered the answer in the docs for mod_wsgi:\n\nAs an additional step however, the WSGI script file described in the instructions would be modified to overlay the virtual environment for the application on top of the baseline environment. This would be done by adding at the very start...
[ 2 ]
[]
[]
[ "apache", "django", "django_piston", "mod_wsgi", "python" ]
stackoverflow_0004170305_apache_django_django_piston_mod_wsgi_python.txt
Q: Tuning mod_wsgi in daemon mode I'm running wsgi application on apache mod_wsgi in daemon mode. I have these lines in the configuration WSGIDaemonProcess app processes=2 threads=3 display-name=%{GROUP} WSGIProcessGroup app How do I find the optimal combination/tuning of processes and threads? EDIT: This link [given in answer bellow] was quite usefull: https://serverfault.com/questions/145617/apache-2-2-mpm-worker-more-threads-or-more-processes/146382#146382 Now, my question is this: If my server gives quite good performance for my needs, should I reduce the number of threads to increase stability / reliability? Can I even set it to 1? A: You might get more information on ServerFault as well. For example: https://serverfault.com/questions/145617/apache-2-2-mpm-worker-more-threads-or-more-processes This is another good resource for the topic: http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading#The_mod_wsgi_Daemon_Processes which briefly describes the options -- including setting threads = 1. I haven't done this yet but it sounds like it doesn't much matter. Supporting multiple threads as well as multiple processors are both well supported. But for my experience level (and probably yours) its worthwhile to eliminate threading as an extra source of concern -- even if it is theoretically rock solid. A: Your best bet is to probably try different bench marks. You can use the apache benchmark command to get a rough estimate at how your configuration is doing. A lot of the tweaking is going to depend on how CPU / IO bound your web app is. The performance is also going to depend on the specs of the server you are hosting on etc.
Tuning mod_wsgi in daemon mode
I'm running wsgi application on apache mod_wsgi in daemon mode. I have these lines in the configuration WSGIDaemonProcess app processes=2 threads=3 display-name=%{GROUP} WSGIProcessGroup app How do I find the optimal combination/tuning of processes and threads? EDIT: This link [given in answer bellow] was quite usefull: https://serverfault.com/questions/145617/apache-2-2-mpm-worker-more-threads-or-more-processes/146382#146382 Now, my question is this: If my server gives quite good performance for my needs, should I reduce the number of threads to increase stability / reliability? Can I even set it to 1?
[ "You might get more information on ServerFault as well. For example: https://serverfault.com/questions/145617/apache-2-2-mpm-worker-more-threads-or-more-processes\nThis is another good resource for the topic: http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading#The_mod_wsgi_Daemon_Processes\nwhich briefly d...
[ 13, 1 ]
[]
[]
[ "apache", "mod_wsgi", "python", "wsgi" ]
stackoverflow_0004165213_apache_mod_wsgi_python_wsgi.txt
Q: How do I validate if an item uploaded to my server is an image or a video? I'd only like to store images and videos. How do I know whether that person uploaded a video or image? How to verify? I'm using Django. A: python-magic looks like a promising place to start. Also, for images at least, I've successfully made use of this snippet.
How do I validate if an item uploaded to my server is an image or a video?
I'd only like to store images and videos. How do I know whether that person uploaded a video or image? How to verify? I'm using Django.
[ "python-magic looks like a promising place to start.\nAlso, for images at least, I've successfully made use of this snippet.\n" ]
[ 0 ]
[]
[]
[ "django", "image", "python", "validation", "video" ]
stackoverflow_0004170403_django_image_python_validation_video.txt
Q: Using sqlite3 to track unit test results I have my own unit testing suite based on the unittest library. I would like to track the history of each test case being run. I would also like to identify after each run tests which flipped from PASS to FAIL or vice versa. I have very little knowledge about databases, but it seems that I could utilize sqlite3 for this task. Are there any existing solutions which integrate unittest and a database? A: Technically, yes. The only thing that you need is some kind of scripting language or shell script that can talk to sqlite. You should think of a database like a file in a file system where you don't have to care about the file format. You just say, here are tables of data, with columns. And each row of that is one record. Much like in a Excel table. So if you are familiar with shell scripts or calling command line tools, you can install sqlite and use the sqlitecommand to interact with the database. Although I think the first thing you should do is to learn basic SQL. There are a lot of SQL tutorials out there.
Using sqlite3 to track unit test results
I have my own unit testing suite based on the unittest library. I would like to track the history of each test case being run. I would also like to identify after each run tests which flipped from PASS to FAIL or vice versa. I have very little knowledge about databases, but it seems that I could utilize sqlite3 for this task. Are there any existing solutions which integrate unittest and a database?
[ "Technically, yes. The only thing that you need is some kind of scripting language or shell script that can talk to sqlite.\nYou should think of a database like a file in a file system where you don't have to care about the file format. You just say, here are tables of data, with columns. And each row of that is on...
[ 0 ]
[]
[]
[ "python", "sqlite", "unit_testing" ]
stackoverflow_0004170442_python_sqlite_unit_testing.txt
Q: Python : Get many list from a list Possible Duplicate: How do you split a list into evenly sized chunks in Python? Hi, I would like to split a list in many list of a length of x elements, like: a = (1, 2, 3, 4, 5) and get : b = ( (1,2), (3,4), (5,) ) if the length is set to 2 or : b = ( (1,2,3), (4,5) ) if the length is equal to 3 ... Is there a nice way to write this ? Otherwise I think the best way is to write it using an iterator ... A: Here's how I'd do it. Iteration, but in a list comprehension. Note the type gets mixed; this may or may not be desired. def sublist(seq, length): return [seq[i:i + length] for i in xrange(0, len(seq), length)] Usage: >>> sublist((1, 2, 3, 4, 5), 1) [(1,), (2,), (3,), (4,), (5,)] >>> sublist([1, 2, 3, 4, 5], 2) [[1, 2], [3, 4], [5]] >>> sublist('12345', 3) ['123', '45'] >>> sublist([1, 2, 3, 4, 5], 73) [[1, 2, 3, 4, 5]] >>> sublist((1, 2, 3, 4, 5), 0) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in sublist ValueError: xrange() arg 3 must not be zero Of course, you can easily make it produce a tuple too if you want - replace the list comprehension [...] with tuple(...). You could also replace seq[i:i + length] with tuple(seq[i:i + length]) or list(seq[i:i + length]) to make it return a fixed type. A: The itertools module documentation. Read it, learn it, love it. Specifically, from the recipes section: import itertools def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return itertools.izip_longest(fillvalue=fillvalue, *args) Which gives: >>> tuple(grouper(3, (1,2,3,4,5))) ((1, 2, 3), (4, 5, None)) which isn't quite what you want...you don't want the None in there...so. a quick fix: >>> tuple(tuple(n for n in t if n) for t in grouper(3, (1,2,3,4,5))) ((1, 2, 3), (4, 5)) If you don't like typing the list comprehension every time, we can move its logic into the function: def my_grouper(n, iterable): "my_grouper(3, 'ABCDEFG') --> ABC DEF G" args = [iter(iterable)] * n return tuple(tuple(n for n in t if n) for t in itertools.izip_longest(*args)) Which gives: >>> tuple(my_grouper(3, (1,2,3,4,5))) ((1, 2, 3), (4, 5)) Done. A: From the python docs on the itertools module: from itertools import izip_longest def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) Example: >>> tuple(grouper(3, (1, 2, 3, 4, 5, 6, 7))) ((1, 2, 3), (4, 5, 6), (7, None, None))
Python : Get many list from a list
Possible Duplicate: How do you split a list into evenly sized chunks in Python? Hi, I would like to split a list in many list of a length of x elements, like: a = (1, 2, 3, 4, 5) and get : b = ( (1,2), (3,4), (5,) ) if the length is set to 2 or : b = ( (1,2,3), (4,5) ) if the length is equal to 3 ... Is there a nice way to write this ? Otherwise I think the best way is to write it using an iterator ...
[ "Here's how I'd do it. Iteration, but in a list comprehension. Note the type gets mixed; this may or may not be desired.\ndef sublist(seq, length):\n return [seq[i:i + length] for i in xrange(0, len(seq), length)]\n\nUsage:\n>>> sublist((1, 2, 3, 4, 5), 1)\n[(1,), (2,), (3,), (4,), (5,)]\n\n>>> sublist([1, 2, 3,...
[ 3, 2, 2 ]
[]
[]
[ "list", "python", "slice" ]
stackoverflow_0004170295_list_python_slice.txt
Q: QTreeView with drag and drop support in PyQt In PyQt 4 I would like to create a QTreeView with possibility to reorganize its structure with drag and drop manipulation. I have implemented my own model(QAbstractItemModel) for QTreeView so my QTreeView properly displays the data. Now I would like to add drag and drop support for tree's nodes to be able to move a node inside the tree from one parent to another one, drag-copy and so on, but I cannot find any complete tutorial how to achieve this. I have found few tutorials and hints for QTreeWidget, but not for QTreeView with custom model. Can someone point me where to look? Thank you. A: You can enable drag and drop support for tree view items by setting QtGui.QAbstractItemView.InternalMove into the dragDropMode property of the treeview control. Also take a look at the documentation here Using drag & drop with item views. Below is a small example of a treeview with internal drag and drop enabled for its items. import sys from PyQt4 import QtGui, QtCore class MainForm(QtGui.QMainWindow): def __init__(self, parent=None): super(MainForm, self).__init__(parent) self.model = QtGui.QStandardItemModel() for k in range(0, 4): parentItem = self.model.invisibleRootItem() for i in range(0, 4): item = QtGui.QStandardItem(QtCore.QString("item %0 %1").arg(k).arg(i)) parentItem.appendRow(item) parentItem = item self.view = QtGui.QTreeView() self.view.setModel(self.model) self.view.setDragDropMode(QtGui.QAbstractItemView.InternalMove) self.setCentralWidget(self.view) def main(): app = QtGui.QApplication(sys.argv) form = MainForm() form.show() app.exec_() if __name__ == '__main__': main() Edit0: treeview + abstract model with drag and drop support import sys from PyQt4 import QtGui, QtCore class TreeModel(QtCore.QAbstractItemModel): def __init__(self): QtCore.QAbstractItemModel.__init__(self) self.nodes = ['node0', 'node1', 'node2'] def index(self, row, column, parent): return self.createIndex(row, column, self.nodes[row]) def parent(self, index): return QtCore.QModelIndex() def rowCount(self, index): if index.internalPointer() in self.nodes: return 0 return len(self.nodes) def columnCount(self, index): return 1 def data(self, index, role): if role == 0: return index.internalPointer() else: return None def supportedDropActions(self): return QtCore.Qt.CopyAction | QtCore.Qt.MoveAction def flags(self, index): if not index.isValid(): return QtCore.Qt.ItemIsEnabled return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | \ QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled def mimeTypes(self): return ['text/xml'] def mimeData(self, indexes): mimedata = QtCore.QMimeData() mimedata.setData('text/xml', 'mimeData') return mimedata def dropMimeData(self, data, action, row, column, parent): print 'dropMimeData %s %s %s %s' % (data.data('text/xml'), action, row, parent) return True class MainForm(QtGui.QMainWindow): def __init__(self, parent=None): super(MainForm, self).__init__(parent) self.treeModel = TreeModel() self.view = QtGui.QTreeView() self.view.setModel(self.treeModel) self.view.setDragDropMode(QtGui.QAbstractItemView.InternalMove) self.setCentralWidget(self.view) def main(): app = QtGui.QApplication(sys.argv) form = MainForm() form.show() app.exec_() if __name__ == '__main__': main() hope this helps, regards
QTreeView with drag and drop support in PyQt
In PyQt 4 I would like to create a QTreeView with possibility to reorganize its structure with drag and drop manipulation. I have implemented my own model(QAbstractItemModel) for QTreeView so my QTreeView properly displays the data. Now I would like to add drag and drop support for tree's nodes to be able to move a node inside the tree from one parent to another one, drag-copy and so on, but I cannot find any complete tutorial how to achieve this. I have found few tutorials and hints for QTreeWidget, but not for QTreeView with custom model. Can someone point me where to look? Thank you.
[ "You can enable drag and drop support for tree view items by setting QtGui.QAbstractItemView.InternalMove into the dragDropMode property of the treeview control. Also take a look at the documentation here Using drag & drop with item views. Below is a small example of a treeview with internal drag and drop enabled f...
[ 19 ]
[]
[]
[ "drag_and_drop", "pyqt", "python", "qtreeview" ]
stackoverflow_0004163740_drag_and_drop_pyqt_python_qtreeview.txt
Q: Poker hand string display I'm brand new to programming and Python and I'm trying my hardest to understand and learn it. I'm not asking for answers but explanations in plain non-computer terms so that i can try to work out the solution myself. Here is one more problem I'm having. I have 4 lists below: short_card = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2'] long_card = ['ace', 'king', 'queen', 'jack', 'ten', 'nine', 'eight', 'seven', 'six', 'five', 'four', 'three', 'deuce'] short_suit = ['c', 'd', 'h', 's'] long_suit = ['clubs', 'diamonds', 'hearts', 'spades'] Now what im supposed to do is write two functions: card_str(c) and hand_str(h). card_str(c) takes a two character string and searches to find out the corresponding characters to display the card in text. For instance if I put 'kh' the program will output "King of Hearts". hand_str(h) takes a list of two character strings and displays the appropriate hand in full text. Again for instance if I put (["Kh", "As", "5d", "2c"]), it will output "King of Hearts, Ace of Spades, Five of Diamonds, Deuce of Clubs". Below is what I have so far: short_card = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2'] long_card = ['ace', 'king', 'queen', 'jack', 'ten', 'nine', 'eight', 'seven', 'six', 'five', 'four', 'three', 'deuce'] short_suit = ['c', 'd', 'h', 's'] long_suit = ['clubs', 'diamonds', 'hearts', 'spades'] def card_str(c): def hand_str(h): #- test harness: do not modify -# for i in range(13): print card_str(short_card[i] + short_suit[i%4]) l = [] for i in range(52): l.append(short_card[i%13] + short_suit[i/13]) print hand_str(l) A: So what you have is two sets of lists, which correlate the input values with the output strings. Note the order of the lists; they're the same. Which should make the index values of the inputs equal to the... A: You don't have much, but I'll say that your lists are in pairs. short_card = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2'] long_card = ['ace', 'king', 'queen', 'jack', 'ten', 'nine', 'eight', 'seven', 'six', 'five', 'four', 'three', 'deuce'] and short_suit = ['c', 'd', 'h', 's'] long_suit = ['clubs', 'diamonds', 'hearts', 'spades'] They're each the same length and in the same order. So the index of 'A' in short_card is the same as the index of 'ace' in long_card. So if you find the index of one, you have the index of the other. This should point you in the right direction. Come back and edit your post when you have more. A: I'd do it slightly differently to the last two posters, and start with the zip function for joining up matching lists. A: >>> def poker_card(c): ... card, suit = c ... short_cards = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2'] ... short_suits = ['c', 'd', 'h', 's'] ... long_cards = ['ace', 'king', 'queen', 'jack', 'ten', 'nine', 'eight', 'seven', 'six', 'five', 'four', 'three', 'deuce'] ... long_suits = ['clubs', 'diamonds', 'hearts', 'spades'] ... return "%s of %s" % (long_cards[short_cards.index(card)], long_suits[short_suits.index(suit)]) ... >>> def poker_hand(hand): ... return [poker_card(c) for c in hand] ... >>> def main(): ... print poker_hand(["Kh", "As", "5d", "2c"]) ... >>> main() ['king of hearts', 'ace of spades', 'five of diamonds', 'deuce of clubs']
Poker hand string display
I'm brand new to programming and Python and I'm trying my hardest to understand and learn it. I'm not asking for answers but explanations in plain non-computer terms so that i can try to work out the solution myself. Here is one more problem I'm having. I have 4 lists below: short_card = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2'] long_card = ['ace', 'king', 'queen', 'jack', 'ten', 'nine', 'eight', 'seven', 'six', 'five', 'four', 'three', 'deuce'] short_suit = ['c', 'd', 'h', 's'] long_suit = ['clubs', 'diamonds', 'hearts', 'spades'] Now what im supposed to do is write two functions: card_str(c) and hand_str(h). card_str(c) takes a two character string and searches to find out the corresponding characters to display the card in text. For instance if I put 'kh' the program will output "King of Hearts". hand_str(h) takes a list of two character strings and displays the appropriate hand in full text. Again for instance if I put (["Kh", "As", "5d", "2c"]), it will output "King of Hearts, Ace of Spades, Five of Diamonds, Deuce of Clubs". Below is what I have so far: short_card = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2'] long_card = ['ace', 'king', 'queen', 'jack', 'ten', 'nine', 'eight', 'seven', 'six', 'five', 'four', 'three', 'deuce'] short_suit = ['c', 'd', 'h', 's'] long_suit = ['clubs', 'diamonds', 'hearts', 'spades'] def card_str(c): def hand_str(h): #- test harness: do not modify -# for i in range(13): print card_str(short_card[i] + short_suit[i%4]) l = [] for i in range(52): l.append(short_card[i%13] + short_suit[i/13]) print hand_str(l)
[ "So what you have is two sets of lists, which correlate the input values with the output strings. Note the order of the lists; they're the same. Which should make the index values of the inputs equal to the...\n", "You don't have much, but I'll say that your lists are in pairs.\nshort_card = ['A', 'K', 'Q', 'J'...
[ 1, 1, 0, 0 ]
[]
[]
[ "list", "python", "search", "string" ]
stackoverflow_0004170238_list_python_search_string.txt
Q: Generate 4000 unique pseudo-random cartesian coordinates FASTER? The range for x and y is from 0 to 99. I am currently doing it like this: excludeFromTrainingSet = [] while len(excludeFromTrainingSet) < 4000: tempX = random.randint(0, 99) tempY = random.randint(0, 99) if [tempX, tempY] not in excludeFromTrainingSet: excludeFromTrainingSet.append([tempX, tempY]) But it takes ages and I really need to speed this up. Any ideas? A: Vincent Savard has an answer that's almost twice as fast as the first solution offered here. Here's my take on it. It requires tuples instead of lists for hashability: def method2(size): ret = set() while len(ret) < size: ret.add((random.randint(0, 99), random.randint(0, 99))) return ret Just make sure that the limit is sane as other answerers have pointed out. For sane input, this is better algorithmically O(n) as opposed to O(n^2) because of the set instead of list. Also, python is much more efficient about loading locals than globals so always put this stuff in a function. EDIT: Actually, I'm not sure that they're O(n) and O(n^2) respectively because of the probabilistic component but the estimations are correct if n is taken as the number of unique elements that they see. They'll both be slower as they approach the total number of available spaces. If you want an amount of points which approaches the total number available, then you might be better off using: import random import itertools def method2(size, min_, max_): range_ = range(min_, max_) points = itertools.product(range_, range_) return random.sample(list(points), size) This will be a memory hog but is sure to be faster as the density of points increases because it avoids looking at the same point more than once. Another option worth profiling (probably better than last one) would be def method3(size, min_, max_): range_ = range(min_, max_) points = list(itertools.product(range_, range_)) N = (max_ - min_)**2 L = N - size i = 1 while i <= L: del points[random.randint(0, N - i)] i += 1 return points A: I'm sure someone is going to come in here with a usage of numpy, but how about using a set and tuple? E.g.: excludeFromTrainingSet = set() while len(excludeFromTrainingSet) < 40000: temp = (random.randint(0, 99), random.randint(0, 99)) if temp not in excludeFromTrainingSet: excludeFromTrainingSet.add(temp) EDIT: Isn't this an infinite loop since there are only 100^2 = 10000 POSSIBLE results, and you're waiting until you get 40000? A: My suggestion : def method2(size): randints = range(0, 100) excludeFromTrainingSet = set() while len(excludeFromTrainingSet) < size: excludeFromTrainingSet.add((random.choice(randints), random.choice(randints))) return excludeFromTrainingSet Instead of generation 2 random numbers every time, you first generate the list of numbers from 0 to 99, then you choose 2 and appends to the list. As others pointed out, there are only 10 000 possibilities so you can't loop until you get 40 000, but you get the point. A: Make a list of all possible (x,y) values: allpairs = list((x,y) for x in xrange(99) for y in xrange(99)) # or with Py2.6 or later: from itertools import product allpairs = list(product(xrange(99),xrange(99))) # or even taking DRY to the extreme allpairs = list(product(*[xrange(99)]*2)) Shuffle the list: from random import shuffle shuffle(allpairs) Read off the first 'n' values: n = 4000 trainingset = allpairs[:n] This runs pretty snappily on my laptop. A: You could make a lookup table of random values... make a random index into that lookup table, and then step through it with a static increment counter... A: Generating 40 thousand numbers inevitably will take a while. But you are performing an O(n) linear search on the excludeFromTrainingSet, which takes quite a while especially later in the process. Use a set instead. You could also consider generating a number of coordinate sets e.g. over night and pickle them, so you don't have to generate new data for each test run (dunno what you're doing, so this might or might not help). Using tuples, as someone noted, is not only the semantically correct choice, it might also help with performance (tuple creation is faster than list creation). Edit: Silly me, using tuples is required when using sets, since set members must be hashable and lists are unhashable. But in your case, your loop isn't terminating because 0..99 is 100 numbers and two-tuples of them have only 100^2 = 10000 unique combinations. Fix that, then apply the above. A: Taking Vince Savard's code: >>> from random import choice >>> def method2(size): ... randints = range(0, 100) ... excludeFromTrainingSet = set() ... while True: ... x = size - len(excludeFromTrainingSet) ... if not x: ... break ... else: ... excludeFromTrainingSet.add((choice(randints), choice(randints)) for _ in range(x)) ... return excludeFromTrainingSet ... >>> s = method2(4000) >>> len(s) 4000 This is not a great algorithm because it has to deal with collisions, but the tuple-generation makes it tolerable. This runs in about a second on my laptop. A: ## for py 3.0+ ## generate 4000 points in 2D ## import random maxn = 10000 goodguys = 0 excluded = [0 for excl in range(0, maxn)] for ntimes in range(0, maxn): alea = random.randint(0, maxn - 1) excluded[alea] += 1 if(excluded[alea] > 1): continue goodguys += 1 if goodguys > 4000: break two_num = divmod(alea, 100) ## Unfold the 2 numbers print(two_num)
Generate 4000 unique pseudo-random cartesian coordinates FASTER?
The range for x and y is from 0 to 99. I am currently doing it like this: excludeFromTrainingSet = [] while len(excludeFromTrainingSet) < 4000: tempX = random.randint(0, 99) tempY = random.randint(0, 99) if [tempX, tempY] not in excludeFromTrainingSet: excludeFromTrainingSet.append([tempX, tempY]) But it takes ages and I really need to speed this up. Any ideas?
[ "Vincent Savard has an answer that's almost twice as fast as the first solution offered here.\n\nHere's my take on it. It requires tuples instead of lists for hashability:\ndef method2(size):\n ret = set()\n while len(ret) < size:\n ret.add((random.randint(0, 99), random.randint(0, 99)))\n return re...
[ 6, 4, 4, 4, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004170054_python.txt
Q: Suggestions for improving this little piece of code? Any suggestions to improve this little piece of code? It works, but there must be a better way of doing it. Especially the first two lines, I have a bunch of them. Can't I merge the two somehow? for iso in set(BAR_Items): if iso+YEAR in heights: mylist.append(heights[iso+YEAR]) mylist.sort() cut = percentile(mylist, POS) Thanks A: The first three lines can be written concisely as a list comprehension. mylist += [heights[iso+YEAR] for iso in set(BAR_Items) if iso+YEAR in heights]
Suggestions for improving this little piece of code?
Any suggestions to improve this little piece of code? It works, but there must be a better way of doing it. Especially the first two lines, I have a bunch of them. Can't I merge the two somehow? for iso in set(BAR_Items): if iso+YEAR in heights: mylist.append(heights[iso+YEAR]) mylist.sort() cut = percentile(mylist, POS) Thanks
[ "The first three lines can be written concisely as a list comprehension.\nmylist += [heights[iso+YEAR] for iso in set(BAR_Items) if iso+YEAR in heights] \n\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0004170646_python.txt
Q: How do you check the mimetype of a file uploaded to your server? it's just a user upload a file. A: UploadedFile.content_type will return the content-type header that was sent with the file when uploaded at the time of upload. If you also need to check files after they are saved you can use the mimetypes module in python. But it appears to only check based on the file extension. import mimetypes file_type, file_encoding = mimetypes.guess_type('/path/to/file') print 'File-type: %s\nFile-encoding: %s' % (file_type, file_encoding) And if you have file-type requirements that are not detected by default you can add the types to mimetypes simply too before using guess_type: mimetypes.add_type('font/ttf', '.ttf') A: UploadedFile.content_type Check http://docs.djangoproject.com/en/dev/topics/http/file-uploads/?from=olddocs for more info
How do you check the mimetype of a file uploaded to your server?
it's just a user upload a file.
[ "UploadedFile.content_type will return the content-type header that was sent with the file when uploaded at the time of upload.\nIf you also need to check files after they are saved you can use the mimetypes module in python. But it appears to only check based on the file extension.\nimport mimetypes\nfile_type, fi...
[ 3, 2 ]
[]
[]
[ "django", "file", "linux", "python", "unix" ]
stackoverflow_0004170637_django_file_linux_python_unix.txt
Q: Python sqlite3: UPDATE failure claims "no such column" The following script evokes the following exception in the UPDATE command. What I think should happen for this simple UPDATE command is that the value of db_2.foo.bar should be doubled from 1 to 2. My guess is that I have some subtle syntax error in the UPDATE statement (or else a bug at the Python or sqlite3 level); however, I've pored over the sqlite3 documentation -- especially the "UPDATE" and "expression" pages -- and don't see that I'm doing anything wrong. db_1.foo_bar= (1,) Traceback (most recent call last): File "try2.py", line 29, in <module> db_2.execute( 'UPDATE foo SET bar = bar + db_1.foo.bar WHERE rowid = db_1.foo.rowid' ) sqlite3.OperationalError: no such column: db_1.foo.bar Any suggestions or workarounds? import sqlite3 # Create db_1, populate it and close it: open( 'db_1.sqlite', 'w+' ) db_1 = sqlite3.connect( 'db_1.sqlite' ) db_1.execute( 'CREATE TABLE foo(bar INTEGER)' ) db_1.execute( 'INSERT INTO foo (bar) VALUES (1)' ) db_1.commit() db_1.close() # Create db_2: open( 'db_2.sqlite', 'w+' ) db_2 = sqlite3.connect( 'db_2.sqlite' ) db_2.execute( 'CREATE TABLE foo(bar INTEGER)' ) # Attach db_1 to db_2 connection: db_2.execute( 'ATTACH "db_1.sqlite" AS db_1' ) # Populate db_2 from db_1: db_2.execute( 'INSERT INTO foo SELECT ALL * FROM db_1.foo' ) # Show that db_1.foo.bar exists: cur_2 = db_2.cursor() cur_2.execute( 'SELECT bar from db_1.foo' ) for result in cur_2.fetchall(): print 'db_1.foo_bar=', result # However, the following claims that db_1.foo.bar does not exist: db_2.execute( 'UPDATE foo SET bar = bar + db_1.foo.bar WHERE rowid = db_1.foo.rowid' ) db_2.execute( 'DETACH db_1') db_2.commit() db_2.close() A: To update foo with values from a different table, you can use a nested SELECT expression. Note that foo.rowid refers to the rowid of the outer table, while t.rowid refers to the rowid of the inner table: cur_2.execute( '''\ UPDATE foo SET bar = bar + IFNULL( (SELECT t.bar FROM db_1.foo AS t WHERE foo.rowid = t.rowid), 0)''' ) To test that the proper rowids are indeed being matched together, I modified your code a bit so the rowids of db_1.foo do not match the rowids of db_2.foo: import sqlite3 # Create db_1, populate it and close it: open( 'db_1.sqlite', 'w+' ) db_1 = sqlite3.connect( 'db_1.sqlite' ) db_1.execute( 'CREATE TABLE foo(bar INTEGER)' ) db_1.execute( 'INSERT INTO foo (rowid,bar) VALUES (2,1)' ) db_1.execute( 'INSERT INTO foo (rowid,bar) VALUES (3,2)' ) db_1.commit() db_1.close() # Create db_2: open( 'db_2.sqlite', 'w+' ) db_2 = sqlite3.connect( 'db_2.sqlite' ) cur_2 = db_2.cursor() cur_2.execute( 'CREATE TABLE foo(bar INTEGER)' ) # Attach db_1 to db_2 connection: cur_2.execute( 'ATTACH "db_1.sqlite" AS db_1' ) # Populate db_2 from db_1: cur_2.execute( 'INSERT INTO foo SELECT * FROM db_1.foo' ) Note the rowids of foo are 1 and 2: cur_2.execute( 'SELECT rowid,bar from foo' ) for result in cur_2.fetchall(): print('foo: {0}'.format(result)) # foo: (1, 1) # foo: (2, 2) Note the rowids of db_1.foo are 2 and 3: # Show that db_1.foo.bar exists: cur_2.execute( 'SELECT rowid,bar from db_1.foo' ) for result in cur_2.fetchall(): print('db_1.foo: {0}'.format(result)) # db_1.foo: (2, 1) # db_1.foo: (3, 2) cur_2.execute( '''\ UPDATE foo SET bar = bar + IFNULL( (SELECT t.bar FROM db_1.foo AS t WHERE foo.rowid = t.rowid), 0)''' ) After the UPDATE, the row with rowid = 1 has not changed, while the row with rowid = 2 has been updated. cur_2.execute( 'SELECT rowid,bar from foo' ) for result in cur_2.fetchall(): print('foo after update: {0} '.format(result)) # foo after update: (1, 1) # foo after update: (2, 3) cur_2.execute('DETACH db_1') db_2.commit() db_2.close() I found these pages helpful in constructing this answer: here and here, though any mistakes are of course my own. A: Hmmm... the problem may very well be that I am looking at the 3.7.3 documentation, whereas my installed version is 3.6.16. Investigating.
Python sqlite3: UPDATE failure claims "no such column"
The following script evokes the following exception in the UPDATE command. What I think should happen for this simple UPDATE command is that the value of db_2.foo.bar should be doubled from 1 to 2. My guess is that I have some subtle syntax error in the UPDATE statement (or else a bug at the Python or sqlite3 level); however, I've pored over the sqlite3 documentation -- especially the "UPDATE" and "expression" pages -- and don't see that I'm doing anything wrong. db_1.foo_bar= (1,) Traceback (most recent call last): File "try2.py", line 29, in <module> db_2.execute( 'UPDATE foo SET bar = bar + db_1.foo.bar WHERE rowid = db_1.foo.rowid' ) sqlite3.OperationalError: no such column: db_1.foo.bar Any suggestions or workarounds? import sqlite3 # Create db_1, populate it and close it: open( 'db_1.sqlite', 'w+' ) db_1 = sqlite3.connect( 'db_1.sqlite' ) db_1.execute( 'CREATE TABLE foo(bar INTEGER)' ) db_1.execute( 'INSERT INTO foo (bar) VALUES (1)' ) db_1.commit() db_1.close() # Create db_2: open( 'db_2.sqlite', 'w+' ) db_2 = sqlite3.connect( 'db_2.sqlite' ) db_2.execute( 'CREATE TABLE foo(bar INTEGER)' ) # Attach db_1 to db_2 connection: db_2.execute( 'ATTACH "db_1.sqlite" AS db_1' ) # Populate db_2 from db_1: db_2.execute( 'INSERT INTO foo SELECT ALL * FROM db_1.foo' ) # Show that db_1.foo.bar exists: cur_2 = db_2.cursor() cur_2.execute( 'SELECT bar from db_1.foo' ) for result in cur_2.fetchall(): print 'db_1.foo_bar=', result # However, the following claims that db_1.foo.bar does not exist: db_2.execute( 'UPDATE foo SET bar = bar + db_1.foo.bar WHERE rowid = db_1.foo.rowid' ) db_2.execute( 'DETACH db_1') db_2.commit() db_2.close()
[ "To update foo with values from a different table, you can use a nested SELECT expression. Note that foo.rowid refers to the rowid of the outer table, while t.rowid refers to the rowid of the inner table:\ncur_2.execute( '''\\\n UPDATE foo SET bar = bar +\n IFNULL( (SELECT t.bar \n FROM db...
[ 1, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0004170171_python_sqlite.txt
Q: Why would one use an egg over an sdist? About the only reason I can think of to distribute a python package as an egg is so that you can not include the .py files with your package (and only include .pyc files, which is a dubious way to protect your code anyway). Aside from that, I can't really think of any reason to upload a package as an egg rather than an sdist. In fact, pip doesn't even support eggs. Is there any real reason to use an egg rather than an sdist? A: One reason: eggs can include compiled C extension modules so that the end user does not need to have the necessary build tools and possible additional headers and libraries to build the extension module from scratch. The drawback to that is that the packager may need to supply multiple eggs to match each targeted platform and Python configuration. If there are many supported configurations, that can prove to be a daunting task but it can be effective for more homogenous environments.
Why would one use an egg over an sdist?
About the only reason I can think of to distribute a python package as an egg is so that you can not include the .py files with your package (and only include .pyc files, which is a dubious way to protect your code anyway). Aside from that, I can't really think of any reason to upload a package as an egg rather than an sdist. In fact, pip doesn't even support eggs. Is there any real reason to use an egg rather than an sdist?
[ "One reason: eggs can include compiled C extension modules so that the end user does not need to have the necessary build tools and possible additional headers and libraries to build the extension module from scratch. The drawback to that is that the packager may need to supply multiple eggs to match each targeted...
[ 3 ]
[]
[]
[ "egg", "packaging", "python", "sdist" ]
stackoverflow_0004170477_egg_packaging_python_sdist.txt
Q: Python Templating and Ajax I was not able to come up with a better title for this post, so if anybody does not find it appropriate , please go ahead and edit it. I am using flask as my python framework, and normally I render templates doing somnething like the below:- @app.route('/home') def userhome(): data=go get user details from the database return render_template("home.html",userdata=data) Now I have a template name home.html in which I iterate over the values of "userdata" like userdata.name, userdata.age etc and these values take their appropriate spaces in the template. However I am working on an application in which navigation is via ajax and no fall back if javascript is not available(basically the app does not work for ppl without javascript). The navigation menu has say few tabs on the left ,(home,youroffers,yourlastreads). The right column is supposed to dynamically change based on what the user clicks. I am unable to understand how I handle templating here. Based on what the user clicks I can send him the required data from the db via a json through an xhrGET or xhrPOST.Does the entire templating have to be handled at the server end and then transfer the entire template via an ajax call. I actually dont like that idea much. Would be great if someone could point me in the right direction here. Now in the page that is loaded via ajax , there are some scripts which are present. Will these scripts work, if loaded via ajax. A: You have two options: template on the server, or template in the browser. To template in the server, you create an endpoint much like you already have, except the template only creates a portion of the page. Then you hit the URL with an Ajax call, and insert the returned HTML somewhere into your page. To template in the browser, your endpoint creates a JSON response. Then a Javascript templating library can take that JSON, create HTML from it, and insert it into the page. There are lots of jQuery templating solutions, for example. A: I would choose server side templating, because unless you find a JS library that handles the same templating language your code isn't going go be DRY. In the home.html template, I'd do something like <%extends base.html%> <%include _user_details.html%> ... <% footer and other stuff%> And keep the actual markup in _user_details.html. This way, for an AJAX request you just render the _user_details.html partial only.
Python Templating and Ajax
I was not able to come up with a better title for this post, so if anybody does not find it appropriate , please go ahead and edit it. I am using flask as my python framework, and normally I render templates doing somnething like the below:- @app.route('/home') def userhome(): data=go get user details from the database return render_template("home.html",userdata=data) Now I have a template name home.html in which I iterate over the values of "userdata" like userdata.name, userdata.age etc and these values take their appropriate spaces in the template. However I am working on an application in which navigation is via ajax and no fall back if javascript is not available(basically the app does not work for ppl without javascript). The navigation menu has say few tabs on the left ,(home,youroffers,yourlastreads). The right column is supposed to dynamically change based on what the user clicks. I am unable to understand how I handle templating here. Based on what the user clicks I can send him the required data from the db via a json through an xhrGET or xhrPOST.Does the entire templating have to be handled at the server end and then transfer the entire template via an ajax call. I actually dont like that idea much. Would be great if someone could point me in the right direction here. Now in the page that is loaded via ajax , there are some scripts which are present. Will these scripts work, if loaded via ajax.
[ "You have two options: template on the server, or template in the browser.\nTo template in the server, you create an endpoint much like you already have, except the template only creates a portion of the page. Then you hit the URL with an Ajax call, and insert the returned HTML somewhere into your page.\nTo templa...
[ 3, 2 ]
[]
[]
[ "ajax", "jquery", "python" ]
stackoverflow_0004170532_ajax_jquery_python.txt
Q: Python Card Display Possible Duplicate: Poker hand string display hi all im having a bit of a hard time figuring this question out . so if i can get any help i would greatly appreciate it. the question is ; Create functions card_str(c) and hand_str(h) which return a string version of a card and a hand of cards, respectively. A card is a string of two characters: a rank followed by a suit. A hand is a list of cards. >>> print card_str("Kh") king of hearts >>> print hand_str([’Kh’, ’As’, ’5d’, ’2c’]) king of hearts, ace of spades, five of diamonds, deuce of clubs Thanks for your time and explaining. A: For card_str(c), you need to convert a combination of value and suit ('Kh', for example), and convert it into a longer string. You'll need to create lists that contain: A dictionary mapping short values (e.g. 'K' or 'A' to long names, 'King' and 'Ace') A dict mapping short suit names to full name ('c' goes to clubs, etc.) You can then then return valdict[c[0]] + 'of' + suitdict[c[1]] (the first element in the argument's long value name + the second element in the argument's long suit name). For hand_str(c), take the list of card names you have, and construct a new list by iterating through c and calling hand_str on each element of c. Then return your new list. Since this is homework, I'll leave the implementation to you. If you get stuck, check out the Python docs. A: Have you used python dictionaries before? I might try something like follows. rank_dict = {"A" : "Ace", "K" : "King", "Q" : "Queen", "J" : "Jack",....} suit_dict = {"h" : "Hearts", "s" : "Spades", "c" : "Clubs", "d" : "Diamonds"} Then you can do something like follows. card_string = "Kh" print(rank_dict[card_string[0:1]] + " of " + suit_dict[card_string[1:]]) A: A good place to get started would be to write out some or all of the input-output pairs. So you might begin with: Kh king of hearts As ace of spades ... Once you have that table, you'll be able to find the commonalities; the pattern. Once you find that, code it up!
Python Card Display
Possible Duplicate: Poker hand string display hi all im having a bit of a hard time figuring this question out . so if i can get any help i would greatly appreciate it. the question is ; Create functions card_str(c) and hand_str(h) which return a string version of a card and a hand of cards, respectively. A card is a string of two characters: a rank followed by a suit. A hand is a list of cards. >>> print card_str("Kh") king of hearts >>> print hand_str([’Kh’, ’As’, ’5d’, ’2c’]) king of hearts, ace of spades, five of diamonds, deuce of clubs Thanks for your time and explaining.
[ "For card_str(c), you need to convert a combination of value and suit ('Kh', for example), and convert it into a longer string. You'll need to create lists that contain:\n\nA dictionary mapping short values (e.g. 'K' or 'A' to long names, 'King' and 'Ace')\nA dict mapping short suit names to full name ('c' goes to ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004170945_python.txt
Q: Is there a Django "app" that can manage your users' profiles? "My Profile", notification options, settings ...The checkbox stuff... I'm familiar with Pinax, but is there a specific app that manages just profiles and accounts? I don't want the other heavy stuff associated with social networking...I only want the profile account management A: There is django-profiles: http://bitbucket.org/ubernostrum/django-profiles/wiki/Home A: Another one, I haven't used either this or the one Mike posted, so caveat emptor. (What's Latin for 'downloader'? ;) http://code.google.com/p/django-profile/
Is there a Django "app" that can manage your users' profiles?
"My Profile", notification options, settings ...The checkbox stuff... I'm familiar with Pinax, but is there a specific app that manages just profiles and accounts? I don't want the other heavy stuff associated with social networking...I only want the profile account management
[ "There is django-profiles:\nhttp://bitbucket.org/ubernostrum/django-profiles/wiki/Home\n", "Another one, I haven't used either this or the one Mike posted, so caveat emptor. (What's Latin for 'downloader'? ;)\nhttp://code.google.com/p/django-profile/\n" ]
[ 1, 0 ]
[]
[]
[ "django", "pinax", "profile", "python" ]
stackoverflow_0004171083_django_pinax_profile_python.txt
Q: What is the best way to distribute code across servers? I have a directory of python programs, classes and packages that I currently distribute to 5 servers. It seems I'm continually going to be adding more servers and right now I'm just doing a basic rsync over from my local box to the servers. What would a better approach be for distributing code across n servers? thanks A: I use Mercurial with fabric to deploy all the source code. Fabric's written in python, so it'll be easy for you to get started. Updating the production service is as simple as fab production deploy. Which ends ups doing something like this: Shut down all the services and put an "Upgrade in Progress" page. Update the source code directory. Run all migrations. Start up all services. It's pretty awesome seeing this all happen automatically. A: First, make sure to keep all code under revision control (if you're not already doing that), so that you can check out new versions of the code from a repository instead of having to copy it to the servers from your workstation. With revision control in place you can use a tool such as Capistrano to automatically check out the code on each server without having to log in to each machine and do a manual checkout. With such a setup, deploying a new version to all servers can be as simple as running $ cap deploy from your local machine. A: While I also use version control to do this, another approach you might consider is to package up the source using whatever package management your host systems use (for example RPMs or dpkgs), and set up the systems to use a custom repository Then an "apt-get upgrade" or "yum update" will update the software on the systems. Then you could use something like "mussh" to run the stop/update/start commands on all the tools. Ideally, you'd push it to a "testing" repository first, have your staging systems install it, and once the testing of that was signed off on you could move it to the production repository. It's very similar to the recommendations of using fabric or version control in general, just another alternative which may suit some people better. The downside to using packages is that you're probably using version control anyway, and you do have to manage version numbers of these packages. I do this using revision tags within my version control, so I could just as easily do an "svn update" or similar on the destination systems. In either case, you may need to consider the migration from one version to the next. If a user loads a page that contains references to other elements, you do the update and those elements go away, what do you do? You may wish to do something either within your deployment scripting, or within your code where you first push out a version with the new page, but keep the old referenced elements, deploy that, and then remove the referenced elements and deploy that later. In this way users won't see broken elements within the page.
What is the best way to distribute code across servers?
I have a directory of python programs, classes and packages that I currently distribute to 5 servers. It seems I'm continually going to be adding more servers and right now I'm just doing a basic rsync over from my local box to the servers. What would a better approach be for distributing code across n servers? thanks
[ "I use Mercurial with fabric to deploy all the source code. Fabric's written in python, so it'll be easy for you to get started. Updating the production service is as simple as fab production deploy. Which ends ups doing something like this:\n\nShut down all the services and put an \"Upgrade in Progress\" page.\n...
[ 4, 1, 0 ]
[]
[]
[ "python", "software_distribution" ]
stackoverflow_0003073429_python_software_distribution.txt
Q: Is there a way to display any media, regardless of type? (especially in Django?) If I have a .mp4 file, it will automatically display a video (flash?) If it's a jpg, it'll just display the image... Edit: I want this embedded inside a webpage. A: As eternicode says, all you need to do is make your views the normal way and pass the querysets to your template. In the template , all you need to do is load the content from your query as part of /media as defined in your settings.py e.g <img src="/media/{{model.object}}" width="135" height="60" alt="thumbnail" /> A: You need specify the "Content-Type" in the http response header. A: no, you must have file view generator, thats mean you have list of pic and video and then for each file generate correct player and tag its easy
Is there a way to display any media, regardless of type? (especially in Django?)
If I have a .mp4 file, it will automatically display a video (flash?) If it's a jpg, it'll just display the image... Edit: I want this embedded inside a webpage.
[ "As eternicode says, all you need to do is make your views the normal way and pass the querysets to your template. \nIn the template , all you need to do is load the content from your query as part of /media as defined in your settings.py e.g \n<img src=\"/media/{{model.object}}\" width=\"135\" height=\"60\" alt=\"...
[ 1, 0, 0 ]
[]
[]
[ "django", "image", "javascript", "python", "video" ]
stackoverflow_0004171255_django_image_javascript_python_video.txt
Q: How to create a well-formatted word document(.DOC) in python on Linux? I want to create new work document from sketch with Python on Linux platform, but do not know how to do that. I do not willing to use RTF or use pythondocx to create docx document. Is there any other way to do so? Remember, I need the document keeps the formatting. Thanks everyone's help! A: The Python docx module allows you to do what you want. It is perfect for you and is as simple as working with any other Python library. A: Openoffice has some Python scripting ability. I only heard about it, haven't studied it nor used it.
How to create a well-formatted word document(.DOC) in python on Linux?
I want to create new work document from sketch with Python on Linux platform, but do not know how to do that. I do not willing to use RTF or use pythondocx to create docx document. Is there any other way to do so? Remember, I need the document keeps the formatting. Thanks everyone's help!
[ "The Python docx module allows you to do what you want. It is perfect for you and is as simple as working with any other Python library.\n", "Openoffice has some Python scripting ability. I only heard about it, haven't studied it nor used it.\n" ]
[ 2, 1 ]
[]
[]
[ "linux", "ms_word", "python" ]
stackoverflow_0004171555_linux_ms_word_python.txt
Q: What builtin functions shouldn't be run by untrusted users? I'm creating a corewars type application that runs on django and allows a user to upload some python code that will control their character. Now, I know the real answer to this is that as long as I'm taking code input from untrusted users I'll have security vulnerabilities. I'm just trying to minimize the risk as much as possible. Here are some that spring to mind: __import__ (I'll probably also do some ast scanning to make sure there aren't any import statements) open file input raw_input Are there any others I'm missing? A: There are lots of answers on what to do in general about restricting Python at http://wiki.python.org/moin/SandboxedPython. When I looked at it some time ago, the Zope RestrictedPython looked the best solution, working with a whitelist system. You'll still need to take care in your own code so that you don't expose any security vulnerabilities, but that seems to be the best system out there. A: You will really need to avoid eval. Imagine code such as: eval("__impor" + "t__('whatever').destroy_your_server") This is probably the most important one. A: Since you sound determined to do this, I'll link you to the standard rexec module, not because I think you should use it (don't - it has known vulnerabilities), but because it might be a good starting point for getting your webserver compromised your own restricted-execution framework. In particular, under the heading "Defining restricted environments" several modules and functions are listed that were considered reasonably safe by the rexec designer; these might be usable as an initial whitelist of sorts. I'd also suggest examining its code for other gotchas you might not have thought of. A: Yeah, you have to whitelist. There are so many ways to hide the bad commands. This is NOT the worst case scenario: the worst case scenario is that someone gets into the database The worst case scenario is getting the entire machine rooted and you not noticing as it probes your other machines and keylogs your passwords. Isolate this machine and consider it hostile (DMZ, block it from being able to launch attacks internally and externally, etc). Run tripwire or AIDE on non-writeable media and log everything to a second host. Finally, as plash shows, there are a lot of dangerous system calls that need to be protected against. A: You should use a whitelist, rather than a blacklist. If you use a blacklist, you will always miss something. Even if you don't, Python will add a function to the standard library, and you won't update your blacklist in time. Things you're currently allowing but probably should not include: compile eval reload (if they do access the filesystem somehow, this is basically import) I agree that this would be very tricky to do correctly. One complication (among many) could be a user accessing one of these functions through a field in another class. I would consider using another isolation mechanism, such as a virtual machine, instead or in addition to this. You might look at how codepad does it. A: If you're not committed to using Python as the language inside the game, one possibility would be to embed Lua using LunaticPython (I suggest the bugfixes branch at https://code.launchpad.net/~dne/lunatic-python/bugfixes). It's much easier to sandbox Lua than Python, and it's much easier to embed Lua than to create your own programming language.
What builtin functions shouldn't be run by untrusted users?
I'm creating a corewars type application that runs on django and allows a user to upload some python code that will control their character. Now, I know the real answer to this is that as long as I'm taking code input from untrusted users I'll have security vulnerabilities. I'm just trying to minimize the risk as much as possible. Here are some that spring to mind: __import__ (I'll probably also do some ast scanning to make sure there aren't any import statements) open file input raw_input Are there any others I'm missing?
[ "There are lots of answers on what to do in general about restricting Python at http://wiki.python.org/moin/SandboxedPython. When I looked at it some time ago, the Zope RestrictedPython looked the best solution, working with a whitelist system. You'll still need to take care in your own code so that you don't expos...
[ 3, 2, 2, 2, 1, 1 ]
[]
[]
[ "built_in", "exec", "python" ]
stackoverflow_0004170639_built_in_exec_python.txt
Q: wxPython Geometry problem I'm trying to get the button to be right of the label. I set the tuple and am still not sure why it covers the label. Also is there a good tutorial available on wxpython geometry? import wx import wx.lib.agw.gradientbutton as GB def GetRoundBitmap( w, h, r ): maskColor = wx.Color(0,0,0) shownColor = wx.Color(5,5,5) b = wx.EmptyBitmap(w,h) dc = wx.MemoryDC(b) dc.SetBrush(wx.Brush(maskColor)) dc.DrawRectangle(0,0,w,h) dc.SetBrush(wx.Brush(shownColor)) dc.SetPen(wx.Pen(shownColor)) dc.DrawRoundedRectangle(0,0,w,h,r) dc.SelectObject(wx.NullBitmap) b.SetMaskColour(maskColor) return b def GetRoundShape( w, h, r ): return wx.RegionFromBitmap( GetRoundBitmap(w,h,r) ) class FancyFrame(wx.Frame): def __init__(self): style = ( wx.CLIP_CHILDREN | wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR | wx.NO_BORDER | wx.FRAME_SHAPED ) wx.Frame.__init__(self, None, title='Fancy', style = style) self.SetSize( (250, 40) ) self.SetPosition( (500,500) ) self.SetTransparent( 160 ) self.Bind(wx.EVT_KEY_UP, self.On_Esc) self.Bind(wx.EVT_MOTION, self.OnMouse) self.Bind(wx.EVT_PAINT, self.OnPaint) if wx.Platform == '__WXGTK__': self.Bind(wx.EVT_WINDOW_CREATE, self.SetRoundShape) else: self.SetRoundShape() self.Show(True) geo = wx.GridBagSizer() self.label = wx.StaticText(self,-1,label=u'Hello !') self.label.SetBackgroundColour("#000000") self.label.SetForegroundColour(wx.WHITE) self.label.SetSize( (50, 10) ) geo.Add(self.label, (0,0)) self.button = GB.GradientButton(self,label="button") self.label.SetBackgroundColour("#9e9e9e") geo.Add(self.button, (0,1)) def SetRoundShape(self, event=None): w, h = self.GetSizeTuple() self.SetShape(GetRoundShape( w,h, 10 ) ) def OnPaint(self, event): dc = wx.PaintDC(self) dc = wx.GCDC(dc) w, h = self.GetSizeTuple() r = 10 dc.SetPen( wx.Pen("#000000", width = 4 ) ) dc.SetBrush( wx.Brush("#9e9e9e") ) dc.DrawRoundedRectangle( 0,0,w,h,r ) def On_Esc(self, event): """quit if user press Esc""" if event.GetKeyCode() == 27 : #27 is Esc self.Close(force=True) else: event.Skip() def OnMouse(self, event): """implement dragging""" if not event.Dragging(): self._dragPos = None return self.CaptureMouse() if not self._dragPos: self._dragPos = event.GetPosition() else: pos = event.GetPosition() displacement = self._dragPos - pos self.SetPosition( self.GetPosition() - displacement ) app = wx.App() f = FancyFrame() app.MainLoop() A: You forgot to set FancyFrame to have the given layout sizer. In other words you need to add one line to the end of your FancyFrame's __init__ method. self.SetSizerAndFit(geo)
wxPython Geometry problem
I'm trying to get the button to be right of the label. I set the tuple and am still not sure why it covers the label. Also is there a good tutorial available on wxpython geometry? import wx import wx.lib.agw.gradientbutton as GB def GetRoundBitmap( w, h, r ): maskColor = wx.Color(0,0,0) shownColor = wx.Color(5,5,5) b = wx.EmptyBitmap(w,h) dc = wx.MemoryDC(b) dc.SetBrush(wx.Brush(maskColor)) dc.DrawRectangle(0,0,w,h) dc.SetBrush(wx.Brush(shownColor)) dc.SetPen(wx.Pen(shownColor)) dc.DrawRoundedRectangle(0,0,w,h,r) dc.SelectObject(wx.NullBitmap) b.SetMaskColour(maskColor) return b def GetRoundShape( w, h, r ): return wx.RegionFromBitmap( GetRoundBitmap(w,h,r) ) class FancyFrame(wx.Frame): def __init__(self): style = ( wx.CLIP_CHILDREN | wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR | wx.NO_BORDER | wx.FRAME_SHAPED ) wx.Frame.__init__(self, None, title='Fancy', style = style) self.SetSize( (250, 40) ) self.SetPosition( (500,500) ) self.SetTransparent( 160 ) self.Bind(wx.EVT_KEY_UP, self.On_Esc) self.Bind(wx.EVT_MOTION, self.OnMouse) self.Bind(wx.EVT_PAINT, self.OnPaint) if wx.Platform == '__WXGTK__': self.Bind(wx.EVT_WINDOW_CREATE, self.SetRoundShape) else: self.SetRoundShape() self.Show(True) geo = wx.GridBagSizer() self.label = wx.StaticText(self,-1,label=u'Hello !') self.label.SetBackgroundColour("#000000") self.label.SetForegroundColour(wx.WHITE) self.label.SetSize( (50, 10) ) geo.Add(self.label, (0,0)) self.button = GB.GradientButton(self,label="button") self.label.SetBackgroundColour("#9e9e9e") geo.Add(self.button, (0,1)) def SetRoundShape(self, event=None): w, h = self.GetSizeTuple() self.SetShape(GetRoundShape( w,h, 10 ) ) def OnPaint(self, event): dc = wx.PaintDC(self) dc = wx.GCDC(dc) w, h = self.GetSizeTuple() r = 10 dc.SetPen( wx.Pen("#000000", width = 4 ) ) dc.SetBrush( wx.Brush("#9e9e9e") ) dc.DrawRoundedRectangle( 0,0,w,h,r ) def On_Esc(self, event): """quit if user press Esc""" if event.GetKeyCode() == 27 : #27 is Esc self.Close(force=True) else: event.Skip() def OnMouse(self, event): """implement dragging""" if not event.Dragging(): self._dragPos = None return self.CaptureMouse() if not self._dragPos: self._dragPos = event.GetPosition() else: pos = event.GetPosition() displacement = self._dragPos - pos self.SetPosition( self.GetPosition() - displacement ) app = wx.App() f = FancyFrame() app.MainLoop()
[ "You forgot to set FancyFrame to have the given layout sizer.\nIn other words you need to add one line to the end of your FancyFrame's __init__ method.\nself.SetSizerAndFit(geo)\n\n" ]
[ 0 ]
[]
[]
[ "geometry", "python", "wxpython" ]
stackoverflow_0003285520_geometry_python_wxpython.txt
Q: Making two scripts communicate I have to make two programs (for example a "script A" (.py) and "script B"(.exe)) communicate. Both programs are on a infinite loop: Script A needs to write to the stdin of script B and afterwards read the stdout of script B thereafter write again etc. Script B I cannot change. Both files are on my hard disk, so I there must be a better way to solve this than networking. I can, however, write files with script A. This is not course homework, I am writing a GUI for a game and I have a few AI's preprogrammed. I have thought of piping (python scripta.py | scriptb.exe), but that seemed to require script A to finish before script B could execute. Then again, as I've never used piping, I might have missed something obvious. I would prefer if the tools needed would be part of standard library, but if they're not, too bad. The solution would have to work on both Linux and Windows. Could any of you point me in the right direction? Thank you for your time. A: If you start "Script B" from within "script A" using the subprocess module, you will be able to directly interact with its stdin and stdout. For example: from subprocess import Popen, PIPE prog = Popen("scriptA.exe", shell=True, stdin=PIPE, stdout=PIPE) prog.stdin.write("This will go to script A\n") print prog.stdout.read() prog.wait() # Wait for scriptA to finish Just be careful, as calls to read will block, meaning if the script doesn't have anything to print, the call will hang until it does. The easiest way to avoid this is to use threading. A: You might be interested in taking a look at Interprocess Communication and Networking.
Making two scripts communicate
I have to make two programs (for example a "script A" (.py) and "script B"(.exe)) communicate. Both programs are on a infinite loop: Script A needs to write to the stdin of script B and afterwards read the stdout of script B thereafter write again etc. Script B I cannot change. Both files are on my hard disk, so I there must be a better way to solve this than networking. I can, however, write files with script A. This is not course homework, I am writing a GUI for a game and I have a few AI's preprogrammed. I have thought of piping (python scripta.py | scriptb.exe), but that seemed to require script A to finish before script B could execute. Then again, as I've never used piping, I might have missed something obvious. I would prefer if the tools needed would be part of standard library, but if they're not, too bad. The solution would have to work on both Linux and Windows. Could any of you point me in the right direction? Thank you for your time.
[ "If you start \"Script B\" from within \"script A\" using the subprocess module, you will be able to directly interact with its stdin and stdout. For example:\nfrom subprocess import Popen, PIPE\n\nprog = Popen(\"scriptA.exe\", shell=True, stdin=PIPE, stdout=PIPE)\n\nprog.stdin.write(\"This will go to script A\\n\...
[ 6, 0 ]
[]
[]
[ "communication", "python" ]
stackoverflow_0004172213_communication_python.txt
Q: Permuting a list of chars takes all my memory (Python) I am building a dictionary of all the alpha and numbers. The problem with this code is "within matter of second consumes 100% of my memory". Do you think my implementation is bad? Any Help is appreciated. from timeit import Timer from itertools import permutations dictionary = [] small_alpha = map(chr, range(97,123)) lookup.append(small_alpha) def test(): for i in permutations(lookup, 10): dictionary.append(''.join(i)) if __name__ == '__main__': test() (Edited) I am a well educated. No intent of hacking. This is realistically not possible even if I have 100 machines. No one can compute such a big number. Just was trying out if it is possible to some extent A: There are 36!/(36-10)! = 922,393,263,052,800 permutations (~1 quadrillion) of 10 alphanumeric characters. Of course this will take all your memory. Assuming each string takes 32 bytes to store (8 bytes for the pointer, 8 bytes for the length, 16 bytes for the content*, on a 64-bit machine), this requires 26.2 PiB of memory. There is no way to store all permutations in a normal machine. Please state what you actually want to do. (*: Actually it takes much more than that, since there are also type information, and in Python 3.x a character costs 2 bytes for UTF-16, and the list itself also takes memory.) Even with just the alphabets the number of permutations is still 19,275,223,968,000 (~20 trillion), and still takes 561 TiB of memory for 32 bytes per string. A: You need about 90077467 GB of memory to store the result data. 2 GB of memory costs $13 (http://www.newegg.com/Product/Product.aspx?Item=N82E16820146214), so you can fix this easily for the low, low price of $585,503,535.50. A: You're doing things pretty much right, using itertools to provide a generator rather than actually producing a list -- right up until you try to create a list. That list simply is going to use up all your memory because it is in fact huge. You should probably write it to a file rather than trying to make a list in memory, but you will need a lot of disk space. A: If you're going to use itertools, then use it all the way! This is a perfect situation for a lazy generator--no need to actually store either the permutations or the data. import itertools small_alpha = itertools.imap(chr, range(97, 123)) numbers = itertools.imap(chr, range(48, 58)) lookup = itertools.chain(small_alpha, numbers) d = (''.join(i) for i in itertools.permutations(lookup, 10)) if __name__ == '__main__': perms = list(itertools.islice(d,10)) print(perms) A: you should utilize the cloud to solve this problem. using gnu parallel would provide you with additional resources to help you build your dictionary. http://unethicalblogger.com/posts/2010/11/gnuparallel_changed_my_life A: Firstly having variable called dictionary that is really a list is very confusing Assuming you have enough memory, it would be much faster to use dictionary = list(permutations(lookup, 10)) However since you don't have enough memory, this will just use up your memory even faster
Permuting a list of chars takes all my memory (Python)
I am building a dictionary of all the alpha and numbers. The problem with this code is "within matter of second consumes 100% of my memory". Do you think my implementation is bad? Any Help is appreciated. from timeit import Timer from itertools import permutations dictionary = [] small_alpha = map(chr, range(97,123)) lookup.append(small_alpha) def test(): for i in permutations(lookup, 10): dictionary.append(''.join(i)) if __name__ == '__main__': test() (Edited) I am a well educated. No intent of hacking. This is realistically not possible even if I have 100 machines. No one can compute such a big number. Just was trying out if it is possible to some extent
[ "There are 36!/(36-10)! = 922,393,263,052,800 permutations (~1 quadrillion) of 10 alphanumeric characters. Of course this will take all your memory.\nAssuming each string takes 32 bytes to store (8 bytes for the pointer, 8 bytes for the length, 16 bytes for the content*, on a 64-bit machine), this requires 26.2 Pi...
[ 10, 2, 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004167586_python.txt
Q: How come my MongoDB query doesn't work? I'm using pymongo: http://api.mongodb.org/python/1.9%2B/index.html for post in db.datasets.find({"set":"flickr"}).sort("num_favs","-1"): ... How come I can't sort this? I'd like it sorted descending. A: second item in each key pair must be ASCENDING, DESCENDING, or GEO2D A: Use .sort("num_favs",-1) instead of ,"-1".
How come my MongoDB query doesn't work?
I'm using pymongo: http://api.mongodb.org/python/1.9%2B/index.html for post in db.datasets.find({"set":"flickr"}).sort("num_favs","-1"): ... How come I can't sort this? I'd like it sorted descending.
[ "second item in each key pair must be ASCENDING, DESCENDING, or GEO2D\n", "Use .sort(\"num_favs\",-1) instead of ,\"-1\".\n" ]
[ 1, 1 ]
[]
[]
[ "database", "mongodb", "python", "sorting" ]
stackoverflow_0004171569_database_mongodb_python_sorting.txt
Q: python: whtat is the right way to remove element from list google no found... I want two solutions: 1) How to remove an element in a for..in.. loop for a list? 2) How to remove all the elements in the list? A: This is almost never what you want to do. Use a list comprehension to filter out the items you don't want. del L[:]
python: whtat is the right way to remove element from list
google no found... I want two solutions: 1) How to remove an element in a for..in.. loop for a list? 2) How to remove all the elements in the list?
[ "\nThis is almost never what you want to do. Use a list comprehension to filter out the items you don't want.\ndel L[:]\n\n" ]
[ 4 ]
[ "1) filter()\n2) list = []\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0004172535_python.txt
Q: python: what does u'{' represent? When I print out a value it has a u in front of it, I think it is some type notation, what is it? Where I can find a list of such notations? A: It meant UNICODE string literal before Python 3. Documentation about all these literal adornments can be found there. A: Unicode Constructors talks about unicode. A: That's creating a unicode string. I'd recommend this section from Dive into Python on the topic There are many advantages to explicitly using unicode, the most common reason for doing so is to force integrity when working with a database.
python: what does u'{' represent?
When I print out a value it has a u in front of it, I think it is some type notation, what is it? Where I can find a list of such notations?
[ "It meant UNICODE string literal before Python 3.\nDocumentation about all these literal adornments can be found there.\n", "Unicode Constructors talks about unicode.\n", "That's creating a unicode string. I'd recommend this section from Dive into Python on the topic\nThere are many advantages to explicitly us...
[ 7, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004172652_python.txt
Q: How can I represent avi video as set of matrices using Python? I have video files written in avi format and I would like to analyze these videos using Python. For that I would like to represent every frame of the video as a 2D matrix. How can I do that? Google search gives me PyMedia as a way to go? Is it really the best choice or there some other approaches that I should to considered? If the PyMedia is a good choice, could anybody pleas to give me a link where I can get exe files to install the module on Windows from binaries? By the way, is it a good idea, in general, to use Python for these purposes? I like Python very much because of its simplicity and I prefer to use it, but if it is really not suitable for analysis of video, I am ready to use something else. ADDED Some people claim that PyMedia is "dead". Is it true? A: Yeah, the latest news on the PyMedia web site is dated 01 Feb 2006. That's a pretty bad sign. The most active and up-to-date open project for manipulating video is ffmpeg. Apparently there is a recently updated python wrapper for it: http://code.google.com/p/pyffmpeg/ In general Python is much too slow for doing any sort of pixel analysis of video. Therefore there will be practically zero libraries of any reasonable level of quality and support for helping at the pixel level of granularity. There are well supported libraries for working at an image level of granularity though. PIL seems to be a popular choice: http://www.pythonware.com/products/pil/
How can I represent avi video as set of matrices using Python?
I have video files written in avi format and I would like to analyze these videos using Python. For that I would like to represent every frame of the video as a 2D matrix. How can I do that? Google search gives me PyMedia as a way to go? Is it really the best choice or there some other approaches that I should to considered? If the PyMedia is a good choice, could anybody pleas to give me a link where I can get exe files to install the module on Windows from binaries? By the way, is it a good idea, in general, to use Python for these purposes? I like Python very much because of its simplicity and I prefer to use it, but if it is really not suitable for analysis of video, I am ready to use something else. ADDED Some people claim that PyMedia is "dead". Is it true?
[ "Yeah, the latest news on the PyMedia web site is dated 01 Feb 2006. That's a pretty bad sign.\nThe most active and up-to-date open project for manipulating video is ffmpeg. Apparently there is a recently updated python wrapper for it: http://code.google.com/p/pyffmpeg/\nIn general Python is much too slow for doi...
[ 1 ]
[]
[]
[ "python", "video", "video_encoding", "video_processing" ]
stackoverflow_0004165566_python_video_video_encoding_video_processing.txt
Q: Scrapy install: no acceptable C compiler found in $PATH I am trying to install Scrapy on a a Mac OS X 10.6.2 machine... When I try to build one of the dependent modules ( libxml2 ) I am getting the following error: configure: error: no acceptable C compiler found in $PATH I assume I need the gcc compiler ... is that easy to install on 10.6? Is there some sort of package I should be installing, so as to not get hunged up like this installing modules in Python? A: You need to install the Apple Xcode Development tools. There would be on Apple Developer Connection site or on your Mac OS X installation CDs/DVD. Ensure that the optional components for command line development are installed ("Unix Development" in the Xcode 3.x installer) A: Might be of interest to know that upgrading from OS X 10.5 to 10.6 apparently unlinks the existing developer tools thus requiring a reinstall from the SL DVD for gcc to work as usual. Most annoying when you thought you had everything set up. A: You need to install XCode ('developer tools') from the Snow Leopard DVD - this includes gcc among much other stuff. You should also run software update after the install to freshen it
Scrapy install: no acceptable C compiler found in $PATH
I am trying to install Scrapy on a a Mac OS X 10.6.2 machine... When I try to build one of the dependent modules ( libxml2 ) I am getting the following error: configure: error: no acceptable C compiler found in $PATH I assume I need the gcc compiler ... is that easy to install on 10.6? Is there some sort of package I should be installing, so as to not get hunged up like this installing modules in Python?
[ "You need to install the Apple Xcode Development tools. There would be on Apple Developer Connection site or on your Mac OS X installation CDs/DVD. Ensure that the optional components for command line development are installed (\"Unix Development\" in the Xcode 3.x installer)\n", "Might be of interest to know tha...
[ 2, 2, 1 ]
[]
[]
[ "gcc", "macos", "python", "scrapy" ]
stackoverflow_0002371997_gcc_macos_python_scrapy.txt
Q: SQLalchemy with nested class I have a rather complex object that takes a few other objects as its members. Something like this: from engine import engine Class Car(object): def __init__(self,engine_type): self.engine=engine(engine_type) Is there a pain-free approach to map such nested definitions to a database, using SQLAlchemy for example? Thanks for your help. I am learning SQLAlchemy and working with ORMS. A: It's not much clear what you're trying to accomplish. If I understood, you are trying to define Car model with engine attribute that points to another Engine model, and by creating Car object with engine_type, the code should either: create Engine object with engine type if it doesn't exist load the Engine object with engine type if exists and then assign it to the Car object. If so, you should do the following. class Engine(object): def __init__(self, engine_type): self.engine_type @staticmethod def load(engine_type): return session.query(Engine)\ .filter(engine_type==engine_type).one() class Car(object): def __init__(self, engine_type): try: engine = Engine.load(engine_type) except NoResultsFound: engine = Engine(session_type) session.add(engine) self.engine=engine You'll need to define to create the 'engine' relationship on the Car mapper yourself, and also you'll need code tweaking to enable scope of the session object where needed.
SQLalchemy with nested class
I have a rather complex object that takes a few other objects as its members. Something like this: from engine import engine Class Car(object): def __init__(self,engine_type): self.engine=engine(engine_type) Is there a pain-free approach to map such nested definitions to a database, using SQLAlchemy for example? Thanks for your help. I am learning SQLAlchemy and working with ORMS.
[ "It's not much clear what you're trying to accomplish. If I understood, you are trying to define Car model with engine attribute that points to another Engine model, and by creating Car object with engine_type, the code should either:\n\ncreate Engine object with engine type if it doesn't exist\nload the Engine obj...
[ 1 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0004172427_orm_python_sqlalchemy.txt
Q: Working datetime objects in Google App Engine In this model class Rep(db.Model): mAUTHOR = db.UserProperty(auto_current_user=True) mUNIQUE = db.StringProperty() mCOUNT = db.IntegerProperty() mDATE = db.DateTimeProperty(auto_now=True) mDATE0 = db.DateTimeProperty(auto_now_add=True) mWEIGHT = db.IntegerProperty() I want to do: mWEIGHT = mCOUNT / mDATE0 within this for loop for i in range(len(UNIQUES)): C_QUERY = Rep.all() C_QUERY.filter("mAUTHOR =", user) C_QUERY.filter("mUNIQUE =", UNIQUES[i]) C_RESULT = C_QUERY.fetch(1) if C_RESULT: rep=C_RESULT[0] rep.mCOUNT+=COUNTS[i] # how to convert mDATE0 to integer so that I can divide: # rep.mWEIGHT = rep.mCOUNT / rep.mDATE0 rep.put() else: C = COUNTS[i] S = UNIQUES[i] write_to_db(S, C) I asked the same question in several other forums and I got good and valuable advice but I am still unable to make this code work because I am confused about (objects, instance, datetime.datetime, seconds, second ... and so on) For instance, I thought that mWEIGHT = mCOUNT / rep.mDATE0.second would turn mDATE0 into seconds; but it does not, it just take the second part from 2010-11-12 18:57:27.338000 ie, 27. And mWEIGHT = mCOUNT / mDATE0.date gives an type mismatch error message. I also tried rep.mWEIGHT = rep.mCOUNT / rep.mDATE0.toordinal() this gives a number like 734088 but all items had the same number. See also my previous question on the same subject. Thank you for your help. EDIT3 This works, thanks! if C_RESULT: rep = C_RESULT[0] rep.mCOUNT+=COUNTS[i] utc_tuple = rep.mDATE0.utctimetuple() # this is actually float not integer mDATE0_integer = time.mktime(utc_tuple) mDATE0_day = mDATE0_integer / 86400 rep.mWEIGHT = float(rep.mCOUNT / mDATE0_day) rep.put() EDIT2 @Constantin: I realized that numbers need to be floats: >>> mCOUNT = 35 >>> div = mCOUNT / mDATE0 >>> div 0 >>> div = float(mCOUNT) / float(mDATE0) >>> div 2.7140704010987625e-08 >>> Not sure how to incorporate this to the script. Any suggestions? EDIT @Constantin: For the item C_RESULT[0] = "new item" this is the result I get. new item: rep: <__main__.Rep object at 0x052186D0> mDATE0_integer: 1289575981 rep.mCOUNT: 35 rep.mWEIGHT: 0 So mDATE0_integer = int(time.mktime(rep.mDATE0.utctimetuple())) works and gives the integer 1289575981 but this division rep.mWEIGHT = rep.mCOUNT / mDATE0_integer results in 0. Any suggestions? A: This should do what you want: import time mWEIGHT = mCOUNT / time.mktime(mDATE0.utctimetuple()) See mktime. mCOUNT / mDATE0.date fails because there is no division operator for int and date. toordinal doesn't suit you because it operates on dates and disregards time completely.
Working datetime objects in Google App Engine
In this model class Rep(db.Model): mAUTHOR = db.UserProperty(auto_current_user=True) mUNIQUE = db.StringProperty() mCOUNT = db.IntegerProperty() mDATE = db.DateTimeProperty(auto_now=True) mDATE0 = db.DateTimeProperty(auto_now_add=True) mWEIGHT = db.IntegerProperty() I want to do: mWEIGHT = mCOUNT / mDATE0 within this for loop for i in range(len(UNIQUES)): C_QUERY = Rep.all() C_QUERY.filter("mAUTHOR =", user) C_QUERY.filter("mUNIQUE =", UNIQUES[i]) C_RESULT = C_QUERY.fetch(1) if C_RESULT: rep=C_RESULT[0] rep.mCOUNT+=COUNTS[i] # how to convert mDATE0 to integer so that I can divide: # rep.mWEIGHT = rep.mCOUNT / rep.mDATE0 rep.put() else: C = COUNTS[i] S = UNIQUES[i] write_to_db(S, C) I asked the same question in several other forums and I got good and valuable advice but I am still unable to make this code work because I am confused about (objects, instance, datetime.datetime, seconds, second ... and so on) For instance, I thought that mWEIGHT = mCOUNT / rep.mDATE0.second would turn mDATE0 into seconds; but it does not, it just take the second part from 2010-11-12 18:57:27.338000 ie, 27. And mWEIGHT = mCOUNT / mDATE0.date gives an type mismatch error message. I also tried rep.mWEIGHT = rep.mCOUNT / rep.mDATE0.toordinal() this gives a number like 734088 but all items had the same number. See also my previous question on the same subject. Thank you for your help. EDIT3 This works, thanks! if C_RESULT: rep = C_RESULT[0] rep.mCOUNT+=COUNTS[i] utc_tuple = rep.mDATE0.utctimetuple() # this is actually float not integer mDATE0_integer = time.mktime(utc_tuple) mDATE0_day = mDATE0_integer / 86400 rep.mWEIGHT = float(rep.mCOUNT / mDATE0_day) rep.put() EDIT2 @Constantin: I realized that numbers need to be floats: >>> mCOUNT = 35 >>> div = mCOUNT / mDATE0 >>> div 0 >>> div = float(mCOUNT) / float(mDATE0) >>> div 2.7140704010987625e-08 >>> Not sure how to incorporate this to the script. Any suggestions? EDIT @Constantin: For the item C_RESULT[0] = "new item" this is the result I get. new item: rep: <__main__.Rep object at 0x052186D0> mDATE0_integer: 1289575981 rep.mCOUNT: 35 rep.mWEIGHT: 0 So mDATE0_integer = int(time.mktime(rep.mDATE0.utctimetuple())) works and gives the integer 1289575981 but this division rep.mWEIGHT = rep.mCOUNT / mDATE0_integer results in 0. Any suggestions?
[ "This should do what you want:\nimport time\nmWEIGHT = mCOUNT / time.mktime(mDATE0.utctimetuple())\n\nSee mktime.\nmCOUNT / mDATE0.date fails because there is no division operator for int and date.\ntoordinal doesn't suit you because it operates on dates and disregards time completely.\n" ]
[ 1 ]
[]
[]
[ "datetime", "google_app_engine", "python" ]
stackoverflow_0004173245_datetime_google_app_engine_python.txt
Q: Extract the SHA1 hash from a torrent file I've had a look around for the answer to this, but I only seem to be able to find software that does it for you. Does anybody know how to go about doing this in python? A: I wrote a piece of python code that verifies the hashes of downloaded files against what's in a .torrent file. Assuming you want to check a download for corruption you may find this useful. You need the bencode package to use this. Bencode is the serialization format used in .torrent files. It can marshal lists, dictionaries, strings and numbers somewhat like JSON. The code takes the hashes contained in the info['pieces'] string: torrent_file = open(sys.argv[1], "rb") metainfo = bencode.bdecode(torrent_file.read()) info = metainfo['info'] pieces = StringIO.StringIO(info['pieces']) That string contains a succession of 20 byte hashes (one for each piece). These hashes are then compared with the hash of the pieces of on-disk file(s). The only complicated part of this code is handling multi-file torrents because a single torrent piece can span more than one file (internally BitTorrent treats multi-file downloads as a single contiguous file). I'm using the generator function pieces_generator() to abstract that away. You may want to read the BitTorrent spec to understand this in more details. Full code bellow: import sys, os, hashlib, StringIO, bencode def pieces_generator(info): """Yield pieces from download file(s).""" piece_length = info['piece length'] if 'files' in info: # yield pieces from a multi-file torrent piece = "" for file_info in info['files']: path = os.sep.join([info['name']] + file_info['path']) print path sfile = open(path.decode('UTF-8'), "rb") while True: piece += sfile.read(piece_length-len(piece)) if len(piece) != piece_length: sfile.close() break yield piece piece = "" if piece != "": yield piece else: # yield pieces from a single file torrent path = info['name'] print path sfile = open(path.decode('UTF-8'), "rb") while True: piece = sfile.read(piece_length) if not piece: sfile.close() return yield piece def corruption_failure(): """Display error message and exit""" print("download corrupted") exit(1) def main(): # Open torrent file torrent_file = open(sys.argv[1], "rb") metainfo = bencode.bdecode(torrent_file.read()) info = metainfo['info'] pieces = StringIO.StringIO(info['pieces']) # Iterate through pieces for piece in pieces_generator(info): # Compare piece hash with expected hash piece_hash = hashlib.sha1(piece).digest() if (piece_hash != pieces.read(20)): corruption_failure() # ensure we've read all pieces if pieces.read(): corruption_failure() if __name__ == "__main__": main() A: Here how I've extracted HASH value from torrent file: #!/usr/bin/python import sys, os, hashlib, StringIO import bencode def main(): # Open torrent file torrent_file = open(sys.argv[1], "rb") metainfo = bencode.bdecode(torrent_file.read()) info = metainfo['info'] print hashlib.sha1(bencode.bencode(info)).hexdigest() if __name__ == "__main__": main() It is the same as running command: transmissioncli -i test.torrent 2>/dev/null | grep "^hash:" | awk '{print $2}' Hope, it helps :)
Extract the SHA1 hash from a torrent file
I've had a look around for the answer to this, but I only seem to be able to find software that does it for you. Does anybody know how to go about doing this in python?
[ "I wrote a piece of python code that verifies the hashes of downloaded files against what's in a .torrent file. Assuming you want to check a download for corruption you may find this useful.\nYou need the bencode package to use this. Bencode is the serialization format used in .torrent files. It can marshal lists, ...
[ 34, 17 ]
[ "According to this, you should be able to find the md5sums of files by searching for the part of the data that looks like:\nd[...]6:md5sum32:[hash is here][...]e\n(SHA is not part of the spec)\n" ]
[ -2 ]
[ "bittorrent", "extract", "hash", "python", "sha1" ]
stackoverflow_0002572521_bittorrent_extract_hash_python_sha1.txt