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: Assigning IDs to instances of a class (Pythonic) I want to have each instance of some class have a unique integer identifier based on the order that I create them, starting with (say) 0. In Java, I could do this with a static class variable. I know I can emulate the same sort of behavior with Python, but what would be the most 'Pythonic' way to do this? Thanks A: The following approach would be relatively pythonic (for my subjective judgement of pythonic - explicit, yet concise): class CounterExample(object): instances_created = 0 def __init__(self): CounterExample.instances_created += 1 def __del__(self): """ If you want to track the current number of instances you can add a hook in __del__. Otherwise use __init__ and just count up. """ CounterExample.instances_created -= 1 If you are facing a large number of classes, which need that kind of attribute, you could also consider writing a metaclass for that. An example of a metaclass: http://www.youtube.com/watch?v=E_kZDvwofHY#t=0h56m10s. A: the-myyn's answer is good -- I think the class object is a perfectly fine place to stash the counter. However, note that as written it's not thread-safe. So wrap it in a classmethod that uses a lock: import threading class CounterExample(object): _next_id = 0 _id_lock = threading.RLock() @classmethod def _new_id(cls): with cls._id_lock: new_id = cls._next_id cls._next_id += 1 return new_id def __init__(self): self.id = self._new_id() def test(): def make_some(n=1000): for i in range(n): c = CounterExample() print "Thread %s; %s has id %i" % (threading.current_thread(), c, c.id) for i in range(10): newthread = threading.Thread(target=make_some) newthread.start() test() This runs 10 threads creating 1000 instances each. If you run it without the locking code, you're likely to end up with the last id lower than 9999, demonstrating the race condition. A: I guess a good question is when and how are they being created? If you're just creating a certain number of them at one point in time then use a range in a for loop. class A: def __init__ (self, id): self.id = id //do other stuff class_list = [] for i in xrange(10): class_list.append(A(i)) That would be one pythonic way. If your making them whenever you need them, then I think the only way is to keep an id static variable somewhere. Though I'm not sure how you're making them. EDIT: Oh, also, when in doubt "import this" can always help you on to the right track for figuring out what is "pythonic" ;)
Assigning IDs to instances of a class (Pythonic)
I want to have each instance of some class have a unique integer identifier based on the order that I create them, starting with (say) 0. In Java, I could do this with a static class variable. I know I can emulate the same sort of behavior with Python, but what would be the most 'Pythonic' way to do this? Thanks
[ "The following approach would be relatively pythonic (for my subjective judgement of pythonic - explicit, yet concise):\nclass CounterExample(object):\n\n instances_created = 0\n\n def __init__(self):\n CounterExample.instances_created += 1\n\n def __del__(self):\n \"\"\" If you want to track the current number of instances\n you can add a hook in __del__. Otherwise use\n __init__ and just count up.\n \"\"\"\n CounterExample.instances_created -= 1\n\nIf you are facing a large number of classes, which need that kind of attribute, you could also consider writing a metaclass for that. \nAn example of a metaclass: http://www.youtube.com/watch?v=E_kZDvwofHY#t=0h56m10s.\n", "the-myyn's answer is good -- I think the class object is a perfectly fine place to stash the counter. However, note that as written it's not thread-safe.\nSo wrap it in a classmethod that uses a lock:\nimport threading\n\nclass CounterExample(object):\n\n _next_id = 0\n _id_lock = threading.RLock()\n\n @classmethod\n def _new_id(cls):\n with cls._id_lock:\n new_id = cls._next_id\n cls._next_id += 1\n return new_id\n\n def __init__(self):\n self.id = self._new_id()\n\ndef test():\n def make_some(n=1000):\n for i in range(n):\n c = CounterExample()\n print \"Thread %s; %s has id %i\" % (threading.current_thread(), c, c.id)\n\n for i in range(10):\n newthread = threading.Thread(target=make_some)\n newthread.start()\n\ntest()\n\nThis runs 10 threads creating 1000 instances each.\nIf you run it without the locking code, you're likely to end up with the last id lower than 9999, demonstrating the race condition.\n", "I guess a good question is when and how are they being created? If you're just creating a certain number of them at one point in time then use a range in a for loop.\nclass A:\n def __init__ (self, id):\n self.id = id\n //do other stuff\n\nclass_list = []\nfor i in xrange(10):\n class_list.append(A(i))\n\nThat would be one pythonic way. If your making them whenever you need them, then I think the only way is to keep an id static variable somewhere. Though I'm not sure how you're making them.\nEDIT: Oh, also, when in doubt \"import this\" can always help you on to the right track for figuring out what is \"pythonic\" ;)\n" ]
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002989870_python.txt
Q: Help with copy and deepcopy in Python I think I tried to ask for far too much in my previous question so apologies for that. Let me lay out my situation in as simple a manner as I can this time. Basically, I've got a bunch of dictionaries that reference my objects, which are in turn mapped using SQLAlchemy. All fine with me. However, I want to make iterative changes to the contents of those dictionaries. The problem is that doing so will change the objects they reference---and using copy.copy() does no good since it only copies the references contained within the dictionary. Thus even if copied something, when I try to, say print the contents of the dictionary, I'll only get the latest updated values for the object. This is why I wanted to use copy.deepcopy() but that does not work with SQLAlchemy. Now I'm in a dilemma since I need to copy certain attributes of my object before making said iterative changes. In summary, I need to use SQLAlchemy and at the same time make sure I can have a copy of my object attributes when making changes so I don't change the referenced object itself. Any advice, help, suggestions, etc.? Edit: Have added some code. class Student(object): def __init__(self, sid, name, allocated_proj_ref, allocated_rank): self.sid = sid self.name = name self.allocated_proj_ref = None self.allocated_rank = None students_table = Table('studs', metadata, Column('sid', Integer, primary_key=True), Column('name', String), Column('allocated_proj_ref', Integer, ForeignKey('projs.proj_id')), Column('allocated_rank', Integer) ) mapper(Student, students_table, properties={'proj' : relation(Project)}) students = {} students[sid] = Student(sid, name, allocated_project, allocated_rank) Thus, the attributes that I will be changing are the allocated_proj_ref and allocated_rank attributes. The students_table is keyed using the unique student ID (sid). Question I'd want to persist the attributes I change above -- I mean, that's basically why I decided to use SQLA. However, the mapped object will be changing, which is not recommended. Thus, if I make the changes to doppelgänger, unmapped object... can I take those changes and update the fields/table for the mapped object. In a sense I'm following David's secondary solution where I create another version of the Class that isn't mapped. I tried using the StudentDBRecord solution mentioned below but got an error! File "Main.py", line 25, in <module> prefsTableFile = 'Database/prefs-table.txt') File "/XXXX/DataReader.py", line 158, in readData readProjectsFile(projectsFile) File "/XXXX/DataReader.py", line 66, in readProjectsFile supervisors[ee_id] = Supervisor(ee_id, name, original_quota, loading_limit) File "<string>", line 4, in __init__ raise exc.UnmappedClassError(class_) sqlalchemy.orm.exc.UnmappedClassError: Class 'ProjectParties.Student' is not mapped Does this mean that Student must be mapped? Health warning! Someone pointed out a really good additional issue here. See, even if I'm calling copy.deepcopy() on a non-mapped object, in this case, let's assume it's the students dictionary I've defined above, deepcopy makes a copy of everything. My allocated_proj_ref is actually a Project object, and I've got a corresponding projects dictionary for that. So I deepcopy both students and projects -- which I am -- he says I'll have cases where the students's allocated_proj_ref attribute will have issues with matching with instances in the projects dictionary. Thus, I take it that I'll have to redefine/override (that's what it's called isn't it?) deepcopy in each Class using def __deecopy__(self, memo): or something like that? I'd I'd like to override __deepcopy__ such that it ignores all the SQLA stuff (which are <class 'sqlalchemy.util.symbol'> and <class 'sqlalchemy.orm.state.InstanceState'>) but copy everything else that's part of the a mapped class. Any suggestions, please? A: Here is another option, but I'm not sure it's applicable to your problem: Retrieve objects from database along with all needed relations. You can either pass lazy='joined' or lazy='subquery' to relations, or call options(eagerload(relation_property) method of query, or just access required properties to trigger their load. Expunge object from session. Lazy loading of object properties won't be supported from this point. Now you can safely modify object. When you need to update the object in the database you have to merge it back into session and commit. Update: Here is prove of concept code sample: from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relation, eagerload metadata = MetaData() Base = declarative_base(metadata=metadata, name='Base') class Project(Base): __tablename__ = 'projects' id = Column(Integer, primary_key=True) name = Column(String) class Student(Base): __tablename__ = 'students' id = Column(Integer, primary_key=True) project_id = Column(ForeignKey(Project.id)) project = relation(Project, cascade='save-update, expunge, merge', lazy='joined') engine = create_engine('sqlite://', echo=True) metadata.create_all(engine) session = sessionmaker(bind=engine)() proj = Project(name='a') stud = Student(project=proj) session.add(stud) session.commit() session.expunge_all() assert session.query(Project.name).all()==[('a',)] stud = session.query(Student).first() # Use options() method if you didn't specify lazy for relations: #stud = session.query(Student).options(eagerload(Student.project)).first() session.expunge(stud) assert stud not in session assert stud.project not in session stud.project.name = 'b' session.commit() # Stores nothing assert session.query(Project.name).all()==[('a',)] stud = session.merge(stud) session.commit() assert session.query(Project.name).all()==[('b',)] A: If I'm remembering/thinking correctly, in SQLAlchemy you normally have only one object at a time that corresponds to a given database record. This is done so that SQLAlchemy can keep your Python objects in sync with the database, and vice-versa (well, not if there are concurrent DB mutations from outside Python, but that's another story). So the problem is that, if you were to copy one of these mapped objects, you'd wind up with two distinct objects that correspond to the same database record. If you change one, then they would have different values, and the database can't match both of them at the same time. I think what you may need to do is decide whether you want the database record to reflect the changes you make when you change an attribute of your copy. If so, then you shouldn't be copying the objects at all, you should just be reusing the same instances. On the other hand, if you don't want the original database record to change when you update the copy, you have another choice: should the copy become a new row in the database? Or should it not be mapped to a database record at all? In the former case, you can implement the copy operation by creating a new instance of the same class and copying over the values, pretty much the same way you created the original object. This would probably be done in the __deepcopy__() method of your SQLAlchemy mapped class. In the latter case (no mapping), you would need a separate class that has all the same fields but is not mapped using SQLAlchemy. Actually, it would probably make more sense to have your SQLAlchemy-mapped class be a subclass of this non-mapped class, and only do the mapping for the subclass. EDIT: OK, to clarify what I meant by that last point: right now you have a Student class that's used to represent your students. What I'm suggesting is that you make Student an unmapped, regular class: class Student(object): def __init__(self, sid, name, allocated_proj_ref, allocated_rank): self.sid = sid self.name = name self.allocated_project = None self.allocated_rank = None and have a subclass, something like StudentDBRecord, that will be mapped to the database. class StudentDBRecord(Student): def __init__(self, student): super(StudentDBRecord, self).__init__(student.sid, student.name, student.allocated_proj_ref, student.allocated_rank) # this call remains the same students_table = Table('studs', metadata, Column('sid', Integer, primary_key=True), Column('name', String), Column('allocated_proj_ref', Integer, ForeignKey('projs.proj_id')), Column('allocated_rank', Integer) ) # this changes mapper(StudentDBRecord, students_table, properties={'proj' : relation(Project)}) Now you would implement your optimization algorithm using instances of Student, which are unmapped - so as the attributes of the Student objects change, nothing happens to the database. This means you can safely use copy or deepcopy as needed. When you're all done, you can change the Student instances to StudentDBRecord instances, something like students = ...dict with best solution... student_records = [StudentDBRecord(s) for s in students.itervalues()] session.commit() This will create mapped objects corresponding to all your students in their optimal state and commit them to the database. EDIT 2: So maybe that doesn't work. A quick fix would be to copy the Student constructor into StudentDBRecord and make StudentDBRecord extend object instead. That is, replace the previous definition of StudentDBRecord with this: class StudentDBRecord(object): def __init__(self, student): self.sid = student.sid self.name = student.name self.allocated_project = student.allocated_project self.allocated_rank = student.allocated_rank Or if you wanted to generalize it: class StudentDBRecord(object): def __init__(self, student): for attr in dir(student): if not attr.startswith('__'): setattr(self, attr, getattr(student, attr)) This latter definition will copy over all non-special properties of the Student to the StudentDBRecord.
Help with copy and deepcopy in Python
I think I tried to ask for far too much in my previous question so apologies for that. Let me lay out my situation in as simple a manner as I can this time. Basically, I've got a bunch of dictionaries that reference my objects, which are in turn mapped using SQLAlchemy. All fine with me. However, I want to make iterative changes to the contents of those dictionaries. The problem is that doing so will change the objects they reference---and using copy.copy() does no good since it only copies the references contained within the dictionary. Thus even if copied something, when I try to, say print the contents of the dictionary, I'll only get the latest updated values for the object. This is why I wanted to use copy.deepcopy() but that does not work with SQLAlchemy. Now I'm in a dilemma since I need to copy certain attributes of my object before making said iterative changes. In summary, I need to use SQLAlchemy and at the same time make sure I can have a copy of my object attributes when making changes so I don't change the referenced object itself. Any advice, help, suggestions, etc.? Edit: Have added some code. class Student(object): def __init__(self, sid, name, allocated_proj_ref, allocated_rank): self.sid = sid self.name = name self.allocated_proj_ref = None self.allocated_rank = None students_table = Table('studs', metadata, Column('sid', Integer, primary_key=True), Column('name', String), Column('allocated_proj_ref', Integer, ForeignKey('projs.proj_id')), Column('allocated_rank', Integer) ) mapper(Student, students_table, properties={'proj' : relation(Project)}) students = {} students[sid] = Student(sid, name, allocated_project, allocated_rank) Thus, the attributes that I will be changing are the allocated_proj_ref and allocated_rank attributes. The students_table is keyed using the unique student ID (sid). Question I'd want to persist the attributes I change above -- I mean, that's basically why I decided to use SQLA. However, the mapped object will be changing, which is not recommended. Thus, if I make the changes to doppelgänger, unmapped object... can I take those changes and update the fields/table for the mapped object. In a sense I'm following David's secondary solution where I create another version of the Class that isn't mapped. I tried using the StudentDBRecord solution mentioned below but got an error! File "Main.py", line 25, in <module> prefsTableFile = 'Database/prefs-table.txt') File "/XXXX/DataReader.py", line 158, in readData readProjectsFile(projectsFile) File "/XXXX/DataReader.py", line 66, in readProjectsFile supervisors[ee_id] = Supervisor(ee_id, name, original_quota, loading_limit) File "<string>", line 4, in __init__ raise exc.UnmappedClassError(class_) sqlalchemy.orm.exc.UnmappedClassError: Class 'ProjectParties.Student' is not mapped Does this mean that Student must be mapped? Health warning! Someone pointed out a really good additional issue here. See, even if I'm calling copy.deepcopy() on a non-mapped object, in this case, let's assume it's the students dictionary I've defined above, deepcopy makes a copy of everything. My allocated_proj_ref is actually a Project object, and I've got a corresponding projects dictionary for that. So I deepcopy both students and projects -- which I am -- he says I'll have cases where the students's allocated_proj_ref attribute will have issues with matching with instances in the projects dictionary. Thus, I take it that I'll have to redefine/override (that's what it's called isn't it?) deepcopy in each Class using def __deecopy__(self, memo): or something like that? I'd I'd like to override __deepcopy__ such that it ignores all the SQLA stuff (which are <class 'sqlalchemy.util.symbol'> and <class 'sqlalchemy.orm.state.InstanceState'>) but copy everything else that's part of the a mapped class. Any suggestions, please?
[ "Here is another option, but I'm not sure it's applicable to your problem:\n\nRetrieve objects from database along with all needed relations. You can either pass lazy='joined' or lazy='subquery' to relations, or call options(eagerload(relation_property) method of query, or just access required properties to trigger their load.\nExpunge object from session. Lazy loading of object properties won't be supported from this point.\nNow you can safely modify object.\nWhen you need to update the object in the database you have to merge it back into session and commit.\n\nUpdate: Here is prove of concept code sample:\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, relation, eagerload\n\nmetadata = MetaData()\nBase = declarative_base(metadata=metadata, name='Base')\n\nclass Project(Base):\n __tablename__ = 'projects'\n id = Column(Integer, primary_key=True)\n name = Column(String)\n\n\nclass Student(Base):\n __tablename__ = 'students'\n id = Column(Integer, primary_key=True)\n project_id = Column(ForeignKey(Project.id))\n project = relation(Project,\n cascade='save-update, expunge, merge',\n lazy='joined')\n\nengine = create_engine('sqlite://', echo=True)\nmetadata.create_all(engine)\nsession = sessionmaker(bind=engine)()\n\nproj = Project(name='a')\nstud = Student(project=proj)\nsession.add(stud)\nsession.commit()\nsession.expunge_all()\nassert session.query(Project.name).all()==[('a',)]\n\nstud = session.query(Student).first()\n# Use options() method if you didn't specify lazy for relations:\n#stud = session.query(Student).options(eagerload(Student.project)).first()\nsession.expunge(stud)\n\nassert stud not in session\nassert stud.project not in session\n\nstud.project.name = 'b'\nsession.commit() # Stores nothing\nassert session.query(Project.name).all()==[('a',)]\n\nstud = session.merge(stud)\nsession.commit()\nassert session.query(Project.name).all()==[('b',)]\n\n", "If I'm remembering/thinking correctly, in SQLAlchemy you normally have only one object at a time that corresponds to a given database record. This is done so that SQLAlchemy can keep your Python objects in sync with the database, and vice-versa (well, not if there are concurrent DB mutations from outside Python, but that's another story). So the problem is that, if you were to copy one of these mapped objects, you'd wind up with two distinct objects that correspond to the same database record. If you change one, then they would have different values, and the database can't match both of them at the same time.\nI think what you may need to do is decide whether you want the database record to reflect the changes you make when you change an attribute of your copy. If so, then you shouldn't be copying the objects at all, you should just be reusing the same instances.\nOn the other hand, if you don't want the original database record to change when you update the copy, you have another choice: should the copy become a new row in the database? Or should it not be mapped to a database record at all? In the former case, you can implement the copy operation by creating a new instance of the same class and copying over the values, pretty much the same way you created the original object. This would probably be done in the __deepcopy__() method of your SQLAlchemy mapped class. In the latter case (no mapping), you would need a separate class that has all the same fields but is not mapped using SQLAlchemy. Actually, it would probably make more sense to have your SQLAlchemy-mapped class be a subclass of this non-mapped class, and only do the mapping for the subclass.\nEDIT: OK, to clarify what I meant by that last point: right now you have a Student class that's used to represent your students. What I'm suggesting is that you make Student an unmapped, regular class:\nclass Student(object):\n def __init__(self, sid, name, allocated_proj_ref, allocated_rank):\n self.sid = sid\n self.name = name\n self.allocated_project = None\n self.allocated_rank = None\n\nand have a subclass, something like StudentDBRecord, that will be mapped to the database.\nclass StudentDBRecord(Student):\n def __init__(self, student):\n super(StudentDBRecord, self).__init__(student.sid, student.name,\n student.allocated_proj_ref, student.allocated_rank)\n\n# this call remains the same\nstudents_table = Table('studs', metadata,\n Column('sid', Integer, primary_key=True),\n Column('name', String),\n Column('allocated_proj_ref', Integer, ForeignKey('projs.proj_id')),\n Column('allocated_rank', Integer)\n)\n\n# this changes\nmapper(StudentDBRecord, students_table, properties={'proj' : relation(Project)})\n\nNow you would implement your optimization algorithm using instances of Student, which are unmapped - so as the attributes of the Student objects change, nothing happens to the database. This means you can safely use copy or deepcopy as needed. When you're all done, you can change the Student instances to StudentDBRecord instances, something like\nstudents = ...dict with best solution...\nstudent_records = [StudentDBRecord(s) for s in students.itervalues()]\nsession.commit()\n\nThis will create mapped objects corresponding to all your students in their optimal state and commit them to the database.\nEDIT 2: So maybe that doesn't work. A quick fix would be to copy the Student constructor into StudentDBRecord and make StudentDBRecord extend object instead. That is, replace the previous definition of StudentDBRecord with this:\nclass StudentDBRecord(object):\n def __init__(self, student):\n self.sid = student.sid\n self.name = student.name\n self.allocated_project = student.allocated_project\n self.allocated_rank = student.allocated_rank\n\nOr if you wanted to generalize it:\nclass StudentDBRecord(object):\n def __init__(self, student):\n for attr in dir(student):\n if not attr.startswith('__'):\n setattr(self, attr, getattr(student, attr))\n\nThis latter definition will copy over all non-special properties of the Student to the StudentDBRecord.\n" ]
[ 2, 1 ]
[]
[]
[ "copy", "python", "sqlalchemy" ]
stackoverflow_0002983275_copy_python_sqlalchemy.txt
Q: cPickle class with data save to file I've big class in Python it's "DataBase-like" class. I want to save it to file - all including data. This is input(example to show the issue, in script database is like 10000 records): import cPickle # DataBase-like class class DataBase: class Arrays: pass class Zones: pass class Nodes: class CR: pass class Links: class CR: pass class Turns: class CR: pass class OrigConnectors: pass class DestConnectors: pass class Paths: pass pass # some basic input into database DataBase.Arrays.Data=[] for i in range(1000): DataBase.Arrays.Data.append([i+4]) print DataBase.Arrays.Data[56] # and now I want to save it to file import cPickle filename='D:/results/file.lft' file=open(filename,'w') cPickle.dump(DataBase, file, protocol=2)` And that's the file I get: €c__main__ DataBase q.` There's no data, just definition. How can I overcome that. Maybe saving my data as a class is not a good idea? A: You are pickling "DataBase" which is a class definition. You need to instantiate an object of class DataBase then pickle that. objDataBase = DataBase() objDataBase.Arrays.Data = etc.... filename='D:/results/file.lft' file=open(filename,'w') cPickle.dump(objDataBase, file, protocol=2) file.close()
cPickle class with data save to file
I've big class in Python it's "DataBase-like" class. I want to save it to file - all including data. This is input(example to show the issue, in script database is like 10000 records): import cPickle # DataBase-like class class DataBase: class Arrays: pass class Zones: pass class Nodes: class CR: pass class Links: class CR: pass class Turns: class CR: pass class OrigConnectors: pass class DestConnectors: pass class Paths: pass pass # some basic input into database DataBase.Arrays.Data=[] for i in range(1000): DataBase.Arrays.Data.append([i+4]) print DataBase.Arrays.Data[56] # and now I want to save it to file import cPickle filename='D:/results/file.lft' file=open(filename,'w') cPickle.dump(DataBase, file, protocol=2)` And that's the file I get: €c__main__ DataBase q.` There's no data, just definition. How can I overcome that. Maybe saving my data as a class is not a good idea?
[ "You are pickling \"DataBase\" which is a class definition. You need to instantiate an object of class DataBase then pickle that.\nobjDataBase = DataBase()\nobjDataBase.Arrays.Data = etc....\n\nfilename='D:/results/file.lft'\nfile=open(filename,'w')\ncPickle.dump(objDataBase, file, protocol=2)\nfile.close()\n\n" ]
[ 4 ]
[]
[]
[ "object_persistence", "pickle", "python", "serialization" ]
stackoverflow_0002991557_object_persistence_pickle_python_serialization.txt
Q: What are alternatives to Asterisq's Constellation Framework for actionscript? i would like to present data in something like Constellation Framework... but without flash what other options are out there? python, html5, javascript would be great, but i have no preference other than no flash (i don't own CS) EDIT: i have found a handful of html5 examples without much source code and infoVis. A: I know of two good options which will work in Javascript: Protovis The JavaScript InfoVis Toolkit In Java, I would recommend Prefuse. I don't know off hand of Python Network libraries, but I'm sure there are some.
What are alternatives to Asterisq's Constellation Framework for actionscript?
i would like to present data in something like Constellation Framework... but without flash what other options are out there? python, html5, javascript would be great, but i have no preference other than no flash (i don't own CS) EDIT: i have found a handful of html5 examples without much source code and infoVis.
[ "I know of two good options which will work in Javascript:\n\nProtovis\nThe JavaScript InfoVis Toolkit\n\nIn Java, I would recommend Prefuse. I don't know off hand of Python Network libraries, but I'm sure there are some.\n" ]
[ 0 ]
[]
[]
[ "actionscript", "flash", "html", "python", "visualization" ]
stackoverflow_0002981723_actionscript_flash_html_python_visualization.txt
Q: Is there an alternative to Pidgin, but with less restrictive licensing? Recently came across pidgin. Its great, and does what I want, but I am not too keen on the GPL license. Other any alternatives, with less restrictive licenses? I would prefer the library to be C or C++, as I am most familiar with those languages, but a an IM library implemented in python would be interesting too. A: Take a look at kde's kopete. The chat client itself is still GPL but it's underlying library libkopete is LGPL. So you could link with it pretty freely. A: Twisted Words
Is there an alternative to Pidgin, but with less restrictive licensing?
Recently came across pidgin. Its great, and does what I want, but I am not too keen on the GPL license. Other any alternatives, with less restrictive licenses? I would prefer the library to be C or C++, as I am most familiar with those languages, but a an IM library implemented in python would be interesting too.
[ "Take a look at kde's kopete. The chat client itself is still GPL but it's underlying library libkopete is LGPL. So you could link with it pretty freely.\n", "Twisted Words\n" ]
[ 4, 1 ]
[]
[]
[ "c", "c++", "pidgin", "python" ]
stackoverflow_0002991867_c_c++_pidgin_python.txt
Q: how to implement a really efficient bitvector sorting in python Actually this is an interesting topic from programming pearls, sorting 10 digits telephone numbers in a limited memory with an efficient algorithm. You can find the whole story here What I am interested in is just how fast the implementation could be in python. I have done a naive implementation with the module bitvector. The code is as following: from BitVector import BitVector import timeit import random import time import sys def sort(input_li): return sorted(input_li) def vec_sort(input_li): bv = BitVector( size = len(input_li) ) for i in input_li: bv[i] = 1 res_li = [] for i in range(len(bv)): if bv[i]: res_li.append(i) return res_li if __name__ == "__main__": test_data = range(int(sys.argv[1])) print 'test_data size is:', sys.argv[1] random.shuffle(test_data) start = time.time() sort(test_data) elapsed = (time.time() - start) print "sort function takes " + str(elapsed) start = time.time() vec_sort(test_data) elapsed = (time.time() - start) print "sort function takes " + str(elapsed) start = time.time() vec_sort(test_data) elapsed = (time.time() - start) print "vec_sort function takes " + str(elapsed) I have tested from array size 100 to 10,000,000 in my macbook(2GHz Intel Core 2 Duo 2GB SDRAM), the result is as following: test_data size is: 1000 sort function takes 0.000274896621704 vec_sort function takes 0.00383687019348 test_data size is: 10000 sort function takes 0.00380706787109 vec_sort function takes 0.0371489524841 test_data size is: 100000 sort function takes 0.0520560741425 vec_sort function takes 0.374383926392 test_data size is: 1000000 sort function takes 0.867373943329 vec_sort function takes 3.80475401878 test_data size is: 10000000 sort function takes 12.9204008579 vec_sort function takes 38.8053860664 What disappoints me is that even when the test_data size is 100,000,000, the sort function is still faster than vec_sort. Is there any way to accelerate the vec_sort function? A: As Niki pointed out, you are comparing a very fast C routine with a Python one. Using psyco speeds it up a little bit for me, but you can really speed it up by using a bit vector module written in C. I used bitarray and then the bit sorting method surpasses the built-in sort for an array size of about 250,000 using psyco. Here's the function that I used: def vec_sort2(input_li): bv = bitarray(len(input_li)) bv.setall(0) for i in input_li: bv[i] = 1 return [i for i in xrange(len(bv)) if bv[i]] Notice also that I have used a list comprehension to construct the sorted list which helps a bit. Using psyco and the above function with your functions I get the following results: test_data size is: 1000000 sort function takes 1.29699993134 vec_sort function takes 3.5150001049 vec_sort2 function takes 0.953999996185 As a side note, BitVector isn't especially optimized even for Python. Before I found bitarray, I did some various tweaks to the module and using my module that has the tweaks, the time for vec_sort is reduced over a second for this size of an array. I haven't submitted my changes to it though because bitarray is just so much faster. A: My Python isn't the best but it looks like you have a bug in your code: bv = BitVector( size = len(input_li) ) The size of your bitvector is the same as the size of your input array. You want the bitvector to be the size of your domain - 10^10. I'm not sure how Python's bitvectors deal with overflows, but if it automatically resizes the bitvector then you are getting quadratic behavior. Additionally I imagine that Python's sort function is implemented in C and is not going to have the overhead of a sort implemented purely in Python. However that probably wouldn't cause an O(nlogn) algorithm to run substantially faster than an O(n) algorithm. Edit: also this sort will only work on large data sets. Your algorithm runs in O(n + 10^10) time (based on your tests I assume you know this) which will be worse than O(nlogn) for small inputs.
how to implement a really efficient bitvector sorting in python
Actually this is an interesting topic from programming pearls, sorting 10 digits telephone numbers in a limited memory with an efficient algorithm. You can find the whole story here What I am interested in is just how fast the implementation could be in python. I have done a naive implementation with the module bitvector. The code is as following: from BitVector import BitVector import timeit import random import time import sys def sort(input_li): return sorted(input_li) def vec_sort(input_li): bv = BitVector( size = len(input_li) ) for i in input_li: bv[i] = 1 res_li = [] for i in range(len(bv)): if bv[i]: res_li.append(i) return res_li if __name__ == "__main__": test_data = range(int(sys.argv[1])) print 'test_data size is:', sys.argv[1] random.shuffle(test_data) start = time.time() sort(test_data) elapsed = (time.time() - start) print "sort function takes " + str(elapsed) start = time.time() vec_sort(test_data) elapsed = (time.time() - start) print "sort function takes " + str(elapsed) start = time.time() vec_sort(test_data) elapsed = (time.time() - start) print "vec_sort function takes " + str(elapsed) I have tested from array size 100 to 10,000,000 in my macbook(2GHz Intel Core 2 Duo 2GB SDRAM), the result is as following: test_data size is: 1000 sort function takes 0.000274896621704 vec_sort function takes 0.00383687019348 test_data size is: 10000 sort function takes 0.00380706787109 vec_sort function takes 0.0371489524841 test_data size is: 100000 sort function takes 0.0520560741425 vec_sort function takes 0.374383926392 test_data size is: 1000000 sort function takes 0.867373943329 vec_sort function takes 3.80475401878 test_data size is: 10000000 sort function takes 12.9204008579 vec_sort function takes 38.8053860664 What disappoints me is that even when the test_data size is 100,000,000, the sort function is still faster than vec_sort. Is there any way to accelerate the vec_sort function?
[ "As Niki pointed out, you are comparing a very fast C routine with a Python one. Using psyco speeds it up a little bit for me, but you can really speed it up by using a bit vector module written in C. I used bitarray and then the bit sorting method surpasses the built-in sort for an array size of about 250,000 using psyco.\nHere's the function that I used:\ndef vec_sort2(input_li):\n bv = bitarray(len(input_li))\n bv.setall(0)\n for i in input_li:\n bv[i] = 1\n\n return [i for i in xrange(len(bv)) if bv[i]]\n\nNotice also that I have used a list comprehension to construct the sorted list which helps a bit. Using psyco and the above function with your functions I get the following results:\ntest_data size is: 1000000\nsort function takes 1.29699993134\nvec_sort function takes 3.5150001049\nvec_sort2 function takes 0.953999996185\n\nAs a side note, BitVector isn't especially optimized even for Python. Before I found bitarray, I did some various tweaks to the module and using my module that has the tweaks, the time for vec_sort is reduced over a second for this size of an array. I haven't submitted my changes to it though because bitarray is just so much faster. \n", "My Python isn't the best but it looks like you have a bug in your code:\nbv = BitVector( size = len(input_li) )\n\nThe size of your bitvector is the same as the size of your input array. You want the bitvector to be the size of your domain - 10^10. I'm not sure how Python's bitvectors deal with overflows, but if it automatically resizes the bitvector then you are getting quadratic behavior.\nAdditionally I imagine that Python's sort function is implemented in C and is not going to have the overhead of a sort implemented purely in Python. However that probably wouldn't cause an O(nlogn) algorithm to run substantially faster than an O(n) algorithm.\nEdit: also this sort will only work on large data sets. Your algorithm runs in O(n + 10^10) time (based on your tests I assume you know this) which will be worse than O(nlogn) for small inputs.\n" ]
[ 3, 1 ]
[]
[]
[ "algorithm", "bitvector", "python", "sorting" ]
stackoverflow_0002991663_algorithm_bitvector_python_sorting.txt
Q: Can't get custom slot working in PyQT4 with QT4 designer I am new to PyQT4. After some tuts I decided to make a simple GUI in which I will enter text in first line and on clicking of Reverse button ,it will show reversed string on second line. I made a custom slot for this,by defining the function in my class.But when I click reverse nothing happens. I have used in-bilt slots for Clear button and Exit button in my GUI and they are working perfectly. If someone can just clarify this custom slot problem it would help me advance further. Thanks in advance. Here's a photo of my GUI http://img196.imageshack.us/img196/7131/diall.png Stringreverse.py Final File import sys from PyQt4 import QtCore, QtGui from stringreverse_ui import Ui_Dialog class MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui=Ui_Dialog() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.pushButton_3,QtCore.SIGNAL("Click()"), self.reverse) def reverse(self): s=self.ui.lineEdit_2.text() self.ui.lineEdit.setText(s[::-1]) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyForm() myapp.show() sys.exit(app.exec_())enter code here A: Try using QtCore.SIGNAL("clicked()") instead of QtCore.SIGNAL("Click()").
Can't get custom slot working in PyQT4 with QT4 designer
I am new to PyQT4. After some tuts I decided to make a simple GUI in which I will enter text in first line and on clicking of Reverse button ,it will show reversed string on second line. I made a custom slot for this,by defining the function in my class.But when I click reverse nothing happens. I have used in-bilt slots for Clear button and Exit button in my GUI and they are working perfectly. If someone can just clarify this custom slot problem it would help me advance further. Thanks in advance. Here's a photo of my GUI http://img196.imageshack.us/img196/7131/diall.png Stringreverse.py Final File import sys from PyQt4 import QtCore, QtGui from stringreverse_ui import Ui_Dialog class MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui=Ui_Dialog() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.pushButton_3,QtCore.SIGNAL("Click()"), self.reverse) def reverse(self): s=self.ui.lineEdit_2.text() self.ui.lineEdit.setText(s[::-1]) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyForm() myapp.show() sys.exit(app.exec_())enter code here
[ "Try using QtCore.SIGNAL(\"clicked()\") instead of QtCore.SIGNAL(\"Click()\").\n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python", "qt4" ]
stackoverflow_0002991945_pyqt4_python_qt4.txt
Q: How Similar are Java, C#, and Python? I know it is a kind of broad question but any answer are appreciated. A: All: Require some form of runtime on your system (JVM/.net/Python runtime) All can probably be compiled to executables without the runtime (this is iffy and situational, none of them are designed to work this way) Are good languages All have specific areas where they are much more appropriate than the other two Java: Tries very hard to be Cross Platform--generally succeeds Little access to platform features that are not in the SDK Slowest of the three to change and does not contain features common to the other two such as closures Very backwards compatible (partly because of the previous point) FAST (about 2x slower than C, quite a few x faster than python) Probably has the most library support of the three Strong multi-platform server systems already deployed using J2EE Scales down to embedded (I've worked on 2 different embedded java projects--coming soon to a cable box near you) Static C# Quicker to add new features Windows only--Mono is cross platform but does not have the library support. Started very similar to Java but has many more language features now. Much better access to windows APIs Not sure about speed--I think it's similar to Java. Very good library support The only one of the three that you have to pay for (it's free for "entry level") Static Python Language is cross platform. Not sure about non-language platform access (such as drag-and-drop)--anyone know? Probably an easier language to learn The only one of the three that does not use c-like syntax Slowest of the three, but still pretty darn fast compared to other dynamic languages. Dynamic This link is also interesting A: Python is a dynamic language where Java and C# are really not. It is totally different than the other two. There are ways to accomplishing things in Python that do not translate well to the others and vice versa. Java and C# look the same, but they have differences between the two under the sheets. Being an expert in one, does not make you an expert in the other by any stretch of the imagination. The syntax is similar and libraries are too, so it would be easier to get up to speed in one or the other, but there are subtleties that can trip you up. A: C# and Java have almost identical syntax and very similar libraries. There are differences that you have to be aware of (Type Erasure in Java, for example). Python is a completely different animal. It is a dynamic language (where the other two aren't). Python winds up being closer in style to something like Ruby. A: Java and C# are statically typed languages, while Python is a dynamically typed language. That's a huge difference. The syntax of Java and C# is similar (but I would not call it "almost identical" as Justin Niessner says). A: Java and c# are pretty similar in terms of syntax and are mostly strongly typed (C# is getting more dynamic with every version), Python is a dynamic language A: Java and C# are very similar and are syntactically similar to C/C++. They also use braces to mark code blocks. Python is completely different. Although imperative like Java and C#, Python uses indentation to define blocks of code. Java and C# are also compiled languages, whereas Python is interpreted and dynamic. Python, Ruby, and Groovy are somewhat similar languages. A: C# and Java are easy to move between, although I don't know many people who are experts in both. C#'s syntax is based off of Java, so they read very, very similarly. They both run cross-platform; Java on the JVM, C# on .NET or Mono. They're both OOP, and widely used for web development. I'd use whichever the team was more familiar with. Python's off to the side there. It's also used frequently as a scripting language. It can use classes and object orientation, but isn't forced to. It's not as well supported for web work. I'd use this for a different set of tasks than C#/Java. A: C# and Java are the two languages you listed that are most similar. Python has a very different syntax, and uses a slightly different programming model. Both C# and Java are Object Oriented languages at their core, with increasing nods to Dynamic Typing. Python began as a Dynamically Typed scripting language and has been picking up more and more Object Oriented features over the years. The C# class library (.NET Framework) is theoretically multi-platform, though it's heavily weighted towards the Windows platform, and any other OS compatibility is largely an afterthought. The .NET framework currently has two "official" frameworks for building windowed applications (Windows Forms, and WPF) and two "official" frameworks for building web applications (ASP.NET, and ASP.NET MVC). Windows Forms is similar to Java Swing, but the other four frameworks are very different from much of what is found in the Java or Python worlds. There are many language features in C# that are different or lacking in Java, such as Delegates. The Java class library is pretty solidly multi-platform. It's officially supported desktop and web frameworks (Swing and J2EE) are generally regarded as slow, and difficult to use. However, there is a very lively open source community which has built several competing frameworks that are very powerful and versatile. Java as a language is very slow to introduce new language features, though it is runtime-compatible with several other languages that run on the Java platform (Groovy, Jython, Scala, etc..). Java is the language which has has the most run-time optimizations put into it, so an application written in Java is almost certainly going to be faster than an application written in C# or Python. Python is an interpreted language (in general), and is pretty solidly multi-platform. Python has no "official" desktop or web frameworks, though desktop applications can be written using GTK or Qt support, both of which are multi-platform. Django has become a de-facto standard for Python web development, and is regarded as a very powerful and expressive framework. Python is at this point fully Object Oriented, and is notable for it's powerful tools for working with collections/arrays/lists. As an interpreted language, Python will be significantly slower than either C# or Java.
How Similar are Java, C#, and Python?
I know it is a kind of broad question but any answer are appreciated.
[ "All:\n\nRequire some form of runtime on your system (JVM/.net/Python runtime)\nAll can probably be compiled to executables without the runtime (this is iffy and situational, none of them are designed to work this way)\nAre good languages\nAll have specific areas where they are much more appropriate than the other two\n\nJava:\n\nTries very hard to be Cross Platform--generally succeeds\nLittle access to platform features that are not in the SDK\nSlowest of the three to change and does not contain features common to the other two such as closures\nVery backwards compatible (partly because of the previous point)\nFAST (about 2x slower than C, quite a few x faster than python)\nProbably has the most library support of the three\nStrong multi-platform server systems already deployed using J2EE\nScales down to embedded (I've worked on 2 different embedded java projects--coming soon to a cable box near you)\nStatic\n\nC#\n\nQuicker to add new features\nWindows only--Mono is cross platform but does not have the library support.\nStarted very similar to Java but has many more language features now.\nMuch better access to windows APIs\nNot sure about speed--I think it's similar to Java.\nVery good library support\nThe only one of the three that you have to pay for (it's free for \"entry level\")\nStatic\n\nPython\n\nLanguage is cross platform. Not sure about non-language platform access (such as drag-and-drop)--anyone know?\nProbably an easier language to learn\nThe only one of the three that does not use c-like syntax\nSlowest of the three, but still pretty darn fast compared to other dynamic languages.\nDynamic\n\nThis link is also interesting\n", "Python is a dynamic language where Java and C# are really not. It is totally different than the other two. There are ways to accomplishing things in Python that do not translate well to the others and vice versa.\nJava and C# look the same, but they have differences between the two under the sheets. Being an expert in one, does not make you an expert in the other by any stretch of the imagination. The syntax is similar and libraries are too, so it would be easier to get up to speed in one or the other, but there are subtleties that can trip you up.\n", "C# and Java have almost identical syntax and very similar libraries. There are differences that you have to be aware of (Type Erasure in Java, for example).\nPython is a completely different animal. It is a dynamic language (where the other two aren't). Python winds up being closer in style to something like Ruby.\n", "Java and C# are statically typed languages, while Python is a dynamically typed language. That's a huge difference.\nThe syntax of Java and C# is similar (but I would not call it \"almost identical\" as Justin Niessner says).\n", "Java and c# are pretty similar in terms of syntax and are mostly strongly typed (C# is getting more dynamic with every version), Python is a dynamic language\n", "Java and C# are very similar and are syntactically similar to C/C++. They also use braces to mark code blocks.\nPython is completely different. Although imperative like Java and C#, Python uses indentation to define blocks of code.\nJava and C# are also compiled languages, whereas Python is interpreted and dynamic.\nPython, Ruby, and Groovy are somewhat similar languages.\n", "C# and Java are easy to move between, although I don't know many people who are experts in both. C#'s syntax is based off of Java, so they read very, very similarly. They both run cross-platform; Java on the JVM, C# on .NET or Mono. They're both OOP, and widely used for web development. I'd use whichever the team was more familiar with.\nPython's off to the side there. It's also used frequently as a scripting language. It can use classes and object orientation, but isn't forced to. It's not as well supported for web work. I'd use this for a different set of tasks than C#/Java.\n", "C# and Java are the two languages you listed that are most similar. Python has a very different syntax, and uses a slightly different programming model. Both C# and Java are Object Oriented languages at their core, with increasing nods to Dynamic Typing. Python began as a Dynamically Typed scripting language and has been picking up more and more Object Oriented features over the years. \nThe C# class library (.NET Framework) is theoretically multi-platform, though it's heavily weighted towards the Windows platform, and any other OS compatibility is largely an afterthought. The .NET framework currently has two \"official\" frameworks for building windowed applications (Windows Forms, and WPF) and two \"official\" frameworks for building web applications (ASP.NET, and ASP.NET MVC). Windows Forms is similar to Java Swing, but the other four frameworks are very different from much of what is found in the Java or Python worlds. There are many language features in C# that are different or lacking in Java, such as Delegates.\nThe Java class library is pretty solidly multi-platform. It's officially supported desktop and web frameworks (Swing and J2EE) are generally regarded as slow, and difficult to use. However, there is a very lively open source community which has built several competing frameworks that are very powerful and versatile. Java as a language is very slow to introduce new language features, though it is runtime-compatible with several other languages that run on the Java platform (Groovy, Jython, Scala, etc..). Java is the language which has has the most run-time optimizations put into it, so an application written in Java is almost certainly going to be faster than an application written in C# or Python. \nPython is an interpreted language (in general), and is pretty solidly multi-platform. Python has no \"official\" desktop or web frameworks, though desktop applications can be written using GTK or Qt support, both of which are multi-platform. Django has become a de-facto standard for Python web development, and is regarded as a very powerful and expressive framework. Python is at this point fully Object Oriented, and is notable for it's powerful tools for working with collections/arrays/lists. As an interpreted language, Python will be significantly slower than either C# or Java.\n" ]
[ 15, 11, 7, 2, 1, 1, 1, 1 ]
[ "Python was made to be simpler, more readable, flexible and object oriented than what existed before - i.e. Java, Perl etc. It's actually closer to Java than it is to Ruby. Ruby is more like Smalltalk. Think of Python as Java without the stuff that mostly gets in your way, makes things awkward to do, slows you down or clutters the essence of your logic. So no semi-colons, curly braces for scoping. No static variable declaration or variables at all really they're identifiers that point to objects instead. \nThere's also a standard style guide for Python unlike other languages. Indentation is used to indicate scope and inconsistent indentation is a syntax error.\nIt also includes some often used things built into the language: lists, dictionaries, sets, generators etc.\nJava is nice for those familiar with C / C++ syntax and are set in their ways, like that syntax and find it readable. Ruby and Python are for those that preferred Pascal or Smalltalk to C, like Lisp etc. \n", "They are not similar at ALL. They all take widely different approaches to OOP, syntax, and static/dynamic typing. \n" ]
[ -1, -2 ]
[ "c#", "java", "python" ]
stackoverflow_0002991554_c#_java_python.txt
Q: networking application and GUI in python I'm writing an application that sends files over network, I want to develop a custom protocol to not limit myself in term on feature richness (http wouldn't be appropriate, the nearest thing is the bittorrent protocol maybe). I've tried with twisted, I've built a good app but there's a bug in twisted that makes my GUI blocking, so I've to switch to another framework/strategy. What do you suggest? Using raw sockets and using gtk mainloop (there are select-like functions in the toolkit) is too much difficult? It's viable running two mainloops in different threads? Asking for suggestions A: Two threads: one for the GUI, one for sending/receiving data. Tkinter would be a perfectly fine toolkit for this. You don't need twisted or any other external libraries or toolkits -- what comes out of the box is sufficient to get the job done. A: Disclaimer: I have little experience with network applications. That being said, the raw sockets isn't terribly difficult to wrap your head around/use, especially if you're not too worried about optimization. That takes more thought, of course. But using GTK and raw sockets should be fairly straightforward. Especially since you've used the twisted framework, which IIRC, just abstracts some of the more nitty-gritty details of socket managing. A: If your application is somewhat similar to bittorrent, why not check the source code of Deluge http://deluge-torrent.org/ and build from it? It is written in Python, it does use the bittorrent protocol and it does have a GTK user interface. A: As an alternative to twisted and whatever GUI library you seem to be using, how about trying PyQt? It provides a GUI and non-blocking sockets all in the same event loop. That way you don't have to worry about interoperability issues, which seem to be the issue you are facing. Hope this helps!
networking application and GUI in python
I'm writing an application that sends files over network, I want to develop a custom protocol to not limit myself in term on feature richness (http wouldn't be appropriate, the nearest thing is the bittorrent protocol maybe). I've tried with twisted, I've built a good app but there's a bug in twisted that makes my GUI blocking, so I've to switch to another framework/strategy. What do you suggest? Using raw sockets and using gtk mainloop (there are select-like functions in the toolkit) is too much difficult? It's viable running two mainloops in different threads? Asking for suggestions
[ "Two threads: one for the GUI, one for sending/receiving data. Tkinter would be a perfectly fine toolkit for this. You don't need twisted or any other external libraries or toolkits -- what comes out of the box is sufficient to get the job done. \n", "Disclaimer: I have little experience with network applications.\nThat being said, the raw sockets isn't terribly difficult to wrap your head around/use, especially if you're not too worried about optimization. That takes more thought, of course. But using GTK and raw sockets should be fairly straightforward. Especially since you've used the twisted framework, which IIRC, just abstracts some of the more nitty-gritty details of socket managing.\n", "If your application is somewhat similar to bittorrent, why not check the source code of Deluge http://deluge-torrent.org/ and build from it? It is written in Python, it does use the bittorrent protocol and it does have a GTK user interface.\n", "As an alternative to twisted and whatever GUI library you seem to be using, how about trying PyQt? It provides a GUI and non-blocking sockets all in the same event loop. That way you don't have to worry about interoperability issues, which seem to be the issue you are facing.\nHope this helps!\n" ]
[ 1, 1, 1, 1 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0002991852_networking_python.txt
Q: Ubuntu quickly (python/gtk) - how to monitor stdin? I'm starting to work with Ubuntu's "quickly" framework, which is python/gtk based. I want to write a gui wrapper for a textmode C state-machine that uses stdin/stdout. I'm new to gtk. I can see that the python print command will write to the terminal window, so I assume I could redirect that to my C program's stdin. But how can I get my quickly program to monitor stdin (i.e. watch for the C program's stdout responses)? I suppose I need some sort of polling loop, but I don't know if/where that is supported within the "quickly" framework. Or is redirection not the way to go - should I be looking at something like gobject.spawn_async? A: The gtk version of select, is glib.io_add_watch, you may want to redirect the stdin/stdout of the process to/from the GUI, you can check an article I've written time ago: http://pygabriel.wordpress.com/2009/07/27/redirecting-the-stdout-on-a-gtk-textview/ A: I'm not sure about the quickly framework, but in Python you can use the subprocess module which spawns a new child process but allows communication via stdin/stdout. http://docs.python.org/library/subprocess.html Take a look at the documentation, but that's pretty useful. If you want to do polling you can use a gobject.timeout_add. You'd create a function something like this: def mypoller(self): data = myproc.communicate() if data[0]: #There's data to read # do something with data else: # Do something else - delete data, return False # to end calls to this function and that would let you read data from your process.
Ubuntu quickly (python/gtk) - how to monitor stdin?
I'm starting to work with Ubuntu's "quickly" framework, which is python/gtk based. I want to write a gui wrapper for a textmode C state-machine that uses stdin/stdout. I'm new to gtk. I can see that the python print command will write to the terminal window, so I assume I could redirect that to my C program's stdin. But how can I get my quickly program to monitor stdin (i.e. watch for the C program's stdout responses)? I suppose I need some sort of polling loop, but I don't know if/where that is supported within the "quickly" framework. Or is redirection not the way to go - should I be looking at something like gobject.spawn_async?
[ "The gtk version of select, is glib.io_add_watch, you may want to redirect the stdin/stdout of the process to/from the GUI, you can check an article I've written time ago:\nhttp://pygabriel.wordpress.com/2009/07/27/redirecting-the-stdout-on-a-gtk-textview/\n", "I'm not sure about the quickly framework, but in Python you can use the subprocess module which spawns a new child process but allows communication via stdin/stdout.\nhttp://docs.python.org/library/subprocess.html\nTake a look at the documentation, but that's pretty useful.\nIf you want to do polling you can use a gobject.timeout_add.\nYou'd create a function something like this:\ndef mypoller(self):\n data = myproc.communicate()\n if data[0]: #There's data to read\n # do something with data\n else:\n # Do something else - delete data, return False\n # to end calls to this function\n\nand that would let you read data from your process.\n" ]
[ 4, 2 ]
[]
[]
[ "canonical_quickly", "gtk", "pygtk", "python" ]
stackoverflow_0002992458_canonical_quickly_gtk_pygtk_python.txt
Q: Python-based password tracker (or dictionary) Where we work we need to remember about 10 long passwords which need to change every so often. I would like to create a utility which can potentially save these passwords in an encrypted file so that we can keep track of them. I can think of some sort of dictionary passwd = {'host1':'pass1', 'host2':'pass2'}, etc, but I don't know what to do about encryption (absolutely zero experience in the topic). So, my question is really two questions: Is there a Linux-based utility which lets you do that? If you were to program it in Python, how would you go about it? A perk of approach two, would be for the software to update the ssh public keys after the password has been changed (you know the pain of updating ~15 tokens once you change your password). As it can be expected, I have zero control over the actual network configuration and the management of scp keys. I can only hope to provide a simple utility to me an my very few coworkers so that, if we need to, we can retrieve a password on demand. Cheers. A: Answers to your questions: Yes. Take a look at KeePass. I wouldn't program a utility like this in Python, because there are available open source tools already. Furthermore, I would have concerns about protecting the unencrypted passwords as they were processed by a Python program. Hope that helps. A: You might want to checkout ecryptfs. It should be available for any Linux OS. On Ubuntu, setting it up is as easy as sudo apt-get install ecryptfs-utils ecryptfs-setup-private This creates a directory for encrypted files, typically called ~/.Private. To use it: mount -t ecryptfs ~/.Private ~/Private This mounts the encrypted files from ~/.Private at the mount point ~/Private. You can read/write the plain text files in ~/Private. umount ~/Private updates the encrypted files in ~/.Private and removes ~/Private. See these links home page linux journal tutorial another tutorial for more information. A: On first i think you can change passwords on md5 of this passwords.. it will give more safety. A: You could use TrueCrypt or AxCrypt -- both are Open Source solutions. I'll echo Mox's concerns about the unencrypted PWs. Of course you could also follow Bruce Schneier's advice about password protection...
Python-based password tracker (or dictionary)
Where we work we need to remember about 10 long passwords which need to change every so often. I would like to create a utility which can potentially save these passwords in an encrypted file so that we can keep track of them. I can think of some sort of dictionary passwd = {'host1':'pass1', 'host2':'pass2'}, etc, but I don't know what to do about encryption (absolutely zero experience in the topic). So, my question is really two questions: Is there a Linux-based utility which lets you do that? If you were to program it in Python, how would you go about it? A perk of approach two, would be for the software to update the ssh public keys after the password has been changed (you know the pain of updating ~15 tokens once you change your password). As it can be expected, I have zero control over the actual network configuration and the management of scp keys. I can only hope to provide a simple utility to me an my very few coworkers so that, if we need to, we can retrieve a password on demand. Cheers.
[ "Answers to your questions:\n\nYes. Take a look at KeePass.\nI wouldn't program a utility like this in Python, because there are available open source tools already. Furthermore, I would have concerns about protecting the unencrypted passwords as they were processed by a Python program.\n\nHope that helps.\n", "You might want to checkout ecryptfs. It should be available for any Linux OS.\nOn Ubuntu, setting it up is as easy as \nsudo apt-get install ecryptfs-utils\necryptfs-setup-private\n\nThis creates a directory for encrypted files, typically called ~/.Private.\nTo use it:\nmount -t ecryptfs ~/.Private ~/Private\n\nThis mounts the encrypted files from ~/.Private at the mount point ~/Private.\nYou can read/write the plain text files in ~/Private. \numount ~/Private\n\nupdates the encrypted files in ~/.Private and removes ~/Private.\nSee these links\n\nhome page\nlinux journal\ntutorial\nanother tutorial\n\nfor more information.\n", "On first i think you can change passwords on md5 of this passwords..\nit will give more safety.\n", "You could use TrueCrypt or AxCrypt -- both are Open Source solutions. I'll echo Mox's concerns about the unencrypted PWs.\nOf course you could also follow Bruce Schneier's advice about password protection... \n" ]
[ 4, 3, 0, 0 ]
[]
[]
[ "encryption", "passwords", "python" ]
stackoverflow_0002992057_encryption_passwords_python.txt
Q: computing z-scores for 2D matrices in scipy/numpy in Python How can I compute the z-score for matrices in Python? Suppose I have the array: a = array([[ 1, 2, 3], [ 30, 35, 36], [2000, 6000, 8000]]) and I want to compute the z-score for each row. The solution I came up with is: array([zs(item) for item in a]) where zs is in scipy.stats.stats. Is there a better built-in vectorized way to do this? Also, is it always good to z-score numbers before using hierarchical clustering with euclidean or seuclidean distance? Can anyone discuss the relative advantages/disadvantages? thanks. A: scipy.stats.stats.zs is defined like this: def zs(a): mu = mean(a,None) sigma = samplestd(a) return (array(a)-mu)/sigma So to extend it to work on a given axis of an ndarray, you could do this: import numpy as np import scipy.stats.stats as sss def my_zs(a,axis=-1): b=np.array(a).swapaxes(axis,-1) mu = np.mean(b,axis=-1)[...,np.newaxis] sigma = sss.samplestd(b,axis=-1)[...,np.newaxis] return (b-mu)/sigma a = np.array([[ 1, 2, 3], [ 30, 35, 36], [2000, 6000, 8000]]) result=np.array([sss.zs(item) for item in a]) my_result=my_zs(a) print(my_result) # [[-1.22474487 0. 1.22474487] # [-1.3970014 0.50800051 0.88900089] # [-1.33630621 0.26726124 1.06904497]] assert(np.allclose(result,my_result)) A: the new zscore of scipy, available in the next release takes arbitrary array dimension http://projects.scipy.org/scipy/changeset/6169
computing z-scores for 2D matrices in scipy/numpy in Python
How can I compute the z-score for matrices in Python? Suppose I have the array: a = array([[ 1, 2, 3], [ 30, 35, 36], [2000, 6000, 8000]]) and I want to compute the z-score for each row. The solution I came up with is: array([zs(item) for item in a]) where zs is in scipy.stats.stats. Is there a better built-in vectorized way to do this? Also, is it always good to z-score numbers before using hierarchical clustering with euclidean or seuclidean distance? Can anyone discuss the relative advantages/disadvantages? thanks.
[ "scipy.stats.stats.zs is defined like this:\ndef zs(a):\n mu = mean(a,None)\n sigma = samplestd(a)\n return (array(a)-mu)/sigma\n\nSo to extend it to work on a given axis of an ndarray, you could do this:\nimport numpy as np\nimport scipy.stats.stats as sss\ndef my_zs(a,axis=-1):\n b=np.array(a).swapaxes(axis,-1) \n mu = np.mean(b,axis=-1)[...,np.newaxis]\n sigma = sss.samplestd(b,axis=-1)[...,np.newaxis]\n return (b-mu)/sigma\n\n\na = np.array([[ 1, 2, 3],\n [ 30, 35, 36],\n [2000, 6000, 8000]]) \nresult=np.array([sss.zs(item) for item in a])\n\nmy_result=my_zs(a)\nprint(my_result)\n# [[-1.22474487 0. 1.22474487]\n# [-1.3970014 0.50800051 0.88900089]\n# [-1.33630621 0.26726124 1.06904497]]\nassert(np.allclose(result,my_result))\n\n", "the new zscore of scipy, available in the next release takes arbitrary array dimension\nhttp://projects.scipy.org/scipy/changeset/6169\n" ]
[ 3, 2 ]
[]
[]
[ "cluster_analysis", "machine_learning", "numpy", "python", "scipy" ]
stackoverflow_0002985135_cluster_analysis_machine_learning_numpy_python_scipy.txt
Q: in pylongs, is there a way to loop through all the controllers and actions? in pylons, is it possible to loop through all the controllers and their actions? I want to create a javascript object that has all the controllers and their actions A: I'm writing this under the assumption that you're trying to do a "table of contents" thing. If this is not the case and the below information is not helpful, my apologies. If you know the controllers you want the actions for before-hand (that is to say, before runtime), you could write def contents(self): return [action for action in dir(self) if all( not action in ['contents','start_response'], not action.startswith('_'), callable(action))] for each controller and then have another controller (ContentsController, say) call the .contents() method for each.
in pylongs, is there a way to loop through all the controllers and actions?
in pylons, is it possible to loop through all the controllers and their actions? I want to create a javascript object that has all the controllers and their actions
[ "I'm writing this under the assumption that you're trying to do a \"table of contents\" thing. If this is not the case and the below information is not helpful, my apologies.\n\nIf you know the controllers you want the actions for before-hand (that is to say, before runtime), you could write\ndef contents(self):\n return [action for action in dir(self) if all(\n not action in ['contents','start_response'],\n not action.startswith('_'),\n callable(action))]\nfor each controller and then have another controller (ContentsController, say) call the .contents() method for each.\n" ]
[ 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002981110_pylons_python.txt
Q: How to ignore GUI as much as possible without rendering APP less GUI developer friendly The substance of an app is more important to me than its apperance, yet GUI always seems to dominate a disproportionate percentage of programmer time, development and target resource requirements/constraints. Ideally I'd like an application architecture that will permit me to develop an app using a lightweight reference GUI/kit and focus on non gui aspects to produce a quality app which is GUI enabled/friendly. I would want APP and the GUI to be sufficiently decoupled to maximize the ease for you GUI experts to plug the app into to some target GUI design/framework/context. e.g. targets such as: termcap GUI, web app GUI framework, desktop GUI, thin client GUI. In short: How do I mostly ignore the GUI, but avoid painting you into a corner when I don't even know who you are yet? A: Write a core library that handles the functionality and provides hooks for progress notification. Then write the interfaces as separate applications or libraries that use the core library. A: The answer you seek is MVC - Model/View/Controller.
How to ignore GUI as much as possible without rendering APP less GUI developer friendly
The substance of an app is more important to me than its apperance, yet GUI always seems to dominate a disproportionate percentage of programmer time, development and target resource requirements/constraints. Ideally I'd like an application architecture that will permit me to develop an app using a lightweight reference GUI/kit and focus on non gui aspects to produce a quality app which is GUI enabled/friendly. I would want APP and the GUI to be sufficiently decoupled to maximize the ease for you GUI experts to plug the app into to some target GUI design/framework/context. e.g. targets such as: termcap GUI, web app GUI framework, desktop GUI, thin client GUI. In short: How do I mostly ignore the GUI, but avoid painting you into a corner when I don't even know who you are yet?
[ "Write a core library that handles the functionality and provides hooks for progress notification. Then write the interfaces as separate applications or libraries that use the core library.\n", "The answer you seek is MVC - Model/View/Controller. \n" ]
[ 3, 1 ]
[]
[]
[ "portability", "python", "user_interface" ]
stackoverflow_0002991910_portability_python_user_interface.txt
Q: HttpError 502 with Google Wave Active Robot API fetch_wavelet() I am trying to use the Google Wave Active Robot API fetch_wavelet() and I get an HTTP 502 error example: from waveapi import robot import passwords robot = robot.Robot('gae-run', 'http://images.com/fake-image.jpg') robot.setup_oauth(passwords.CONSUMER_KEY, passwords.CONSUMER_SECRET, server_rpc_base='http://www-opensocial.googleusercontent.com/api/rpc') wavelet = robot.fetch_wavelet('googlewave.com!w+dtuZi6t3C','googlewave.com!conv+root') robot.submit(wavelet) self.response.out.write(wavelet.creator) But the error I get is this: Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 511, in __call__ handler.get(*groups) File "/base/data/home/apps/clstff/gae-run.342467577023864664/main.py", line 23, in get robot.submit(wavelet) File "/base/data/home/apps/clstff/gae-run.342467577023864664/waveapi/robot.py", line 486, in submit res = self.make_rpc(pending) File "/base/data/home/apps/clstff/gae-run.342467577023864664/waveapi/robot.py", line 251, in make_rpc raise IOError('HttpError ' + str(code)) IOError: HttpError 502 Any ideas? Edit: When clstff@appspot.com is not a member of the wave I get the correct error message Error: RPC Error500: internalError: clstff@appspot.com is not a participant of wave id: [WaveId:googlewave.com!w+Pq1HgvssD] wavelet id: [WaveletId:googlewave.com!conv+root]. Unable to apply operation: {'method':'robot.fetchWave','id':'655720','waveId':'googlewave.com!w+Pq1HgvssD','waveletId':'googlewave.com!conv+root','blipId':'null','parameters':{}} But when clstff@appsot.com is a member of the wave I get the http 502 error. IOError: HttpError 502 A: Joe Gregorio answered my question on the Google Wave API Google group Did you make any changes to the wavelet before submitting it? I think there was an old bug where sending in an empty change would cause a 502, this might be a regression in that behavior. If I removed the robot.submit(wavelet) line, it worked!
HttpError 502 with Google Wave Active Robot API fetch_wavelet()
I am trying to use the Google Wave Active Robot API fetch_wavelet() and I get an HTTP 502 error example: from waveapi import robot import passwords robot = robot.Robot('gae-run', 'http://images.com/fake-image.jpg') robot.setup_oauth(passwords.CONSUMER_KEY, passwords.CONSUMER_SECRET, server_rpc_base='http://www-opensocial.googleusercontent.com/api/rpc') wavelet = robot.fetch_wavelet('googlewave.com!w+dtuZi6t3C','googlewave.com!conv+root') robot.submit(wavelet) self.response.out.write(wavelet.creator) But the error I get is this: Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 511, in __call__ handler.get(*groups) File "/base/data/home/apps/clstff/gae-run.342467577023864664/main.py", line 23, in get robot.submit(wavelet) File "/base/data/home/apps/clstff/gae-run.342467577023864664/waveapi/robot.py", line 486, in submit res = self.make_rpc(pending) File "/base/data/home/apps/clstff/gae-run.342467577023864664/waveapi/robot.py", line 251, in make_rpc raise IOError('HttpError ' + str(code)) IOError: HttpError 502 Any ideas? Edit: When clstff@appspot.com is not a member of the wave I get the correct error message Error: RPC Error500: internalError: clstff@appspot.com is not a participant of wave id: [WaveId:googlewave.com!w+Pq1HgvssD] wavelet id: [WaveletId:googlewave.com!conv+root]. Unable to apply operation: {'method':'robot.fetchWave','id':'655720','waveId':'googlewave.com!w+Pq1HgvssD','waveletId':'googlewave.com!conv+root','blipId':'null','parameters':{}} But when clstff@appsot.com is a member of the wave I get the http 502 error. IOError: HttpError 502
[ "Joe Gregorio answered my question on the Google Wave API Google group\n\nDid you make any changes to the\n wavelet before submitting it? I think\n there was an old bug where sending in\n an empty change would cause a 502,\n this might be a regression in that\n behavior.\n\nIf I removed the robot.submit(wavelet) line, it worked!\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "google_wave", "python" ]
stackoverflow_0002982956_google_app_engine_google_wave_python.txt
Q: Python - how to check if weak reference is still available I am passing some weakrefs from Python into C++ class, but C++ destructors are actively trying to access the ref when the real object is already dead, obviously it crashes... Is there any Python C/API approach to find out if Python reference is still alive or any other known workaround for this ? Thanks A: From Python C API documentation: PyObject* PyWeakref_GetObject(PyObject *ref) Return value: Borrowed reference. Return the referenced object from a weak reference, ref. If the referent is no longer live, returns None. New in version 2.2. A: If you call PyWeakref_GetObject on the weak reference it should return either Py_None or NULL, I forget which. But you should check if it's returning one of those and that will tell you that the referenced object is no longer alive.
Python - how to check if weak reference is still available
I am passing some weakrefs from Python into C++ class, but C++ destructors are actively trying to access the ref when the real object is already dead, obviously it crashes... Is there any Python C/API approach to find out if Python reference is still alive or any other known workaround for this ? Thanks
[ "From Python C API documentation:\n\nPyObject* PyWeakref_GetObject(PyObject *ref)\n Return value: Borrowed reference.\n Return the referenced object from a weak reference, ref. If the referent\n is no longer live, returns None. New in version 2.2. \n\n", "If you call PyWeakref_GetObject on the weak reference it should return either Py_None or NULL, I forget which. But you should check if it's returning one of those and that will tell you that the referenced object is no longer alive.\n" ]
[ 4, 3 ]
[]
[]
[ "c++", "python", "reference", "weak" ]
stackoverflow_0002993393_c++_python_reference_weak.txt
Q: Python import error: Symbol not found, but the symbol is *is not* present in the file I get this error when I try to import ssrc.spread: ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/ssrc/_spread.so, 2): Symbol not found: __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE The file in question (_spread.so) includes the symbol: $ nm _spread.so | grep _ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE (twice because the file is a fat ppc/x86 binary) EDIT: okay, as James points out, the U means that the symbol is undefined but required by the object file. With some more digging I've noticed (where I should have looked first...) these linker errors during compilation: CC=g++ CXX=g++ g++-4.0 -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -O3 -I../.. -I../.. -I/usr/local/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -O2 -I/usr/local/include -std=c++98 -pipe -fno-gnu-keywords -fvisibility-inlines-hidden -o SsrcSpread.o -c SsrcSpread.cc CC=g++ CXX=g++ /bin/sh ../../libtool --tag=CXX --mode=link g++-4.0 -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -bundle -undefined dynamic_lookup -F/Library/Frameworks -framework Python \ -pthread -D_REENTRANT -pedantic -Wall -Wno-long-long -Winline -Woverloaded-virtual -Wold-style-cast -Wsign-promo -L../../ssrc -lssrcspread -L/usr/local/lib -ltspread-core -o _spread.so SsrcSpread.o mkdir .libs g++-4.0 -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -bundle -undefined dynamic_lookup -F/Library/Frameworks -framework Python -pthread -D_REENTRANT -pedantic -Wall -Wno-long-long -Winline -Woverloaded-virtual -Wold-style-cast -Wsign-promo -o _spread.so SsrcSpread.o -Wl,-bind_at_load -L/Dev/libssrcspread-1.0.6/ssrc /Dev/libssrcspread-1.0.6/ssrc/.libs/libssrcspread.a -L/usr/local/lib -ltspread-core ld: warning: in ~/Dev/libssrcspread-1.0.6/ssrc/.libs/libssrcspread.a, file was built for unsupported file format which is not the architecture being linked (ppc) ld: warning: in /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib/libtspread-core.dylib, file was built for unsupported file format which is not the architecture being linked (ppc) ld: warning: in /Dev/libssrcspread-1.0.6/ssrc/.libs/libssrcspread.a, file was built for unsupported file format which is not the architecture being linked (i386) ld: warning: in /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib/libtspread-core.dylib, file was built for unsupported file format which is not the architecture being linked (i386) I'm also not entirely sure that the 10.4 sdk is the right one for compiling python modules (but switching to 10.6 didn't seem to help). A: $ nm _spread.so | grep _ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE The _spread.so file does not include the symbol, it is depending on it. The U means undefined. I feel like there may be a version mismatch somewhere, perhaps between the headers and the library binaries. Do you have multiple versions installed?
Python import error: Symbol not found, but the symbol is *is not* present in the file
I get this error when I try to import ssrc.spread: ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/ssrc/_spread.so, 2): Symbol not found: __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE The file in question (_spread.so) includes the symbol: $ nm _spread.so | grep _ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE (twice because the file is a fat ppc/x86 binary) EDIT: okay, as James points out, the U means that the symbol is undefined but required by the object file. With some more digging I've noticed (where I should have looked first...) these linker errors during compilation: CC=g++ CXX=g++ g++-4.0 -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -O3 -I../.. -I../.. -I/usr/local/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -O2 -I/usr/local/include -std=c++98 -pipe -fno-gnu-keywords -fvisibility-inlines-hidden -o SsrcSpread.o -c SsrcSpread.cc CC=g++ CXX=g++ /bin/sh ../../libtool --tag=CXX --mode=link g++-4.0 -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -bundle -undefined dynamic_lookup -F/Library/Frameworks -framework Python \ -pthread -D_REENTRANT -pedantic -Wall -Wno-long-long -Winline -Woverloaded-virtual -Wold-style-cast -Wsign-promo -L../../ssrc -lssrcspread -L/usr/local/lib -ltspread-core -o _spread.so SsrcSpread.o mkdir .libs g++-4.0 -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -bundle -undefined dynamic_lookup -F/Library/Frameworks -framework Python -pthread -D_REENTRANT -pedantic -Wall -Wno-long-long -Winline -Woverloaded-virtual -Wold-style-cast -Wsign-promo -o _spread.so SsrcSpread.o -Wl,-bind_at_load -L/Dev/libssrcspread-1.0.6/ssrc /Dev/libssrcspread-1.0.6/ssrc/.libs/libssrcspread.a -L/usr/local/lib -ltspread-core ld: warning: in ~/Dev/libssrcspread-1.0.6/ssrc/.libs/libssrcspread.a, file was built for unsupported file format which is not the architecture being linked (ppc) ld: warning: in /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib/libtspread-core.dylib, file was built for unsupported file format which is not the architecture being linked (ppc) ld: warning: in /Dev/libssrcspread-1.0.6/ssrc/.libs/libssrcspread.a, file was built for unsupported file format which is not the architecture being linked (i386) ld: warning: in /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib/libtspread-core.dylib, file was built for unsupported file format which is not the architecture being linked (i386) I'm also not entirely sure that the 10.4 sdk is the right one for compiling python modules (but switching to 10.6 didn't seem to help).
[ "$ nm _spread.so | grep _ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE\n U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE\n U __ZN17ssrcspread_v1_0_67Mailbox11ZeroTimeoutE\n\nThe _spread.so file does not include the symbol, it is depending on it. The U means undefined.\nI feel like there may be a version mismatch somewhere, perhaps between the headers and the library binaries. Do you have multiple versions installed?\n" ]
[ 2 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002989233_macos_python.txt
Q: Django snippet with logic is there a way to create a Django snippet that has logic? I think about something like contact template tag: {% contact_form %} with template: <form action="send_contact_form" method="POST">...</form> with logic: def send_contact_form(): ... I want to be able to use it anywhere in my projects. It should work only by specifying 1 template tag... Do you know what I mean? Is it possible? Thanks in advance, Etam. A: Custom template tags.
Django snippet with logic
is there a way to create a Django snippet that has logic? I think about something like contact template tag: {% contact_form %} with template: <form action="send_contact_form" method="POST">...</form> with logic: def send_contact_form(): ... I want to be able to use it anywhere in my projects. It should work only by specifying 1 template tag... Do you know what I mean? Is it possible? Thanks in advance, Etam.
[ "Custom template tags.\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0002993191_django_django_forms_django_templates_python.txt
Q: Fast method call scheduling in Python For some part of my project I need a process-local scheduling system that will allow me to delay method execution on few seconds. I have thousands of “clients” of this system, so using threading.Timer for each delay is a bad idea because I will quickly reach OS thread limit. I've implemented a system that use only one thread for timing control. The main idea is to keep sorted task (time + func + args + kwargs) queue and to use single threading.Timer to schedule/cancel executions of the head of this queue. This scheme works, but I'm not happy with performance. ~2000 clients that schedule dummy tasks every ~10 seconds cause the process to take 40% of CPU time. Looking at profiler output I see that all time is spent on new threading.Timers construction, its start and particularly on new threads creation. I believe there is a better way. Now I think about rewriting the LightTimer so that there will be one execution thread controllable by threading.Event and several timing threads that will set() the event. For example: I schedule a task to call in 10 secs. The task is added to a queue. Timing thread #1 starts time.sleep(10) before event.set() Then I schedule a task to call in 11 secs. The task is added to the queue. Nothing happens with timing thread, it will notice new task after wake up. Then I schedule a task to call in 5 secs. The task is prepended to the queue. Timing thread #2 starts time.sleep(5) because #1 sleeps already for a longer interval. I hope you've caught the idea. What do you think about this way? Is there a better way? Maybe I can utilize some linux system features to make optimal solution? A: An alternative implementation you could use is to use the time.time() method to calculate the absolute time each queued function should be executed. Place this time and your function-to-be-called in an object wrapper that overrides the comparison operator using the execution time to determine order. Then use the heapq module to maintain a min-heap. This will provide you with an efficient datastructure where element 0 of the heap is always your next event. One way to implement the actual calls would be to use a separate thread to execute the callbacks. The heap will need to be protected with a mutex and you can use a condition variable to implement the scheduling. In an infinite loop, just lookup the next time to execute a function (element 0 of the heap) and use the condition variable's wait() method with the timeout set to the next execution time. Your heap insertion method could then use the condition variable's notify() method to wake the scheduling thread early if the newly inserted function should occur prior to the earliest one already in the heap. A: Have you looked at the sched module in the Python standard library? Running the scheduler on a dedicated thread (and having all the scheduled actions be "put a bound method and its args on a queue" from which threads in a pool peel and execute it -- much as I wrote in the Nutshell chapter on threads, except that in that case there was no scheduling) should do what you want. A: You are unlikely to reach the OS thread limit with "a few thousand clients"; you may consume a lot of unnecessary memory with the stacks for all those threads though. Have a look at what twisted does, it allows a process to multiplex a lot of events (including timers) in a way which has proven to work quite well with large numbers of events. You can also combine event-driven and multi-process models, by running several processes per machine and doing event-driven logic in each one - say one process can handle 2,000 clients, you can still run 30x processes (provided there is sufficient overall resource) and gain better throughput, especially on modern multi-core hardware.
Fast method call scheduling in Python
For some part of my project I need a process-local scheduling system that will allow me to delay method execution on few seconds. I have thousands of “clients” of this system, so using threading.Timer for each delay is a bad idea because I will quickly reach OS thread limit. I've implemented a system that use only one thread for timing control. The main idea is to keep sorted task (time + func + args + kwargs) queue and to use single threading.Timer to schedule/cancel executions of the head of this queue. This scheme works, but I'm not happy with performance. ~2000 clients that schedule dummy tasks every ~10 seconds cause the process to take 40% of CPU time. Looking at profiler output I see that all time is spent on new threading.Timers construction, its start and particularly on new threads creation. I believe there is a better way. Now I think about rewriting the LightTimer so that there will be one execution thread controllable by threading.Event and several timing threads that will set() the event. For example: I schedule a task to call in 10 secs. The task is added to a queue. Timing thread #1 starts time.sleep(10) before event.set() Then I schedule a task to call in 11 secs. The task is added to the queue. Nothing happens with timing thread, it will notice new task after wake up. Then I schedule a task to call in 5 secs. The task is prepended to the queue. Timing thread #2 starts time.sleep(5) because #1 sleeps already for a longer interval. I hope you've caught the idea. What do you think about this way? Is there a better way? Maybe I can utilize some linux system features to make optimal solution?
[ "An alternative implementation you could use is to use the time.time() method to calculate the absolute time each queued function should be executed. Place this time and your function-to-be-called in an object wrapper that overrides the comparison operator using the execution time to determine order. Then use the heapq module to maintain a min-heap. This will provide you with an efficient datastructure where element 0 of the heap is always your next event. \nOne way to implement the actual calls would be to use a separate thread to execute the callbacks. The heap will need to be protected with a mutex and you can use a condition variable to implement the scheduling. In an infinite loop, just lookup the next time to execute a function (element 0 of the heap) and use the condition variable's wait() method with the timeout set to the next execution time. Your heap insertion method could then use the condition variable's notify() method to wake the scheduling thread early if the newly inserted function should occur prior to the earliest one already in the heap.\n", "Have you looked at the sched module in the Python standard library? Running the scheduler on a dedicated thread (and having all the scheduled actions be \"put a bound method and its args on a queue\" from which threads in a pool peel and execute it -- much as I wrote in the Nutshell chapter on threads, except that in that case there was no scheduling) should do what you want.\n", "You are unlikely to reach the OS thread limit with \"a few thousand clients\"; you may consume a lot of unnecessary memory with the stacks for all those threads though.\nHave a look at what twisted does, it allows a process to multiplex a lot of events (including timers) in a way which has proven to work quite well with large numbers of events.\nYou can also combine event-driven and multi-process models, by running several processes per machine and doing event-driven logic in each one - say one process can handle 2,000 clients, you can still run 30x processes (provided there is sufficient overall resource) and gain better throughput, especially on modern multi-core hardware.\n" ]
[ 2, 2, 0 ]
[]
[]
[ "linux", "multithreading", "python", "scheduling", "timer" ]
stackoverflow_0002990088_linux_multithreading_python_scheduling_timer.txt
Q: how to set a pop up menu on a particular table view item i have a QTableView , and i need to show a popup menu that shows the item properties . i need to set the context menu to apear only when you right click over a particular items in that tableview. but coudln't find a way to do it . i can set the context menu to appear when your over the table . i cant have it for each item . so how do i set the context menu over items in the tableview ? please tell me if the idea was not clear enough thanks in advance A: Assuming you're in control of when the menu pops up, then you'll want to use the indexAt(QPoint) member function in order to determine what item the mouse is over. If you're not currently in control of when the menu shows up, you'll need to set the view's contextMenuPolicy to something that will give you control over it. For example, if you subclass and override contextMenuEvent the implementation might look something like the following: void MyView::contextMenuEvent ( QContextMenuEvent * event ) { QModelIndex index = indexAt(event->pos()); if (index.data(Qt::UserRole + NEEDS_CONTEXT_MENU_ROLE_OFFSET).toBool()) // display context menu else // don't display context menu } You could also install an event handler to avoid subclassing.
how to set a pop up menu on a particular table view item
i have a QTableView , and i need to show a popup menu that shows the item properties . i need to set the context menu to apear only when you right click over a particular items in that tableview. but coudln't find a way to do it . i can set the context menu to appear when your over the table . i cant have it for each item . so how do i set the context menu over items in the tableview ? please tell me if the idea was not clear enough thanks in advance
[ "Assuming you're in control of when the menu pops up, then you'll want to use the indexAt(QPoint) member function in order to determine what item the mouse is over.\nIf you're not currently in control of when the menu shows up, you'll need to set the view's contextMenuPolicy to something that will give you control over it.\nFor example, if you subclass and override contextMenuEvent the implementation might look something like the following:\nvoid MyView::contextMenuEvent ( QContextMenuEvent * event )\n{\n QModelIndex index = indexAt(event->pos());\n if (index.data(Qt::UserRole + NEEDS_CONTEXT_MENU_ROLE_OFFSET).toBool())\n // display context menu\n else\n // don't display context menu\n}\n\nYou could also install an event handler to avoid subclassing.\n" ]
[ 2 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0002993426_pyqt_pyqt4_python_qt_qt4.txt
Q: how to create a theme with QT im looking for a way to make my pyqt interface look nicer by adding a theme to it. im new to Qt and i still have no idea how to add a custom theme for widgets.. so how is that possible ? and is it possible through qt designer ? sorry for my bad english , its my third language. i hope the idea is clear enough . please let me know if something was unclear .. thanks in advace A: The most easily implemented method is via Qt's style sheets that are quite similar to CSS. Take a look at the style reference if you need anything more complicated. Qt Designer does give you access to the styleSheet property, although I'd recommend using a separate file for it if you're doing anything non-trivial.
how to create a theme with QT
im looking for a way to make my pyqt interface look nicer by adding a theme to it. im new to Qt and i still have no idea how to add a custom theme for widgets.. so how is that possible ? and is it possible through qt designer ? sorry for my bad english , its my third language. i hope the idea is clear enough . please let me know if something was unclear .. thanks in advace
[ "The most easily implemented method is via Qt's style sheets that are quite similar to CSS. Take a look at the style reference if you need anything more complicated. Qt Designer does give you access to the styleSheet property, although I'd recommend using a separate file for it if you're doing anything non-trivial.\n" ]
[ 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0002993375_pyqt_pyqt4_python_qt_qt4.txt
Q: Spawning and waiting for child processes in Python The relevant part of the code looks like this: pids = [] for size in SIZES: pids.append(os.spawnv(os.P_NOWAIT, RESIZECMD, [RESIZECMD, lotsOfOptions])) # Wait for all spawned imagemagick processes to finish while pids: (pid, status) = os.waitpid(0, 0) if pid: pids.remove(pid) What this should be doing is spawning all of the processes off, then waiting for each process to finish before continuing. What it does is work for the most part but sometimes crash on the next section (when it expects all of these processes to be finished). Is there something wrong with this? Is there a better way of doing it? The environment it has to work on is CentOS with Python 2.4, but I'm testing on Cygwin with Python 2.5, so it could be that it fails on my machine but will work on the Linux one (the Linux machine is very slow and this error is rare, so I haven't been able to get it on there). A: The recommended way to start subprocess is to use the subprocess module. pipe = Popen(["program", "arg1", "arg2"]) pipe.wait() A: I would recommend you install python-subprocess32 -- a robust backport of Python 3's version of the subprocess standard library module, suitable for Python 2.4 to 2.7, and by far the best way to run subprocesses in Python 2. Then, in the loop you'll do pids.append(subprocess.Popen([RESIZECMD, lot, of, options]) and the following loop will just be a simple for pid in pids: pid.wait()
Spawning and waiting for child processes in Python
The relevant part of the code looks like this: pids = [] for size in SIZES: pids.append(os.spawnv(os.P_NOWAIT, RESIZECMD, [RESIZECMD, lotsOfOptions])) # Wait for all spawned imagemagick processes to finish while pids: (pid, status) = os.waitpid(0, 0) if pid: pids.remove(pid) What this should be doing is spawning all of the processes off, then waiting for each process to finish before continuing. What it does is work for the most part but sometimes crash on the next section (when it expects all of these processes to be finished). Is there something wrong with this? Is there a better way of doing it? The environment it has to work on is CentOS with Python 2.4, but I'm testing on Cygwin with Python 2.5, so it could be that it fails on my machine but will work on the Linux one (the Linux machine is very slow and this error is rare, so I haven't been able to get it on there).
[ "The recommended way to start subprocess is to use the subprocess module.\npipe = Popen([\"program\", \"arg1\", \"arg2\"])\npipe.wait()\n\n", "I would recommend you install python-subprocess32 -- a robust backport of Python 3's version of the subprocess standard library module, suitable for Python 2.4 to 2.7, and by far the best way to run subprocesses in Python 2. Then, in the loop you'll do\npids.append(subprocess.Popen([RESIZECMD, lot, of, options])\n\nand the following loop will just be a simple\nfor pid in pids:\n pid.wait()\n\n" ]
[ 5, 3 ]
[]
[]
[ "cygwin", "linux", "process", "python" ]
stackoverflow_0002993487_cygwin_linux_process_python.txt
Q: Searching for duplicate records within a text file where the duplicate is determined by only two fields First, Python Newbie; be patient/kind. Next, once a month I receive a large text file (think 7 Million records) to test for duplicate values. This is catalog information. I get 7 fields, but the two I'm interested in are a supplier code and a full orderable part number. To determine if the record is dupliacted, I compress all special characters from the part number (except . and #) and create a compressed part number. The test for duplicates becomes the supplier code and compressed part number combination. This part is fairly straight forward. Currently, I am just copying the original file with 2 new columns (compressed part and duplicate indicator). If the part is a duplicate, I put a "YES" in the last field. Now that this is done, I want to be able to go back (or better yet, at the same time) to get the previous record where there was a supplier code/compressed part number match. So far, my code looks like this: # Compress Full Part to a Compressed Part # and Check for Duplicates on Supplier Code # and Compressed Part combination import sys import re import time #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ start=time.time() try: file1 = open("C:\Accounting\May Accounting\May.txt", "r") except IOError: print >> sys.stderr, "Cannot Open Read File" sys.exit(1) try: file2 = open(file1.name[0:len(file1.name)-4] + "_" + "COMPRESSPN.txt", "a") except IOError: print >> sys.stderr, "Cannot Open Write File" sys.exit(1) hdrList="CIGSUPPLIER|FULL_PART|PART_STATUS|ALIAS_FLAG|ACQUISITION_FLAG|COMPRESSED_PART|DUPLICATE_INDICATOR" file2.write(hdrList+chr(10)) lines_seen=set() affirm="YES" records = file1.readlines() for record in records: fields = record.split(chr(124)) if fields[0]=="CIGSupplier": continue #If incoming file has a header line, skip it file2.write(fields[0]+"|"), #Supplier Code file2.write(fields[1]+"|"), #Full_Part file2.write(fields[2]+"|"), #Part Status file2.write(fields[3]+"|"), #Alias Flag file2.write(re.sub("[$\r\n]", "", fields[4])+"|"), #Acquisition Flag file2.write(re.sub("[^0-9a-zA-Z.#]", "", fields[1])+"|"), #Compressed_Part dupechk=fields[0]+"|"+re.sub("[^0-9a-zA-Z.#]", "", fields[1]) if dupechk not in lines_seen: file2.write(chr(10)) lines_seen.add(dupechk) else: file2.write(affirm+chr(10)) print "it took", time.time() - start, "seconds." #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ file2.close() file1.close() It runs in less than 6 minutes, so I am happy with this part, even if it is not elegant. Right now, when I get my results, I import the results into Access and do a self join to locate the duplicates. Loading/querying/exporting results in Access a file this size takes around an hour, so I would like to be able to export the matched duplicates to another text file or an Excel file. Confusing enough? Thanks. A: Maybe you could consider building a dictionary mapping (supplier_number, compressed_part_number) tuples to data structures (nested lists perhaps, or instances of a custom class for improved readability & maintainability) holding information on line numbers for the lines the records matching the key tuple appear in your file plus possibly the complete records themselves. This would end up putting all the data from the file into a large in-memory dictionary, which might or might not be a problem depending on your requirements; if you skip the actual records and only hold line numbers, the dictionary will be much smaller. You can then iterate over the entries in the dictionary spitting out the duplicates to a file as you go. A: I think you should sort the entries in the input file first. Maybe it will consume too much memory, but you should first try to read all input in memory, sort this based upon the value of dupechk and then you can iterate over all entries and easily see if there are two or more identical records. Because identical records are grouped, it is easy to output just those records. A: This might be more efficient/feasible for the large files you are dealing with: Sort the file based on the supplier code and compressed part number - dump it to a temporary file. I don't think it is worth actually tacking on the compressed part number, just compute it from the full part number when needed. However, that is pure conjecture and definitely deserves some quick benchmarking. Iterate through the temporary file (might want to take advantage of 'with'). Check if current line's supplier code and compressed part number is identical to previous one - if it is, you have identified a duplicate. Handle as you see fit. Since the file is sorted you reduce the memory requirement of needing to store all the lines in memory to a set of consecutive identical lines. A: You are already reading the whole file into memory. You don't need to sort. Instead of a set, have a dict mapping (supplier, compressed_pn) to line_number_last_seen - 1. That way, when you discover a duplicate, you can output the two duplicate records immediately. This method requires only one pass over the file. You don't need to write a temporary file. If you often have 3 or more records with the same key, you may wish to use an approach that maps the key to a list of line indices. At the end of reading the file, you iterate over the dictionary looking for lists with more than 1 entry. A: Couple of comments: Using file.readlines on a large file is wasteful - it's reading the entire file into memory. You should, instead, take advantage that a file is iterable, reading a single line at a time by default. Your file format is basically a CSV, with a pipe instead of a comma as a separator. So, use the CSV module. The CSV is written in C and escapes most of the interpreted overhead. It also provides a nice iterable interface which also does not require reading the whole file into memory, either. You should additionally use a DictReader from the csv module. If the header is in the file, great, the class will parse it and use as the keys further on. If not, specify the header in the code. Either way, fields[0] is uninformative and error prone. fields["CIGSUPPLIER"] is much more self-documenting. Just as with reading, use the csv module for writing. Again, you can specify the delimiter. Don't use file2.write(char(10)). Use file2.write('\n'), and open your file appropriately. Alternatively, if you're using the csv.writer class, these become unnecessary. Otherwise, your logic and flow looks alright. I'd overall advise against using the chr(*) calls, unless that character is truly unprintable. newlines and pipes are printable (or have supported escapes), and should be used as such.
Searching for duplicate records within a text file where the duplicate is determined by only two fields
First, Python Newbie; be patient/kind. Next, once a month I receive a large text file (think 7 Million records) to test for duplicate values. This is catalog information. I get 7 fields, but the two I'm interested in are a supplier code and a full orderable part number. To determine if the record is dupliacted, I compress all special characters from the part number (except . and #) and create a compressed part number. The test for duplicates becomes the supplier code and compressed part number combination. This part is fairly straight forward. Currently, I am just copying the original file with 2 new columns (compressed part and duplicate indicator). If the part is a duplicate, I put a "YES" in the last field. Now that this is done, I want to be able to go back (or better yet, at the same time) to get the previous record where there was a supplier code/compressed part number match. So far, my code looks like this: # Compress Full Part to a Compressed Part # and Check for Duplicates on Supplier Code # and Compressed Part combination import sys import re import time #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ start=time.time() try: file1 = open("C:\Accounting\May Accounting\May.txt", "r") except IOError: print >> sys.stderr, "Cannot Open Read File" sys.exit(1) try: file2 = open(file1.name[0:len(file1.name)-4] + "_" + "COMPRESSPN.txt", "a") except IOError: print >> sys.stderr, "Cannot Open Write File" sys.exit(1) hdrList="CIGSUPPLIER|FULL_PART|PART_STATUS|ALIAS_FLAG|ACQUISITION_FLAG|COMPRESSED_PART|DUPLICATE_INDICATOR" file2.write(hdrList+chr(10)) lines_seen=set() affirm="YES" records = file1.readlines() for record in records: fields = record.split(chr(124)) if fields[0]=="CIGSupplier": continue #If incoming file has a header line, skip it file2.write(fields[0]+"|"), #Supplier Code file2.write(fields[1]+"|"), #Full_Part file2.write(fields[2]+"|"), #Part Status file2.write(fields[3]+"|"), #Alias Flag file2.write(re.sub("[$\r\n]", "", fields[4])+"|"), #Acquisition Flag file2.write(re.sub("[^0-9a-zA-Z.#]", "", fields[1])+"|"), #Compressed_Part dupechk=fields[0]+"|"+re.sub("[^0-9a-zA-Z.#]", "", fields[1]) if dupechk not in lines_seen: file2.write(chr(10)) lines_seen.add(dupechk) else: file2.write(affirm+chr(10)) print "it took", time.time() - start, "seconds." #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ file2.close() file1.close() It runs in less than 6 minutes, so I am happy with this part, even if it is not elegant. Right now, when I get my results, I import the results into Access and do a self join to locate the duplicates. Loading/querying/exporting results in Access a file this size takes around an hour, so I would like to be able to export the matched duplicates to another text file or an Excel file. Confusing enough? Thanks.
[ "Maybe you could consider building a dictionary mapping (supplier_number, compressed_part_number) tuples to data structures (nested lists perhaps, or instances of a custom class for improved readability & maintainability) holding information on line numbers for the lines the records matching the key tuple appear in your file plus possibly the complete records themselves.\nThis would end up putting all the data from the file into a large in-memory dictionary, which might or might not be a problem depending on your requirements; if you skip the actual records and only hold line numbers, the dictionary will be much smaller.\nYou can then iterate over the entries in the dictionary spitting out the duplicates to a file as you go.\n", "I think you should sort the entries in the input file first. Maybe it will consume too much memory, but you should first try to read all input in memory, sort this based upon the value of dupechk and then you can iterate over all entries and easily see if there are two or more identical records. Because identical records are grouped, it is easy to output just those records.\n", "This might be more efficient/feasible for the large files you are dealing with:\n\nSort the file based on the supplier code and compressed part number - dump it to a temporary file. I don't think it is worth actually tacking on the compressed part number, just compute it from the full part number when needed. However, that is pure conjecture and definitely deserves some quick benchmarking.\nIterate through the temporary file (might want to take advantage of 'with'). Check if current line's supplier code and compressed part number is identical to previous one - if it is, you have identified a duplicate. Handle as you see fit. Since the file is sorted you reduce the memory requirement of needing to store all the lines in memory to a set of consecutive identical lines.\n\n", "You are already reading the whole file into memory. You don't need to sort. Instead of a set, have a dict mapping (supplier, compressed_pn) to line_number_last_seen - 1. That way, when you discover a duplicate, you can output the two duplicate records immediately. This method requires only one pass over the file. You don't need to write a temporary file.\nIf you often have 3 or more records with the same key, you may wish to use an approach that maps the key to a list of line indices. At the end of reading the file, you iterate over the dictionary looking for lists with more than 1 entry.\n", "Couple of comments:\n\nUsing file.readlines on a large file is wasteful - it's reading the entire file into memory. You should, instead, take advantage that a file is iterable, reading a single line at a time by default.\nYour file format is basically a CSV, with a pipe instead of a comma as a separator. So, use the CSV module. The CSV is written in C and escapes most of the interpreted overhead. It also provides a nice iterable interface which also does not require reading the whole file into memory, either.\nYou should additionally use a DictReader from the csv module. If the header is in the file, great, the class will parse it and use as the keys further on. If not, specify the header in the code. Either way, fields[0] is uninformative and error prone. fields[\"CIGSUPPLIER\"] is much more self-documenting.\nJust as with reading, use the csv module for writing. Again, you can specify the delimiter. \nDon't use file2.write(char(10)). Use file2.write('\\n'), and open your file appropriately. Alternatively, if you're using the csv.writer class, these become unnecessary.\n\nOtherwise, your logic and flow looks alright. I'd overall advise against using the chr(*) calls, unless that character is truly unprintable. newlines and pipes are printable (or have supported escapes), and should be used as such.\n" ]
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002991967_python.txt
Q: Display constantly updating information in-place in command-line window using python? I am essentially building a timer. I have a python script that monitors for an event and then prints out the seconds that have elapsed since that event. Instead of an ugly stream of numbers printed to the command line, I would like to display only the current elapsed time "in-place"-- so that only one number is visible at any given time. Is there a simple way to do this? If possible I'd like to use built-in python modules. I'm on Windows, so simpler the better. (E.g. no X11). A: I use this: http://newcenturycomputers.net/projects/wconio.html A: Outputting \b will move the output cursor left 1 cell, and outputting \r will return it to column 0. Make sure to flush the output often though.
Display constantly updating information in-place in command-line window using python?
I am essentially building a timer. I have a python script that monitors for an event and then prints out the seconds that have elapsed since that event. Instead of an ugly stream of numbers printed to the command line, I would like to display only the current elapsed time "in-place"-- so that only one number is visible at any given time. Is there a simple way to do this? If possible I'd like to use built-in python modules. I'm on Windows, so simpler the better. (E.g. no X11).
[ "I use this: http://newcenturycomputers.net/projects/wconio.html\n", "Outputting \\b will move the output cursor left 1 cell, and outputting \\r will return it to column 0. Make sure to flush the output often though.\n" ]
[ 3, 3 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0002993805_command_line_python.txt
Q: wxPython TreeCtrl without showing root while still showing arrows I am making a python tree visualizer using wxPython. It would be used like so: show_tree([ 'A node with no children', ('A node with children', 'A child node', ('A child node with children', 'Another child')) ]) It worked fine but it shows a root with a value of "Tree". I made it so that it would create multiple roots but then learned that I wasn't allowed to do that. I reverted to the original code but used changed it from this: self.tree = wx.TreeCtrl(self) to this: self.tree = wx.TreeCtrl(self, style=wx.TR_HIDE_ROOT). It worked but it didn't show the little arrows on the side so you wouldn't know which nodes had children. Is there any way to hide the root node but keep the arrows. Note: I am on a Mac using Python version 2.5 and wxPython version 2.8.4.0. A: Note: When I posted this I did not realize you were able to apply multiple styles to trees. After trying everything, I realized that it was a combination of TR_HIDE_ROOT and TR_HAS_BUTTONS that does the trick of hiding the root while still showing arrows on the left side that allow you to collapse and hide nodes with children. This is the code I ended up using: self.tree = wx.TreeCtrl(self, style=wx.TR_HAS_BUTTONS + wx.TR_HIDE_ROOT) A: Could wxTR_LINES_AT_ROOT be what you're looking for? From wxWidgets documentation: wxTR_LINES_AT_ROOT Use this style to show lines between root nodes. Only applicable if wxTR_HIDE_ROOT is set and wxTR_NO_LINES is not set. disclaimer: this is for WX in c++, not python but it should be equivalent
wxPython TreeCtrl without showing root while still showing arrows
I am making a python tree visualizer using wxPython. It would be used like so: show_tree([ 'A node with no children', ('A node with children', 'A child node', ('A child node with children', 'Another child')) ]) It worked fine but it shows a root with a value of "Tree". I made it so that it would create multiple roots but then learned that I wasn't allowed to do that. I reverted to the original code but used changed it from this: self.tree = wx.TreeCtrl(self) to this: self.tree = wx.TreeCtrl(self, style=wx.TR_HIDE_ROOT). It worked but it didn't show the little arrows on the side so you wouldn't know which nodes had children. Is there any way to hide the root node but keep the arrows. Note: I am on a Mac using Python version 2.5 and wxPython version 2.8.4.0.
[ "Note: When I posted this I did not realize you were able to apply multiple styles to trees.\nAfter trying everything, I realized that it was a combination of TR_HIDE_ROOT and TR_HAS_BUTTONS that does the trick of hiding the root while still showing arrows on the left side that allow you to collapse and hide nodes with children. This is the code I ended up using:\nself.tree = wx.TreeCtrl(self, style=wx.TR_HAS_BUTTONS + wx.TR_HIDE_ROOT)\n\n", "Could wxTR_LINES_AT_ROOT be what you're looking for?\nFrom wxWidgets documentation:\n\nwxTR_LINES_AT_ROOT\n Use this style to show lines between root nodes.\n Only applicable if wxTR_HIDE_ROOT is set\n and wxTR_NO_LINES is not set.\n\ndisclaimer: this is for WX in c++, not python but it should be equivalent\n" ]
[ 9, 1 ]
[]
[]
[ "python", "root_node", "tree", "treecontrol", "wxwidgets" ]
stackoverflow_0002925971_python_root_node_tree_treecontrol_wxwidgets.txt
Q: Python + PostgreSQL + strange ascii = UTF8 encoding error I have ascii strings which contain the character "\x80" to represent the euro symbol: >>> print "\x80" € When inserting string data containing this character into my database, I get: psycopg2.DataError: invalid byte sequence for encoding "UTF8": 0x80 HINT: This error can also happen if the byte sequence does not match the encodi ng expected by the server, which is controlled by "client_encoding". I'm a unicode newbie. How can I convert my strings containing "\x80" to valid UTF-8 containing that same euro symbol? I've tried calling .encode and .decode on various strings, but run into errors: >>> "\x80".encode("utf-8") Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> "\x80".encode("utf-8") UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: ordinal not in range(128) A: The question starts with a false premise: I have ascii strings which contain the character "\x80" to represent the euro symbol. ASCII characters are in the range "\x00" to "\x7F" inclusive. The previously-accepted now-deleted answer operated under two gross misapprehensions (1) that locale == encoding (2) that the latin1 encoding maps "\x80" to a Euro character. In fact, all of the ISO-8859-x encodings map "\x80" to U+0080 which is one of the C1 control characters, not a Euro character. Only 3 of those encodings (x in (7, 15, 16)) provide the Euro character, as "\xA4". See this Wikipedia article. You need to know what encoding your data is in. What machine was it created on? How? The locale it was created in (not necessarily yours) may give you a clue. Note that "My data is encoded in latin1" is up there with "The cheque's in the mail" and "Of course I'll love you in the morning". Your data is probably encoded in one of the cp125x encodings found on Windows platforms. Note that all of them except cp1251 (Windows Cyrillic) map "\x80" to the euro character: >>> ['\x80'.decode('cp125' + str(x), 'replace') for x in range(9)] [u'\u20ac', u'\u0402', u'\u20ac', u'\u20ac', u'\u20ac', u'\u20ac', u'\u20ac', u'\u20ac', u'\u20ac'] Update in response to the OP's comment I'm reading this data from a file, e.g. open(fname).read(). It contains strings with \x80 in them that represents the euro character. it's just a plain text file. it is generated by another program, but I don't know how it goes about generating the text. what would be a good solution? I'm thinking I can assume that it outputs "\x80" for a euro character, meaning I can assume it's encoded with a cp125x that has that char as the euro. This is a bit confusing: First you say It contains strings with \x80 in them that represents the euro character But later you say I'm thinking I can assume that it outputs "\x80" for a euro character Please explain. Selecting an appropriate cp125x encoding: Where (geographical location) was the file created? In what language(s) is the text written? Any characters other than the presumed euro with values > "\x7f"? If so, which ones and what context are they used in? Update 2 If you don't "know how the program is written", neither you nor we can form an opinion on whether it always uses "\x80" for the euro character. Although doing otherwise would be monumental silliness, it can't be ruled out. If the text is written in the English language and/or it is written in the USA, and/or it's written on a Windows platform, then it's reasonably certain that cp1252 is the way to go ... until you get evidence to the contrary, in which case you'd need to guess an encoding by yourself or answer the (what language, what locality) questions.
Python + PostgreSQL + strange ascii = UTF8 encoding error
I have ascii strings which contain the character "\x80" to represent the euro symbol: >>> print "\x80" € When inserting string data containing this character into my database, I get: psycopg2.DataError: invalid byte sequence for encoding "UTF8": 0x80 HINT: This error can also happen if the byte sequence does not match the encodi ng expected by the server, which is controlled by "client_encoding". I'm a unicode newbie. How can I convert my strings containing "\x80" to valid UTF-8 containing that same euro symbol? I've tried calling .encode and .decode on various strings, but run into errors: >>> "\x80".encode("utf-8") Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> "\x80".encode("utf-8") UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: ordinal not in range(128)
[ "The question starts with a false premise:\n\nI have ascii strings which contain the character \"\\x80\" to represent the euro symbol.\n\nASCII characters are in the range \"\\x00\" to \"\\x7F\" inclusive.\nThe previously-accepted now-deleted answer operated under two gross misapprehensions (1) that locale == encoding (2) that the latin1 encoding maps \"\\x80\" to a Euro character.\nIn fact, all of the ISO-8859-x encodings map \"\\x80\" to U+0080 which is one of the C1 control characters, not a Euro character. Only 3 of those encodings (x in (7, 15, 16)) provide the Euro character, as \"\\xA4\". See this Wikipedia article.\nYou need to know what encoding your data is in. What machine was it created on? How? The locale it was created in (not necessarily yours) may give you a clue.\nNote that \"My data is encoded in latin1\" is up there with \"The cheque's in the mail\" and \"Of course I'll love you in the morning\". Your data is probably encoded in one of the cp125x encodings found on Windows platforms. Note that all of them except cp1251 (Windows Cyrillic) map \"\\x80\" to the euro character:\n>>> ['\\x80'.decode('cp125' + str(x), 'replace') for x in range(9)]\n[u'\\u20ac', u'\\u0402', u'\\u20ac', u'\\u20ac', u'\\u20ac', u'\\u20ac', u'\\u20ac', u'\\u20ac', u'\\u20ac']\n\nUpdate in response to the OP's comment\n\nI'm reading this data from a file, e.g. open(fname).read(). It contains strings with \\x80 in them that represents the euro character. it's just a plain text file. it is generated by another program, but I don't know how it goes about generating the text. what would be a good solution? I'm thinking I can assume that it outputs \"\\x80\" for a euro character, meaning I can assume it's encoded with a cp125x that has that char as the euro.\n\nThis is a bit confusing: First you say\n\nIt contains strings with \\x80 in them that represents the euro character\n\nBut later you say \n\nI'm thinking I can assume that it outputs \"\\x80\" for a euro character\n\nPlease explain.\nSelecting an appropriate cp125x encoding: Where (geographical location) was the file created? In what language(s) is the text written? Any characters other than the presumed euro with values > \"\\x7f\"? If so, which ones and what context are they used in?\nUpdate 2 If you don't \"know how the program is written\", neither you nor we can form an opinion on whether it always uses \"\\x80\" for the euro character. Although doing otherwise would be monumental silliness, it can't be ruled out.\nIf the text is written in the English language and/or it is written in the USA, and/or it's written on a Windows platform, then it's reasonably certain that cp1252 is the way to go ... until you get evidence to the contrary, in which case you'd need to guess an encoding by yourself or answer the (what language, what locality) questions.\n" ]
[ 12 ]
[]
[]
[ "encoding", "postgresql", "python", "unicode", "utf_8" ]
stackoverflow_0002991660_encoding_postgresql_python_unicode_utf_8.txt
Q: Read -> change -> save. Thread safe This code should automatically connect players when they enter a game. But the problem is when two users try to connect at the same time - in this case 2nd user can easily overwrite changes made by 1st user ('room_1' variable). How could I make it thread safe? def join(userId): users = memcache.get('room_1') users.append(userId) memcache.set('room_1', users) return users I'm using Google App Engine (python) and going to implement simple game-server for exchanging peers given by Adobe Stratus. A: Something like this may work. class Room(db.Model): users = db.StringListProperty() def join(userId): def _transaction(): room = Room.get_by_key_name('room_1') if room is None: room = Room(key_name = 'room_1', users = []) room.users.append(userId) room.put() return room.users return db.run_in_transaction(_transaction) A: In Memcache, the INCR operation is atomic, and returns the new value incremented. For instance, if a value is set to 0, you can obtain a lock optimistically by incrementing it. If you get by 1, you can safely write a value. If you get back a 2, you should retry the transaction. http://code.google.com/appengine/docs/python/memcache/functions.html A: You need a read/write lock on your room lists. A: memcache is 'just' a cache, and in its usual guise it's not suitable for an atomic data store, which is what you're trying to use it for. I'd suggest using the GAE datastore instead, which is designed for this sort of issue.
Read -> change -> save. Thread safe
This code should automatically connect players when they enter a game. But the problem is when two users try to connect at the same time - in this case 2nd user can easily overwrite changes made by 1st user ('room_1' variable). How could I make it thread safe? def join(userId): users = memcache.get('room_1') users.append(userId) memcache.set('room_1', users) return users I'm using Google App Engine (python) and going to implement simple game-server for exchanging peers given by Adobe Stratus.
[ "Something like this may work.\nclass Room(db.Model):\n users = db.StringListProperty()\n\ndef join(userId):\n def _transaction():\n room = Room.get_by_key_name('room_1')\n if room is None:\n room = Room(key_name = 'room_1', users = [])\n room.users.append(userId)\n room.put()\n return room.users\n return db.run_in_transaction(_transaction)\n\n", "In Memcache, the INCR operation is atomic, and returns the new value incremented. For instance, if a value is set to 0, you can obtain a lock optimistically by incrementing it. If you get by 1, you can safely write a value. If you get back a 2, you should retry the transaction.\nhttp://code.google.com/appengine/docs/python/memcache/functions.html\n", "You need a read/write lock on your room lists. \n", "memcache is 'just' a cache, and in its usual guise it's not suitable for an atomic data store, which is what you're trying to use it for. I'd suggest using the GAE datastore instead, which is designed for this sort of issue.\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "thread_safety" ]
stackoverflow_0002987429_google_app_engine_python_thread_safety.txt
Q: Python - help on custom wx.Python (pyDev) class I have been hitting a dead end with this program. I am trying to build a class that will let me control the BIP's of a button when it is in use. so far this is what i have (see following.) It keeps running this weird error TypeError: 'module' object is not callable - I, coming from C++ and C# (for some reason the #include... is so much easier) , have no idea what that means, Google is of no help so... I know I need some real help with syntax and such - anything would be helpful. I know there are a lot of questions in this I would really appreciate the help! Note: The base code found here was used to create a skeleton for this 'custom button class' Custom Button import wx from wxPython.wx import * class Custom_Button(wx.PyControl): # The BMP's # AM I DOING THIS RIGHT? - I am trying to get empty 'global' # variables within the class Mouse_over_bmp = None #wxEmptyBitmap(1,1,1) # When the mouse is over Norm_bmp = None #wxEmptyBitmap(1,1,1) # The normal BMP Push_bmp = None #wxEmptyBitmap(1,1,1) # The down BMP Pos_bmp = wx.Point(0,0) # The posisition of the button def __init__(self, parent, NORM_BMP, PUSH_BMP, MOUSE_OVER_BMP, pos, size, text="", id=-1, **kwargs): wx.PyControl.__init__(self,parent, id, **kwargs) # The conversions, hereafter, were to solve another but. I don't know if it is # necessary to do this since the source being given to the class (in this case) # is a BMP - is there a better way to prevent an error that i have not # stumbled accost? # Set the BMP's to the ones given in the constructor self.Mouse_over_bmp = wx.Bitmap(wx.Image(MOUSE_OVER_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) self.Norm_bmp = wx.Bitmap(wx.Image(NORM_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) self.Push_bmp = wx.Bitmap(wx.Image(PUSH_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) self.Pos_bmp = self.pos self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown) self.Bind(wx.EVT_LEFT_UP, self._onMouseUp) self.Bind(wx.EVT_LEAVE_WINDOW, self._onMouseLeave) self.Bind(wx.EVT_ENTER_WINDOW, self._onMouseEnter) self.Bind(wx.EVT_ERASE_BACKGROUND,self._onEraseBackground) self.Bind(wx.EVT_PAINT,self._onPaint) self._mouseIn = self._mouseDown = False def _onMouseEnter(self, event): self._mouseIn = True def _onMouseLeave(self, event): self._mouseIn = False def _onMouseDown(self, event): self._mouseDown = True def _onMouseUp(self, event): self._mouseDown = False self.sendButtonEvent() def sendButtonEvent(self): event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId()) event.SetInt(0) event.SetEventObject(self) self.GetEventHandler().ProcessEvent(event) def _onEraseBackground(self,event): # reduce flicker pass def _onPaint(self, event): dc = wx.BufferedPaintDC(self) dc.SetFont(self.GetFont()) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear() dc.DrawBitmap(self.Norm_bmp) # draw whatever you want to draw # draw glossy bitmaps e.g. dc.DrawBitmap if self._mouseIn: # If the Mouse is over the button dc.DrawBitmap(self, self.Mouse_over_bmp, self.Pos_bmp, useMask=False) if self._mouseDown: # If the Mouse clicks the button dc.DrawBitmap(self, self.Push_bmp, self.Pos_bmp, useMask=False) Main.py import wx import Custom_Button from wxPython.wx import * ID_ABOUT = 101 ID_EXIT = 102 class MyFrame(wx.Frame): def __init__(self, parent, ID, title): wxFrame.__init__(self, parent, ID, title, wxDefaultPosition, wxSize(400, 400)) self.CreateStatusBar() self.SetStatusText("Program testing custom button overlays") menu = wxMenu() menu.Append(ID_ABOUT, "&About", "More information about this program") menu.AppendSeparator() menu.Append(ID_EXIT, "E&xit", "Terminate the program") menuBar = wxMenuBar() menuBar.Append(menu, "&File"); self.SetMenuBar(menuBar) self.Button1 = Custom_Button(self, parent, -1, "D:/Documents/Python/Normal.bmp", "D:/Documents/Python/Clicked.bmp", "D:/Documents/Python/Over.bmp", wx.Point(200,200), wx.Size(300,100)) EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self, ID_EXIT, self.TimeToQuit) def OnAbout(self, event): dlg = wxMessageDialog(self, "Testing the functions of custom " "buttons using pyDev and wxPython", "About", wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() def TimeToQuit(self, event): self.Close(true) class MyApp(wx.App): def OnInit(self): frame = MyFrame(NULL, -1, "wxPython | Buttons") frame.Show(true) self.SetTopWindow(frame) return true app = MyApp(0) app.MainLoop() Errors (and traceback) /home/wallter/python/Custom Button overlay/src/Custom_Button.py:8: DeprecationWarning: The wxPython compatibility package is no longer automatically generated or actively maintained. Please switch to the wx package as soon as possible. I have never been able to get this to go away whenever using wxPython any help? from wxPython.wx import * Traceback (most recent call last): File "/home/wallter/python/Custom Button overlay/src/Main.py", line 57, in <module> app = MyApp(0) File "/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode/wx/_core.py", line 7978, in __init__ self._BootstrapApp() File "/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode/wx/_core.py", line 7552, in _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "/home/wallter/python/Custom Button overlay/src/Main.py", line 52, in OnInit frame = MyFrame(NULL, -1, "wxPython | Buttons") File "/home/wallter/python/Custom Button overlay/src/Main.py", line 32, in __init__ wx.Point(200,200), wx.Size(300,100)) TypeError: 'module' object is not callable I have tried removing the "wx.Point(200,200), wx.Size(300,100))" just to have the error move up to the line above. Have I declared it right? help? Prevous questions with this code: here A: Commented out this whole thing and the error went away and a window popped up: self.Button1 = Custom_Button(self, parent, -1, "D:/Documents/Python/Normal.bmp", "D:/Documents/Python/Clicked.bmp", "D:/Documents/Python/Over.bmp", wx.Point(200,200), wx.Size(300,100)) So getting somewhere here... okay found the problem: It's the import Custom_Button. That just imports the module. You want to use the class with the same name in that module instead so: from Custom_Button import Custom_Button And that problem is fixed. You can then move on to the next error... It was a bit hard to see the problem right away for me because you're programming in a different style than Python. Unlike other programming languages, Python has a particular Programming Style defined in a document. There are slight deviations from it here and there but overall most good Python developers follow it rather closely because it makes sense and helps make spotting problems easier. Official Python Style Guide Google Version Google version adds more to it and is a bit more restrictive even. So it this case the module files should instead named custom_button.py and main.py. The class should be named CustomButton. A: When you import a module in Python, think of it as importing a namespace one level up in C# For instance in C#, when you say import System.IO; you can specify var file = new File("a.txt"); But if you just say import System; you have to say var file = new IO.File("a.txt"); In Python if you did the equivilent import System.IO you'd still need to say file = IO.File("a.txt") In order to not need to preface it in Python, you'd either need to say from System.IO import File or from System.IO import * which is more like the C# version. The advantage of being able to specify specific classes is when you have namespaces with lots of classes, or maybe there are conflicting class names in 2 modules you want to import. In C# you'd either need to alias the namespace or specify the full name, where you can instead just import the specific ones you want in Python.
Python - help on custom wx.Python (pyDev) class
I have been hitting a dead end with this program. I am trying to build a class that will let me control the BIP's of a button when it is in use. so far this is what i have (see following.) It keeps running this weird error TypeError: 'module' object is not callable - I, coming from C++ and C# (for some reason the #include... is so much easier) , have no idea what that means, Google is of no help so... I know I need some real help with syntax and such - anything would be helpful. I know there are a lot of questions in this I would really appreciate the help! Note: The base code found here was used to create a skeleton for this 'custom button class' Custom Button import wx from wxPython.wx import * class Custom_Button(wx.PyControl): # The BMP's # AM I DOING THIS RIGHT? - I am trying to get empty 'global' # variables within the class Mouse_over_bmp = None #wxEmptyBitmap(1,1,1) # When the mouse is over Norm_bmp = None #wxEmptyBitmap(1,1,1) # The normal BMP Push_bmp = None #wxEmptyBitmap(1,1,1) # The down BMP Pos_bmp = wx.Point(0,0) # The posisition of the button def __init__(self, parent, NORM_BMP, PUSH_BMP, MOUSE_OVER_BMP, pos, size, text="", id=-1, **kwargs): wx.PyControl.__init__(self,parent, id, **kwargs) # The conversions, hereafter, were to solve another but. I don't know if it is # necessary to do this since the source being given to the class (in this case) # is a BMP - is there a better way to prevent an error that i have not # stumbled accost? # Set the BMP's to the ones given in the constructor self.Mouse_over_bmp = wx.Bitmap(wx.Image(MOUSE_OVER_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) self.Norm_bmp = wx.Bitmap(wx.Image(NORM_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) self.Push_bmp = wx.Bitmap(wx.Image(PUSH_BMP, wx.BITMAP_TYPE_ANY).ConvertToBitmap()) self.Pos_bmp = self.pos self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown) self.Bind(wx.EVT_LEFT_UP, self._onMouseUp) self.Bind(wx.EVT_LEAVE_WINDOW, self._onMouseLeave) self.Bind(wx.EVT_ENTER_WINDOW, self._onMouseEnter) self.Bind(wx.EVT_ERASE_BACKGROUND,self._onEraseBackground) self.Bind(wx.EVT_PAINT,self._onPaint) self._mouseIn = self._mouseDown = False def _onMouseEnter(self, event): self._mouseIn = True def _onMouseLeave(self, event): self._mouseIn = False def _onMouseDown(self, event): self._mouseDown = True def _onMouseUp(self, event): self._mouseDown = False self.sendButtonEvent() def sendButtonEvent(self): event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId()) event.SetInt(0) event.SetEventObject(self) self.GetEventHandler().ProcessEvent(event) def _onEraseBackground(self,event): # reduce flicker pass def _onPaint(self, event): dc = wx.BufferedPaintDC(self) dc.SetFont(self.GetFont()) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear() dc.DrawBitmap(self.Norm_bmp) # draw whatever you want to draw # draw glossy bitmaps e.g. dc.DrawBitmap if self._mouseIn: # If the Mouse is over the button dc.DrawBitmap(self, self.Mouse_over_bmp, self.Pos_bmp, useMask=False) if self._mouseDown: # If the Mouse clicks the button dc.DrawBitmap(self, self.Push_bmp, self.Pos_bmp, useMask=False) Main.py import wx import Custom_Button from wxPython.wx import * ID_ABOUT = 101 ID_EXIT = 102 class MyFrame(wx.Frame): def __init__(self, parent, ID, title): wxFrame.__init__(self, parent, ID, title, wxDefaultPosition, wxSize(400, 400)) self.CreateStatusBar() self.SetStatusText("Program testing custom button overlays") menu = wxMenu() menu.Append(ID_ABOUT, "&About", "More information about this program") menu.AppendSeparator() menu.Append(ID_EXIT, "E&xit", "Terminate the program") menuBar = wxMenuBar() menuBar.Append(menu, "&File"); self.SetMenuBar(menuBar) self.Button1 = Custom_Button(self, parent, -1, "D:/Documents/Python/Normal.bmp", "D:/Documents/Python/Clicked.bmp", "D:/Documents/Python/Over.bmp", wx.Point(200,200), wx.Size(300,100)) EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self, ID_EXIT, self.TimeToQuit) def OnAbout(self, event): dlg = wxMessageDialog(self, "Testing the functions of custom " "buttons using pyDev and wxPython", "About", wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() def TimeToQuit(self, event): self.Close(true) class MyApp(wx.App): def OnInit(self): frame = MyFrame(NULL, -1, "wxPython | Buttons") frame.Show(true) self.SetTopWindow(frame) return true app = MyApp(0) app.MainLoop() Errors (and traceback) /home/wallter/python/Custom Button overlay/src/Custom_Button.py:8: DeprecationWarning: The wxPython compatibility package is no longer automatically generated or actively maintained. Please switch to the wx package as soon as possible. I have never been able to get this to go away whenever using wxPython any help? from wxPython.wx import * Traceback (most recent call last): File "/home/wallter/python/Custom Button overlay/src/Main.py", line 57, in <module> app = MyApp(0) File "/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode/wx/_core.py", line 7978, in __init__ self._BootstrapApp() File "/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode/wx/_core.py", line 7552, in _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "/home/wallter/python/Custom Button overlay/src/Main.py", line 52, in OnInit frame = MyFrame(NULL, -1, "wxPython | Buttons") File "/home/wallter/python/Custom Button overlay/src/Main.py", line 32, in __init__ wx.Point(200,200), wx.Size(300,100)) TypeError: 'module' object is not callable I have tried removing the "wx.Point(200,200), wx.Size(300,100))" just to have the error move up to the line above. Have I declared it right? help? Prevous questions with this code: here
[ "Commented out this whole thing and the error went away and a window popped up:\n self.Button1 = Custom_Button(self, parent, -1, \n \"D:/Documents/Python/Normal.bmp\", \n \"D:/Documents/Python/Clicked.bmp\",\n \"D:/Documents/Python/Over.bmp\",\n wx.Point(200,200), wx.Size(300,100))\n\nSo getting somewhere here...\nokay found the problem:\nIt's the import Custom_Button. That just imports the module. You want to use the class with the same name in that module instead so:\nfrom Custom_Button import Custom_Button\n\nAnd that problem is fixed. You can then move on to the next error...\nIt was a bit hard to see the problem right away for me because you're programming in a different style than Python. Unlike other programming languages, Python has a particular Programming Style defined in a document. There are slight deviations from it here and there but overall most good Python developers follow it rather closely because it makes sense and helps make spotting problems easier.\nOfficial Python Style Guide\nGoogle Version\nGoogle version adds more to it and is a bit more restrictive even.\nSo it this case the module files should instead named custom_button.py and main.py. The class should be named CustomButton. \n", "When you import a module in Python, think of it as importing a namespace one level up in C#\nFor instance in C#, when you say\nimport System.IO; you can specify\nvar file = new File(\"a.txt\");\nBut if you just say import System; you have to say\nvar file = new IO.File(\"a.txt\"); \nIn Python if you did the equivilent import System.IO you'd still need to say\nfile = IO.File(\"a.txt\")\nIn order to not need to preface it in Python, you'd either need to say\nfrom System.IO import File or from System.IO import * which is more like the C# version.\nThe advantage of being able to specify specific classes is when you have namespaces with lots of classes, or maybe there are conflicting class names in 2 modules you want to import. In C# you'd either need to alias the namespace or specify the full name, where you can instead just import the specific ones you want in Python.\n" ]
[ 2, 1 ]
[]
[]
[ "class_design", "custom_controls", "pydev", "python", "wxpython" ]
stackoverflow_0002994289_class_design_custom_controls_pydev_python_wxpython.txt
Q: Extracting Information from Images What are some fast and somewhat reliable ways to extract information about images? I've been tinkering with OpenCV and this seems so far to be the best route plus it has Python bindings. So to be more specific I'd like to determine what I can about what's in an image. So for example the haar face detection and full body detection classifiers are great - now I can tell that most likely there are faces and / or people in the image as well as about how many. okay - what else - how about whether there are any buildings and if so what do they seem to be - huts, office buildings etc? Is there sky visible, grass, trees and so forth. From what I've read about training classifiers to detect objects, it seems like a rather laborious process 10,000 or so wrong images and 5,000 or so correct samples to train a classifier. I'm hoping that there are some decent ones around already instead of having to do this all myself for a bunch of different objects - or is there some other way to go about this sort of thing? A: Your question is difficult to answer without more clarification about the types of images you are analyzing and your purpose. The tone of the post seems that you are interested in tinkering -- that's fine. If you want to tinker, one example application might be iris identification using wavelet analysis. You can also try motion tracking; I've done that in OpenCV using the sample projects, and it is kind of interesting. You can try image segmentation for the purpose of scene analysis; take an outdoor photo and segment the image according to texture and/or color. There is no hard number for how large your training set must be. It is highly application dependent. A few hundred images may suffice.
Extracting Information from Images
What are some fast and somewhat reliable ways to extract information about images? I've been tinkering with OpenCV and this seems so far to be the best route plus it has Python bindings. So to be more specific I'd like to determine what I can about what's in an image. So for example the haar face detection and full body detection classifiers are great - now I can tell that most likely there are faces and / or people in the image as well as about how many. okay - what else - how about whether there are any buildings and if so what do they seem to be - huts, office buildings etc? Is there sky visible, grass, trees and so forth. From what I've read about training classifiers to detect objects, it seems like a rather laborious process 10,000 or so wrong images and 5,000 or so correct samples to train a classifier. I'm hoping that there are some decent ones around already instead of having to do this all myself for a bunch of different objects - or is there some other way to go about this sort of thing?
[ "Your question is difficult to answer without more clarification about the types of images you are analyzing and your purpose.\nThe tone of the post seems that you are interested in tinkering -- that's fine. If you want to tinker, one example application might be iris identification using wavelet analysis. You can also try motion tracking; I've done that in OpenCV using the sample projects, and it is kind of interesting. You can try image segmentation for the purpose of scene analysis; take an outdoor photo and segment the image according to texture and/or color.\nThere is no hard number for how large your training set must be. It is highly application dependent. A few hundred images may suffice.\n" ]
[ 2 ]
[]
[]
[ "identification", "image", "opencv", "python" ]
stackoverflow_0002994398_identification_image_opencv_python.txt
Q: Network Communication program in python Basically what I'm trying to achieve is a program which allow users to connect to a each other over a network in, essentially, a chat room. What I'm currently struggling with is writing the code so that the users can connect to each other without knowing the IP-address of the computer that the other users are using or knowing the IP-address of a server. Does anyone know of a way in which I could simply have all of the users scan the IP range of my network in order to find any active 'room' and then give the user a chance to connect to it? Also, the hope is that there will be no need for a central server to run this from, rather every user will simply be connected to all other user, essentially being the server and client at the same time. A: I can give you two suggestions. First of all, UDP packets to the broadcast address of your network will be received by everybody. Secondly, there is a protocol for programs offering certain services to find each other on a local network. That protocol is called mDNS, ZeroConf, or Bonjour. Using broadcast UDP is likely going to be the faster route. But if I were you, I'd learn how to use ZeroConf instead. It's supported well under IPv6 and already used by several interesting programs such as SubEthaEdit and Gobby. Here is a link to a nice tutorial for implementing something that speaks ZeroConf in Python. Another recommendation... If you want to hand roll your own broadcast/multicast UDP code and you can be sure that all of the systems you're on are running a Linux that's newer than 2003 or so, and all the Windows systems are XP or better, you can probably get away with using IPv6. The IPv6 link-local (think same LAN) all hosts multicast address is ff02::1. That's really simple and easy, and it will reach all the other systems on the same LAN. It's much better than having to figure out what your network's broadcast address is with IPv4.
Network Communication program in python
Basically what I'm trying to achieve is a program which allow users to connect to a each other over a network in, essentially, a chat room. What I'm currently struggling with is writing the code so that the users can connect to each other without knowing the IP-address of the computer that the other users are using or knowing the IP-address of a server. Does anyone know of a way in which I could simply have all of the users scan the IP range of my network in order to find any active 'room' and then give the user a chance to connect to it? Also, the hope is that there will be no need for a central server to run this from, rather every user will simply be connected to all other user, essentially being the server and client at the same time.
[ "I can give you two suggestions. First of all, UDP packets to the broadcast address of your network will be received by everybody. Secondly, there is a protocol for programs offering certain services to find each other on a local network. That protocol is called mDNS, ZeroConf, or Bonjour.\nUsing broadcast UDP is likely going to be the faster route. But if I were you, I'd learn how to use ZeroConf instead. It's supported well under IPv6 and already used by several interesting programs such as SubEthaEdit and Gobby.\nHere is a link to a nice tutorial for implementing something that speaks ZeroConf in Python.\nAnother recommendation... If you want to hand roll your own broadcast/multicast UDP code and you can be sure that all of the systems you're on are running a Linux that's newer than 2003 or so, and all the Windows systems are XP or better, you can probably get away with using IPv6. The IPv6 link-local (think same LAN) all hosts multicast address is ff02::1. That's really simple and easy, and it will reach all the other systems on the same LAN. It's much better than having to figure out what your network's broadcast address is with IPv4.\n" ]
[ 6 ]
[]
[]
[ "client_server", "networking", "p2p", "python" ]
stackoverflow_0002994430_client_server_networking_p2p_python.txt
Q: Using classes for the first time,help in debugging here is post my code:this is no the entire code but enough to explain my doubt.please discard any code line which u find irrelavent enter code here saving_tree={} isLeaf=False class tree: global saving_tree rootNode=None lispTree=None def __init__(self,x): file=x string=file.readlines() #print string self.lispTree=S_expression(string) self.rootNode=BinaryDecisionNode(0,'Root',self.lispTree) class BinaryDecisionNode: global saving_tree def __init__(self,ind,name,lispTree,parent=None): self.parent=parent nodes=lispTree.getNodes(ind) print nodes self.isLeaf=(nodes[0]==1) nodes=nodes[1]#Nodes are stored self.name=name self.children=[] if self.isLeaf: #Leaf Node print nodes #Set the leaf data self.attribute=nodes print "LeafNode is ",nodes else: #Set the question self.attribute=lispTree.getString(nodes[0]) self.attribute=self.attribute.split() print "Question: ",self.attribute,self.name tree={} tree={str(self.name):self.attribute} saving_tree=tree #Add the children for i in range(1,len(nodes)):#Since node 0 is a question # print "Adding child ",nodes[i]," who has ",len(nodes)-1," siblings" self.children.append(BinaryDecisionNode(nodes[i],self.name+str(i),lispTree,self)) print saving_tree i wanted to save some data in saving_tree{},which i have declared previously and want to use that saving tree in the another function outside the class.when i asked to print saving_tree it printing but,only for that instance.i want the saving_tree{} to have the data to store data of all instance and access it outside. when i asked for print saving_tree outside the class it prints empty{}.. please tell me the required modification to get my required output and use saving_tree{} outside the class.. A: saving_tree is not global in the __init__ method (which is a different scope than the class body). You could fix that by adding global saving_tree as the first statement in the method (and remove that in the body which plays no role). A better approach would be to forget about global and use a class attribute instead: class BinaryDecisionTree(object): saving_tree = None def __init__ ... ... BinaryDecisionTree.saving_tree = ... globals are always, at best, a so-so approach, and one of the advantages of moving to OOP (object oriented programming, i.e., class statements) is that it saves any need for global as you can always use class or instance attributes instead.
Using classes for the first time,help in debugging
here is post my code:this is no the entire code but enough to explain my doubt.please discard any code line which u find irrelavent enter code here saving_tree={} isLeaf=False class tree: global saving_tree rootNode=None lispTree=None def __init__(self,x): file=x string=file.readlines() #print string self.lispTree=S_expression(string) self.rootNode=BinaryDecisionNode(0,'Root',self.lispTree) class BinaryDecisionNode: global saving_tree def __init__(self,ind,name,lispTree,parent=None): self.parent=parent nodes=lispTree.getNodes(ind) print nodes self.isLeaf=(nodes[0]==1) nodes=nodes[1]#Nodes are stored self.name=name self.children=[] if self.isLeaf: #Leaf Node print nodes #Set the leaf data self.attribute=nodes print "LeafNode is ",nodes else: #Set the question self.attribute=lispTree.getString(nodes[0]) self.attribute=self.attribute.split() print "Question: ",self.attribute,self.name tree={} tree={str(self.name):self.attribute} saving_tree=tree #Add the children for i in range(1,len(nodes)):#Since node 0 is a question # print "Adding child ",nodes[i]," who has ",len(nodes)-1," siblings" self.children.append(BinaryDecisionNode(nodes[i],self.name+str(i),lispTree,self)) print saving_tree i wanted to save some data in saving_tree{},which i have declared previously and want to use that saving tree in the another function outside the class.when i asked to print saving_tree it printing but,only for that instance.i want the saving_tree{} to have the data to store data of all instance and access it outside. when i asked for print saving_tree outside the class it prints empty{}.. please tell me the required modification to get my required output and use saving_tree{} outside the class..
[ "saving_tree is not global in the __init__ method (which is a different scope than the class body). You could fix that by adding global saving_tree as the first statement in the method (and remove that in the body which plays no role).\nA better approach would be to forget about global and use a class attribute instead:\nclass BinaryDecisionTree(object):\n saving_tree = None\n def __init__ ...\n ...\n BinaryDecisionTree.saving_tree = ...\n\nglobals are always, at best, a so-so approach, and one of the advantages of moving to OOP (object oriented programming, i.e., class statements) is that it saves any need for global as you can always use class or instance attributes instead.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002994655_python.txt
Q: IronPython For Unit Testing over C# We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. Is it ideal choice to write unit test cases in IronPython instead of C#? Any body has done like that? I wrote few test cases, they seems to be good. But hairy pointy managers won't accept. A: Python is excellent for UnitTesting C# code. Our app is 75% in Python and 25% C#(Python.Net), and our unit tests are 100% python. I find that it's much easier to make use of stubs and mocks in Python which is probably one of the most critical components that enable one to write effective unittests. A: Will's answer is good - you're introducing a new requirement for developers. In addition, what's the tool support like? I haven't tried any of this myself, but I'd want to know: How easy is it to debug into failing unit tests? How easy is it to run unit tests from the IDE? (e.g. with ReSharper) How easy is it to automate the unit tests from a continuous build server? It could be that all of these are fine - but you should make check them, and document the results. There are other options as well as IronPython, of course - Boo being a fairly obvious choice. A: Python being a much less verbose language than C# might actually lower the barrier to writing unit tests since there is still a lot of developers that are resistant to doing automated unit testing in general. Introducing and having them use a language like IronPython that typically tends to take less time to write the equivalent code in C# might actually encourage more unit tests to be written which is always a good thing. Plus, by using IronPython for your test code, you might end up with less lines of code (LOC) for your project overall meaning that your unit tests might be more likely to be maintained in the long run versus being ignored and/or discarded. A: Actually testing is a great opportunity to try integrating a new language. Languages like Python shine especially well in testing, and it's a low risk project to try - the worst case is not too bad at all. As far as experience testing another language in Python, I've tested C and C++ systems like this and it was excellent. I think it's definitely worth a shot. What Jon says is true, though - the level of tooling for Python in general, and IronPython in particular, is nowhere near that of C#. How much that affects you is something you'll find out in your pilot. A: There's an obvious disadvantage which is that everyone working on the code now needs to be proficient in two languages, not just one. I'm fairly hairy but not very pointy, but I do see why managers might be sceptical. A: I've recently been re-evaluating my testing attitudes after discovering parameterised testing in mbUnit and NUnit. Previously, I recommended Python unittest as a way to automate any testing possible, because of the concise nature and discoverability of the tests. Parameterised tests allow you to customise the test fixtures with a range of data parameters and thus your C# tests can end up even more concise than Python tests. [TestCase(12, 3, 4)] [TestCase(12, 2, 6)] [TestCase(12, 4, 3)] [TestCase(12, 0, 0, ExpectedException = typeof(System.DivideByZeroException), TestName = “DivisionByZeroThrowsExceptionType”)] [TestCase(12, 0, 0, ExpectedExceptionName = “System.DivideByZeroException”, TestName = “DivisionByZeroThrowsNamedException”)] public void IntegerDivisionWithResultPassedToTest(int n, int d, int q) { Assert.AreEqual(q, n / d); } A: Very interesting. What would happen if you write all your code with IronPython (not just the unit tests)? Would you end up with approximately 10 times less code? Maybe I should learn IronPython too. A: I gotta go with Will and Jon.. I would prefer my tests be in the same language as the code I'm testing; it causes fewer cognitive context switches. But maybe I'm just not as mentally agile as I once was. Jon
IronPython For Unit Testing over C#
We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. Is it ideal choice to write unit test cases in IronPython instead of C#? Any body has done like that? I wrote few test cases, they seems to be good. But hairy pointy managers won't accept.
[ "Python is excellent for UnitTesting C# code. Our app is 75% in Python and 25% C#(Python.Net), and our unit tests are 100% python. \nI find that it's much easier to make use of stubs and mocks in Python which is probably one of the most critical components that enable one to write effective unittests.\n", "Will's answer is good - you're introducing a new requirement for developers.\nIn addition, what's the tool support like? I haven't tried any of this myself, but I'd want to know:\n\nHow easy is it to debug into failing unit tests?\nHow easy is it to run unit tests from the IDE? (e.g. with ReSharper)\nHow easy is it to automate the unit tests from a continuous build server?\n\nIt could be that all of these are fine - but you should make check them, and document the results.\nThere are other options as well as IronPython, of course - Boo being a fairly obvious choice.\n", "Python being a much less verbose language than C# might actually lower the barrier to writing unit tests since there is still a lot of developers that are resistant to doing automated unit testing in general. Introducing and having them use a language like IronPython that typically tends to take less time to write the equivalent code in C# might actually encourage more unit tests to be written which is always a good thing.\nPlus, by using IronPython for your test code, you might end up with less lines of code (LOC) for your project overall meaning that your unit tests might be more likely to be maintained in the long run versus being ignored and/or discarded.\n", "Actually testing is a great opportunity to try integrating a new language. Languages like Python shine especially well in testing, and it's a low risk project to try - the worst case is not too bad at all.\nAs far as experience testing another language in Python, I've tested C and C++ systems like this and it was excellent. I think it's definitely worth a shot.\nWhat Jon says is true, though - the level of tooling for Python in general, and IronPython in particular, is nowhere near that of C#. How much that affects you is something you'll find out in your pilot.\n", "There's an obvious disadvantage which is that everyone working on the code now needs to be proficient in two languages, not just one. I'm fairly hairy but not very pointy, but I do see why managers might be sceptical.\n", "I've recently been re-evaluating my testing attitudes after discovering parameterised testing in mbUnit and NUnit. Previously, I recommended Python unittest as a way to automate any testing possible, because of the concise nature and discoverability of the tests.\nParameterised tests allow you to customise the test fixtures with a range of data parameters and thus your C# tests can end up even more concise than Python tests.\n[TestCase(12, 3, 4)]\n[TestCase(12, 2, 6)]\n[TestCase(12, 4, 3)]\n[TestCase(12, 0, 0, ExpectedException = typeof(System.DivideByZeroException),\n TestName = “DivisionByZeroThrowsExceptionType”)]\n[TestCase(12, 0, 0, ExpectedExceptionName = “System.DivideByZeroException”,\n TestName = “DivisionByZeroThrowsNamedException”)]\npublic void IntegerDivisionWithResultPassedToTest(int n, int d, int q)\n{\n Assert.AreEqual(q, n / d);\n}\n\n", "Very interesting. \nWhat would happen if you write all your code with IronPython (not just the unit tests)? Would you end up with approximately 10 times less code? \nMaybe I should learn IronPython too. \n", "I gotta go with Will and Jon..\nI would prefer my tests be in the same language as the code I'm testing; it causes fewer cognitive context switches. But maybe I'm just not as mentally agile as I once was.\n\nJon\n\n" ]
[ 6, 4, 3, 3, 2, 1, 0, 0 ]
[]
[]
[ "c#", "ironpython", "python", "unit_testing" ]
stackoverflow_0000340128_c#_ironpython_python_unit_testing.txt
Q: Monitor web sites visited using Internet Explorer, Opera, Chrome, Firefox and Safari in Python I am working on a project for work and have seemed to run into a small problem. The project is a similar program to Web Nanny, but branded to my client's company. It will have features such as website blocking by URL, keyword and web activity logs. I would also need it to be able to "pause" downloads until an acceptable username and password is entered. I found a script to monitor the URL visited in Internet Explorer (shown below), but it seems to slow the browser down considerably. I have not found any support or ideas onhow to implement this in other browsers. So, my questions are: 1). How to I monitor other browser activity / visited URLs? 2). How do I prevent downloading unless an acceptable username and password is entered? from win32com.client import Dispatch,WithEvents import time,threading,pythoncom,sys stopEvent=threading.Event() class EventSink(object): def OnNavigateComplete2(self,*args): print "complete",args stopEvent.set() def waitUntilReady(ie): if ie.ReadyState!=4: while 1: print "waiting" pythoncom.PumpWaitingMessages() stopEvent.wait(.2) if stopEvent.isSet() or ie.ReadyState==4: stopEvent.clear() break; time.clock() ie=Dispatch('InternetExplorer.Application',EventSink) ev=WithEvents(ie,EventSink) ie.Visible=1 ie.Navigate("http://www.google.com") waitUntilReady(ie) print "location",ie.LocationName ie.Navigate("http://www.aol.com") waitUntilReady(ie) print "location",ie.LocationName print ie.LocationName,time.clock() print ie.ReadyState A: I would recommend looking into a nice web proxy. If the machines are all on the same network you can implement a transparent caching web proxy and put filtering rules on it. They tend to be high speed and can do lots of cool things. I have had some luck with Squid. Would this solve your situation? A: You need to implement this as a C++ BHO, sink DWebBrowserEvents2::OnBeforeNavigate and implement your logic there as it is a place that will block the navigate synchronously until you return, and you can cancel the navigation there as well.
Monitor web sites visited using Internet Explorer, Opera, Chrome, Firefox and Safari in Python
I am working on a project for work and have seemed to run into a small problem. The project is a similar program to Web Nanny, but branded to my client's company. It will have features such as website blocking by URL, keyword and web activity logs. I would also need it to be able to "pause" downloads until an acceptable username and password is entered. I found a script to monitor the URL visited in Internet Explorer (shown below), but it seems to slow the browser down considerably. I have not found any support or ideas onhow to implement this in other browsers. So, my questions are: 1). How to I monitor other browser activity / visited URLs? 2). How do I prevent downloading unless an acceptable username and password is entered? from win32com.client import Dispatch,WithEvents import time,threading,pythoncom,sys stopEvent=threading.Event() class EventSink(object): def OnNavigateComplete2(self,*args): print "complete",args stopEvent.set() def waitUntilReady(ie): if ie.ReadyState!=4: while 1: print "waiting" pythoncom.PumpWaitingMessages() stopEvent.wait(.2) if stopEvent.isSet() or ie.ReadyState==4: stopEvent.clear() break; time.clock() ie=Dispatch('InternetExplorer.Application',EventSink) ev=WithEvents(ie,EventSink) ie.Visible=1 ie.Navigate("http://www.google.com") waitUntilReady(ie) print "location",ie.LocationName ie.Navigate("http://www.aol.com") waitUntilReady(ie) print "location",ie.LocationName print ie.LocationName,time.clock() print ie.ReadyState
[ "I would recommend looking into a nice web proxy. If the machines are all on the same network you can implement a transparent caching web proxy and put filtering rules on it. They tend to be high speed and can do lots of cool things.\nI have had some luck with Squid. Would this solve your situation?\n", "You need to implement this as a C++ BHO, sink DWebBrowserEvents2::OnBeforeNavigate and implement your logic there as it is a place that will block the navigate synchronously until you return, and you can cancel the navigation there as well.\n" ]
[ 2, 0 ]
[]
[]
[ "google_chrome", "internet_explorer", "opera", "python", "safari" ]
stackoverflow_0002994486_google_chrome_internet_explorer_opera_python_safari.txt
Q: django auth : strange error with authenticate() I am using authenticate() to authenticating users manually. Using admin interface I can see that there is no 'last_login' attribute for Users Debug traceback is : Environment: Request Method: GET Request URL: https://localhost/login/ Django Version: 1.1.1 Python Version: 2.6.5 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'mobius.polls'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/pymodules/python2.6/django/contrib/auth/__init__.py" in login 55. user.last_login = datetime.datetime.now() Exception Type: AttributeError at /login/ Exception Value: 'unicode' object has no attribute 'last_login' I cant figure out, why is there this discrepancy. Any kind of help would be appreciated. Thanks in advance! A: The problem isn't with authenticate(), it seems to be with login() which you appear to be passing a unicode into, rather than a django.contrib.auth.models.User object. You should probably be getting that User object from authenticate() user = authenticate(username=username, password=password) ... login(request, user) authenticate and login docs A: The exception value tells it: "user" is a unicode object instead of a django.contrib.auth.models.User object. Are you sure that the database is accessible? try: python manage.py shell >>> from django.contrib.auth.models import User >>> u = User.objects.get(pk=1) >>> u.last_login This code must work correctly. If not, then there's something wrong with your database setup. (maybe you did not do python manage.py syncdb ?) Please post your database related parts of settings.py as well. From your current information it's not easy to find the cause of your problem. The full traceback is helpful as well.
django auth : strange error with authenticate()
I am using authenticate() to authenticating users manually. Using admin interface I can see that there is no 'last_login' attribute for Users Debug traceback is : Environment: Request Method: GET Request URL: https://localhost/login/ Django Version: 1.1.1 Python Version: 2.6.5 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'mobius.polls'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/pymodules/python2.6/django/contrib/auth/__init__.py" in login 55. user.last_login = datetime.datetime.now() Exception Type: AttributeError at /login/ Exception Value: 'unicode' object has no attribute 'last_login' I cant figure out, why is there this discrepancy. Any kind of help would be appreciated. Thanks in advance!
[ "The problem isn't with authenticate(), it seems to be with login() which you appear to be passing a unicode into, rather than a django.contrib.auth.models.User object.\nYou should probably be getting that User object from authenticate()\nuser = authenticate(username=username, password=password)\n...\nlogin(request, user)\n\nauthenticate and login docs\n", "The exception value tells it: \"user\" is a unicode object instead of a django.contrib.auth.models.User object. Are you sure that the database is accessible? try:\npython manage.py shell\n>>> from django.contrib.auth.models import User\n>>> u = User.objects.get(pk=1)\n>>> u.last_login\n\nThis code must work correctly. If not, then there's something wrong with your database setup. (maybe you did not do python manage.py syncdb ?)\nPlease post your database related parts of settings.py as well. From your current information it's not easy to find the cause of your problem.\nThe full traceback is helpful as well.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0002995736_django_django_authentication_python.txt
Q: Efficient and accurate way to compact and compare Python lists? I'm trying to a somewhat sophisticated diff between individual rows in two CSV files. I need to ensure that a row from one file does not appear in the other file, but I am given no guarantee of the order of the rows in either file. As a starting point, I've been trying to compare the hashes of the string representations of the rows (i.e. Python lists). For example: import csv hashes = [] for row in csv.reader(open('old.csv','rb')): hashes.append( hash(str(row)) ) for row in csv.reader(open('new.csv','rb')): if hash(str(row)) not in hashes: print 'Not found' But this is failing miserably. I am constrained by artificially imposed memory limits that I cannot change, and thusly I went with the hashes instead of storing and comparing the lists directly. Some of the files I am comparing can be hundreds of megabytes in size. Any ideas for a way to accurately compress Python lists so that they can be compared in terms of simple equality to other lists? I.e. a hashing system that actually works? Bonus points: why didn't the above method work? EDIT: Thanks for all the great suggestions! Let me clarify some things. "Miserable failure" means that two rows that have the exact same data, after being read in by the CSV.reader object are not hashing to the same value after calling str on the list object. I shall try hashlib at some suggestions below. I also cannot do a hash on the raw file, since two lines below contain the same data, but different characters on the line: 1, 2.3, David S, Monday 1, 2.3, "David S", Monday I am also already doing things like string stripping to make the data more uniform, but it seems to no avail. I'm not looking for an extremely smart diff logic, i.e. that 0 is the same as 0.0. EDIT 2: Problem solved. What basically worked is that I needed to a bit more pre-formatting like converting ints and floats, and so forth AND I needed to change my hashing function. Both these changes seemed to do the job for me. A: It's hard to give a great answer without knowing more about your constraints, but if you can store a hash for each line of each file then you should be ok. At the very least you'll need to be able to store the hash list for one file, which you then would sort and write to disk, then you can march through the two sorted lists together. The only reason why I can imagine the above not working as written would be because your hashing function doesn't always give the same output for a given input. You could test that a second run through old.csv generates the same list. It may have to do with errant spaces, tabs-instead-of-spaces, differing capitalization, "automatic Mind, even if the hashes are equivalent you don't know that the lines match; you only know that they might match. You still need to check that the candidate lines do match. (You may also get the situation where more than one line in the input file generates the same hash, so you'll need to handle that as well.) After you fill your hashes variable, you should consider turning it into a set (hashes = set(hashes)) so that your lookups can be faster than linear. A: Given the loose syntactic definition of CSV, it is possible for two rows to be semantically equal while being lexically different. The various Dialect definitions give some clue as two how two rows could be individually well-formed but incommensurable. And this example shows how they could be in the same dialect and not string equivalent: 0, 0 0, 0.0 More information would help yield a better answer your question. A: More information would be needed on what exactly "failing miserably" means. If you are just not getting correct comparison between the two, perhaps Hashlib might solve that. I've run into trouble previously when using the built in hash library, and solved it with that. Edit: As someone suggested on another post, the issue could be with assuming that the two files are required to have each line be EXACTLY the same. You might want to try parsing the csv fields and appending them to a string with identical formatting (maybe trim spaces, force lowercase, etc) before computing the hash. A: I'm pretty sure that the "failing miserably" line refers to a failure in time that comes from your current algorithm being O(N^2) which is quite bad for how big your files are. As has been mentioned, you can use a set to alieviate this problem (will become O(N)) or if you aren't able to do that for some reason then you can sort the list of hashes and use a binary search on it (will become O(N log N) which is also doable. You can use the bisect module if you go the binary search route. Also, it has been mentioned that you may have the problem of a clash in the hashes: two lines yielding the same hash when the lines aren't exactly the same. If you discover that this is a problem that you are experiencing, you will have to store info with each hash about where to seek the line corresponding to the hash in the old.csv file and then seek the line out and compare the two lines. An alternative to your current method is to sort the two files beforehand (using some sort of merge sort to disk perhaps or shell sort) and, keeping pointers to lines in each file, compare the two lines. Check if they match, and if not then advance the line that is measured as being lesser. This algorithm is also O(N log N) as long as an O(N log N) method is used for sorting. The sorting could also be done by putting each file into a database and having the database sort them. A: This is likely a problem with (mis)using hash. See this SO question; as the answers there point out, you probably want hashlib. A: You need to say what your problem really is. Your description "I need to ensure that a row from one file does not appear in the other file" is consistent with the body of your second loop being if hash(...) in hashes: print "Found (an interloper)" rather that what you have. We can't tell you "why didn't the above method work" because you haven't told us what the symptoms of "failed miserably" and "didn't work" are. A: Have you perhaps considered running a sort (if possible) - you'll have to go over twice of course - but might solve the mem problem.
Efficient and accurate way to compact and compare Python lists?
I'm trying to a somewhat sophisticated diff between individual rows in two CSV files. I need to ensure that a row from one file does not appear in the other file, but I am given no guarantee of the order of the rows in either file. As a starting point, I've been trying to compare the hashes of the string representations of the rows (i.e. Python lists). For example: import csv hashes = [] for row in csv.reader(open('old.csv','rb')): hashes.append( hash(str(row)) ) for row in csv.reader(open('new.csv','rb')): if hash(str(row)) not in hashes: print 'Not found' But this is failing miserably. I am constrained by artificially imposed memory limits that I cannot change, and thusly I went with the hashes instead of storing and comparing the lists directly. Some of the files I am comparing can be hundreds of megabytes in size. Any ideas for a way to accurately compress Python lists so that they can be compared in terms of simple equality to other lists? I.e. a hashing system that actually works? Bonus points: why didn't the above method work? EDIT: Thanks for all the great suggestions! Let me clarify some things. "Miserable failure" means that two rows that have the exact same data, after being read in by the CSV.reader object are not hashing to the same value after calling str on the list object. I shall try hashlib at some suggestions below. I also cannot do a hash on the raw file, since two lines below contain the same data, but different characters on the line: 1, 2.3, David S, Monday 1, 2.3, "David S", Monday I am also already doing things like string stripping to make the data more uniform, but it seems to no avail. I'm not looking for an extremely smart diff logic, i.e. that 0 is the same as 0.0. EDIT 2: Problem solved. What basically worked is that I needed to a bit more pre-formatting like converting ints and floats, and so forth AND I needed to change my hashing function. Both these changes seemed to do the job for me.
[ "It's hard to give a great answer without knowing more about your constraints, but if you can store a hash for each line of each file then you should be ok. At the very least you'll need to be able to store the hash list for one file, which you then would sort and write to disk, then you can march through the two sorted lists together.\nThe only reason why I can imagine the above not working as written would be because your hashing function doesn't always give the same output for a given input. You could test that a second run through old.csv generates the same list. It may have to do with errant spaces, tabs-instead-of-spaces, differing capitalization, \"automatic\nMind, even if the hashes are equivalent you don't know that the lines match; you only know that they might match. You still need to check that the candidate lines do match. (You may also get the situation where more than one line in the input file generates the same hash, so you'll need to handle that as well.)\nAfter you fill your hashes variable, you should consider turning it into a set (hashes = set(hashes)) so that your lookups can be faster than linear.\n", "Given the loose syntactic definition of CSV, it is possible for two rows to be semantically equal while being lexically different. The various Dialect definitions give some clue as two how two rows could be individually well-formed but incommensurable. And this example shows how they could be in the same dialect and not string equivalent:\n0, 0\n0, 0.0\n\nMore information would help yield a better answer your question.\n", "More information would be needed on what exactly \"failing miserably\" means. If you are just not getting correct comparison between the two, perhaps Hashlib might solve that.\nI've run into trouble previously when using the built in hash library, and solved it with that.\nEdit: As someone suggested on another post, the issue could be with assuming that the two files are required to have each line be EXACTLY the same. You might want to try parsing the csv fields and appending them to a string with identical formatting (maybe trim spaces, force lowercase, etc) before computing the hash.\n", "I'm pretty sure that the \"failing miserably\" line refers to a failure in time that comes from your current algorithm being O(N^2) which is quite bad for how big your files are. As has been mentioned, you can use a set to alieviate this problem (will become O(N)) or if you aren't able to do that for some reason then you can sort the list of hashes and use a binary search on it (will become O(N log N) which is also doable. You can use the bisect module if you go the binary search route.\nAlso, it has been mentioned that you may have the problem of a clash in the hashes: two lines yielding the same hash when the lines aren't exactly the same. If you discover that this is a problem that you are experiencing, you will have to store info with each hash about where to seek the line corresponding to the hash in the old.csv file and then seek the line out and compare the two lines.\nAn alternative to your current method is to sort the two files beforehand (using some sort of merge sort to disk perhaps or shell sort) and, keeping pointers to lines in each file, compare the two lines. Check if they match, and if not then advance the line that is measured as being lesser. This algorithm is also O(N log N) as long as an O(N log N) method is used for sorting. The sorting could also be done by putting each file into a database and having the database sort them. \n", "This is likely a problem with (mis)using hash. See this SO question; as the answers there point out, you probably want hashlib.\n", "You need to say what your problem really is. Your description \"I need to ensure that a row from one file does not appear in the other file\" is consistent with the body of your second loop being if hash(...) in hashes: print \"Found (an interloper)\" rather that what you have.\nWe can't tell you \"why didn't the above method work\" because you haven't told us what the symptoms of \"failed miserably\" and \"didn't work\" are.\n", "Have you perhaps considered running a sort (if possible) - you'll have to go over twice of course - but might solve the mem problem.\n" ]
[ 4, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "comparison", "hash", "list", "python" ]
stackoverflow_0002994159_comparison_hash_list_python.txt
Q: How to poll a file in /sys I am stuck reading a file in /sys/ which contains the light intensity in Lux of the ambient light sensor on my Nokia N900 phone. See thread on talk.maemo.org here I tried to use pyinotify to poll the file but this looks some kind of wrong to me since the file is alway "process_IN_OPEN", "process_IN_ACCESS" and "process_IN_CLOSE_NOWRITE" I basically want to get the changes ASAP and if something changed trigger an event, execute a class... Here's the code I tried, which works, but not as I expected (I was hoping for process_IN_MODIFY to be triggered): #!/usr/bin/env python import os, time, pyinotify import pyinotify ambient_sensor = '/sys/class/i2c-adapter/i2c-2/2-0029/lux' wm = pyinotify.WatchManager() # Watch Manager mask = pyinotify.ALL_EVENTS def action(self, the_event): value = open(the_event.pathname, 'r').read().strip() return value class EventHandler(pyinotify.ProcessEvent): ... def process_IN_MODIFY(self, event): print "MODIFY event:", action(self, event) ... #log.setLevel(10) notifier = pyinotify.ThreadedNotifier(wm, EventHandler()) notifier.start() wdd = wm.add_watch(ambient_sensor, mask) wdd time.sleep(5) notifier.stop() Update 1: Mmmh, all I came up without having a clue if there is a special mechanism is the following: f = open('/sys/class/i2c-adapter/i2c-2/2-0029/lux') while True: value = f.read() print value f.seek(0) This, wrapped in a own thread, could to the trick, but does anyone have a smarter, less CPU-hogging and faster way to get the latest value? A: Since the /sys/file is a pseudo-file which just presents a view on an underlying, volatile operating system value, it makes sense that there would never be a modify event raised. Since the file is "modified" from below it doesn't follow regular file-system semantics. If a modify event is never raised, using a package like pinotify isn't going to get you anywhere. 'twould be better to look for a platform-specific mechanism. Response to Update 1: Since the N900 maemo runtime supports GFileMonitor, you'd do well to check if it can provide the asynchronous event that you desire. Busy waiting - as I gather you know - is wasteful. On a phone it can really drain a battery. You should at least sleep in your busy loop. A: Mmmh, all I came up without having a clue if there is a special mechanism is the following: f = open('/sys/class/i2c-adapter/i2c-2/2-0029/lux') while True: value = f.read() print value f.seek(0) This, wrapped in a own thread, could to the trick, but does anyone have a smarter, less CPU-hogging and faster way to get the latest value? Cheers Bjoern
How to poll a file in /sys
I am stuck reading a file in /sys/ which contains the light intensity in Lux of the ambient light sensor on my Nokia N900 phone. See thread on talk.maemo.org here I tried to use pyinotify to poll the file but this looks some kind of wrong to me since the file is alway "process_IN_OPEN", "process_IN_ACCESS" and "process_IN_CLOSE_NOWRITE" I basically want to get the changes ASAP and if something changed trigger an event, execute a class... Here's the code I tried, which works, but not as I expected (I was hoping for process_IN_MODIFY to be triggered): #!/usr/bin/env python import os, time, pyinotify import pyinotify ambient_sensor = '/sys/class/i2c-adapter/i2c-2/2-0029/lux' wm = pyinotify.WatchManager() # Watch Manager mask = pyinotify.ALL_EVENTS def action(self, the_event): value = open(the_event.pathname, 'r').read().strip() return value class EventHandler(pyinotify.ProcessEvent): ... def process_IN_MODIFY(self, event): print "MODIFY event:", action(self, event) ... #log.setLevel(10) notifier = pyinotify.ThreadedNotifier(wm, EventHandler()) notifier.start() wdd = wm.add_watch(ambient_sensor, mask) wdd time.sleep(5) notifier.stop() Update 1: Mmmh, all I came up without having a clue if there is a special mechanism is the following: f = open('/sys/class/i2c-adapter/i2c-2/2-0029/lux') while True: value = f.read() print value f.seek(0) This, wrapped in a own thread, could to the trick, but does anyone have a smarter, less CPU-hogging and faster way to get the latest value?
[ "Since the /sys/file is a pseudo-file which just presents a view on an underlying, volatile operating system value, it makes sense that there would never be a modify event raised. Since the file is \"modified\" from below it doesn't follow regular file-system semantics.\nIf a modify event is never raised, using a package like pinotify isn't going to get you anywhere. 'twould be better to look for a platform-specific mechanism.\nResponse to Update 1:\nSince the N900 maemo runtime supports GFileMonitor, you'd do well to check if it can provide the asynchronous event that you desire.\nBusy waiting - as I gather you know - is wasteful. On a phone it can really drain a battery. You should at least sleep in your busy loop.\n", "Mmmh, all I came up without having a clue if there is a special mechanism is the following:\nf = open('/sys/class/i2c-adapter/i2c-2/2-0029/lux')\nwhile True:\n value = f.read()\n print value\n f.seek(0)\n\nThis, wrapped in a own thread, could to the trick, but does anyone have a smarter, less CPU-hogging and faster way to get the latest value?\nCheers\nBjoern\n" ]
[ 1, 0 ]
[]
[]
[ "maemo", "pyinotify", "python", "sys" ]
stackoverflow_0002995664_maemo_pyinotify_python_sys.txt
Q: Why doesn't Python require exactly four spaces per indentation level? Whitespace is signification in Python in that code blocks are defined by their indentation. Furthermore, Guido van Rossum recommends using four spaces per indentation level (see PEP 8: Style Guide for Python Code). What was the reasoning behind not requiring exactly four spaces per indentation level as well? Are there any technical reasons? It seems like all the arguments that can be made for making whitespace define code blocks can also be used to argument for setting an exact whitespace length for one indentation level (say four spaces). A: There are no technical reasons. It would not be too hard to modify the Python interpreter to require exactly four spaces per indentation level. Here is one use case for other indentation levels: when typing into the interactive interpreter, it's very handy to use one-space indentations. It saves on typing, it's easier to count the number of spaces correctly, and readability is not a major concern (since the code isn't even saved in a file). A: Another case that I just encountered on the tutor@python.org mailing list - A blind programmer who is working in Python uses a reader program - apparently the reader program isn't terribly fond of multiple spaces, so it's easier on him to use a single space. There's really no good or technical reason to require exactly 4 spaces, and I think the best argument against requirement is that programmers hate to be restricted, especially by stupid and somewhat arbitrary rules. Sure we all agree that 4 spaces is best and most of us have editors automagically set our indentation, but on the occasions you don't want to use 4 spaces - one off script code, etc. - you have now alienated a programmer who feels the crushing hand of an arbitrary (style) requirement. The importance of whitespace isn't a problem for most people for a few reasons. First, I can't think of a single (good) programmer who would argue that proper code formatting is a bad thing. Second, logic requires us to separate our code into blocks. Many languages use {} delimiters. In assembly it's usually labels. Python's choice of whitespace is actually fairly natural, at least for the English language. When you read a book, or a newspaper, or a blog post, when someone makes a quote it's usually indented. Paragraphs are separated by a blank line or two. Chapters are usually separated by blank space at the end of a page and blank space at the beginning of the next. So whitespace is a good thing, but forcing programmers to adhere to your particular standard will get programmers to go do something else with their time. A: See PEP 666 - Reject Foolish Indentation A: Using 1 space (or tab) saves space while code-golfing :-p A: Joel's Best Software Writing antology starts with Ken Arnold's interesting and provocative essay "Style is Substance", from Ken's post you can also read here. It's a well-argued essay with the thesis, and I quote, that "the only way to get from where we are to a place where we stop worrying about style is to enforce it as part of the language". It's the only essay I've ever read that proposes that languages' compilers should lock down every aspect of style (your idea about locking down amount of indentation, for example, would be part of that -- not just in Python, either... Ken's main past contributions are Jini, curses, javaspaces, rogue, and parts of Corba, nothing Python-related). It makes really good points, and in the online version's comments you can see some counterpoints (alas, not necessarily equally well argued). I do find it ironic that one responder talks about "Fortran and its strong formatting rules"; that sounds like somebody who never used Fortran, or used it with very shallow and marginal understanding of it. How many languages do you know where you can write, for example, total count = 1 000 000 ...? In Fortran, you can! The spaces are irrelevant, and ignored by the compiler, inside both identifiers and number literals, so you don't have to use underscores or camelcase to make multiword identifiers usable (just use spaces between words!) and it's easy to make large numbers readable too. Some languages did adopt this kind of rules, but most forbid spaces within identifiers and numbers. Of course style flexibility always comes with risks of errors, e.g., in Fortran's case, DO 10 I = 1. 5 assigns to variable DO10I the number 1.5, while the almost-undistinguishable DO 10 I = 1, 5 loops five times on the block from here to line 10 (I believe a real-world occurrence of a bug like this one -- dot instead of comma drastically changing the code's meaning -- once damaged a space mission, but don't recall the exact details). So, please don't take Fortran as an example either for or against "locking down", because in many stylistic aspects it's so incredibly loose instead! Some examples of lockdown include modern languages that take e.g. case conventions and make them enforced parts of the language (uppercase initials for classes, etc) -- I believe Ruby at least warns about this and some other languages actually give compiler errors if you (e.g.) name a class with a lowercase initial or a non-class with an uppercase one. I think the resulting enforced uniformity is a good thing, and I don't see why it should be different where the enforced aspect of style is spacing rather than casing, etc. IOW, Arnold has mostly convinced me about this;-). A: While there are implications made by requiring consistent indentation within a single block, there are no implications made by having indentation levels between blocks be either the same or different. In other words, what would be the point? Comparing it to the whitespace requirement isn't really valid because whitespace is a part of the syntax of Python: it defines scope. So long as scope can be unambiguously defined, why do we care how many spaces are used to define it? What benefit would be offered by forcing everyone to use some (completely arbitrary) fixed number of spaces? What if your word processor forced you to indent paragraphs exactly four spaces? It would be annoying, and it would serve no purpose. It shouldn't serve a purpose to have a fixed number of spaces of indentation. Think about it this way: Python doesn't have a 'whitespace' requirement so much as it has a requirement that you find a way to define scope without braces. What fell out of that was whitespace, and saying it has a 'whitespace requirement' is easier and more obvious than saying it has a 'scope definition sans braces' requirement, so for purposes of succinct communication, we just say it has a 'whitespace requirement' ;-) A: Python is all about rapid prototyping. A lot of the good designs only work because most Python programmers have good practices. That's why we don't depend on accessors and mutators as much as Java, and we can access array indices with negative numbers. In my opinion, limiting the whitespaces to 4 and disallowing tabs doesn't make Python more readable on a large-scale. For a long time, there has been very few issues, because of the good practices we advocate. I truly believe it. Python comes with convenience. A: reindent.py changes any python file to use 4-space indents and no hard tab characters. Having this handy utility around obviates the need to force others to program Python in the 4-space style. PS. Perl, Java, C programmers spend many brain cycles fussing with semicolon syntax errors. Every brain cycle wasted on syntax fluff is a cycle not spend solving real programming problems. One of Python's advantages for rapid development is that it minimizes syntax rules that end up wasting brain cycles. Therefore fewer syntax requirements are better than more. A: Beyond the reasons given above there's another really good reason why you'd want the interpreter to support minimal indentation: Saving space. Due to the limitations of freezing Python bytecode it isn't always practical to ship something with just .pyc files instead of the actual code. This means that if you're writing code to run on a a platform with very limited space (say, an OpenWRT router) it makes a lot of sense to keep the number of spaces to a minimum to save disk space. This is why I wrote pyminifier A: Python is already different than other languages in the way whitespace and line breaks are so significant. It's a unique part of the language and is very clean to work with of course, but I think to add this restriction would reduce flexibility. Also, I like two spaces.... I'd be forced to write my programs with two spaces and then run them through a space doubler script as a compile step. A: To avoid the problems that occur with make's requirement to have tab characters in-front of each action. For example It is a pain if you have tab equals four spaces and you're flicking back and forth from a .c file and a Makefile
Why doesn't Python require exactly four spaces per indentation level?
Whitespace is signification in Python in that code blocks are defined by their indentation. Furthermore, Guido van Rossum recommends using four spaces per indentation level (see PEP 8: Style Guide for Python Code). What was the reasoning behind not requiring exactly four spaces per indentation level as well? Are there any technical reasons? It seems like all the arguments that can be made for making whitespace define code blocks can also be used to argument for setting an exact whitespace length for one indentation level (say four spaces).
[ "There are no technical reasons. It would not be too hard to modify the Python interpreter to require exactly four spaces per indentation level.\nHere is one use case for other indentation levels: when typing into the interactive interpreter, it's very handy to use one-space indentations. It saves on typing, it's easier to count the number of spaces correctly, and readability is not a major concern (since the code isn't even saved in a file).\n", "Another case that I just encountered on the tutor@python.org mailing list - A blind programmer who is working in Python uses a reader program - apparently the reader program isn't terribly fond of multiple spaces, so it's easier on him to use a single space.\nThere's really no good or technical reason to require exactly 4 spaces, and I think the best argument against requirement is that programmers hate to be restricted, especially by stupid and somewhat arbitrary rules. Sure we all agree that 4 spaces is best and most of us have editors automagically set our indentation, but on the occasions you don't want to use 4 spaces - one off script code, etc. - you have now alienated a programmer who feels the crushing hand of an arbitrary (style) requirement.\nThe importance of whitespace isn't a problem for most people for a few reasons. First, I can't think of a single (good) programmer who would argue that proper code formatting is a bad thing. Second, logic requires us to separate our code into blocks. Many languages use {} delimiters. In assembly it's usually labels. Python's choice of whitespace is actually fairly natural, at least for the English language. When you read a book, or a newspaper, or a blog post, when someone makes a quote it's usually indented. Paragraphs are separated by a blank line or two. Chapters are usually separated by blank space at the end of a page and blank space at the beginning of the next. So whitespace is a good thing, but forcing programmers to adhere to your particular standard will get programmers to go do something else with their time.\n", "See PEP 666 - Reject Foolish Indentation\n", "Using 1 space (or tab) saves space while code-golfing :-p\n", "Joel's Best Software Writing antology starts with Ken Arnold's interesting and provocative essay \"Style is Substance\", from Ken's post you can also read here. It's a well-argued essay with the thesis, and I quote, that \"the only way to get from where we are to a place where we stop worrying about style is to enforce it as part of the language\".\nIt's the only essay I've ever read that proposes that languages' compilers should lock down every aspect of style (your idea about locking down amount of indentation, for example, would be part of that -- not just in Python, either... Ken's main past contributions are Jini, curses, javaspaces, rogue, and parts of Corba, nothing Python-related). It makes really good points, and in the online version's comments you can see some counterpoints (alas, not necessarily equally well argued).\nI do find it ironic that one responder talks about \"Fortran and its strong formatting rules\"; that sounds like somebody who never used Fortran, or used it with very shallow and marginal understanding of it. How many languages do you know where you can write, for example,\ntotal count = 1 000 000\n\n...? In Fortran, you can! The spaces are irrelevant, and ignored by the compiler, inside both identifiers and number literals, so you don't have to use underscores or camelcase to make multiword identifiers usable (just use spaces between words!) and it's easy to make large numbers readable too. Some languages did adopt this kind of rules, but most forbid spaces within identifiers and numbers.\nOf course style flexibility always comes with risks of errors, e.g., in Fortran's case,\nDO 10 I = 1. 5\n\nassigns to variable DO10I the number 1.5, while the almost-undistinguishable\nDO 10 I = 1, 5\n\nloops five times on the block from here to line 10 (I believe a real-world occurrence of a bug like this one -- dot instead of comma drastically changing the code's meaning -- once damaged a space mission, but don't recall the exact details).\nSo, please don't take Fortran as an example either for or against \"locking down\", because in many stylistic aspects it's so incredibly loose instead!\nSome examples of lockdown include modern languages that take e.g. case conventions and make them enforced parts of the language (uppercase initials for classes, etc) -- I believe Ruby at least warns about this and some other languages actually give compiler errors if you (e.g.) name a class with a lowercase initial or a non-class with an uppercase one. I think the resulting enforced uniformity is a good thing, and I don't see why it should be different where the enforced aspect of style is spacing rather than casing, etc. IOW, Arnold has mostly convinced me about this;-).\n", "While there are implications made by requiring consistent indentation within a single block, there are no implications made by having indentation levels between blocks be either the same or different. In other words, what would be the point? \nComparing it to the whitespace requirement isn't really valid because whitespace is a part of the syntax of Python: it defines scope. So long as scope can be unambiguously defined, why do we care how many spaces are used to define it? What benefit would be offered by forcing everyone to use some (completely arbitrary) fixed number of spaces? \nWhat if your word processor forced you to indent paragraphs exactly four spaces? It would be annoying, and it would serve no purpose. It shouldn't serve a purpose to have a fixed number of spaces of indentation. \nThink about it this way: Python doesn't have a 'whitespace' requirement so much as it has a requirement that you find a way to define scope without braces. What fell out of that was whitespace, and saying it has a 'whitespace requirement' is easier and more obvious than saying it has a 'scope definition sans braces' requirement, so for purposes of succinct communication, we just say it has a 'whitespace requirement' ;-)\n", "Python is all about rapid prototyping. A lot of the good designs only work because most Python programmers have good practices. That's why we don't depend on accessors and mutators as much as Java, and we can access array indices with negative numbers.\nIn my opinion, limiting the whitespaces to 4 and disallowing tabs doesn't make Python more readable on a large-scale. For a long time, there has been very few issues, because of the good practices we advocate.\nI truly believe it.\nPython comes with convenience.\n", "reindent.py changes any python file to use 4-space indents and no hard tab characters.\nHaving this handy utility around obviates the need to force others to program\nPython in the 4-space style.\nPS. Perl, Java, C programmers spend many brain cycles fussing with semicolon syntax errors. Every brain cycle wasted on syntax fluff is a cycle not spend solving real programming problems. One of Python's advantages for rapid development is that it minimizes syntax rules that end up wasting brain cycles. Therefore fewer syntax requirements are better than more.\n", "Beyond the reasons given above there's another really good reason why you'd want the interpreter to support minimal indentation: Saving space. Due to the limitations of freezing Python bytecode it isn't always practical to ship something with just .pyc files instead of the actual code. This means that if you're writing code to run on a a platform with very limited space (say, an OpenWRT router) it makes a lot of sense to keep the number of spaces to a minimum to save disk space.\nThis is why I wrote pyminifier\n", "Python is already different than other languages in the way whitespace and line breaks are so significant. It's a unique part of the language and is very clean to work with of course, but I think to add this restriction would reduce flexibility.\nAlso, I like two spaces.... I'd be forced to write my programs with two spaces and then run them through a space doubler script as a compile step.\n", "To avoid the problems that occur with make's requirement to have tab characters in-front of each action.\nFor example It is a pain if you have tab equals four spaces and you're flicking back and forth from a .c file and a Makefile\n" ]
[ 30, 11, 8, 6, 5, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "indentation", "python" ]
stackoverflow_0002966285_indentation_python.txt
Q: What is the difference between a module and a script in Python? Think the title summarizes the question :-) A: A script is generally a directly executable piece of code, run by itself. A module is generally a library, imported by other pieces of code. Note that there's no internal distinction -- both are executable and importable, although library code often won't do anything (or will just run its unit tests) when executed directly and importing code designed to be a script will cause it to execute, hence the common if __name__ == "__main__" test. A: Any Python module may be executed as a script. The only significant difference is that when imported as a module the filename is used as the basis for the module name whereas if you execute it as a script the module is named __main__. This distinction makes it possible to have different behaviour when imported by enclosing script specific code in a block guarded by if __name__=="__main__". This has been known to cause confusion when a user attempts to import the main module under its own name rather than importing __main__. A minor difference between scripts and modules is that when you import a module the system will attempt to use an existing .pyc file (provided it exists and is up to date and for that version of Python) and if it has to compile from a .py file it will attempt to save a .pyc file. When you run a .py file as script it does not attempt to load a previously compiled module, nor will it attempt to save the compiled code. For this reason it may be worth keeping scripts small to minimise startup time.
What is the difference between a module and a script in Python?
Think the title summarizes the question :-)
[ "A script is generally a directly executable piece of code, run by itself. A module is generally a library, imported by other pieces of code.\nNote that there's no internal distinction -- both are executable and importable, although library code often won't do anything (or will just run its unit tests) when executed directly and importing code designed to be a script will cause it to execute, hence the common if __name__ == \"__main__\" test.\n", "Any Python module may be executed as a script. The only significant difference is that when imported as a module the filename is used as the basis for the module name whereas if you execute it as a script the module is named __main__.\nThis distinction makes it possible to have different behaviour when imported by enclosing script specific code in a block guarded by if __name__==\"__main__\". This has been known to cause confusion when a user attempts to import the main module under its own name rather than importing __main__.\nA minor difference between scripts and modules is that when you import a module the system will attempt to use an existing .pyc file (provided it exists and is up to date and for that version of Python) and if it has to compile from a .py file it will attempt to save a .pyc file. When you run a .py file as script it does not attempt to load a previously compiled module, nor will it attempt to save the compiled code. For this reason it may be worth keeping scripts small to minimise startup time.\n" ]
[ 62, 31 ]
[]
[]
[ "module", "python", "scripting" ]
stackoverflow_0002996110_module_python_scripting.txt
Q: Elegant ways to print out a bunch of instance attributes in python 2.6? First some background. I'm parsing a simple file format, and wish to re-use the results in python code later, so I made a very simple class hierarchy and wrote the parser to construct objects from the original records in the text files I'm working from. At the same time I'd like to load the data into a legacy database, the loader files for which take a simple tab-separated format. The most straightforward way would be to just do something like: print "{0}\t{1}\t....".format(record.id, record.attr1, len(record.attr1), ...) Because there are so many columns to print out though, I thought I'd use the Template class to make it a bit easier to see what's what, i.e.: templ = Template("$id\t$attr1\t$attr1_len\t...") And I figured I could just use the record in place of the map used by a substitute call, with some additional keywords for derived values: print templ.substitute(record, attr1_len=len(record.attr1), ...) Unfortunately this fails, complaining that the record instance does not have an attribute __getitem__. So my question is twofold: do I need to implement __getitem__ and if so how? is there a more elegant way for something like this where you just need to output a bunch of attributes you already know the name for? A: class MyRecord: #.... def __getitem__(self, key): return getattr(self, key) A: If you make attr1's length a property or attribute of the record class (so you're really just printing instance attributes as the title implies), you could just do this. attrs = ['id', 'attr1', 'attr1_len', ...] print '\t'.join(getattr(record, attr) for attr in attrs)
Elegant ways to print out a bunch of instance attributes in python 2.6?
First some background. I'm parsing a simple file format, and wish to re-use the results in python code later, so I made a very simple class hierarchy and wrote the parser to construct objects from the original records in the text files I'm working from. At the same time I'd like to load the data into a legacy database, the loader files for which take a simple tab-separated format. The most straightforward way would be to just do something like: print "{0}\t{1}\t....".format(record.id, record.attr1, len(record.attr1), ...) Because there are so many columns to print out though, I thought I'd use the Template class to make it a bit easier to see what's what, i.e.: templ = Template("$id\t$attr1\t$attr1_len\t...") And I figured I could just use the record in place of the map used by a substitute call, with some additional keywords for derived values: print templ.substitute(record, attr1_len=len(record.attr1), ...) Unfortunately this fails, complaining that the record instance does not have an attribute __getitem__. So my question is twofold: do I need to implement __getitem__ and if so how? is there a more elegant way for something like this where you just need to output a bunch of attributes you already know the name for?
[ "class MyRecord:\n #.... \n def __getitem__(self, key):\n return getattr(self, key)\n\n", "If you make attr1's length a property or attribute of the record class (so you're really just printing instance attributes as the title implies), you could just do this.\nattrs = ['id', 'attr1', 'attr1_len', ...]\nprint '\\t'.join(getattr(record, attr) for attr in attrs)\n\n" ]
[ 2, 2 ]
[]
[]
[ "oop", "output_formatting", "python" ]
stackoverflow_0002997010_oop_output_formatting_python.txt
Q: importing classes python Just wondering why import sys exit(0) gives me this error: Traceback (most recent call last): File "<pyshell#1>", line 1, in ? exit(0) TypeError: 'str' object is not callable but from sys import exit exit(0) works fine? A: Python imports only the chosen names into the namespace. Your equivalent first solution should be sys.exit(0) since import sys imports only the sys keyword into the current namespace. A: See http://effbot.org/zone/import-confusion.htm for all the different ways to use import in Python. import sys This imports the sys module and binds it to the name "sys" in your namespace. "exit", and other members of the sys module are not brought into the namespace directly but can be accessed like so: sys.exit(0) from sys import exit This imports specific members of the sys module into your namespace. Specifically this binds the name "exit" to the sys.exit function. exit(0) To see what's in your namespace, use the dir function. >>> import sys >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'sys'] >>> >>> from sys import exit >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'exit', 'sys'] You can even see what all is in the sys module itself: >>> dir(sys) ['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver'] A: Ok from your Answers I can remeber that: import sys from * would import all members from sys
importing classes python
Just wondering why import sys exit(0) gives me this error: Traceback (most recent call last): File "<pyshell#1>", line 1, in ? exit(0) TypeError: 'str' object is not callable but from sys import exit exit(0) works fine?
[ "Python imports only the chosen names into the namespace.\nYour equivalent first solution should be\nsys.exit(0)\n\nsince import sys imports only the sys keyword into the current namespace.\n", "See http://effbot.org/zone/import-confusion.htm for all the different ways to use import in Python.\nimport sys\nThis imports the sys module and binds it to the name \"sys\" in your namespace. \"exit\", and other members of the sys module are not brought into the namespace directly but can be accessed like so:\nsys.exit(0)\n\nfrom sys import exit\nThis imports specific members of the sys module into your namespace. Specifically this binds the name \"exit\" to the sys.exit function.\nexit(0)\n\nTo see what's in your namespace, use the dir function.\n>>> import sys\n>>> dir()\n['__builtins__', '__doc__', '__name__', '__package__', 'sys']\n>>>\n>>> from sys import exit\n>>> dir()\n['__builtins__', '__doc__', '__name__', '__package__', 'exit', 'sys']\n\nYou can even see what all is in the sys module itself:\n>>> dir(sys)\n['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']\n\n", "Ok from your Answers I can remeber that:\nimport sys from *\n\nwould import all members from sys\n" ]
[ 8, 6, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002997105_import_python.txt
Q: Datastore performance, my code or the datastore latency I had for the last month a bit of a problem with a quite basic datastore query. It involves 2 db.Models with one referring to the other with a db.ReferenceProperty. The problem is that according to the admin logs the request takes about 2-4 seconds to complete. I strip it down to a bare form and a list to display the results. The put works fine, but the get accumulates (in my opinion) way to much cpu time. #The get look like this: outputData['items'] = {} labelsData = Label.all() for label in labelsData: labelItem = label.item.name if labelItem not in outputData['items']: outputData['items'][labelItem] = { 'item' : labelItem, 'labels' : [] } outputData['items'][labelItem]['labels'].append(label.text) path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, outputData)) #And the models: class Item(db.Model): name = db.StringProperty() class Label(db.Model): text = db.StringProperty() lang = db.StringProperty() item = db.ReferenceProperty(Item) I've tried to make it a number of different way ie. instead of ReferenceProperty storing all Label keys in the Item Model as a db.ListProperty. My test data is just 10 rows in Item and 40 in Label. So my questions: Is it a fools errand to try to optimize this since the high cpu usage is due to the problems with the datastore or have I just screwed up somewhere in the code? ..fredrik EDIT: I got a great response from djidjadji at the google appengine mailing list. The new code looks like this: outputData['items'] = {} labelsData = Label.all().fetch(1000) labelItems = db.get([Label.item.get_value_for_datastore(label) for label in labelsData ]) for label,labelItem in zip(labelsData, labelItems): name = labelItem.name try: outputData['items'][name]['labels'].append(label.text) except KeyError: outputData['items'][name] = { 'item' : name, 'labels' : [label.text] } A: There's certainly things you can do to optimize your code. For example, you're iterating over a query, which is less efficient than fetching the query and iterating over the results. I'd recommend using Appstats to profile your app, and check out the Patterns of Doom series of posts. A: Don't just try things. That's guessing. You'll only be right some of the time. Don't ask other people to guess either, for the same reason. Be right every time. Just pause the code several times and look at the call stack. That will tell you exactly what's going on.
Datastore performance, my code or the datastore latency
I had for the last month a bit of a problem with a quite basic datastore query. It involves 2 db.Models with one referring to the other with a db.ReferenceProperty. The problem is that according to the admin logs the request takes about 2-4 seconds to complete. I strip it down to a bare form and a list to display the results. The put works fine, but the get accumulates (in my opinion) way to much cpu time. #The get look like this: outputData['items'] = {} labelsData = Label.all() for label in labelsData: labelItem = label.item.name if labelItem not in outputData['items']: outputData['items'][labelItem] = { 'item' : labelItem, 'labels' : [] } outputData['items'][labelItem]['labels'].append(label.text) path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, outputData)) #And the models: class Item(db.Model): name = db.StringProperty() class Label(db.Model): text = db.StringProperty() lang = db.StringProperty() item = db.ReferenceProperty(Item) I've tried to make it a number of different way ie. instead of ReferenceProperty storing all Label keys in the Item Model as a db.ListProperty. My test data is just 10 rows in Item and 40 in Label. So my questions: Is it a fools errand to try to optimize this since the high cpu usage is due to the problems with the datastore or have I just screwed up somewhere in the code? ..fredrik EDIT: I got a great response from djidjadji at the google appengine mailing list. The new code looks like this: outputData['items'] = {} labelsData = Label.all().fetch(1000) labelItems = db.get([Label.item.get_value_for_datastore(label) for label in labelsData ]) for label,labelItem in zip(labelsData, labelItems): name = labelItem.name try: outputData['items'][name]['labels'].append(label.text) except KeyError: outputData['items'][name] = { 'item' : name, 'labels' : [label.text] }
[ "There's certainly things you can do to optimize your code. For example, you're iterating over a query, which is less efficient than fetching the query and iterating over the results.\nI'd recommend using Appstats to profile your app, and check out the Patterns of Doom series of posts.\n", "Don't just try things. That's guessing. You'll only be right some of the time. Don't ask other people to guess either, for the same reason.\nBe right every time.\nJust pause the code several times and look at the call stack. That will tell you exactly what's going on.\n" ]
[ 3, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "optimization", "python" ]
stackoverflow_0002995981_google_app_engine_google_cloud_datastore_optimization_python.txt
Q: 404 when getting private YouTube video even when logged in with the owner's account using gdata-python-client If a YouTube video is set as private and I try to fetch it using the gdata Python API a 404 RequestError is raised, even though I have done a programmatic login with the account that owns that video: from gdata.youtube import service yt_service = service.YouTubeService(email=my_email, password=my_password, client_id=my_client_id, source=my_source, developer_key=my_developer_key) yt_service.ProgrammaticLogin() yt_service.GetYouTubeVideoEntry(video_id='IcVqemzfyYs') --------------------------------------------------------------------------- RequestError Traceback (most recent call last) <ipython console> /usr/lib/python2.4/site-packages/gdata/youtube/service.pyc in GetYouTubeVideoEntry(self, uri, video_id) 203 elif video_id and not uri: 204 uri = '%s/%s' % (YOUTUBE_VIDEO_URI, video_id) --> 205 return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString) 206 207 def GetYouTubeContactFeed(self, uri=None, username='default'): /usr/lib/python2.4/site-packages/gdata/service.pyc in Get(self, uri, extra_headers, redirects_remaining, encoding, converter) 1100 'body': result_body} 1101 else: -> 1102 raise RequestError, {'status': server_response.status, 1103 'reason': server_response.reason, 'body': result_body} 1104 RequestError: {'status': 404, 'body': 'Video not found', 'reason': 'Not Found'} This happens every time, unless I go into my YouTube account (through the YouTube website) and set it public, after that I can set it as private and back to public using the Python API. Am I missing a step or is there another (or any) way to fetch a YouTube video set as private from the API? Thanks in advance. A: Apparently the YouTube Data API doesn't allow this (yet), so to workaround this I use the GetYouTubeUserFeed method of a YouTubeService instance to obtain a list of all the video entries I need (whether they are private or public): from gdata.youtube import service VIDEO_ID = 'IcVqemzfyYs' yt_service = service.YouTubeService(email=my_email, password=my_password, client_id=my_client_id, source=my_source, developer_key=my_developer_key) yt_service.ProgrammaticLogin() userfeed = yt_service.GetYouTubeUserFeed(username=my_email[:my_email.index('@')]) video_entry = reduce(lambda e1, e2: e1 if e1.id.text.endswith(VIDEO_ENTRY) else (e2 if e2.id.text.endswith(VIDEO_ENTRY) else None), userfeed.entry) Hope this helps anyone having the same problem :)
404 when getting private YouTube video even when logged in with the owner's account using gdata-python-client
If a YouTube video is set as private and I try to fetch it using the gdata Python API a 404 RequestError is raised, even though I have done a programmatic login with the account that owns that video: from gdata.youtube import service yt_service = service.YouTubeService(email=my_email, password=my_password, client_id=my_client_id, source=my_source, developer_key=my_developer_key) yt_service.ProgrammaticLogin() yt_service.GetYouTubeVideoEntry(video_id='IcVqemzfyYs') --------------------------------------------------------------------------- RequestError Traceback (most recent call last) <ipython console> /usr/lib/python2.4/site-packages/gdata/youtube/service.pyc in GetYouTubeVideoEntry(self, uri, video_id) 203 elif video_id and not uri: 204 uri = '%s/%s' % (YOUTUBE_VIDEO_URI, video_id) --> 205 return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString) 206 207 def GetYouTubeContactFeed(self, uri=None, username='default'): /usr/lib/python2.4/site-packages/gdata/service.pyc in Get(self, uri, extra_headers, redirects_remaining, encoding, converter) 1100 'body': result_body} 1101 else: -> 1102 raise RequestError, {'status': server_response.status, 1103 'reason': server_response.reason, 'body': result_body} 1104 RequestError: {'status': 404, 'body': 'Video not found', 'reason': 'Not Found'} This happens every time, unless I go into my YouTube account (through the YouTube website) and set it public, after that I can set it as private and back to public using the Python API. Am I missing a step or is there another (or any) way to fetch a YouTube video set as private from the API? Thanks in advance.
[ "Apparently the YouTube Data API doesn't allow this (yet), so to workaround this I use the GetYouTubeUserFeed method of a YouTubeService instance to obtain a list of all the video entries I need (whether they are private or public):\nfrom gdata.youtube import service\nVIDEO_ID = 'IcVqemzfyYs'\nyt_service = service.YouTubeService(email=my_email,\n password=my_password,\n client_id=my_client_id,\n source=my_source,\n developer_key=my_developer_key)\nyt_service.ProgrammaticLogin()\nuserfeed = yt_service.GetYouTubeUserFeed(username=my_email[:my_email.index('@')])\nvideo_entry = reduce(lambda e1, e2: e1 if e1.id.text.endswith(VIDEO_ENTRY) else (e2 if e2.id.text.endswith(VIDEO_ENTRY) else None),\n userfeed.entry)\n\nHope this helps anyone having the same problem :)\n" ]
[ 0 ]
[]
[]
[ "gdata_api", "python", "youtube_api" ]
stackoverflow_0002991636_gdata_api_python_youtube_api.txt
Q: Using upload_data on Google AppEngine doesn't let me update entities with id based keys This seems so basic - I must be missing something. I am trying to download my entities, update a few properties, and upload the entities. I'm using the Django nonrel & appengine projects, so all the entities are stored as id rather than name. I can download the entities to csv fine, but when I upload (via appcfg.py upload_data ...), the keys come in as name=... rather than id=... In the config file, I added - import_transform: transform.create_foreign_key('auth_user', key_is_id=True) to see if this would, as the documentation for transform states, "convert the key into an integer to be used as an id." With this import_transform, I get this error - ErrorOnTransform: Numeric keys are not supported on input at this time. Any ideas? A: As the error message indicates, overwriting entities with numeric IDs isn't currently supported. You may be able to work around it by providing a post-upload function that recreates the entity with the relevant key, but I'd suggest stepping back and analyzing why you're doing this - why not just update the entities in-place on App Engine, or use remote_api to do this? Doing a bulk download and upload seems a cumbersome way to handle it.
Using upload_data on Google AppEngine doesn't let me update entities with id based keys
This seems so basic - I must be missing something. I am trying to download my entities, update a few properties, and upload the entities. I'm using the Django nonrel & appengine projects, so all the entities are stored as id rather than name. I can download the entities to csv fine, but when I upload (via appcfg.py upload_data ...), the keys come in as name=... rather than id=... In the config file, I added - import_transform: transform.create_foreign_key('auth_user', key_is_id=True) to see if this would, as the documentation for transform states, "convert the key into an integer to be used as an id." With this import_transform, I get this error - ErrorOnTransform: Numeric keys are not supported on input at this time. Any ideas?
[ "As the error message indicates, overwriting entities with numeric IDs isn't currently supported. You may be able to work around it by providing a post-upload function that recreates the entity with the relevant key, but I'd suggest stepping back and analyzing why you're doing this - why not just update the entities in-place on App Engine, or use remote_api to do this? Doing a bulk download and upload seems a cumbersome way to handle it.\n" ]
[ 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002992107_django_google_app_engine_python.txt
Q: Copy call signature to decorator If I do the following def mydecorator(f): def wrapper(*args, **kwargs): f(*args, **kwargs) wrapper.__doc__ = f.__doc__ wrapper.__name__ = f.__name__ return wrapper @mydecorator def myfunction(a,b,c): '''My docstring''' pass And then type help myfunction, I get: Help on function myfunction in module __main__: myfunction(*args, **kwargs) My docstring So the name and docstring are correctly copied over. Is there a way to also copy over the actual call signature, in this case (a, b, c)? A: Here is an example using Michele Simionato's decorator module to fix the signature: import decorator @decorator.decorator def mydecorator(f,*args, **kwargs): return f(*args, **kwargs) @mydecorator def myfunction(a,b,c): '''My docstring''' pass help(myfunction) # Help on function myfunction in module __main__: # myfunction(a, b, c) # My docstring A: Try the decorator module, available here: http://pypi.python.org/pypi/decorator/3.2.0 Relevant portion of the docs: http://micheles.googlecode.com/hg/decorator/documentation.html#statement-of-the-problem A: This functionality is supplied by the Python standard library's inspect module, specifically by inspect.getargspec. >>> import inspect >>> def f(a, b, c=0, *args, **kwargs): return ... >>> inspect.getargspec(f) ArgSpec(args=['a', 'b', 'c'], varargs='args', keywords='kwargs', defaults=(0,))
Copy call signature to decorator
If I do the following def mydecorator(f): def wrapper(*args, **kwargs): f(*args, **kwargs) wrapper.__doc__ = f.__doc__ wrapper.__name__ = f.__name__ return wrapper @mydecorator def myfunction(a,b,c): '''My docstring''' pass And then type help myfunction, I get: Help on function myfunction in module __main__: myfunction(*args, **kwargs) My docstring So the name and docstring are correctly copied over. Is there a way to also copy over the actual call signature, in this case (a, b, c)?
[ "Here is an example using Michele Simionato's decorator module to fix the signature:\nimport decorator\n\n@decorator.decorator\ndef mydecorator(f,*args, **kwargs):\n return f(*args, **kwargs)\n\n@mydecorator\ndef myfunction(a,b,c):\n '''My docstring'''\n pass\n\nhelp(myfunction)\n# Help on function myfunction in module __main__:\n\n# myfunction(a, b, c)\n# My docstring\n\n", "Try the decorator module, available here: http://pypi.python.org/pypi/decorator/3.2.0\nRelevant portion of the docs: http://micheles.googlecode.com/hg/decorator/documentation.html#statement-of-the-problem\n", "This functionality is supplied by the Python standard library's inspect module, specifically by inspect.getargspec. \n>>> import inspect\n>>> def f(a, b, c=0, *args, **kwargs): return\n... \n>>> inspect.getargspec(f)\nArgSpec(args=['a', 'b', 'c'], varargs='args', keywords='kwargs', defaults=(0,))\n\n" ]
[ 9, 3, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002982974_decorator_python.txt
Q: Django: Filtering datetime field by *only* the year value? I'm trying to spit out a django page which lists all entries by the year they were created. So, for example: 2010: Note 4 Note 5 Note 6 2009: Note 1 Note 2 Note 3 It's proving more difficult than I would have expected. The model from which the data comes is below: class Note(models.Model): business = models.ForeignKey(Business) note = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'client_note' @property def note_year(self): return self.created.strftime('%Y') def __unicode__(self): return '%s' % self.note I've tried a few different ways, but seem to run into hurdles down every path. I'm guessing an effective 'group by' method would do the trick (PostGres DB Backend), but I can't seem to find any Django functionality that supports it. I tried getting individual years from the database but I struggled to find a way of filtering datetime fields by just the year value. Finally, I tried adding the note_year @property but because it's derived, I can't filter those values. Any suggestions for an elegant way to do this? I figure it should be pretty straightforward, but I'm having a heckuva time with it. Any ideas much appreciated. A: Either construct custom SQL or use date_list = Note.objects.all().dates('created', 'year') for years in date_list: Note.objects.filter(created__year = years.year) This is the way it is done in date based generic views. A: You can use django.views.generic.date_based.archive_year or use year field lookup.
Django: Filtering datetime field by *only* the year value?
I'm trying to spit out a django page which lists all entries by the year they were created. So, for example: 2010: Note 4 Note 5 Note 6 2009: Note 1 Note 2 Note 3 It's proving more difficult than I would have expected. The model from which the data comes is below: class Note(models.Model): business = models.ForeignKey(Business) note = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'client_note' @property def note_year(self): return self.created.strftime('%Y') def __unicode__(self): return '%s' % self.note I've tried a few different ways, but seem to run into hurdles down every path. I'm guessing an effective 'group by' method would do the trick (PostGres DB Backend), but I can't seem to find any Django functionality that supports it. I tried getting individual years from the database but I struggled to find a way of filtering datetime fields by just the year value. Finally, I tried adding the note_year @property but because it's derived, I can't filter those values. Any suggestions for an elegant way to do this? I figure it should be pretty straightforward, but I'm having a heckuva time with it. Any ideas much appreciated.
[ "Either construct custom SQL or use\ndate_list = Note.objects.all().dates('created', 'year')\n\nfor years in date_list:\n Note.objects.filter(created__year = years.year)\n\nThis is the way it is done in date based generic views. \n", "You can use django.views.generic.date_based.archive_year or use year field lookup.\n" ]
[ 43, 3 ]
[]
[]
[ "django", "django_models", "django_queryset", "group_by", "python" ]
stackoverflow_0002997433_django_django_models_django_queryset_group_by_python.txt
Q: XML library similar to simplejson/json? - Python is there a similar library to simplejson, which would enable quick serialization of data to and from XML. e.g. json.loads('{vol:'III', title:'Magical Unicorn'}') e.g. json.dumps([1,2,3,4,5]) Any ideas? A: You're not going to find anything for xml as consistent as json, because xml doesn't know about data types. It depends on you to follow conventions or enforce adherence to an xml schema file. That being said, if you're willing to accept the XML-RPC data structure mapping and a few limitations, check out the xmlrpclib package that lives in the Python standard library: http://docs.python.org/library/xmlrpclib.html#convenience-functions >>> import xmlrpclib >>> s = xmlrpclib.dumps( ({'vol':'III', 'title':'Magical Unicorn'},)) >>> print s <params> <param> <value><struct> <member> <name>vol</name> <value><string>III</string></value> </member> <member> <name>title</name> <value><string>Magical Unicorn</string></value> </member> </struct></value> </param> </params> >>> xmlrpclib.loads(s)[0] ({'vol': 'III', 'title': 'Magical Unicorn'},) >>> A: You can look how they have done it in Django: xml_serializer.py and tailor this to your needs. A: I don't know of one. Unless xmlrpc counts... In case you are thinking about rolling your own: Doing anything with ElementTree is a pleasure, compared with most other XML libraries. But, since you'd probably end up with a representation that would be non-standarized, you would need to control both sides, right? Then why not just pick json, pickle or something that is already there? In case you want to use the xmlrpclib module: xmlrpclib.dumps(data) Forest mentions limitations in xmlrpclib, which is a good point. Some that I've seen myself: Integers can't be more than 2^31-1 or the library will complain. "None" values typically aren't OK, but you can get around that. There are probably other limitations as well. Apart from that, the xmlrpc-protocol is pretty verbose. if you need to worry about how much data is sent, it's not the best one. But no XML version will be very efficient. A: It's not as straight forward with xml, as it is with json because, there is no "type mapping" between the datatypes of xml and python. Heck XML data can be anything, as mapped within the corresponding XSL. As for the API is concerned, which you are mostly bothered about, I recommend Element Tree For a good tutorial on Parsing XML using Element Tree, I refer you to Mark Pilgrim's Dive into Python3 A: What about lxml?
XML library similar to simplejson/json? - Python
is there a similar library to simplejson, which would enable quick serialization of data to and from XML. e.g. json.loads('{vol:'III', title:'Magical Unicorn'}') e.g. json.dumps([1,2,3,4,5]) Any ideas?
[ "You're not going to find anything for xml as consistent as json, because xml doesn't know about data types. It depends on you to follow conventions or enforce adherence to an xml schema file.\nThat being said, if you're willing to accept the XML-RPC data structure mapping and a few limitations, check out the xmlrpclib package that lives in the Python standard library:\nhttp://docs.python.org/library/xmlrpclib.html#convenience-functions\n>>> import xmlrpclib\n>>> s = xmlrpclib.dumps( ({'vol':'III', 'title':'Magical Unicorn'},))\n>>> print s\n<params>\n<param>\n<value><struct>\n<member>\n<name>vol</name>\n<value><string>III</string></value>\n</member>\n<member>\n<name>title</name>\n<value><string>Magical Unicorn</string></value>\n</member>\n</struct></value>\n</param>\n</params>\n\n>>> xmlrpclib.loads(s)[0]\n({'vol': 'III', 'title': 'Magical Unicorn'},)\n>>> \n\n", "You can look how they have done it in Django: xml_serializer.py and tailor this to your needs.\n", "I don't know of one. Unless xmlrpc counts... \nIn case you are thinking about rolling your own: Doing anything with ElementTree is a pleasure, compared with most other XML libraries.\nBut, since you'd probably end up with a representation that would be non-standarized, you would need to control both sides, right?\nThen why not just pick json, pickle or something that is already there?\nIn case you want to use the xmlrpclib module:\nxmlrpclib.dumps(data)\n\nForest mentions limitations in xmlrpclib, which is a good point. Some that I've seen myself: Integers can't be more than 2^31-1 or the library will complain. \"None\" values typically aren't OK, but you can get around that. \nThere are probably other limitations as well.\nApart from that, the xmlrpc-protocol is pretty verbose. if you need to worry about how much data is sent, it's not the best one. But no XML version will be very efficient. \n", "It's not as straight forward with xml, as it is with json because, there is no \"type mapping\" between the datatypes of xml and python. Heck XML data can be anything, as mapped within the corresponding XSL.\nAs for the API is concerned, which you are mostly bothered about, I recommend Element Tree\nFor a good tutorial on Parsing XML using Element Tree, I refer you to Mark Pilgrim's Dive into Python3\n", "What about lxml? \n" ]
[ 3, 3, 2, 2, 1 ]
[]
[]
[ "json", "python", "simplejson", "xml" ]
stackoverflow_0002996678_json_python_simplejson_xml.txt
Q: Matching a+ in a regex This should be easy, but I've managed to stump 2 people so far at work & I've been at it for over 3 hours now, so here goes. I need to replace a+ with aplus (along with a few other cases) with the Python re module. eg. "I passed my a+ exam." needs to become "I passed my aplus exam." Just using \ba+ works fine most of the time, but fails in the case of a+b, so I can't use it, it needs to match a+ as a distinct word. I've tried \ba+\b but that fails because I assume the + is a word boundary. I've also tried \ba+\W which does work, but is greedy and eats up the space (or any other non-alpha char that would be there). Any suggestions please? A: Turn that \W into an assertion. \ba\+(?=\W) or, better, \ba\+(?!\w) since the negative assertion allows matching the a+ at end of string too. A: >>> re.sub(r'\ba\+\s', 'aplus ', 'I passed my a+ exam.') 'I passed my aplus exam.' >>> re.sub(r'\ba\+\s', 'aplus ', 'a+b') 'a+b' A: You need to escape the + as it has a special meaning in regexp (one or many a's). search a\+ instead of a+
Matching a+ in a regex
This should be easy, but I've managed to stump 2 people so far at work & I've been at it for over 3 hours now, so here goes. I need to replace a+ with aplus (along with a few other cases) with the Python re module. eg. "I passed my a+ exam." needs to become "I passed my aplus exam." Just using \ba+ works fine most of the time, but fails in the case of a+b, so I can't use it, it needs to match a+ as a distinct word. I've tried \ba+\b but that fails because I assume the + is a word boundary. I've also tried \ba+\W which does work, but is greedy and eats up the space (or any other non-alpha char that would be there). Any suggestions please?
[ "Turn that \\W into an assertion.\n\\ba\\+(?=\\W)\n\nor, better,\n\\ba\\+(?!\\w)\n\nsince the negative assertion allows matching the a+ at end of string too.\n", ">>> re.sub(r'\\ba\\+\\s', 'aplus ', 'I passed my a+ exam.')\n'I passed my aplus exam.'\n>>> re.sub(r'\\ba\\+\\s', 'aplus ', 'a+b')\n'a+b'\n\n", "You need to escape the + as it has a special meaning in regexp (one or many a's).\nsearch a\\+ instead of a+\n" ]
[ 8, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002997869_python_regex.txt
Q: Python Threading I'm trying to make a simple program that continually displays and updates a label that displays the CPU usage, while having other unrelated things going on. I've done enough research to know that threading is likely going to be involved. However, I'm having trouble applying what I've seen in simple examples of threading to what I'm trying to do. What I currently have going: import Tkinter import psutil,time from PIL import Image, ImageTk class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.labelVariable = Tkinter.StringVar() self.label = Tkinter.Label(self,textvariable=self.labelVariable) self.label.pack() self.button = Tkinter.Button(self,text='button',command=self.A) self.button.pack() def A (self): G = str(round(psutil.cpu_percent(), 1)) + '%' print G self.labelVariable.set(G) def B (self): print "hello" if __name__ == "__main__": app = simpleapp_tk(None) app.mainloop() In the above code I'm basically trying to get command A continually running, while allowing command B to be done when the users presses the button. A: You should never attempt to alter a UI element from a thread that isn't the main thread. What you probably want is after(delay_ms, callback, args). Some information can be over at http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm. As a sample, here's a quick script to show a clock (Note: I've never really used Tk). from Tkinter import * from time import strftime class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.label_var = StringVar() self.label = Label(self, textvariable=self.label_var) self.label.pack() # Start the loop self.go() def go(self): self.label_var.set(strftime("%H:%M:%S")) # The callback is only called once, so call it every time self.after(1000, self.go) app = App() mainloop() A: You don't need threads for such a simple task. You can simply schedule your task to run every second or so, which can be done with the 'after' method; First, add this method to your simpleapp_tk class: def update(self): G = str(round(psutil.cpu_percent(), 1)) + '%' self.labelVariable.set(G) self.after(1000, self.update) Then, in your initialize method add this call: self.update() This will cause the label to be updated to the current cpu value. The update method will then re-schedule itself to run again in one second.
Python Threading
I'm trying to make a simple program that continually displays and updates a label that displays the CPU usage, while having other unrelated things going on. I've done enough research to know that threading is likely going to be involved. However, I'm having trouble applying what I've seen in simple examples of threading to what I'm trying to do. What I currently have going: import Tkinter import psutil,time from PIL import Image, ImageTk class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.labelVariable = Tkinter.StringVar() self.label = Tkinter.Label(self,textvariable=self.labelVariable) self.label.pack() self.button = Tkinter.Button(self,text='button',command=self.A) self.button.pack() def A (self): G = str(round(psutil.cpu_percent(), 1)) + '%' print G self.labelVariable.set(G) def B (self): print "hello" if __name__ == "__main__": app = simpleapp_tk(None) app.mainloop() In the above code I'm basically trying to get command A continually running, while allowing command B to be done when the users presses the button.
[ "You should never attempt to alter a UI element from a thread that isn't the main thread. \nWhat you probably want is after(delay_ms, callback, args). Some information can be over at http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm.\nAs a sample, here's a quick script to show a clock (Note: I've never really used Tk).\nfrom Tkinter import *\nfrom time import strftime\n\nclass App(Frame):\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.label_var = StringVar()\n self.label = Label(self, textvariable=self.label_var)\n self.label.pack()\n # Start the loop\n self.go()\n\n def go(self):\n self.label_var.set(strftime(\"%H:%M:%S\"))\n # The callback is only called once, so call it every time\n self.after(1000, self.go)\n\napp = App()\nmainloop()\n\n", "You don't need threads for such a simple task. You can simply schedule your task to run every second or so, which can be done with the 'after' method;\nFirst, add this method to your simpleapp_tk class:\ndef update(self):\n G = str(round(psutil.cpu_percent(), 1)) + '%'\n self.labelVariable.set(G)\n self.after(1000, self.update)\n\nThen, in your initialize method add this call:\nself.update()\n\nThis will cause the label to be updated to the current cpu value. The update method will then re-schedule itself to run again in one second. \n" ]
[ 4, 2 ]
[]
[]
[ "multithreading", "python", "tkinter" ]
stackoverflow_0002987913_multithreading_python_tkinter.txt
Q: Avoid 404 page override I 'm using django-lfs with default django-app.Its appear django-lfs override 404 default template. How to avoid this process A: Within the templates folder, there is should be a 404.html. Remove that, and django defaults to the standard 404 page!
Avoid 404 page override
I 'm using django-lfs with default django-app.Its appear django-lfs override 404 default template. How to avoid this process
[ "Within the templates folder, there is should be a 404.html. Remove that, and django defaults to the standard 404 page!\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002997764_django_python.txt
Q: Importing Python modules without installing - Sybase ASE I need to use the Sybase Python module but our SA's won't install because it's not in the repo's. I've downloaded it and placed it on the box and would just like to 'import' or 'include' the module without installing it first. - Is this possible? From the looks of it (Sybase ASE) it needs some type of compilation before use. Is it possible for this type of work around? A: If you can get Sybase to use a virtual environment (I know nothing about Sybase, sorry), perhaps you could install the module using virtualenv, which generally doesn't require root access or SA approval. A: From the sybase documentation it looks like compilation is required, and Google tells me that it's not available in the easy_install repos either. It may be easier to do a little social engineering (cookies anyone?) to get the modules installed for you. I don't know what your work environment is like, but if you really need the python Sybase module to do your job, either 1) the SA's should be installing it anyway, or 2) you need to be using something different. You could always try writing a python script that does the d/l and install automagically and give it to the SAs so they don't have to worry about the "difficulty" of doing something besides apt-getting. I don't know about the virtual environments, though - that might be an ideal avenue. A: Assuming you meet the prerequisites for compiling, untarring it and then running: python setup.py build_ext should produce a sybasect shared object. Copying this file and the Sybase.py file somwhere onto PYTHONPATH might just do it for you.
Importing Python modules without installing - Sybase ASE
I need to use the Sybase Python module but our SA's won't install because it's not in the repo's. I've downloaded it and placed it on the box and would just like to 'import' or 'include' the module without installing it first. - Is this possible? From the looks of it (Sybase ASE) it needs some type of compilation before use. Is it possible for this type of work around?
[ "If you can get Sybase to use a virtual environment (I know nothing about Sybase, sorry), perhaps you could install the module using virtualenv, which generally doesn't require root access or SA approval.\n", "From the sybase documentation it looks like compilation is required, and Google tells me that it's not available in the easy_install repos either.\nIt may be easier to do a little social engineering (cookies anyone?) to get the modules installed for you. I don't know what your work environment is like, but if you really need the python Sybase module to do your job, either 1) the SA's should be installing it anyway, or 2) you need to be using something different.\nYou could always try writing a python script that does the d/l and install automagically and give it to the SAs so they don't have to worry about the \"difficulty\" of doing something besides apt-getting.\nI don't know about the virtual environments, though - that might be an ideal avenue.\n", "Assuming you meet the prerequisites for compiling, untarring it and then running:\npython setup.py build_ext\n\nshould produce a sybasect shared object. Copying this file and the Sybase.py file somwhere onto PYTHONPATH might just do it for you.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "module", "python", "sap_ase" ]
stackoverflow_0002997697_module_python_sap_ase.txt
Q: deleting all the file of certain size i have bunch of log files and I have to delete the files of some small sizes, which were erroneous files that got created. ( 63bytes ). I have to copy only those files which have data in it . A: Shell (linux); find . -type f -size 63c -delete Will traverse subdirectories (unless you tell it otherwise) A: Since you tagged your question with "python" here is how you could do this in that language: target_size = 63 import os for dirpath, dirs, files in os.walk('.'): for file in files: path = os.path.join(dirpath, file) if os.stat(path).st_size == target_size: os.remove(path) A: The Perl one liner is perl -e 'unlink grep {-s == 63} glob "*"' Although, it is always a good idea to test what it would do before running it: perl -le 'print for grep {-s == 63} glob "*"' If you want to walk an entire directory tree, you will need a different versions: #find all files in the current hierarchy that are 63 bytes long. perl -MFile::Find=find -le 'find sub {print $File::Find::name if -s == 63}, "."' #delete all files in the current hierarchy that 63 bytes long perl -MFile::Find=find -e 'find sub {unlink if -s == 63}, "."' I am using need $File::Find::name in the finding version so you get the whole path, the unlinking version doesn't need it because File::Find changes directory into the each target directory and sets $_ to be the file name (which is how -s and unlink get the filename). You may also want to look up grep and glob
deleting all the file of certain size
i have bunch of log files and I have to delete the files of some small sizes, which were erroneous files that got created. ( 63bytes ). I have to copy only those files which have data in it .
[ "Shell (linux);\nfind . -type f -size 63c -delete\n\nWill traverse subdirectories (unless you tell it otherwise)\n", "Since you tagged your question with \"python\" here is how you could do this in that language:\ntarget_size = 63\nimport os\nfor dirpath, dirs, files in os.walk('.'):\n for file in files: \n path = os.path.join(dirpath, file)\n if os.stat(path).st_size == target_size:\n os.remove(path)\n\n", "The Perl one liner is\nperl -e 'unlink grep {-s == 63} glob \"*\"'\n\nAlthough, it is always a good idea to test what it would do before running it:\nperl -le 'print for grep {-s == 63} glob \"*\"'\n\nIf you want to walk an entire directory tree, you will need a different versions:\n#find all files in the current hierarchy that are 63 bytes long.\nperl -MFile::Find=find -le 'find sub {print $File::Find::name if -s == 63}, \".\"'\n\n#delete all files in the current hierarchy that 63 bytes long\nperl -MFile::Find=find -e 'find sub {unlink if -s == 63}, \".\"'\n\nI am using need $File::Find::name in the finding version so you get the whole path, the unlinking version doesn't need it because File::Find changes directory into the each target directory and sets $_ to be the file name (which is how -s and unlink get the filename). You may also want to look up grep and glob\n" ]
[ 18, 10, 6 ]
[]
[]
[ "perl", "python", "shell" ]
stackoverflow_0002994035_perl_python_shell.txt
Q: How to make every Class Method call a specified method before execution? I want to make my Python Class behave in such a way that when any Class method is called a default method is executed first without explicitly specifying this in the called Class. An example may help :) Class animals: def _internalMethod(): self.respires = True def cat(): self._internalMethod() self.name = 'cat' def dog(): self._internalMethod() self.name = 'dog' I want _internalMethod() to be called automatically when any method is called from an instance of animals, rather than stating it explicitly in the def of each method. Is there an elegant way to do this? Cheers, A: You could use a metaclass and getattribute to decorate all methods dynamically (if you are using Python 2, be sure to subclass from object!). Another option is just to have a fixup on the class, like: def add_method_call(func, method_name): def replacement(self, *args, **kw): getattr(self, method_name)() return func(self, *args, **kw) return replacement def change_all_attrs(cls, added_method): for method_name in dir(cls): attr = getattr(cls, method_name) if callable(attr): setattr(cls, method_name, add_method_call(attr, added_method)) class animals(object): ... change_all_attrs(animals, '_internalMethod') This is kind of sloppy, dir() won't get any methods in superclasses, and you might catch properties and other objects you don't intend to due to the simple callable(attr) test. But it might work fine for you. If using Python 2.7+ you can use a class decorator instead of calling change_all_attrs after creating the class, but the effect is the same (except you'll have to rewrite change_all_attrs to make it a decorator).
How to make every Class Method call a specified method before execution?
I want to make my Python Class behave in such a way that when any Class method is called a default method is executed first without explicitly specifying this in the called Class. An example may help :) Class animals: def _internalMethod(): self.respires = True def cat(): self._internalMethod() self.name = 'cat' def dog(): self._internalMethod() self.name = 'dog' I want _internalMethod() to be called automatically when any method is called from an instance of animals, rather than stating it explicitly in the def of each method. Is there an elegant way to do this? Cheers,
[ "You could use a metaclass and getattribute to decorate all methods dynamically (if you are using Python 2, be sure to subclass from object!).\nAnother option is just to have a fixup on the class, like:\ndef add_method_call(func, method_name):\n def replacement(self, *args, **kw):\n getattr(self, method_name)()\n return func(self, *args, **kw)\n return replacement\n\ndef change_all_attrs(cls, added_method):\n for method_name in dir(cls):\n attr = getattr(cls, method_name)\n if callable(attr):\n setattr(cls, method_name, add_method_call(attr, added_method))\n\nclass animals(object):\n ...\n\nchange_all_attrs(animals, '_internalMethod')\n\nThis is kind of sloppy, dir() won't get any methods in superclasses, and you might catch properties and other objects you don't intend to due to the simple callable(attr) test. But it might work fine for you.\nIf using Python 2.7+ you can use a class decorator instead of calling change_all_attrs after creating the class, but the effect is the same (except you'll have to rewrite change_all_attrs to make it a decorator).\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0002998969_python.txt
Q: Is there a Python library that eases the creation of CLI utilities like Django management commands? I want to create a set of command-line utilities in python that would be used like so: python utility.py command1 -option arg Very similar to django management commands. Is there any library that eases the creation of such commands? A: Baker is rather nice I think. Optfunc maybe also. A: Optparse is the way to go A: Take a look at plac. I haven't used it as I stumbled to it just recently. It looks simple enough, though. A: You just want to create a two-level command? You should use argparse -- it's simple enough, is similar to optparse but makes the two-level command thing easy, and will be in the standard library with Python 2.7.
Is there a Python library that eases the creation of CLI utilities like Django management commands?
I want to create a set of command-line utilities in python that would be used like so: python utility.py command1 -option arg Very similar to django management commands. Is there any library that eases the creation of such commands?
[ "Baker is rather nice I think. Optfunc maybe also.\n", "Optparse is the way to go\n", "Take a look at plac. I haven't used it as I stumbled to it just recently. It looks simple enough, though.\n", "You just want to create a two-level command? You should use argparse -- it's simple enough, is similar to optparse but makes the two-level command thing easy, and will be in the standard library with Python 2.7.\n" ]
[ 5, 2, 2, 2 ]
[]
[]
[ "command_line", "django", "python" ]
stackoverflow_0002995894_command_line_django_python.txt
Q: Passing values into regex match function In python (it's a Django filter), I'm doing this: lReturn = re.sub(r'\[usecase:([ \w]+)]', r'EXTEND WITH <a href="/usecase/%s/\1/">\1</a>' % pCurrentProjectName, lReturn) I'd like to use a function instead of a string (so I can check that the usercase is a valid name), so it would change to this: def _match_function(matchobj): lMatch = matchobj.group(1) return "EXTEND WITH <a href='/usecase/%s/%s/'>%s</a>" % (pCurrentProjectName, lMatch, lMatch) lReturn = re.sub(r'\[usecase:([ \w]+)]', _match_function, lReturn) How do I get pCurrentProjectName into the _match_function() function? A: You could create a function that returns a function (a closure): def _match_function(name): def f(matchobj): lMatch = matchobj.group(1) return "EXTEND WITH <a href='/usecase/%s/%s/'>%s</a>" % (name, lMatch, lMatch) return f lReturn = re.sub(r'\[usecase:([ \w]+)]', _match_function(pCurrentProjectName), lReturn)
Passing values into regex match function
In python (it's a Django filter), I'm doing this: lReturn = re.sub(r'\[usecase:([ \w]+)]', r'EXTEND WITH <a href="/usecase/%s/\1/">\1</a>' % pCurrentProjectName, lReturn) I'd like to use a function instead of a string (so I can check that the usercase is a valid name), so it would change to this: def _match_function(matchobj): lMatch = matchobj.group(1) return "EXTEND WITH <a href='/usecase/%s/%s/'>%s</a>" % (pCurrentProjectName, lMatch, lMatch) lReturn = re.sub(r'\[usecase:([ \w]+)]', _match_function, lReturn) How do I get pCurrentProjectName into the _match_function() function?
[ "You could create a function that returns a function (a closure):\ndef _match_function(name):\n def f(matchobj):\n lMatch = matchobj.group(1)\n return \"EXTEND WITH <a href='/usecase/%s/%s/'>%s</a>\" % (name, lMatch, lMatch)\n return f\n\nlReturn = re.sub(r'\\[usecase:([ \\w]+)]', _match_function(pCurrentProjectName), lReturn)\n\n" ]
[ 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002999205_python_regex.txt
Q: Trying to use py2exe, but python is not recognized I am following the the tutorial at http://www.py2exe.org/index.cgi/Tutorial to figure out how to use py2exe. I get down to step 3 where you are supposed to run the command: python setup.py py2exe I do that and then I get this error: 'python' is not recognized as an internal or external command, operable program or batch file. I have python 2.4 installed on my machine. any idea's? I am sure it is something simple. A: Python just isn't on your path. If you indeed have Python 2.4, it should be C:\Python24\python.exe with the default installer. Wherever the file is located, if you don't set Python's folder in your path, you will write the command as C:\Python24\python.exe setup.py py2exe (or whatever the correct path is). Depending on how your installation was configured, you might be able to just do setup.py py2exe since Windows might automatically associate *.py files with Python. You might want to also read "Finding the Python Executable" from the Python documentation. A: You need to add python to your system path. This is done differently on different OSs. Instructions for most versions of Windows You need to add C:\Python24 or whereever python is on your computer.
Trying to use py2exe, but python is not recognized
I am following the the tutorial at http://www.py2exe.org/index.cgi/Tutorial to figure out how to use py2exe. I get down to step 3 where you are supposed to run the command: python setup.py py2exe I do that and then I get this error: 'python' is not recognized as an internal or external command, operable program or batch file. I have python 2.4 installed on my machine. any idea's? I am sure it is something simple.
[ "Python just isn't on your path. If you indeed have Python 2.4, it should be C:\\Python24\\python.exe with the default installer.\nWherever the file is located, if you don't set Python's folder in your path, you will write the command as\nC:\\Python24\\python.exe setup.py py2exe\n\n(or whatever the correct path is).\nDepending on how your installation was configured, you might be able to just do \nsetup.py py2exe\n\nsince Windows might automatically associate *.py files with Python.\nYou might want to also read \"Finding the Python Executable\" from the Python documentation.\n", "You need to add python to your system path. This is done differently on different OSs. Instructions for most versions of Windows\nYou need to add C:\\Python24 or whereever python is on your computer.\n" ]
[ 2, 0 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0002999427_py2exe_python.txt
Q: Python: split files using multiple split delimiters I have multiple CSV files which I need to parse in a loop to gather information. The problem is that while they are the same format, some are delimited by '\t' and others by ','. After this, I want to remove the double-quote from around the string. Can python split via multiple possible delimiters? At the minute, I can split the line with one by using: f = open(filename, "r") fields = f.readlines() for fs in fields: sf = fs.split('\t') tf = [fi.strip ('"') for fi in sf] A: Splitting the file like that is not a good idea: It will fail if there is a comma within one of the fields. For example (for a tab-delimited file): The line "field1"\t"Hello, world"\t"field3" will be split into 4 fields instead of 3. Instead, you should use the csv module. It contains the helpful Sniffer class which can detect which delimiters are used in the file. The csv module will also remove the double-quotes for you. import csv csvfile = open("example.csv") dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) for line in reader: #process line A: You can do this with regex (optionally compiled): sf = re.split(r'[,\t]', fs) This doesn't account for e.g. commas inside tab-delimited fields. I would see if the csv module is helpful.
Python: split files using multiple split delimiters
I have multiple CSV files which I need to parse in a loop to gather information. The problem is that while they are the same format, some are delimited by '\t' and others by ','. After this, I want to remove the double-quote from around the string. Can python split via multiple possible delimiters? At the minute, I can split the line with one by using: f = open(filename, "r") fields = f.readlines() for fs in fields: sf = fs.split('\t') tf = [fi.strip ('"') for fi in sf]
[ "Splitting the file like that is not a good idea: It will fail if there is a comma within one of the fields. For example (for a tab-delimited file): The line \"field1\"\\t\"Hello, world\"\\t\"field3\" will be split into 4 fields instead of 3.\nInstead, you should use the csv module. It contains the helpful Sniffer class which can detect which delimiters are used in the file. The csv module will also remove the double-quotes for you.\nimport csv\n\ncsvfile = open(\"example.csv\")\ndialect = csv.Sniffer().sniff(csvfile.read(1024))\ncsvfile.seek(0)\nreader = csv.reader(csvfile, dialect)\n\nfor line in reader:\n #process line\n\n", "You can do this with regex (optionally compiled):\nsf = re.split(r'[,\\t]', fs)\n\nThis doesn't account for e.g. commas inside tab-delimited fields. I would see if the csv module is helpful.\n" ]
[ 14, 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002999373_csv_python.txt
Q: Parsing timestamp with Python2.4 I want to parse a timestamp from a log file that has been written via datetime.datetime.now().strftime('%Y%m%d%H%M%S') and then compute the number of seconds that have passed since this timestamp. I know I could do it with datetime.datetime.strptime to get back a datetime object and then compute a timedelta. Problem is, the strptime function has been introduced with Python 2.5 and I'm using Python2.4.4 (an upgrade is not possible in my context). Any easy way to do this? A: >>> ts = time.mktime(time.strptime('20040412234551', '%Y%m%d%H%M%S')) >>> ts 1081809951.0 >>> datetime.datetime.fromtimestamp(ts) datetime.datetime(2004, 4, 12, 23, 45, 51) A: now = datetime.datetime.now() then = datetime.datetime(*time.strptime('20080227034510' ,'%Y%m%d%H%M%S')[0:6]) difference = now - then A: There is a strptime function in the time module in python 2.4 already. You'd have to convert that to a datetime object for example via the detour of the unix timestamp, don't know if there's a better way. A: There's also mx.DateTime which is now free to use and it quite a bit easier to deal with and more flexible than Python's built in datetime module for well just about everything. Works in python 2.3+ No * and [0:6] shenanigans required. Egenix Download >>> import mx.DateTime as dt >>> then = dt.DateTimeFrom(dt.strptime('20040412234551', '%Y%m%d%H%M%S')) >>> delta = dt.now() - then >>> delta <DateTimeDelta object for '2247:13:09:22.31' at 2ab37d666b58> >>> delta.hours 53941.156198977762 >>> delta.days 2247.5481749574069
Parsing timestamp with Python2.4
I want to parse a timestamp from a log file that has been written via datetime.datetime.now().strftime('%Y%m%d%H%M%S') and then compute the number of seconds that have passed since this timestamp. I know I could do it with datetime.datetime.strptime to get back a datetime object and then compute a timedelta. Problem is, the strptime function has been introduced with Python 2.5 and I'm using Python2.4.4 (an upgrade is not possible in my context). Any easy way to do this?
[ ">>> ts = time.mktime(time.strptime('20040412234551', '%Y%m%d%H%M%S'))\n>>> ts\n1081809951.0\n>>> datetime.datetime.fromtimestamp(ts)\ndatetime.datetime(2004, 4, 12, 23, 45, 51)\n\n", "now = datetime.datetime.now()\nthen = datetime.datetime(*time.strptime('20080227034510' ,'%Y%m%d%H%M%S')[0:6])\ndifference = now - then\n\n", "There is a strptime function in the time module in python 2.4 already. You'd have to convert that to a datetime object for example via the detour of the unix timestamp, don't know if there's a better way.\n", "There's also mx.DateTime which is now free to use and it quite a bit easier to deal with and more flexible than Python's built in datetime module for well just about everything. Works in python 2.3+ No * and [0:6] shenanigans required.\nEgenix Download\n>>> import mx.DateTime as dt\n>>> then = dt.DateTimeFrom(dt.strptime('20040412234551', '%Y%m%d%H%M%S'))\n>>> delta = dt.now() - then\n>>> delta\n<DateTimeDelta object for '2247:13:09:22.31' at 2ab37d666b58>\n>>> delta.hours\n53941.156198977762\n>>> delta.days\n2247.5481749574069\n\n" ]
[ 5, 1, 0, 0 ]
[]
[]
[ "datetime", "parsing", "python", "python_2.4" ]
stackoverflow_0002997777_datetime_parsing_python_python_2.4.txt
Q: Getting youtube links from embedded youtube video on pages? Is there a regex to get youtube video links or ids from embedded youtube videos on webpages? A: To find: "<object(.*)youtube.com/v/(.*)\"(.*)</object>" To convert to a link: replace("<object(.*)youtube.com/v/(.*)\"(.*)</object>", '<a href="http://www.youtube.com/watch?v=\\2">click here</a>', $str) source
Getting youtube links from embedded youtube video on pages?
Is there a regex to get youtube video links or ids from embedded youtube videos on webpages?
[ "To find:\n\"<object(.*)youtube.com/v/(.*)\\\"(.*)</object>\"\nTo convert to a link:\nreplace(\"<object(.*)youtube.com/v/(.*)\\\"(.*)</object>\", '<a href=\"http://www.youtube.com/watch?v=\\\\2\">click here</a>', $str) \nsource\n" ]
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002998517_python_regex.txt
Q: Specifying the Python interpreter for vim's :python command (Mac)Vim seems to be picking up /usr/bin/python instead of the one that's at the front of my path (/Library/Frameworks/Python.framework/Versions/2.6/bin/python) when I use the :python command. Is this entirely a compile-time thing or can I somehow override it? A: Seems like it is an entirely compile-time thing: $ ldd /usr/bin/vim | grep python libpython2.5.so.1.0 => /usr/lib/libpython2.5.so.1.0 (0xb6bcc000) my vim --version also reports being built against a specific python. $ vim --version | tr '-' '\n' | grep python +python +quickfix +reltime +rightleft +ruby +scrollbind +signs +smartindent I/usr/include/python2.5 L/usr/lib/python2.5/config lpython2.5 another symptom of this is that the :python command won't work with vim unless vim --version reports +python.
Specifying the Python interpreter for vim's :python command
(Mac)Vim seems to be picking up /usr/bin/python instead of the one that's at the front of my path (/Library/Frameworks/Python.framework/Versions/2.6/bin/python) when I use the :python command. Is this entirely a compile-time thing or can I somehow override it?
[ "Seems like it is an entirely compile-time thing:\n$ ldd /usr/bin/vim | grep python\nlibpython2.5.so.1.0 => /usr/lib/libpython2.5.so.1.0 (0xb6bcc000)\n\nmy vim --version also reports being built against a specific python.\n$ vim --version | tr '-' '\\n' | grep python\n+python +quickfix +reltime +rightleft +ruby +scrollbind +signs +smartindent \nI/usr/include/python2.5 \nL/usr/lib/python2.5/config \nlpython2.5 \n\nanother symptom of this is that the :python command won't work with vim unless vim --version reports +python.\n" ]
[ 14 ]
[]
[]
[ "environment_variables", "python", "vim" ]
stackoverflow_0002999315_environment_variables_python_vim.txt
Q: How to access GMail (IMAP Email) from my Shell/Python script to download a zip file attached to an email and process it? I have to process a file everyday. This file is sent to my Email once everyday. If I can get to this email once every day and download the attachment, that had be awesome. Is it even remotely possible to do such a thing? Thanks! A: Please see How can I download all emails with attachments from Gmail? for a practical example. A: This is certainly possible. Check out imaplib in Python's standard library; with it doing what you want should be quite straightforward. Also, you can process zip files directly in Python using the zipfile library. A: Your best bet is to create an IMAP Folder for your daily emails to be sent to and then create a filter in GMail to send those files there. Your Python script can then check ONLY that folder on some interval and assume that whatever ends up in there is the file you want. A quick search yielded sooo many results for IMAP fetching examples in Python, I'll leave that part up to you, but I will say that libgmail looks pretty neat.
How to access GMail (IMAP Email) from my Shell/Python script to download a zip file attached to an email and process it?
I have to process a file everyday. This file is sent to my Email once everyday. If I can get to this email once every day and download the attachment, that had be awesome. Is it even remotely possible to do such a thing? Thanks!
[ "Please see How can I download all emails with attachments from Gmail? for a practical example.\n", "This is certainly possible. Check out imaplib in Python's standard library; with it doing what you want should be quite straightforward. Also, you can process zip files directly in Python using the zipfile library.\n", "Your best bet is to create an IMAP Folder for your daily emails to be sent to and then create a filter in GMail to send those files there. Your Python script can then check ONLY that folder on some interval and assume that whatever ends up in there is the file you want.\nA quick search yielded sooo many results for IMAP fetching examples in Python, I'll leave that part up to you, but I will say that libgmail looks pretty neat.\n" ]
[ 6, 1, 1 ]
[]
[]
[ "download", "gmail", "imap", "python", "shell" ]
stackoverflow_0003000014_download_gmail_imap_python_shell.txt
Q: How do you redirect a standard stream of a C++ routine wrapped with SWIG and exposed to Python? Is it possible to control the standard streams of C++ code in python? The code is wrapped with SWIG and then exposed to Python where I call one of its functions. I am getting all kinds of unwanted messages coming from C++ code and I want to suppress them either by not using the output stream or by redirecting it to a bit bucket, e.g. devnull from the os module. A: I think the best way is to implement a simple function/method in C or C++ of your extension to redirect the stdout output, see dup for example, I think it will work fine.
How do you redirect a standard stream of a C++ routine wrapped with SWIG and exposed to Python?
Is it possible to control the standard streams of C++ code in python? The code is wrapped with SWIG and then exposed to Python where I call one of its functions. I am getting all kinds of unwanted messages coming from C++ code and I want to suppress them either by not using the output stream or by redirecting it to a bit bucket, e.g. devnull from the os module.
[ "I think the best way is to implement a simple function/method in C or C++ of your extension to redirect the stdout output, see dup for example, I think it will work fine.\n" ]
[ 1 ]
[]
[]
[ "c++", "outputstream", "python", "standards", "swig" ]
stackoverflow_0002942284_c++_outputstream_python_standards_swig.txt
Q: Utilizing multiple python projects I have a python app, that I'm developing. There is a need to use another library, that resides in different directory. The file layout looks like this: dir X has two project dirs: current-project xLibrary I'd like to use xLibrary in currentProject. I've been trying writting code as if all the sources resided in the same directory and calling my projects main script with: PYTHONPATH=.:../xLibrary ./current-project.py but this does not work. I'd like to use its code base without installing the library globaly or copying it to my project's directory. Is it possible? Or if not, how should I deal with this problem. A: It's generally a good programming practice to isolate packages into actual packages and treat them as such. If you're sure you'd like to continue with that approach though you can modify the search path from within python via: import sys sys.path.append( "<path_containing_the_other_python_files>" ) To avoid embedding absolute paths, you can use os.path.abspath(__file__) to obtain the absolute path to the currently executing .py file and follow up with a few os.path.dirname() calls to construct the proper relative path for inclusion to sys.path A slightly altered approach that would allow you to get the best of both worlds would be to add an __init__.py file to xLibrary's directory then add the path containing 'xLibrary' to sys.path instead. Subsequent Python code could then import everything "properly" via from xLibrary import my_module rather than just import my_module which could be confusing to people accustomed to the standard package directory layout. A: This depends how you use xLibrary from current-project. If you do something like from xLibrary import module1 inside current-project, the xLibrary needs to be laid out as a Python package: xLibrary/ xLibrary/__init__.py xLibrary/module1.py # or whatever other modules the package consists of In this case, you should include xLibrary's parent directory in PYTHONPATH: PYTHONPATH=.:.. ./current-project.py However, if xLibrary is just a collection of Python modules that you import individually (that is, if you do import module1 and import module2 ìn current-project, with xLibrary containing the files module1.py and module2.py), you should include xLibrary in PYTHONPATH just as you did: PYTHONPATH=.:../xLibrary ./current-project.py A: bash$ ln -s ../xLibrary xLibrary A: First, it is probably better to use absolute paths in your PYTHONPATH variable. Second, I don't think you need to add current directory to the path. Other than that, it would be good to know what it is that doesn't work and what the error message is. The command line you have there seems to be missing a semicolon Try these two: a=12 echo $a b=12 ;echo $b ...and you'll see the difference. A: Apart from the other suggestions, you may consider the virtualenv package. After writing a little setup.py file you can "virtually install" the library and avoid all the PYTHONPATH munging in general. This is a really good practice and is encouraged by the python community. Otherwise I prefer the use of sys.path method (by Rakis)
Utilizing multiple python projects
I have a python app, that I'm developing. There is a need to use another library, that resides in different directory. The file layout looks like this: dir X has two project dirs: current-project xLibrary I'd like to use xLibrary in currentProject. I've been trying writting code as if all the sources resided in the same directory and calling my projects main script with: PYTHONPATH=.:../xLibrary ./current-project.py but this does not work. I'd like to use its code base without installing the library globaly or copying it to my project's directory. Is it possible? Or if not, how should I deal with this problem.
[ "It's generally a good programming practice to isolate packages into actual packages and treat them as such. If you're sure you'd like to continue with that approach though you can modify the search path from within python via:\nimport sys\nsys.path.append( \"<path_containing_the_other_python_files>\" )\n\nTo avoid embedding absolute paths, you can use os.path.abspath(__file__) to obtain the absolute path to the currently executing .py file and follow up with a few os.path.dirname() calls to construct the proper relative path for inclusion to sys.path\nA slightly altered approach that would allow you to get the best of both worlds would be to add an __init__.py file to xLibrary's directory then add the path containing 'xLibrary' to sys.path instead. Subsequent Python code could then import everything \"properly\" via from xLibrary import my_module rather than just import my_module which could be confusing to people accustomed to the standard package directory layout.\n", "This depends how you use xLibrary from current-project.\nIf you do something like from xLibrary import module1 inside current-project, the xLibrary needs to be laid out as a Python package:\nxLibrary/\nxLibrary/__init__.py\nxLibrary/module1.py # or whatever other modules the package consists of\n\nIn this case, you should include xLibrary's parent directory in PYTHONPATH:\nPYTHONPATH=.:.. ./current-project.py\n\nHowever, if xLibrary is just a collection of Python modules that you import individually (that is, if you do import module1 and import module2 ìn current-project, with xLibrary containing the files module1.py and module2.py), you should include xLibrary in PYTHONPATH just as you did:\nPYTHONPATH=.:../xLibrary ./current-project.py\n\n", "bash$ ln -s ../xLibrary xLibrary\n\n", "First, it is probably better to use absolute paths in your PYTHONPATH variable.\nSecond, I don't think you need to add current directory to the path.\nOther than that, it would be good to know what it is that doesn't work and what the error message is.\nThe command line you have there seems to be missing a semicolon\nTry these two:\na=12 echo $a\nb=12 ;echo $b\n\n...and you'll see the difference.\n", "Apart from the other suggestions, you may consider the virtualenv package. After writing a little setup.py file you can \"virtually install\" the library and avoid all the PYTHONPATH munging in general.\nThis is a really good practice and is encouraged by the python community.\nOtherwise I prefer the use of sys.path method (by Rakis)\n" ]
[ 2, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003000921_python.txt
Q: C++ Swig Python (Embedded Python in C++) works in Release but not in Debug Platform: Windows 7, 64 bit (x64), Visual Studio 2008 I chose Python & Swig binding as the scripting environment of the application. As a prototype, created a simple VS solution with main() which initializes Python (Py_Initalize, Py_setPyHome, etc) & executes test.py. In the same solution created another project which is a DLL of a simple class. Used SWIG to wrap this class. This DLL is the _MyClasses.pyd. test.py creates the objects of my class & calls its member functions. All this works like a charm in the Release mode. But does not work in Debug mode (even tried banging my head on the laptop ;-) ). Output of my work looks like this (in both release & debug): x64 -debug - _MyClasses.pyd - MyClasses.py - test.exe - test.py - python26.dll - python26_d.dll Note that the debug version is linked against python26_d.lib. Had to build python myself for this! test.py import MyClasses print "ello" m = MyClasses.Male("John Doe", 25) print m.getType() Male is the C++ class. The problem: Traceback (most recent call last): File "test.py", line 6, in <module> import MyClasses File "...\x64\Debug\MyClasses.py", line 25, in <module> _MyClasses = swig_import_helper() File "...\x64\Debug\MyClasses.py", line 17, in swig_imp ort_helper import _MyClasses ImportError: No module named _MyClasses [15454 refs] I am used to Makefiles & am new to Visual Studio. I dont know who the culprit is here: Swig, The debug build of Python, Visual Studio, my stupidity. Thank you in advance. It will be a great help. A: Alright - found it. The debug output dll has to be named xxx_d.pyd!! In above case it would be _MyClasses_d.pyd
C++ Swig Python (Embedded Python in C++) works in Release but not in Debug
Platform: Windows 7, 64 bit (x64), Visual Studio 2008 I chose Python & Swig binding as the scripting environment of the application. As a prototype, created a simple VS solution with main() which initializes Python (Py_Initalize, Py_setPyHome, etc) & executes test.py. In the same solution created another project which is a DLL of a simple class. Used SWIG to wrap this class. This DLL is the _MyClasses.pyd. test.py creates the objects of my class & calls its member functions. All this works like a charm in the Release mode. But does not work in Debug mode (even tried banging my head on the laptop ;-) ). Output of my work looks like this (in both release & debug): x64 -debug - _MyClasses.pyd - MyClasses.py - test.exe - test.py - python26.dll - python26_d.dll Note that the debug version is linked against python26_d.lib. Had to build python myself for this! test.py import MyClasses print "ello" m = MyClasses.Male("John Doe", 25) print m.getType() Male is the C++ class. The problem: Traceback (most recent call last): File "test.py", line 6, in <module> import MyClasses File "...\x64\Debug\MyClasses.py", line 25, in <module> _MyClasses = swig_import_helper() File "...\x64\Debug\MyClasses.py", line 17, in swig_imp ort_helper import _MyClasses ImportError: No module named _MyClasses [15454 refs] I am used to Makefiles & am new to Visual Studio. I dont know who the culprit is here: Swig, The debug build of Python, Visual Studio, my stupidity. Thank you in advance. It will be a great help.
[ "Alright - found it. The debug output dll has to be named xxx_d.pyd!! In above case it would be _MyClasses_d.pyd\n" ]
[ 1 ]
[]
[]
[ "debugging", "python", "swig" ]
stackoverflow_0003000612_debugging_python_swig.txt
Q: Unwanted behaviour from dict.fromkeys I'd like to initialise a dictionary of sets (in Python 2.6) using dict.fromkeys, but the resulting structure behaves strangely. More specifically: >>>> x = {}.fromkeys(range(10), set([])) >>>> x {0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]), 7: set([]), 8: set([]), 9: set([])} >>>> x[5].add(3) >>>> x {0: set([3]), 1: set([3]), 2: set([3]), 3: set([3]), 4: set([3]), 5: set([3]), 6: set([3]), 7: set([3]), 8: set([3]), 9: set([3])} I obviously don't want to add 3 to all sets, only to the set that corresponds to x[5]. Of course, I can avoid the problem by initialising x without fromkeys, but I'd like to understand what I'm missing here. A: The second argument to dict.fromkeys is just a value. You've created a dictionary that has the same set as the value for every key. Presumably you understand the way this works: >>> a = set() >>> b = a >>> b.add(1) >>> b set([1]) >>> a set([1]) you're seeing the same behavior there; in your case, x[0], x[1], x[2] (etc) are all different ways to access the exact same set object. This is a bit easier to see with objects whose string representation includes their memory address, where you can see that they're identical: >>> dict.fromkeys(range(2), object()) {0: <object object at 0x1001da080>, 1: <object object at 0x1001da080>} A: You can do this with a generator expression: x = dict( (i,set()) for i in range(10) ) In Python 3, you can use a dictionary comprehension: x = { i : set() for i in range(10) } In both cases, the expression set() is evaluated for each element, instead of being evaluated once and copied to each element. A: Because of this from the dictobject.c: while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) { Py_INCREF(key); Py_INCREF(value); if (insertdict(mp, key, hash, value)) return NULL; } The value is your "set([])", it is evaluated only once then their result object reference count is incremented and added to the dictionary, it doesn't evaluates it every time it adds into the dict. A: The reason its working this way is that set([]) creates an object (a set object). Fromkeys then uses that specific object to create all its dictionary entries. Consider: >>> x {0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]), 7: set([]), 8: set([]), 9: set([])} >>> x[0] is x[1] True All the sets are the same! A: #To do what you want: import copy s = set([]) x = {} for n in range(0,5): x[n] = copy.deepcopy(s) x[2].add(3) print x #Printing #{0: set([]), 1: set([]), 2: set([3]), 3: set([]), 4: set([])}
Unwanted behaviour from dict.fromkeys
I'd like to initialise a dictionary of sets (in Python 2.6) using dict.fromkeys, but the resulting structure behaves strangely. More specifically: >>>> x = {}.fromkeys(range(10), set([])) >>>> x {0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]), 7: set([]), 8: set([]), 9: set([])} >>>> x[5].add(3) >>>> x {0: set([3]), 1: set([3]), 2: set([3]), 3: set([3]), 4: set([3]), 5: set([3]), 6: set([3]), 7: set([3]), 8: set([3]), 9: set([3])} I obviously don't want to add 3 to all sets, only to the set that corresponds to x[5]. Of course, I can avoid the problem by initialising x without fromkeys, but I'd like to understand what I'm missing here.
[ "The second argument to dict.fromkeys is just a value. You've created a dictionary that has the same set as the value for every key. Presumably you understand the way this works:\n>>> a = set()\n>>> b = a\n>>> b.add(1)\n>>> b\nset([1])\n>>> a\nset([1])\n\nyou're seeing the same behavior there; in your case, x[0], x[1], x[2] (etc) are all different ways to access the exact same set object.\nThis is a bit easier to see with objects whose string representation includes their memory address, where you can see that they're identical:\n>>> dict.fromkeys(range(2), object())\n{0: <object object at 0x1001da080>,\n 1: <object object at 0x1001da080>}\n\n", "You can do this with a generator expression:\nx = dict( (i,set()) for i in range(10) )\n\nIn Python 3, you can use a dictionary comprehension:\nx = { i : set() for i in range(10) }\n\nIn both cases, the expression set() is evaluated for each element, instead of being evaluated once and copied to each element. \n", "Because of this from the dictobject.c:\nwhile (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash))\n{\n Py_INCREF(key);\n Py_INCREF(value);\n if (insertdict(mp, key, hash, value))\n return NULL;\n}\n\nThe value is your \"set([])\", it is evaluated only once then their result object reference count is incremented and added to the dictionary, it doesn't evaluates it every time it adds into the dict.\n", "The reason its working this way is that set([]) creates an object (a set object). Fromkeys then uses that specific object to create all its dictionary entries. Consider:\n>>> x\n{0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), \n6: set([]), 7: set([]), 8: set([]), 9: set([])}\n>>> x[0] is x[1]\nTrue\n\nAll the sets are the same!\n", "\n#To do what you want:\n\nimport copy\ns = set([])\nx = {}\nfor n in range(0,5):\n x[n] = copy.deepcopy(s)\nx[2].add(3)\nprint x\n\n#Printing\n#{0: set([]), 1: set([]), 2: set([3]), 3: set([]), 4: set([])}\n\n" ]
[ 19, 18, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003000468_python.txt
Q: How do I make a python window always be on bottom? How do I make a python window always be on bottom? A: If you're talking about Tkinter, you can use: window.geometry('300x200-5+40') Where the 300x200 is the size, and -5+40 is the positioning offsets.
How do I make a python window always be on bottom?
How do I make a python window always be on bottom?
[ "If you're talking about Tkinter, you can use:\n window.geometry('300x200-5+40')\n\nWhere the 300x200 is the size, and -5+40 is the positioning offsets.\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter", "windows" ]
stackoverflow_0003000447_python_tkinter_windows.txt
Q: PHP CURL sending POST to Django app issue This code in PHP sends a HTTP POST to a Django app using CURL lib. I need that this code sends POST but redirect to the page in the same submit. Like a simple form does. The PHP Code: $c = curl_init(); curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); curl_setopt($c, CURLOPT_URL, "http://www.xxx.com"); curl_setopt($c, CURLOPT_POST, true); curl_setopt($c, CURLOPT_POSTFIELDS, 'Var='.$var); curl_exec($c); curl_close ($c); In this case, the PHP is sending the HTTP POST, but is not redirecting to the page. He is printing the result. My URL still .php and not a django/url/ I need be redirected to the django URL with the Post like a simple form in HTML does. Any Idea? Thanks. A: Your code does a server-side POST request to the page. You can't "redirect" the user to the same "instance" of the page. If you need to do it in one step, print out a form with method="POST" and hidden fields and then add JavaScript which automatically submits it.
PHP CURL sending POST to Django app issue
This code in PHP sends a HTTP POST to a Django app using CURL lib. I need that this code sends POST but redirect to the page in the same submit. Like a simple form does. The PHP Code: $c = curl_init(); curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); curl_setopt($c, CURLOPT_URL, "http://www.xxx.com"); curl_setopt($c, CURLOPT_POST, true); curl_setopt($c, CURLOPT_POSTFIELDS, 'Var='.$var); curl_exec($c); curl_close ($c); In this case, the PHP is sending the HTTP POST, but is not redirecting to the page. He is printing the result. My URL still .php and not a django/url/ I need be redirected to the django URL with the Post like a simple form in HTML does. Any Idea? Thanks.
[ "Your code does a server-side POST request to the page. You can't \"redirect\" the user to the same \"instance\" of the page.\nIf you need to do it in one step, print out a form with method=\"POST\" and hidden fields and then add JavaScript which automatically submits it.\n" ]
[ 1 ]
[]
[]
[ "curl", "django", "php", "python" ]
stackoverflow_0003001122_curl_django_php_python.txt
Q: Define a global in a Python module from a C API I am developing a module for Python using a C API. How can I create a variable that is seen as global from Python? For example, if my module is module, I want to create a variable g that does this job: import module print module.g In particular, g is an integer. Solution from Alex Martelli PyObject *m = Py_InitModule("mymodule", mymoduleMethods); PyObject *v = PyLong_FromLong((long) 23); PyObject_SetAttrString(m, "g", v); Py_DECREF(v); A: You can use PyObject_SetAttrString in your module's initialization routine, with first argument o being (the cast to (PyObject*) of) your module, second argument attr_name being "g", third argument v being a variable PyObject *v = PyLong_FromLong((long) 23); (or whatever other value of course, 23 is just an example!-). Do remember to decref v afterwards. There are other ways, but this one is simple and general.
Define a global in a Python module from a C API
I am developing a module for Python using a C API. How can I create a variable that is seen as global from Python? For example, if my module is module, I want to create a variable g that does this job: import module print module.g In particular, g is an integer. Solution from Alex Martelli PyObject *m = Py_InitModule("mymodule", mymoduleMethods); PyObject *v = PyLong_FromLong((long) 23); PyObject_SetAttrString(m, "g", v); Py_DECREF(v);
[ "You can use PyObject_SetAttrString in your module's initialization routine, with first argument o being (the cast to (PyObject*) of) your module, second argument attr_name being \"g\", third argument v being a variable\nPyObject *v = PyLong_FromLong((long) 23);\n\n(or whatever other value of course, 23 is just an example!-).\nDo remember to decref v afterwards.\nThere are other ways, but this one is simple and general.\n" ]
[ 4 ]
[]
[]
[ "c", "global_variables", "python", "python_c_api", "python_module" ]
stackoverflow_0003001239_c_global_variables_python_python_c_api_python_module.txt
Q: What good open source programs exist for fuzzing popular image file types? I am looking for a free, open source, portable fuzzing tool for popular image file types that is written in either Java, Python, or Jython. Ideally, it would accept specifications for the fuzzable fields using some kind of declarative constraints. Non-procedural grammar for specifying constraints are greatly preferred. Otherwise, might as well write them all in Python or whatever. Just specifying ranges of valid values or expressions for them. Ideally, it would support some kind of generative programming to export the fuzzer into various programming languages to suit cases where more customization was required. If it supported a direct-manipulation GUI for controlling parameter values and ranges, that would be nice too. The file formats that should be supported are: GIF JPEG PNG So basically, it should be sort of a toolkit consisting of ready-to-run utility, a framework or library, and be capable of generating the fuzzed files directly as well as from programs it generates. It needs to be simple so that test images can be created quickly. It should have a batch capability for creating a series of images. Creating just one at a time would be too painful. I do not want a hacking tool, just a QA tool. Basically, I just want to address concerns that it is taking too long to get commonplace image rendering/parsing libraries stable and trustworthy. A: Peach has a file fuzzing module. Here is an excellent quick start tutorial for using the file fuzzing module to attack mplayer using a sound file: http://peachfuzzer.com/TutorialFileFuzzing I recommend focusing on the file's header. A: Not exactly what you are asking for, but for getting quick up and running some fuzz tests for file formats, you should check out Radamsa from OUSPG, Oulu University Secure Programming Group. Radamsa can take bunch of files, for example jpeg files, and turn those into fuzzed images. It can also learn some structure from multiple files, so it's not just random bit flipping of bits and bytes. It's also really cool that Radamsa can listen on TCP socket. That way you can use a script to connect to Radamsa to receive one fuzzed file per connection. A: Okay, I don't think it has a ready-to-run utility, but people use PIL (Python Imaging Library) to generate captchas all the time, so it can probably fuzz images. (At least, assuming that my definition of "fuzz" is correct and that what you mean is adding random noise to an image for some purpose.) Of course, all your talking about ready-to-run utilities and generating programs to fuzz images is confusing me. What I'm wondering is, why is all that necessary? What use-case do you have for wanting a program that can make programs to fuzz images when most practical concerns could be solved by simply writing a script that loads an image and does the fuzzing using PIL? A: You might want to consider 'bringing in the Gimp!' [ to paraphrase Pulp Fiction there...] http://www.gimp.org/docs/python/index.html
What good open source programs exist for fuzzing popular image file types?
I am looking for a free, open source, portable fuzzing tool for popular image file types that is written in either Java, Python, or Jython. Ideally, it would accept specifications for the fuzzable fields using some kind of declarative constraints. Non-procedural grammar for specifying constraints are greatly preferred. Otherwise, might as well write them all in Python or whatever. Just specifying ranges of valid values or expressions for them. Ideally, it would support some kind of generative programming to export the fuzzer into various programming languages to suit cases where more customization was required. If it supported a direct-manipulation GUI for controlling parameter values and ranges, that would be nice too. The file formats that should be supported are: GIF JPEG PNG So basically, it should be sort of a toolkit consisting of ready-to-run utility, a framework or library, and be capable of generating the fuzzed files directly as well as from programs it generates. It needs to be simple so that test images can be created quickly. It should have a batch capability for creating a series of images. Creating just one at a time would be too painful. I do not want a hacking tool, just a QA tool. Basically, I just want to address concerns that it is taking too long to get commonplace image rendering/parsing libraries stable and trustworthy.
[ "Peach has a file fuzzing module. Here is an excellent quick start tutorial for using the file fuzzing module to attack mplayer using a sound file: http://peachfuzzer.com/TutorialFileFuzzing \nI recommend focusing on the file's header.\n", "Not exactly what you are asking for, but for getting quick up and running some fuzz tests for file formats, you should check out Radamsa from OUSPG, Oulu University Secure Programming Group.\nRadamsa can take bunch of files, for example jpeg files, and turn those into fuzzed images. It can also learn some structure from multiple files, so it's not just random bit flipping of bits and bytes.\nIt's also really cool that Radamsa can listen on TCP socket. That way you can use a script to connect to Radamsa to receive one fuzzed file per connection.\n", "Okay, I don't think it has a ready-to-run utility, but people use PIL (Python Imaging Library) to generate captchas all the time, so it can probably fuzz images. (At least, assuming that my definition of \"fuzz\" is correct and that what you mean is adding random noise to an image for some purpose.)\nOf course, all your talking about ready-to-run utilities and generating programs to fuzz images is confusing me. What I'm wondering is, why is all that necessary? What use-case do you have for wanting a program that can make programs to fuzz images when most practical concerns could be solved by simply writing a script that loads an image and does the fuzzing using PIL?\n", "You might want to consider 'bringing in the Gimp!' [ to paraphrase Pulp Fiction there...]\nhttp://www.gimp.org/docs/python/index.html\n" ]
[ 3, 2, 0, 0 ]
[]
[]
[ "fuzzer", "generator", "image", "java", "python" ]
stackoverflow_0002210303_fuzzer_generator_image_java_python.txt
Q: Return an object after parsing xml with SAX I have some large XML files to parse and have created an object class to contain my relevant data. Unfortunately, I am unsure how to return the object for later processing. Right now I pickle my data and moments later depickle the object for access. This seems wasteful, and there surely must be a way of grabbing my data without hitting the disk. def endElement(self, name): if name == "info": # done collecting this iteration self.data.setX(self.x) self.data.setY(self.y) elif name == "lastTagOfInterest": # done with file # want to return my object from here filehandler = open(self.outputname + ".pi", "w") pickle.dump(self.data, filehandler) filehandler.close() I have tried putting a return statement in my endElement tag, but that does not seem to get passed up the chain to where I call the SAX parser. Thanks for any tips. A: Bah, sat and thought about it for a second and the answer was obvious. Return quit the method, and then just pull out the data field from the ContentHandler object I had created.
Return an object after parsing xml with SAX
I have some large XML files to parse and have created an object class to contain my relevant data. Unfortunately, I am unsure how to return the object for later processing. Right now I pickle my data and moments later depickle the object for access. This seems wasteful, and there surely must be a way of grabbing my data without hitting the disk. def endElement(self, name): if name == "info": # done collecting this iteration self.data.setX(self.x) self.data.setY(self.y) elif name == "lastTagOfInterest": # done with file # want to return my object from here filehandler = open(self.outputname + ".pi", "w") pickle.dump(self.data, filehandler) filehandler.close() I have tried putting a return statement in my endElement tag, but that does not seem to get passed up the chain to where I call the SAX parser. Thanks for any tips.
[ "Bah, sat and thought about it for a second and the answer was obvious. Return quit the method, and then just pull out the data field from the ContentHandler object I had created.\n" ]
[ 1 ]
[]
[]
[ "python", "sax", "xml" ]
stackoverflow_0003001350_python_sax_xml.txt
Q: Passing arguments to a python service I need some help with a python service. I have a service written in Python. What I need to do is to pass it some arguments. Let me give you an example to explain it a bit better. Lets say I have a service, that does nothing but writes something to a log. I'd like to write the same thing into the log several times, so I use a loop. I would like to pass the counter for the loop when I start the service, but I have no idea how. I start the service with: win32serviceutil.HandleCommandLine(WinService) I'm looking for something like win32serviceutil.HandleCommandLine(WinService,10) I don't really care how its done, as long as I can pass arguments to it. Have been trying to get this to work for the better part of the day with no luck. Also, the service isn't run directly, but is imported and then run from there. EDIT: Here is an example, hopefully it will clear some things up. This is in WindowsService.py: import win32serviceutil, win32service, win32event, servicemanager, win32serviceutil class LoopService(win32serviceutil.ServiceFramework): _svc_name_ = "LoopService" _svc_description_ = "LoopService" _svc_display_name_ = "LoopService" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING); win32event.SetEvent(self.hWaitStop); def SvcDoRun(self): i = 0; while i < 5: servicemanager.LogInfoMsg("just something to put in the log"); i += 1 win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) This is in the main script: import service.WindowsService, win32serviceutil win32serviceutil.HandleCommandLine(service.WindowsService.LoopService); As it is now, the loop will execute a fixed amount of times. What I would like is to simply send the value to the service somehow. Don't really care how. A: Sorry, not enough info to answer your question. This seem an application-specific thing. The only thing I can think is to review the code of win32serviceutil.HandleCommandLine method and WinService class to determine which one writes to the log. Then, you have to make a subclass and override the method responsible to write in the log to receive an additional argument. Finally, you must chance all references from the original class to the new one. -- Added, after the edition of the question. Clearer, but still insufficient. You need to review win32serviceutil.HandleCommandLine and see how it invokes service.WindowsService.LoopService.__init__. In particular, how HandleCommandLine generates args and how you can control it. If you are in a hurry, you can do: class LoopService(win32serviceutil.ServiceFramework): repetitions = 5 # ... def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) self.repetitions = LoopService.repetitions # ... def SvcDoRun(self): for i in range(self.repetitions): servicemanager.LogInfoMsg("just something to put in the log"); win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) Then you can control the number of repetition changing LoopService.repetitions before creating a new instance. import service.WindowsService, win32serviceutil service.WindowsService.LoopService.repetitions = 10 win32serviceutil.HandleCommandLine(service.WindowsService.LoopService); This works, but it's ugly. Try to control args and then set self.repetition accordingly. A: I don't think you can pass argument directly to the service. You can probably use the environment (set environment variable before starting the service and read it from the service).
Passing arguments to a python service
I need some help with a python service. I have a service written in Python. What I need to do is to pass it some arguments. Let me give you an example to explain it a bit better. Lets say I have a service, that does nothing but writes something to a log. I'd like to write the same thing into the log several times, so I use a loop. I would like to pass the counter for the loop when I start the service, but I have no idea how. I start the service with: win32serviceutil.HandleCommandLine(WinService) I'm looking for something like win32serviceutil.HandleCommandLine(WinService,10) I don't really care how its done, as long as I can pass arguments to it. Have been trying to get this to work for the better part of the day with no luck. Also, the service isn't run directly, but is imported and then run from there. EDIT: Here is an example, hopefully it will clear some things up. This is in WindowsService.py: import win32serviceutil, win32service, win32event, servicemanager, win32serviceutil class LoopService(win32serviceutil.ServiceFramework): _svc_name_ = "LoopService" _svc_description_ = "LoopService" _svc_display_name_ = "LoopService" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING); win32event.SetEvent(self.hWaitStop); def SvcDoRun(self): i = 0; while i < 5: servicemanager.LogInfoMsg("just something to put in the log"); i += 1 win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) This is in the main script: import service.WindowsService, win32serviceutil win32serviceutil.HandleCommandLine(service.WindowsService.LoopService); As it is now, the loop will execute a fixed amount of times. What I would like is to simply send the value to the service somehow. Don't really care how.
[ "Sorry, not enough info to answer your question. This seem an application-specific thing.\nThe only thing I can think is to review the code of win32serviceutil.HandleCommandLine method and WinService class to determine which one writes to the log. Then, you have to make a subclass and override the method responsible to write in the log to receive an additional argument. Finally, you must chance all references from the original class to the new one.\n-- Added, after the edition of the question.\nClearer, but still insufficient. You need to review win32serviceutil.HandleCommandLine and see how it invokes service.WindowsService.LoopService.__init__. In particular, how HandleCommandLine generates args and how you can control it.\nIf you are in a hurry, you can do:\nclass LoopService(win32serviceutil.ServiceFramework):\n repetitions = 5\n # ... \n\n def __init__(self,args):\n win32serviceutil.ServiceFramework.__init__(self,args)\n self.hWaitStop = win32event.CreateEvent(None,0,0,None)\n self.repetitions = LoopService.repetitions\n\n # ...\n\n def SvcDoRun(self):\n for i in range(self.repetitions):\n servicemanager.LogInfoMsg(\"just something to put in the log\");\n win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)\n\nThen you can control the number of repetition changing LoopService.repetitions before creating a new instance.\nimport service.WindowsService, win32serviceutil\nservice.WindowsService.LoopService.repetitions = 10\nwin32serviceutil.HandleCommandLine(service.WindowsService.LoopService);\n\nThis works, but it's ugly. Try to control args and then set self.repetition accordingly. \n", "I don't think you can pass argument directly to the service. You can probably use the environment (set environment variable before starting the service and read it from the service).\n" ]
[ 0, 0 ]
[]
[]
[ "python", "service" ]
stackoverflow_0003000476_python_service.txt
Q: Python "string_escape" vs "unicode_escape" According to the docs, the builtin string encoding string_escape: Produce[s] a string that is suitable as string literal in Python source code ...while the unicode_escape: Produce[s] a string that is suitable as Unicode literal in Python source code So, they should have roughly the same behaviour. BUT, they appear to treat single quotes differently: >>> print """before '" \0 after""".encode('string-escape') before \'" \x00 after >>> print """before '" \0 after""".encode('unicode-escape') before '" \x00 after The string_escape escapes the single quote while the Unicode one does not. Is it safe to assume that I can simply: >>> escaped = my_string.encode('unicode-escape').replace("'", "\\'") ...and get the expected behaviour? Edit: Just to be super clear, the expected behavior is getting something suitable as a literal. A: According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used. They are both driven by the same function, unicodeescape_string. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote. A: Within the range 0 ≤ c < 128, yes the ' is the only difference for CPython 2.6. >>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128)) set(["'"]) Outside of this range the two types are not exchangeable. >>> '\x80'.encode('string_escape') '\\x80' >>> '\x80'.encode('unicode_escape') Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128) >>> u'1'.encode('unicode_escape') '1' >>> u'1'.encode('string_escape') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: escape_encode() argument 1 must be str, not unicode On Python 3.x, the string_escape encoding no longer exists, since str can only store Unicode.
Python "string_escape" vs "unicode_escape"
According to the docs, the builtin string encoding string_escape: Produce[s] a string that is suitable as string literal in Python source code ...while the unicode_escape: Produce[s] a string that is suitable as Unicode literal in Python source code So, they should have roughly the same behaviour. BUT, they appear to treat single quotes differently: >>> print """before '" \0 after""".encode('string-escape') before \'" \x00 after >>> print """before '" \0 after""".encode('unicode-escape') before '" \x00 after The string_escape escapes the single quote while the Unicode one does not. Is it safe to assume that I can simply: >>> escaped = my_string.encode('unicode-escape').replace("'", "\\'") ...and get the expected behaviour? Edit: Just to be super clear, the expected behavior is getting something suitable as a literal.
[ "According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used.\nThey are both driven by the same function, unicodeescape_string. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.\n", "Within the range 0 ≤ c < 128, yes the ' is the only difference for CPython 2.6.\n>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))\nset([\"'\"])\n\nOutside of this range the two types are not exchangeable.\n>>> '\\x80'.encode('string_escape')\n'\\\\x80'\n>>> '\\x80'.encode('unicode_escape')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nUnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)\n\n>>> u'1'.encode('unicode_escape')\n'1'\n>>> u'1'.encode('string_escape')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: escape_encode() argument 1 must be str, not unicode\n\nOn Python 3.x, the string_escape encoding no longer exists, since str can only store Unicode.\n" ]
[ 26, 14 ]
[]
[]
[ "encoding", "escaping", "python", "python_2.x", "quotes" ]
stackoverflow_0002969044_encoding_escaping_python_python_2.x_quotes.txt
Q: compressed archive with quick access to individual file I need to come up with a file format for new application I am writing. This file will need to hold a bunch other text files which are mostly text but can be other formats as well. Naturally, a compressed tar file seems to fit the bill. The problem is that I want to be able to retrieve some data from the file very quickly and getting just a particular file from a tar.gz file seems to take longer than it should. I am assumeing that this is because it has to decompress the entire file even though I just want one. When I have just a regular uncompressed tar file I can get that data real quick. Lets say the file I need quickly is called data.dat For example the command... tar -x data.dat -zf myfile.tar.gz ... is what takes a lot longer than I'd like. MP3 files have id3 data and jpeg files have exif data that can be read in quickly without opening the entire file. I would like my data.dat file to be available in a similar way. I was thinking that I could leave it uncompressed and seperate from the rest of the files in myfile.tar.gz I could then create a tar file of data.dat and myfile.tar.gz and then hopefully that data would be able to be retrieved faster because it is at the head of outer tar file and is uncompressed. Does this sound right?... putting a compressed tar inside of a tar file? Basically, my need is to have an archive type of file with quick access to one particular file. Tar does this just fine, but I'd also like to have that data compressed and as soon as I do that, I no longer have quick access. Are there other archive formats that will give me that quick access I need? As a side note, this application will be written in Python. If the solution calls for a re-invention of the wheel with my own binary format I am familiar with C and would have no problem writing the Python module in C. Idealy I'd just use tar, dd, cat, gzip, etc though. Thanks, ~Eric A: ZIP seems to be appropriate for your situation. Files are compressed individually, which means you access them without streaming through everything before. In Python, you can use zipfile.
compressed archive with quick access to individual file
I need to come up with a file format for new application I am writing. This file will need to hold a bunch other text files which are mostly text but can be other formats as well. Naturally, a compressed tar file seems to fit the bill. The problem is that I want to be able to retrieve some data from the file very quickly and getting just a particular file from a tar.gz file seems to take longer than it should. I am assumeing that this is because it has to decompress the entire file even though I just want one. When I have just a regular uncompressed tar file I can get that data real quick. Lets say the file I need quickly is called data.dat For example the command... tar -x data.dat -zf myfile.tar.gz ... is what takes a lot longer than I'd like. MP3 files have id3 data and jpeg files have exif data that can be read in quickly without opening the entire file. I would like my data.dat file to be available in a similar way. I was thinking that I could leave it uncompressed and seperate from the rest of the files in myfile.tar.gz I could then create a tar file of data.dat and myfile.tar.gz and then hopefully that data would be able to be retrieved faster because it is at the head of outer tar file and is uncompressed. Does this sound right?... putting a compressed tar inside of a tar file? Basically, my need is to have an archive type of file with quick access to one particular file. Tar does this just fine, but I'd also like to have that data compressed and as soon as I do that, I no longer have quick access. Are there other archive formats that will give me that quick access I need? As a side note, this application will be written in Python. If the solution calls for a re-invention of the wheel with my own binary format I am familiar with C and would have no problem writing the Python module in C. Idealy I'd just use tar, dd, cat, gzip, etc though. Thanks, ~Eric
[ "ZIP seems to be appropriate for your situation. Files are compressed individually, which means you access them without streaming through everything before.\nIn Python, you can use zipfile.\n" ]
[ 3 ]
[]
[]
[ "archive", "file_format", "python", "tar" ]
stackoverflow_0003002196_archive_file_format_python_tar.txt
Q: Split a key that is a string of numbers into single digit keys in Python I would like to turn the following dictionary: dictionary = { 4388464: ['getting'] 827862 : ['Taruma', 'Varuna'] ... } into: dictionary = { 4: {3: {8: {8: {4: {6: {4: {'words': ['getting']}}}}}}} 8: {2: {7: {8: {6: {2: {'words': ['Taruma', 'Varuna']}}}}}} ... } This will then allow me to use the dictionary like: dictionary[8][2][7][8][6][2]['words'] instead of: dictionary[827862]. A: import pprint dictionary = { 4388464: ['getting'], 43881: ['got'], 827862 : ['Taruma', 'Varuna'], } d2 = {} def add_it(d, k, words): knum = int(k[0]) if len(k) == 1: d[knum] = {'words': words} else: dsub = d.setdefault(knum, {}) add_it(dsub, k[1:], words) for k, words in dictionary.items(): add_it(d2, list(str(k)), words) pprint.pprint(d2) prints: {4: {3: {8: {8: {1: {'words': ['got']}, 4: {6: {4: {'words': ['getting']}}}}}}}, 8: {2: {7: {8: {6: {2: {'words': ['Taruma', 'Varuna']}}}}}}} A: A short solution to produce the dictionaries: def num2dict( n, d ): if n < 10: return { n: d } else: q, r = divmod( n, 10 ) return num2dict( q, { r: d } ) print( num2dict( 4388464, { 'words': [ 'getting' ] } ) ) A: You could try using a recursive defaultdict: from collections import defaultdict # define a hierarchical defaultdict (of defaultdicts (of defaultdicts...)) class recursivedefaultdict(defaultdict): def __init__(self): self.default_factory = type(self) # add an iterator recursively to create entries, sub-entries, etc. def addToTree(it, v, accum): try: addToTree(it, v, accum[it.next()]) except StopIteration: accum["words"] = v # test it out dictionary = { 4388464: ['getting'], 43881: ['got'], 827862 : ['Taruma', 'Varuna'], } d2 = recursivedefaultdict() for k,v in dictionary.iteritems(): addToTree(iter(str(k)), v, d2) # use recursion again to view the results def dumpDict(d,indent=""): for k,v in d.iteritems(): if k == "words": print "%s- %s : %s" % (indent, k, v) else: print "%s- %s:" % (indent, k) dumpDict(v, indent+" ") dumpDict(d2) Gives: - 8: - 2: - 7: - 8: - 6: - 2: - words : ['Taruma', 'Varuna'] - 4: - 3: - 8: - 8: - 1: - words : ['got'] - 4: - 6: - 4: - words : ['getting'] I think a recursive defaultdict is a beautiful way to create these nested dicts of unpredictable length. (Note that there will be trouble though, if the next value we add uses 43884 as the key, as there already exists an entry for d2[4][3][8][8][4].)
Split a key that is a string of numbers into single digit keys in Python
I would like to turn the following dictionary: dictionary = { 4388464: ['getting'] 827862 : ['Taruma', 'Varuna'] ... } into: dictionary = { 4: {3: {8: {8: {4: {6: {4: {'words': ['getting']}}}}}}} 8: {2: {7: {8: {6: {2: {'words': ['Taruma', 'Varuna']}}}}}} ... } This will then allow me to use the dictionary like: dictionary[8][2][7][8][6][2]['words'] instead of: dictionary[827862].
[ "import pprint\n\ndictionary = {\n 4388464: ['getting'],\n 43881: ['got'],\n 827862 : ['Taruma', 'Varuna'],\n}\n\nd2 = {}\n\ndef add_it(d, k, words):\n knum = int(k[0])\n if len(k) == 1:\n d[knum] = {'words': words}\n else:\n dsub = d.setdefault(knum, {})\n add_it(dsub, k[1:], words)\n\nfor k, words in dictionary.items():\n add_it(d2, list(str(k)), words)\n\n\npprint.pprint(d2)\n\nprints:\n{4: {3: {8: {8: {1: {'words': ['got']},\n 4: {6: {4: {'words': ['getting']}}}}}}},\n 8: {2: {7: {8: {6: {2: {'words': ['Taruma', 'Varuna']}}}}}}}\n\n", "A short solution to produce the dictionaries:\ndef num2dict( n, d ):\n if n < 10:\n return { n: d }\n else:\n q, r = divmod( n, 10 )\n return num2dict( q, { r: d } )\n\nprint( num2dict( 4388464, { 'words': [ 'getting' ] } ) )\n\n", "You could try using a recursive defaultdict:\nfrom collections import defaultdict\n\n# define a hierarchical defaultdict (of defaultdicts (of defaultdicts...))\nclass recursivedefaultdict(defaultdict):\n def __init__(self):\n self.default_factory = type(self)\n\n# add an iterator recursively to create entries, sub-entries, etc.\ndef addToTree(it, v, accum):\n try:\n addToTree(it, v, accum[it.next()])\n except StopIteration:\n accum[\"words\"] = v\n\n# test it out\ndictionary = { \n 4388464: ['getting'], \n 43881: ['got'], \n 827862 : ['Taruma', 'Varuna'], \n} \n\nd2 = recursivedefaultdict()\nfor k,v in dictionary.iteritems():\n addToTree(iter(str(k)), v, d2)\n\n\n# use recursion again to view the results\ndef dumpDict(d,indent=\"\"):\n for k,v in d.iteritems():\n if k == \"words\":\n print \"%s- %s : %s\" % (indent, k, v)\n else:\n print \"%s- %s:\" % (indent, k)\n dumpDict(v, indent+\" \")\n\ndumpDict(d2)\n\nGives:\n- 8:\n - 2:\n - 7:\n - 8:\n - 6:\n - 2:\n - words : ['Taruma', 'Varuna']\n- 4:\n - 3:\n - 8:\n - 8:\n - 1:\n - words : ['got']\n - 4:\n - 6:\n - 4:\n - words : ['getting']\n\nI think a recursive defaultdict is a beautiful way to create these nested dicts of unpredictable length. (Note that there will be trouble though, if the next value we add uses 43884 as the key, as there already exists an entry for d2[4][3][8][8][4].)\n" ]
[ 5, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002997279_dictionary_python.txt
Q: blank lines in file after sorting content of a text file in python I have this small script that sorts the content of a text file # The built-in function `open` opens a file and returns a file object. # Read mode opens a file for reading only. try: f = open("tracks.txt", "r") try: # Read the entire contents of a file at once. # string = f.read() # OR read one line at a time. #line = f.readline() # OR read all the lines into a list. lines = f.readlines() lines.sort() f.close() f = open('tracks.txt', 'w') f.writelines(lines) # Write a sequence of strings to a file finally: f.close() except IOError: pass the only problem is that the text is displayed at the bottom of the text file everytime it's sortened... I assume it also sorts the blank lines...anybody knows why? and maybe can you suggest some tips on how to avoid this happening? thanks in advance A: An "empty" line read from a text file is represented in Python by a string containing only a newline ("\n"). You may also want to avoid lines whose "data" consists only of spaces, tabs, etc ("whitespace"). The str.strip() method lets you detect both cases (a newline is whitespace). f = open("tracks.txt", "r") # omit empty lines and lines containing only whitespace lines = [line for line in f if line.strip()] f.close() lines.sort() # now write the output file A: This is a perfect opportunity to do some test-based development (see below). Some observations: In the example below, I omit the aspect of reading from and writing to a file. That's not essential to this question, in my opinion. I assume you want to strip trailing newlines and omit blank lines. If not, you'll need to adjust. (But you'll have the framework for asserting/confirming the expected behavior.) I agree with chryss above that you generally don't need to reflexively wrap things in try blocks in Python. That's an anti-pattern that comes from Java (which forces it), I believe. Anyway, here's the test: import unittest def sort_lines(text): """Return text sorted by line, remove empty lines and strip trailing whitespace.""" lines = text.split('\n') non_empty = [line.rstrip() for line in lines if line.strip()] non_empty.sort() return '\n'.join(non_empty) class SortTest(unittest.TestCase): def test(self): data_to_sort = """z some stuff c some other stuff d more stuff after blank lines b another line a the last line""" actual = sort_lines(data_to_sort) expected = """a the last line b another line c some other stuff d more stuff after blank lines z some stuff""" self.assertEquals(actual, expected, "no match!") unittest.main() A: The reason it sorts the blank lines is that they are there. A blank line is an empty string followed by \n (or \r\n or \r, depending on the OS). Perfectly sortable. I should like to note that "try:" nested into a "try:... except" block is a bit ugly, and I'd close the file after reading, for style's sake.
blank lines in file after sorting content of a text file in python
I have this small script that sorts the content of a text file # The built-in function `open` opens a file and returns a file object. # Read mode opens a file for reading only. try: f = open("tracks.txt", "r") try: # Read the entire contents of a file at once. # string = f.read() # OR read one line at a time. #line = f.readline() # OR read all the lines into a list. lines = f.readlines() lines.sort() f.close() f = open('tracks.txt', 'w') f.writelines(lines) # Write a sequence of strings to a file finally: f.close() except IOError: pass the only problem is that the text is displayed at the bottom of the text file everytime it's sortened... I assume it also sorts the blank lines...anybody knows why? and maybe can you suggest some tips on how to avoid this happening? thanks in advance
[ "An \"empty\" line read from a text file is represented in Python by a string containing only a newline (\"\\n\"). You may also want to avoid lines whose \"data\" consists only of spaces, tabs, etc (\"whitespace\"). The str.strip() method lets you detect both cases (a newline is whitespace).\nf = open(\"tracks.txt\", \"r\")\n# omit empty lines and lines containing only whitespace\nlines = [line for line in f if line.strip()]\nf.close()\nlines.sort()\n# now write the output file\n\n", "This is a perfect opportunity to do some test-based development (see below). Some observations:\n\nIn the example below, I omit the aspect of reading from and writing to a file. That's not essential to this question, in my opinion.\nI assume you want to strip trailing newlines and omit blank lines. If not, you'll need to adjust. (But you'll have the framework for asserting/confirming the expected behavior.)\nI agree with chryss above that you generally don't need to reflexively wrap things in try blocks in Python. That's an anti-pattern that comes from Java (which forces it), I believe.\n\nAnyway, here's the test:\nimport unittest\n\ndef sort_lines(text):\n \"\"\"Return text sorted by line, remove empty lines and strip trailing whitespace.\"\"\"\n lines = text.split('\\n')\n non_empty = [line.rstrip() for line in lines if line.strip()]\n non_empty.sort()\n return '\\n'.join(non_empty)\n\nclass SortTest(unittest.TestCase):\n\n def test(self):\n data_to_sort = \"\"\"z some stuff\nc some other stuff\n\n\nd more stuff after blank lines\nb another line\na the last line\"\"\"\n\n actual = sort_lines(data_to_sort)\n expected = \"\"\"a the last line\nb another line\nc some other stuff\nd more stuff after blank lines\nz some stuff\"\"\"\n\n self.assertEquals(actual, expected, \"no match!\")\n\nunittest.main()\n\n", "The reason it sorts the blank lines is that they are there. A blank line is an empty string followed by \\n (or \\r\\n or \\r, depending on the OS). Perfectly sortable.\nI should like to note that \"try:\" nested into a \"try:... except\" block is a bit ugly, and I'd close the file after reading, for style's sake.\n" ]
[ 24, 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003002392_python.txt
Q: does BeautifulSoup strips inline CSS and javascript content hey guys does beautifulSoup strips css and javascript content? after using content3 = ''.join(BeautifulSoup(content).findAll(text=True)) i still have them lingering around. A: What exactly do you want to strip, all script and style elements? It should be something like: ''.join(BeautifulSoup(content).findAll(text=lambda text: text.parent.name != "script" and text.parent.name != "style"))
does BeautifulSoup strips inline CSS and javascript content
hey guys does beautifulSoup strips css and javascript content? after using content3 = ''.join(BeautifulSoup(content).findAll(text=True)) i still have them lingering around.
[ "What exactly do you want to strip, all script and style elements? It should be something like:\n''.join(BeautifulSoup(content).findAll(text=lambda text: \ntext.parent.name != \"script\" and \ntext.parent.name != \"style\"))\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003002534_beautifulsoup_python.txt
Q: Iterating dictionary indexes in django templates I have a dictionary with embedded objects, which looks something like this: notes = { 2009: [<Note: Test note>, <Note: Another test note>], 2010: [<Note: Third test note>, <Note: Fourth test note>], } I'm trying to access each of the note objects inside a django template, and having a helluva time navigating to them. In short, I'm not sure how to extract by index in django templating. Current template code is: <h3>Notes</h3> {% for year in notes %} {{ year }} # Works fine {% for note in notes.year %} {{ note }} # Returns blank {% endfor %} {% endfor %} If I replace {% for note in notes.year %} with {% for note in notes.2010 %} things work fine, but I need that '2010' to be dynamic. Any suggestions much appreciated. A: Try: <h3>Notes</h3> {% for year, notes in notes.items %} {{ year }} {% for note in notes %} {{ note }} {% endfor %} {% endfor %}
Iterating dictionary indexes in django templates
I have a dictionary with embedded objects, which looks something like this: notes = { 2009: [<Note: Test note>, <Note: Another test note>], 2010: [<Note: Third test note>, <Note: Fourth test note>], } I'm trying to access each of the note objects inside a django template, and having a helluva time navigating to them. In short, I'm not sure how to extract by index in django templating. Current template code is: <h3>Notes</h3> {% for year in notes %} {{ year }} # Works fine {% for note in notes.year %} {{ note }} # Returns blank {% endfor %} {% endfor %} If I replace {% for note in notes.year %} with {% for note in notes.2010 %} things work fine, but I need that '2010' to be dynamic. Any suggestions much appreciated.
[ "Try: \n<h3>Notes</h3>\n{% for year, notes in notes.items %}\n {{ year }}\n {% for note in notes %}\n {{ note }}\n {% endfor %}\n{% endfor %}\n\n" ]
[ 8 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003002728_django_django_templates_python.txt
Q: SQL get data out of BEGIN; ...; END; block in python I want to run many select queries at once by putting them between BEGIN; END;. I tried the following: cur = connection.cursor() cur.execute(""" BEGIN; SELECT ...; END;""") res = cur.fetchall() However, I get the error: psycopg2.ProgrammingError: no results to fetch How can I actually get data this way? Likewise, if I just have many selects in a row, I only get data back from the latest one. Is there a way to get data out of all of them? A: Postgresql doesn't actually support returning multiple result sets from a single command. If you pass this input to psql: BEGIN; SELECT ...; END; it will split this up client-side and actually execute three statements, only the second of which returns a result set. "BEGIN" and "END" are SQL-level commands to start/finish a transaction. (There may be a lower-level protocol for doing this but I can't remember). You probably don't want to issue them directly, but rather have your driver (psycopg2) handle this. For example, with Perl's DBI I specify AutoCommit=>0 when connecting and it implicitly issues a "BEGIN" before my first command; and then "END" (or "COMMIT" etc) when I explicitly call $dbh->commit; I guess Python's DB-API works rather like this, since other systems such as JDBC do as well... A: If you're just SELECTing something and you don't have a function that performs any DML or the like, you shouldn't need to make an explicit transaction for any reason I'm aware of.
SQL get data out of BEGIN; ...; END; block in python
I want to run many select queries at once by putting them between BEGIN; END;. I tried the following: cur = connection.cursor() cur.execute(""" BEGIN; SELECT ...; END;""") res = cur.fetchall() However, I get the error: psycopg2.ProgrammingError: no results to fetch How can I actually get data this way? Likewise, if I just have many selects in a row, I only get data back from the latest one. Is there a way to get data out of all of them?
[ "Postgresql doesn't actually support returning multiple result sets from a single command. If you pass this input to psql:\nBEGIN;\nSELECT ...;\nEND;\n\nit will split this up client-side and actually execute three statements, only the second of which returns a result set.\n\"BEGIN\" and \"END\" are SQL-level commands to start/finish a transaction. (There may be a lower-level protocol for doing this but I can't remember). You probably don't want to issue them directly, but rather have your driver (psycopg2) handle this. For example, with Perl's DBI I specify AutoCommit=>0 when connecting and it implicitly issues a \"BEGIN\" before my first command; and then \"END\" (or \"COMMIT\" etc) when I explicitly call $dbh->commit; I guess Python's DB-API works rather like this, since other systems such as JDBC do as well...\n", "If you're just SELECTing something and you don't have a function that performs any DML or the like, you shouldn't need to make an explicit transaction for any reason I'm aware of.\n" ]
[ 4, 0 ]
[]
[]
[ "postgresql", "python", "sql", "sqlobject" ]
stackoverflow_0003002033_postgresql_python_sql_sqlobject.txt
Q: Does Python work in larger teams? I read this post last night and it got me thinking. I like python and "batteries", pypi and such. But I've only done python solo. Never tried it in a team. Are the points that Ted mentions valid? If they are how do teams cope with them? Does Python work in teams or even large teams? Or it kills productivity? I personally see the problems he mentions when I come back to my old code. Even when working with other modules sometimes I need to peek inside. I would like to hear people with experience on this. A: Python works fine in teams. Whether a language works in large teams is largely a factor of how well the team works together, and has little to do with the language. A: I currently work on a large Django app, and in my previous job I worked on a large Java project (desktop app, not web, but still appropriate to this discussion), and I'm kind of torn between agreeing and disagreeing with the author. While I enjoy Python over Java, and have ample experience working with other dynamically-typed languages like Ruby and Objective-C, I'm still not convinced of which is better (static vs. dynamic). Sometimes in Python-land, I do think that it would be nicer to have static types and a compiler to prevent some errors; I don't like Java's type model, but Scala has a decent type system that doesn't get in the way but prevents a lot of errors. That said, I think the successes/failures of using Python or Java have more to do with a team's experience and background. I feel like this article would be better titled "Straying from Java makes me nervous", since the author seems to mostly be saying, "I have experience with Java. I don't understand/have experience with Python. Thus, I'm more comfortable writing Java code." I think experienced Python developers learn to work with/around most of the "problems" he perceives; Python is not Java and requires a different approach to programming. I also had to chuckle a bit at this line: Java has a well thought out hierarchy of checked and runtime exceptions. I think most would agree that Java's exception hierarchy is confusing at best, and that checked exceptions were a worthwhile but failed experiment that doesn't really make code more robust (I suppose they do if used properly, but how many Java programmers use exceptions properly?). A: I've worked on teams using Java and I'm currently working on a team using Python. All things considered, I would say that the Python code is much more precise and far easier to understand than the Java code that my other teams produced. The whole "There should be one-- and preferably only one --obvious way to do it" mantra helps immensely. I agree with the author's point about PyDev... my team has been using PyCharm for the past few months and its been AMAZING!!! The author's point about Python's exceptions, in my opinion, isn't a very good one. In the Java world, most checked exceptions (exceptions that are listed after the 'throws' keyword on method definitions) are usually just caught and re-throws as runtime exceptions anyway. It is widely thought that Java shouldn't even have checked exceptions and instead use an exception system closer to what Python's is currently. See this article for more about Java's checked exceptions.. All in all, I think that working in a team setting with Python vs. Java - I prefer Python. I worked in teams doing Java for 6 years and on a team doing Python for 6 months and I've seen some massive productivity benefits from the clean, readable syntax of Python. A: Indeed, Python does work in large teams, but if you're comparing it to other languages it definitely has shortcomings. For one, there are more team-related tools for things like C# and Java. I've worked in Eclipse on large projects in both Python and Java, and team integration worked better in Java, specifically the doc generation and auto-formatting. But the one thing I really liked about working on a large Python project was it's readability. In Java I was going to the coders much more often to have them explain code, but Python was easier to understand. Of course, this may also be due to how the two projects were coded, who coded them, and my aptitude in the two languages.
Does Python work in larger teams?
I read this post last night and it got me thinking. I like python and "batteries", pypi and such. But I've only done python solo. Never tried it in a team. Are the points that Ted mentions valid? If they are how do teams cope with them? Does Python work in teams or even large teams? Or it kills productivity? I personally see the problems he mentions when I come back to my old code. Even when working with other modules sometimes I need to peek inside. I would like to hear people with experience on this.
[ "Python works fine in teams. Whether a language works in large teams is largely a factor of how well the team works together, and has little to do with the language.\n", "I currently work on a large Django app, and in my previous job I worked on a large Java project (desktop app, not web, but still appropriate to this discussion), and I'm kind of torn between agreeing and disagreeing with the author.\nWhile I enjoy Python over Java, and have ample experience working with other dynamically-typed languages like Ruby and Objective-C, I'm still not convinced of which is better (static vs. dynamic). Sometimes in Python-land, I do think that it would be nicer to have static types and a compiler to prevent some errors; I don't like Java's type model, but Scala has a decent type system that doesn't get in the way but prevents a lot of errors.\nThat said, I think the successes/failures of using Python or Java have more to do with a team's experience and background. I feel like this article would be better titled \"Straying from Java makes me nervous\", since the author seems to mostly be saying, \"I have experience with Java. I don't understand/have experience with Python. Thus, I'm more comfortable writing Java code.\" I think experienced Python developers learn to work with/around most of the \"problems\" he perceives; Python is not Java and requires a different approach to programming.\nI also had to chuckle a bit at this line:\n\nJava has a well thought out hierarchy of checked and runtime exceptions.\n\nI think most would agree that Java's exception hierarchy is confusing at best, and that checked exceptions were a worthwhile but failed experiment that doesn't really make code more robust (I suppose they do if used properly, but how many Java programmers use exceptions properly?).\n", "I've worked on teams using Java and I'm currently working on a team using Python. All things considered, I would say that the Python code is much more precise and far easier to understand than the Java code that my other teams produced. The whole \"There should be one-- and preferably only one --obvious way to do it\" mantra helps immensely. \nI agree with the author's point about PyDev... my team has been using PyCharm for the past few months and its been AMAZING!!!\nThe author's point about Python's exceptions, in my opinion, isn't a very good one. In the Java world, most checked exceptions (exceptions that are listed after the 'throws' keyword on method definitions) are usually just caught and re-throws as runtime exceptions anyway. It is widely thought that Java shouldn't even have checked exceptions and instead use an exception system closer to what Python's is currently. See this article for more about Java's checked exceptions..\nAll in all, I think that working in a team setting with Python vs. Java - I prefer Python. I worked in teams doing Java for 6 years and on a team doing Python for 6 months and I've seen some massive productivity benefits from the clean, readable syntax of Python.\n", "Indeed, Python does work in large teams, but if you're comparing it to other languages it definitely has shortcomings. For one, there are more team-related tools for things like C# and Java. I've worked in Eclipse on large projects in both Python and Java, and team integration worked better in Java, specifically the doc generation and auto-formatting.\nBut the one thing I really liked about working on a large Python project was it's readability. In Java I was going to the coders much more often to have them explain code, but Python was easier to understand. Of course, this may also be due to how the two projects were coded, who coded them, and my aptitude in the two languages.\n" ]
[ 13, 7, 1, 0 ]
[]
[]
[ "collaboration", "python" ]
stackoverflow_0002999160_collaboration_python.txt
Q: Calling Python app/script from C# I'm building an ASP.NET MVC (C#) site where I want to implement STV (Single Transferable Vote) voting. I've used OpenSTV for voting scenarios before, with great success, but I've never used it programmatically. The OpenSTV Google Code project offers a Python script that allows usage of OpenSTV from other applications: import sys sys.path.append("path to openstv package") from openstv.ballots import Ballots from openstv.ReportPlugins.TextReport import TextReport from openstv.plugins import getMethodPlugins (ballotFname, method, reportFname) = sys.argv[1:] methods = getMethodPlugins("byName") f = open(reportFname, "w") try: b = Ballots() b.loadUnknown(ballotFname) except Exception, msg: print >> f, ("Unable to read ballots from %s" % ballotFname) print >> f, msg sys.exit(-1) try: e = methods[method](b) e.runElection() except Exception, msg: print >> f, ("Unable to count votes using %s" % method) print >> f, msg sys.exit(-1) try: r = TextReport(e, outputFile=f) r.generateReport(); except Exception, msg: print >> f, "Unable to write report" print >> f, msg sys.exit(-1) f.close() Is there a way for me to make such a Python call from my C# ASP.NET MVC site? If so, how? Thanks in advance! A: Here is a good example on how to call IronPython from C#, including passing arguments and returning results; of course you'll have to make that code into a function, with ballotFname and reportFname as its arguments. A: The best way is probably to use IronPython. See this answer for a starting point.
Calling Python app/script from C#
I'm building an ASP.NET MVC (C#) site where I want to implement STV (Single Transferable Vote) voting. I've used OpenSTV for voting scenarios before, with great success, but I've never used it programmatically. The OpenSTV Google Code project offers a Python script that allows usage of OpenSTV from other applications: import sys sys.path.append("path to openstv package") from openstv.ballots import Ballots from openstv.ReportPlugins.TextReport import TextReport from openstv.plugins import getMethodPlugins (ballotFname, method, reportFname) = sys.argv[1:] methods = getMethodPlugins("byName") f = open(reportFname, "w") try: b = Ballots() b.loadUnknown(ballotFname) except Exception, msg: print >> f, ("Unable to read ballots from %s" % ballotFname) print >> f, msg sys.exit(-1) try: e = methods[method](b) e.runElection() except Exception, msg: print >> f, ("Unable to count votes using %s" % method) print >> f, msg sys.exit(-1) try: r = TextReport(e, outputFile=f) r.generateReport(); except Exception, msg: print >> f, "Unable to write report" print >> f, msg sys.exit(-1) f.close() Is there a way for me to make such a Python call from my C# ASP.NET MVC site? If so, how? Thanks in advance!
[ "Here is a good example on how to call IronPython from C#, including passing arguments and returning results; of course you'll have to make that code into a function, with ballotFname and reportFname as its arguments.\n", "The best way is probably to use IronPython. See this answer for a starting point.\n" ]
[ 4, 3 ]
[]
[]
[ "asp.net", "asp.net_mvc", "c#", "openstv", "python" ]
stackoverflow_0003002402_asp.net_asp.net_mvc_c#_openstv_python.txt
Q: sql select from a large number of IDs I have a table, Foo. I run a query on Foo to get the ids from a subset of Foo. I then want to run a more complicated set of queries, but only on those IDs. Is there an efficient way to do this? The best I can think of is creating a query such as: SELECT ... --complicated stuff WHERE ... --more stuff AND id IN (1, 2, 3, 9, 413, 4324, ..., 939393) That is, I construct a huge "IN" clause. Is this efficient? Is there a more efficient way of doing this, or is the only way to JOIN with the inital query that gets the IDs? If it helps, I'm using SQLObject to connect to a PostgreSQL database, and I have access to the cursor that executed the query to get all the IDs. UPDATE: I should mention that the more complicated queries all either rely on these IDs, or create more IDs to look up in the other queries. If I were to make one large query, I'd end up joining six tables at once or so, which might be too slow. A: One technique I've used in the past is to put the IDs into a temp table, and then use that to drive a sequence of queries. Something like: BEGIN; CREATE TEMP TABLE search_result ON COMMIT DROP AS SELECT entity_id FROM entity /* long complicated search joins and conditions ... */; -- Fetch primary entities SELECT entity_id, entity.x /*, ... */ FROM entity JOIN search_result USING (entity_id); -- Fetch some related entities SELECT entity_id, related_entity_id, related_entity.x /*, ... */ FROM related_entity JOIN search_result USING (entity_id); -- And more, as required END; This is particularly useful where the search result entities have multiple one-to-many relationships which you want to fetch without either a) doing N*M+1 selects or b) doing a cartesian join of related entities. A: I would think it might be useful to use a VIEW. Simple create a view with your query for ID's, then join to that view via ID. That will limit your results to the required subset of ID's without an expensive IN statement. I do know that the IN statement is more expensive then an EXISTS statement would be. A: I think the join with the criteria to select the id's will be more efficient because the query optimizer has more options to do the right thing. Use the explain plan to see how postgresql will approach it. A: You are almost certainly better off with a join, however, another option is to use a sub select, i.e. SELECT ... --complicated stuff WHERE ... --more stuff AND id IN (select distinct id from Foo where ...)
sql select from a large number of IDs
I have a table, Foo. I run a query on Foo to get the ids from a subset of Foo. I then want to run a more complicated set of queries, but only on those IDs. Is there an efficient way to do this? The best I can think of is creating a query such as: SELECT ... --complicated stuff WHERE ... --more stuff AND id IN (1, 2, 3, 9, 413, 4324, ..., 939393) That is, I construct a huge "IN" clause. Is this efficient? Is there a more efficient way of doing this, or is the only way to JOIN with the inital query that gets the IDs? If it helps, I'm using SQLObject to connect to a PostgreSQL database, and I have access to the cursor that executed the query to get all the IDs. UPDATE: I should mention that the more complicated queries all either rely on these IDs, or create more IDs to look up in the other queries. If I were to make one large query, I'd end up joining six tables at once or so, which might be too slow.
[ "One technique I've used in the past is to put the IDs into a temp table, and then use that to drive a sequence of queries. Something like:\nBEGIN;\nCREATE TEMP TABLE search_result ON COMMIT DROP AS\n SELECT entity_id\n FROM entity /* long complicated search joins and conditions ... */;\n-- Fetch primary entities\nSELECT entity_id, entity.x /*, ... */\nFROM entity JOIN search_result USING (entity_id);\n-- Fetch some related entities\nSELECT entity_id, related_entity_id, related_entity.x /*, ... */\nFROM related_entity JOIN search_result USING (entity_id);\n-- And more, as required\nEND;\n\nThis is particularly useful where the search result entities have multiple one-to-many relationships which you want to fetch without either a) doing N*M+1 selects or b) doing a cartesian join of related entities.\n", "I would think it might be useful to use a VIEW. Simple create a view with your query for ID's, then join to that view via ID. That will limit your results to the required subset of ID's without an expensive IN statement.\nI do know that the IN statement is more expensive then an EXISTS statement would be.\n", "I think the join with the criteria to select the id's will be more efficient because the query optimizer has more options to do the right thing. Use the explain plan to see how postgresql will approach it.\n", "You are almost certainly better off with a join, however, another option is to use a sub select, i.e.\nSELECT ... --complicated stuff\nWHERE ... --more stuff\n AND id IN (select distinct id from Foo where ...)\n\n" ]
[ 6, 1, 0, 0 ]
[]
[]
[ "postgresql", "python", "sql", "sqlobject" ]
stackoverflow_0003001786_postgresql_python_sql_sqlobject.txt
Q: what is the recommended way of running a embedded web server within a desktop app (say wsgi server with pyqt) The desktop app should start the web server on launch and should shut it down on close. Assuming that the desktop is the only client allowed to connect to the web server, what is the best way to write this? Both the web server and the desktop run in a blocking loop of their own. So, should I be using threads or multiprocessing? A: Use something like CherryPy or paste.httpserver. You can use wsgiref's server, and it generally works okay locally, but if you are doing Ajax the single-threaded nature of wsgiref can cause some odd results, or if you ever do a subrequest you'll get a race condition. But for most cases it'll be fine. It might be useful to you not to have an embedded threaded server (both CherryPy and paste.httpserver are threaded), in which case wsgiref would be helpful (all requests will run from the same thread). Note that if you use CherryPy or paste.httpserver all requests will automatically happen in subthreads (those packages do the thread spawning for you), and you probably will not be able to directly touch the GUI code from your web code (since GUI code usually doesn't like to be handled by threads). For any of them the server code blocks, so you need to spawn a thread to start the server in. Twisted can run in your normal GUI event loop, but unless that's important it adds a lot of complexity. Do not use BaseHTTPServer or SimpleHTTPServer, they are silly and complicated and in all cases where you might use then you should use wsgiref instead. Every single case, as wsgiref is has a sane API (WSGI) while these servers have silly APIs. A: Have a look at the BaseHTTPServer package, or better yet the SimpleHTTPServer. Pretty simple and easy to use. A: In Sauce RC, we use CherryPy. Since it's pure Python, it's very easy to embed it (as source on disk or in a zip file).
what is the recommended way of running a embedded web server within a desktop app (say wsgi server with pyqt)
The desktop app should start the web server on launch and should shut it down on close. Assuming that the desktop is the only client allowed to connect to the web server, what is the best way to write this? Both the web server and the desktop run in a blocking loop of their own. So, should I be using threads or multiprocessing?
[ "Use something like CherryPy or paste.httpserver. You can use wsgiref's server, and it generally works okay locally, but if you are doing Ajax the single-threaded nature of wsgiref can cause some odd results, or if you ever do a subrequest you'll get a race condition. But for most cases it'll be fine. It might be useful to you not to have an embedded threaded server (both CherryPy and paste.httpserver are threaded), in which case wsgiref would be helpful (all requests will run from the same thread). \nNote that if you use CherryPy or paste.httpserver all requests will automatically happen in subthreads (those packages do the thread spawning for you), and you probably will not be able to directly touch the GUI code from your web code (since GUI code usually doesn't like to be handled by threads). For any of them the server code blocks, so you need to spawn a thread to start the server in. Twisted can run in your normal GUI event loop, but unless that's important it adds a lot of complexity.\nDo not use BaseHTTPServer or SimpleHTTPServer, they are silly and complicated and in all cases where you might use then you should use wsgiref instead. Every single case, as wsgiref is has a sane API (WSGI) while these servers have silly APIs.\n", "Have a look at the BaseHTTPServer package, or better yet the SimpleHTTPServer. Pretty simple and easy to use.\n", "In Sauce RC, we use CherryPy. Since it's pure Python, it's very easy to embed it (as source on disk or in a zip file).\n" ]
[ 6, 2, 1 ]
[]
[]
[ "desktop", "pyqt", "python", "user_interface", "wsgi" ]
stackoverflow_0003001185_desktop_pyqt_python_user_interface_wsgi.txt
Q: Python: Access dictionary value inside of tuple and sort quickly by dict value I know that wasn't clear. Here's what I'm doing specifically. I have my list of dictionaries here: dict = [{int=0, value=A}, {int=1, value=B}, ... n] and I want to take them in combinations, so I used itertools and it gave me a tuple (Well, okay it gave me a memory object that I then used enumerate on so I could loop over it and enumerate gave ma tuple): for (index, tuple) in enumerate(combinations(dict, 2)): and this is where I have my problem. I want to identify which of the two items in the combination has the bigger 'int' value and which has the smaller value and assign them to variables (I'm actually using more than 2 in the combination so I can't just say if tuple[0]['int'] > tuple[1]['int'] and do the assignment because I'd have to list this out a bunch of times and that's hard to manage). I was going to assign each 'int' value to a variable, sort it in a list, index the 'int' value in the list by 1, 2, 3, 4, 5 ... etc., then go back and access the dictionary I wanted by the int value and then assign the dictionary to a variable so I knew which was bigger. But I have a big list and lists and variable assignments are resource intensive and this is taking a long time (I had only a little bit of that written and it was taking forever to run). So I was hoping someone knew a fast way to do this. I actually could list out every possible combination of assignmnets using the if/thens but it's just like 5 pages of if/thens and assignments and is hard to read and manage when I want to change it. You've probably gathered this, but I"m new at programming. thx A: for (index, tuple) in enumerate(combinations(dict, 2)): thesmall = min(tuple, key=lambda d: d['int']) thelarge = max(tuple, key=lambda d: d['int']) If you need more than just min and max, then inorder = sorted(tuple, key=lambda d: d['int']) and there you have all the dicts in order as required.
Python: Access dictionary value inside of tuple and sort quickly by dict value
I know that wasn't clear. Here's what I'm doing specifically. I have my list of dictionaries here: dict = [{int=0, value=A}, {int=1, value=B}, ... n] and I want to take them in combinations, so I used itertools and it gave me a tuple (Well, okay it gave me a memory object that I then used enumerate on so I could loop over it and enumerate gave ma tuple): for (index, tuple) in enumerate(combinations(dict, 2)): and this is where I have my problem. I want to identify which of the two items in the combination has the bigger 'int' value and which has the smaller value and assign them to variables (I'm actually using more than 2 in the combination so I can't just say if tuple[0]['int'] > tuple[1]['int'] and do the assignment because I'd have to list this out a bunch of times and that's hard to manage). I was going to assign each 'int' value to a variable, sort it in a list, index the 'int' value in the list by 1, 2, 3, 4, 5 ... etc., then go back and access the dictionary I wanted by the int value and then assign the dictionary to a variable so I knew which was bigger. But I have a big list and lists and variable assignments are resource intensive and this is taking a long time (I had only a little bit of that written and it was taking forever to run). So I was hoping someone knew a fast way to do this. I actually could list out every possible combination of assignmnets using the if/thens but it's just like 5 pages of if/thens and assignments and is hard to read and manage when I want to change it. You've probably gathered this, but I"m new at programming. thx
[ "for (index, tuple) in enumerate(combinations(dict, 2)):\n thesmall = min(tuple, key=lambda d: d['int'])\n thelarge = max(tuple, key=lambda d: d['int'])\n\nIf you need more than just min and max, then\n inorder = sorted(tuple, key=lambda d: d['int'])\n\nand there you have all the dicts in order as required.\n" ]
[ 2 ]
[]
[]
[ "dictionary", "python", "sorting", "tuples" ]
stackoverflow_0003003072_dictionary_python_sorting_tuples.txt
Q: sqlobject: No connection has been defined for this thread or process I'm using sqlobject in Python. I connect to the database with conn = connectionForURI(connStr) conn.makeConnection() This succeeds, and I can do queries on the connection: g_conn = conn.getConnection() cur = g_conn.cursor() cur.execute(query) res = cur.fetchall() This works as intended. However, I also defined some classes, e.g: class User(SQLObject): class sqlmeta: table = "gui_user" username = StringCol(length=16, alternateID=True) password = StringCol(length=16) balance = FloatCol(default=0) When I try to do a query using the class: User.selectBy(username="foo") I get an exception: ... File "c:\python25\lib\site-packages\SQLObject-0.12.4-py2.5.egg\sqlobject\main.py", line 1371, in selectBy conn = connection or cls._connection File "c:\python25\lib\site-packages\SQLObject-0.12.4-py2.5.egg\sqlobject\dbconnection.py", line 837, in __get__ return self.getConnection() File "c:\python25\lib\site-packages\SQLObject-0.12.4-py2.5.egg\sqlobject\dbconnection.py", line 850, in getConnection "No connection has been defined for this thread " AttributeError: No connection has been defined for this thread or process How do I define a connection for a thread? I just realized I can pass in a connection keyword which I can give conn to to make it work, but how do I get it to work if I weren't to do that? A: Do: from sqlobject import sqlhub, connectionForURI sqlhub.processConnection = connectionForURI(connStr)
sqlobject: No connection has been defined for this thread or process
I'm using sqlobject in Python. I connect to the database with conn = connectionForURI(connStr) conn.makeConnection() This succeeds, and I can do queries on the connection: g_conn = conn.getConnection() cur = g_conn.cursor() cur.execute(query) res = cur.fetchall() This works as intended. However, I also defined some classes, e.g: class User(SQLObject): class sqlmeta: table = "gui_user" username = StringCol(length=16, alternateID=True) password = StringCol(length=16) balance = FloatCol(default=0) When I try to do a query using the class: User.selectBy(username="foo") I get an exception: ... File "c:\python25\lib\site-packages\SQLObject-0.12.4-py2.5.egg\sqlobject\main.py", line 1371, in selectBy conn = connection or cls._connection File "c:\python25\lib\site-packages\SQLObject-0.12.4-py2.5.egg\sqlobject\dbconnection.py", line 837, in __get__ return self.getConnection() File "c:\python25\lib\site-packages\SQLObject-0.12.4-py2.5.egg\sqlobject\dbconnection.py", line 850, in getConnection "No connection has been defined for this thread " AttributeError: No connection has been defined for this thread or process How do I define a connection for a thread? I just realized I can pass in a connection keyword which I can give conn to to make it work, but how do I get it to work if I weren't to do that?
[ "Do:\nfrom sqlobject import sqlhub, connectionForURI\n\nsqlhub.processConnection = connectionForURI(connStr)\n\n" ]
[ 3 ]
[]
[]
[ "python", "sql", "sqlobject" ]
stackoverflow_0003000908_python_sql_sqlobject.txt
Q: averaging matrix efficiently in Python, given an n x p matrix, e.g. 4 x 4, how can I return a matrix that's 4 x 2 that simply averages the first two columns and the last two columns for all 4 rows of the matrix? e.g. given: a = array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) return a matrix that has the average of a[:, 0] and a[:, 1] and the average of a[:, 2] and a[:, 3]. I want this to work for an arbitrary matrix of n x p assuming that the number of columns I am averaging of n is obviously evenly divisible by n. let me clarify: for each row, I want to take the average of the first two columns, then the average of the last two columns. So it would be: 1 + 2 / 2, 3 + 4 / 2 <- row 1 of new matrix 5 + 6 / 2, 7 + 8 / 2 <- row 2 of new matrix, etc. which should yield a 4 by 2 matrix rather than 4 x 4. thanks. A: How about using some math? You can define a matrix M = [[0.5,0],[0.5,0],[0,0.5],[0,0.5]] so that A*M is what you want. from numpy import array, matrix A = array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) M = matrix([[0.5,0], [0.5,0], [0,0.5], [0,0.5]]) print A*M Generating M is pretty simple too, entries are 1/n or zero. A: reshape - get mean - reshape >>> a.reshape(-1, a.shape[1]//2).mean(1).reshape(a.shape[0],-1) array([[ 1.5, 3.5], [ 5.5, 7.5], [ 9.5, 11.5], [ 13.5, 15.5]]) is supposed to work for any array size, and reshape doesn't make a copy. A: It's a bit unclear what should happen for matrices with n > 4, but this code will do what you want: a = N.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], dtype=float) avg = N.vstack((N.average(a[:,0:2], axis=1), N.average(a[:,2:4], axis=1))).T This yields avg = array([[ 1.5, 3.5], [ 5.5, 7.5], [ 9.5, 11.5], [ 13.5, 15.5]]) A: Here's a way to do it. You only need to change groupsize to make it work with other sizes like you said, though I'm not fully sure what you want. groupsize = 2 out = np.hstack([np.mean(x,axis=1,out=np.zeros((a.shape[0],1))) for x in np.hsplit(a,groupsize)]) yields array([[ 1.5, 3.5], [ 5.5, 7.5], [ 9.5, 11.5], [ 13.5, 15.5]]) for out. Hopefully it gives you some ideas on how to do exactly what it is that you want to do. You can make groupsize dependent on the dimensions of a for instance.
averaging matrix efficiently
in Python, given an n x p matrix, e.g. 4 x 4, how can I return a matrix that's 4 x 2 that simply averages the first two columns and the last two columns for all 4 rows of the matrix? e.g. given: a = array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) return a matrix that has the average of a[:, 0] and a[:, 1] and the average of a[:, 2] and a[:, 3]. I want this to work for an arbitrary matrix of n x p assuming that the number of columns I am averaging of n is obviously evenly divisible by n. let me clarify: for each row, I want to take the average of the first two columns, then the average of the last two columns. So it would be: 1 + 2 / 2, 3 + 4 / 2 <- row 1 of new matrix 5 + 6 / 2, 7 + 8 / 2 <- row 2 of new matrix, etc. which should yield a 4 by 2 matrix rather than 4 x 4. thanks.
[ "How about using some math? You can define a matrix M = [[0.5,0],[0.5,0],[0,0.5],[0,0.5]] so that A*M is what you want.\nfrom numpy import array, matrix\n\nA = array([[1, 2, 3, 4], \n [5, 6, 7, 8], \n [9, 10, 11, 12], \n [13, 14, 15, 16]])\nM = matrix([[0.5,0],\n [0.5,0],\n [0,0.5],\n [0,0.5]])\nprint A*M\n\nGenerating M is pretty simple too, entries are 1/n or zero.\n", "reshape - get mean - reshape\n>>> a.reshape(-1, a.shape[1]//2).mean(1).reshape(a.shape[0],-1)\narray([[ 1.5, 3.5],\n [ 5.5, 7.5],\n [ 9.5, 11.5],\n [ 13.5, 15.5]])\n\nis supposed to work for any array size, and reshape doesn't make a copy.\n", "It's a bit unclear what should happen for matrices with n > 4, but this code will do what you want:\na = N.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], dtype=float)\navg = N.vstack((N.average(a[:,0:2], axis=1), N.average(a[:,2:4], axis=1))).T\n\nThis yields avg =\narray([[ 1.5, 3.5],\n [ 5.5, 7.5],\n [ 9.5, 11.5],\n [ 13.5, 15.5]])\n\n", "Here's a way to do it. You only need to change groupsize to make it work with other sizes like you said, though I'm not fully sure what you want.\ngroupsize = 2\nout = np.hstack([np.mean(x,axis=1,out=np.zeros((a.shape[0],1))) for x in np.hsplit(a,groupsize)])\n\nyields\narray([[ 1.5, 3.5],\n [ 5.5, 7.5],\n [ 9.5, 11.5],\n [ 13.5, 15.5]])\n\nfor out. Hopefully it gives you some ideas on how to do exactly what it is that you want to do. You can make groupsize dependent on the dimensions of a for instance.\n" ]
[ 5, 4, 1, 1 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0002978323_numpy_python_scipy.txt
Q: What is a more efficient way in Python to return list elements which are not in a second list? Is there a faster way to do this in python? [f for f in list_1 if not f in list_2] list_1 and list_2 both consist of about 120.000 strings. It takes about 4 minutes to generate the new list. A: If you put list_2 into a set, it should make the containment checking a lot quicker: s = set(list_2) [f for f in list_1 if not f in s] This is because x in list is an O(n) check, while x in set is constant-time. Another way is to use set-difference: list(set(list_1).difference(set(list_2))) However, this probably won't be faster than the first way - also, it'll eliminate duplicates from list_1 which you may not want. A: Depending on what you want to do with the new list, it might be sufficient if you do some kind of lazy evaluation with itertools.ifilter() (so you don't spent time, building the new list beforehand, but you should transform list_2 to a set before in any case, so lookup is O(1)): import itertools: set_2 = set(list_2) for f in itertools.ifilter(lambda x: x not in set_2, list_1): # do something with f
What is a more efficient way in Python to return list elements which are not in a second list?
Is there a faster way to do this in python? [f for f in list_1 if not f in list_2] list_1 and list_2 both consist of about 120.000 strings. It takes about 4 minutes to generate the new list.
[ "If you put list_2 into a set, it should make the containment checking a lot quicker:\ns = set(list_2)\n[f for f in list_1 if not f in s]\n\nThis is because x in list is an O(n) check, while x in set is constant-time. \nAnother way is to use set-difference:\nlist(set(list_1).difference(set(list_2)))\n\nHowever, this probably won't be faster than the first way - also, it'll eliminate duplicates from list_1 which you may not want. \n", "Depending on what you want to do with the new list, it might be sufficient if you do some kind of lazy evaluation with itertools.ifilter() (so you don't spent time, building the new list beforehand, but you should transform list_2 to a set before in any case, so lookup is O(1)):\nimport itertools:\nset_2 = set(list_2)\n\nfor f in itertools.ifilter(lambda x: x not in set_2, list_1):\n # do something with f\n\n" ]
[ 9, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003003390_python.txt
Q: Specifying custom URL schema in appengine using app.yaml? I am trying to have a custom URL which looks like this: example.com/site/yahoo.com which would hit this script like this= example.com/details?domain=yahoo.com can this be done using app.yaml? the basic idea is to call "details" with the input "yahoo.com" A: You can't really rewrite the URLs per se, but you can use regular expression groups to perform a similar kind of thing. In your app.yaml file, try something like: handlers: - url: /site/(.+) script: site.py And in your site.py: SiteHandler(webapp.RequestHandler): def get(self, site): # the site parameter will be what was passed in the URL! pass def main(): application = webapp.WSGIApplication([('/site/(.+)', SiteHandler)], debug=True) util.run_wsgi_app(application) What happens is, whatever you have after /site/ in the request URL will be passed to SiteHandler's get() method in the site parameter. From there you can do whatever it is you wanted to do at /details?domain=yahoo.com, or simply redirect to that URL.
Specifying custom URL schema in appengine using app.yaml?
I am trying to have a custom URL which looks like this: example.com/site/yahoo.com which would hit this script like this= example.com/details?domain=yahoo.com can this be done using app.yaml? the basic idea is to call "details" with the input "yahoo.com"
[ "You can't really rewrite the URLs per se, but you can use regular expression groups to perform a similar kind of thing.\nIn your app.yaml file, try something like:\nhandlers:\n- url: /site/(.+)\n script: site.py\n\nAnd in your site.py:\nSiteHandler(webapp.RequestHandler):\n def get(self, site):\n # the site parameter will be what was passed in the URL!\n pass\n\ndef main():\n application = webapp.WSGIApplication([('/site/(.+)', SiteHandler)], debug=True)\n util.run_wsgi_app(application)\n\nWhat happens is, whatever you have after /site/ in the request URL will be passed to SiteHandler's get() method in the site parameter. From there you can do whatever it is you wanted to do at /details?domain=yahoo.com, or simply redirect to that URL.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python", "rewrite" ]
stackoverflow_0003003624_google_app_engine_python_rewrite.txt
Q: facing problem when trying to send an email using python I wrote the code like this import smtplib server=smtplib.SMTP('localhost') Then it raised an error like error: [Errno 10061] No connection could be made because the target machine actively refused it I am new to SMTP, can you tell what exactly the problem is? A: It sounds like SMTP is not set up on the computer you are trying this from. Try using your ISP's mail server (often something like mail.example.com) or make sure you have an SMTP server installed locally. A: Rather than trying to install smtp library locally, you can setup a simple smtp server on a console. Do this: python -m smtpd -n -c DebuggingServer localhost:1025 And all mails will be printed to the console. A: To send e-mail using the Python SMTP module you need to somehow obtain the name of a valid mail exchanger (MX). That's either a local hub or smart relay of your own or you can query DNS for the public MX records for each target host/domain name. This requirement is glossed over in the docs. It's a horrible omission in Python's standard libraries is that they don't provide an easy way to query DNS for an MX record. (There are rather nice third party Python DNS libraries such as DNSPython and PyDNS with extensive support for way more DNS than you need for anything related to e-mail). In general you're probably better off using a list of hubs or relays from your own network (or ISP). This is because your efforts to send mail directly to the published MX hosts may otherwise run afoul of various attempts to fight spam. (For example it frequently won't be possible from wireless networks in coffee shops, hotels, and across common household cable and DSL connections; most of those address ranges are listed in various databases as potential sorts of spam). In that case you could store and/or retrieve the names/address of your local mail hubs (or smart relays) through any means you like. It could be a .cfg file (ConfigParser), or through an LDAP or SQL query or even (gasp!) hard-coded into your scripts. If, however, your code is intended to run on a suitable network (for example in a colo, or a data center) then you'll have to do your own MX resolution. You could install one of the aforementioned PyPI packages. If you need to limit yourself to the standard libraries then you might be able to rely on the commonly available dig utility that's included with most installations of Linux, MacOS X, Solaris, FreeBSD and other fine operating systems. In that case you'd call a command like dig +short aol.com mx | awk '{print $NF}' through subprocess.Popen() which can be done with this rather ugly one-liner: mxers = subprocess.Popen("dig +short %s mx | awk '{print $NF}'" % target_domain, stdout=subprocess.PIPE, shell=True).communicate()[0].split() Then you can attempt to make an SMTP connection to each of the resulting hostnames in turn. (This is fine so long as your "target_domain" value is adequately sanitized; don't pass untrusted data through Popen() with shell=True). The safer version looks even hairier: mxers = subprocess.Popen(["dig", "+short", target_domain, "mx"], stdout=subprocess.PIPE).communicate()[0].split()[1::2] ... where the slice/stride at the end is replacing the call to awk and thus obviating the need for shell=True
facing problem when trying to send an email using python
I wrote the code like this import smtplib server=smtplib.SMTP('localhost') Then it raised an error like error: [Errno 10061] No connection could be made because the target machine actively refused it I am new to SMTP, can you tell what exactly the problem is?
[ "It sounds like SMTP is not set up on the computer you are trying this from. Try using your ISP's mail server (often something like mail.example.com) or make sure you have an SMTP server installed locally.\n", "Rather than trying to install smtp library locally, you can setup a simple smtp server on a console.\nDo this:\npython -m smtpd -n -c DebuggingServer localhost:1025\n\nAnd all mails will be printed to the console.\n", "To send e-mail using the Python SMTP module you need to somehow obtain the name of a valid mail exchanger (MX). That's either a local hub or smart relay of your own or you can query DNS for the public MX records for each target host/domain name.\nThis requirement is glossed over in the docs. It's a horrible omission in Python's standard libraries is that they don't provide an easy way to query DNS for an MX record. (There are rather nice third party Python DNS libraries such as DNSPython and PyDNS with extensive support for way more DNS than you need for anything related to e-mail).\nIn general you're probably better off using a list of hubs or relays from your own network (or ISP). This is because your efforts to send mail directly to the published MX hosts may otherwise run afoul of various attempts to fight spam. (For example it frequently won't be possible from wireless networks in coffee shops, hotels, and across common household cable and DSL connections; most of those address ranges are listed in various databases as potential sorts of spam). In that case you could store and/or retrieve the names/address of your local mail hubs (or smart relays) through any means you like. It could be a .cfg file (ConfigParser), or through an LDAP or SQL query or even (gasp!) hard-coded into your scripts.\nIf, however, your code is intended to run on a suitable network (for example in a colo, or a data center) then you'll have to do your own MX resolution. You could install one of the aforementioned PyPI packages. If you need to limit yourself to the standard libraries then you might be able to rely on the commonly available dig utility that's included with most installations of Linux, MacOS X, Solaris, FreeBSD and other fine operating systems.\nIn that case you'd call a command like dig +short aol.com mx | awk '{print $NF}' through subprocess.Popen() which can be done with this rather ugly one-liner:\nmxers = subprocess.Popen(\"dig +short %s mx | awk '{print $NF}'\"\n % target_domain, stdout=subprocess.PIPE,\n shell=True).communicate()[0].split()\n\nThen you can attempt to make an SMTP connection to each of the resulting hostnames in\nturn. (This is fine so long as your \"target_domain\" value is adequately sanitized; don't pass untrusted data through Popen() with shell=True).\nThe safer version looks even hairier:\nmxers = subprocess.Popen([\"dig\", \"+short\", target_domain, \"mx\"], \n stdout=subprocess.PIPE).communicate()[0].split()[1::2]\n\n... where the slice/stride at the end is replacing the call to awk and thus obviating\nthe need for shell=True\n" ]
[ 2, 2, 0 ]
[]
[]
[ "python", "smtp" ]
stackoverflow_0003004006_python_smtp.txt
Q: How to get progress bar to time Class exectution I am trying to use progress bar to show the progress of a script. I want it increase progress after every function in a class is executed. The code I have tried is below: import progressbar from time import sleep class hello(): def no(self): print 'hello!' def yes(self): print 'No!!!!!!' def pro(): bar = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()]) for i in Yep(): bar.update(Yep.i()) sleep(0.1) bar.finish() if __name__ == "__main__": Yep = hello() pro() Does anyone know how to get this working. Thanks A: does this do what you want ? import progressbar from time import sleep class hello(): def no(self): print 'hello!' def yes(self): print 'No!!!!!!' def __call__(self) : methods = [self.no, self.yes] return [ (x[0]*100/len(methods), x[1]) for x in enumerate(methods) ] def pro(): bar = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()]) for percent, method in Yep(): bar.update(percent) method() sleep(0.1) bar.finish() if __name__ == "__main__": Yep = hello() pro() Possible improvement : discover the methods to call by their name (for example prefix them with progress_)
How to get progress bar to time Class exectution
I am trying to use progress bar to show the progress of a script. I want it increase progress after every function in a class is executed. The code I have tried is below: import progressbar from time import sleep class hello(): def no(self): print 'hello!' def yes(self): print 'No!!!!!!' def pro(): bar = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()]) for i in Yep(): bar.update(Yep.i()) sleep(0.1) bar.finish() if __name__ == "__main__": Yep = hello() pro() Does anyone know how to get this working. Thanks
[ "does this do what you want ?\nimport progressbar\nfrom time import sleep\n\nclass hello():\n def no(self):\n print 'hello!'\n\n def yes(self):\n print 'No!!!!!!'\n\n def __call__(self) :\n methods = [self.no, self.yes]\n return [ (x[0]*100/len(methods), x[1]) for x in enumerate(methods) ]\n\ndef pro():\n bar = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])\n\n for percent, method in Yep():\n bar.update(percent)\n method()\n sleep(0.1)\n bar.finish()\n\nif __name__ == \"__main__\":\n Yep = hello()\n pro()\n\nPossible improvement : discover the methods to call by their name (for example prefix them with progress_)\n" ]
[ 2 ]
[]
[]
[ "class", "progress_bar", "python" ]
stackoverflow_0003004533_class_progress_bar_python.txt
Q: KindError: Property r must be an instance of SecondModel, why? class FirstModel(db.Model): p = db.StringProperty() r=db.ReferenceProperty(SecondModel) class SecondModel(db.Model): r = db.ReferenceProperty(FirstModel) class sss(webapp.RequestHandler): def get(self): a=FirstModel() a.p='sss' a.put() b=SecondModel() b.r=a b.put() a.r=b a.put() self.response.out.write(str(b.r.p)) the error is : Traceback (most recent call last): File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__ handler.get(*groups) File "D:\zjm_code\helloworld\a.py", line 158, in get a.r=b File "D:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 3009, in __set__ value = self.validate(value) File "D:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 3048, in validate (self.name, self.reference_class.kind())) KindError: Property r must be an instance of SecondModel thanks A: The code you show shouldn't even compile - you can't instantiate a reference property with a class that isn't yet defined - unless you have another definition of SecondModel somewhere that you haven't included, in which case the issue is that FirstModel has a reference to the original SecondModel, but you're passing it an instance of the new one you overwrote that one with. A: it is ok now : class SecondModel(db.Model): pass class FirstModel(db.Model): p = db.StringProperty(choices=set(["aa", "bb", "cc"])) r=db.ReferenceProperty(SecondModel) class SecondModel(db.Model): r = db.ReferenceProperty(FirstModel) s=db.StringProperty() class sss(webapp.RequestHandler): def get(self): #''' a=FirstModel() a.p='cc' a.put() b=SecondModel() b.r=a b.s='kkk' b.put() a.r=b.key() a.put() #''' #a=FirstModel.all().filter('p =','cc').get() #b=a.r #self.response.out.write(a.secondmodel_set.filter('r = ', a).get().s) self.response.out.write(b.r.p+'<br/>'+a.r.s)
KindError: Property r must be an instance of SecondModel, why?
class FirstModel(db.Model): p = db.StringProperty() r=db.ReferenceProperty(SecondModel) class SecondModel(db.Model): r = db.ReferenceProperty(FirstModel) class sss(webapp.RequestHandler): def get(self): a=FirstModel() a.p='sss' a.put() b=SecondModel() b.r=a b.put() a.r=b a.put() self.response.out.write(str(b.r.p)) the error is : Traceback (most recent call last): File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__ handler.get(*groups) File "D:\zjm_code\helloworld\a.py", line 158, in get a.r=b File "D:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 3009, in __set__ value = self.validate(value) File "D:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 3048, in validate (self.name, self.reference_class.kind())) KindError: Property r must be an instance of SecondModel thanks
[ "The code you show shouldn't even compile - you can't instantiate a reference property with a class that isn't yet defined - unless you have another definition of SecondModel somewhere that you haven't included, in which case the issue is that FirstModel has a reference to the original SecondModel, but you're passing it an instance of the new one you overwrote that one with.\n", "it is ok now :\nclass SecondModel(db.Model):\n pass\n\nclass FirstModel(db.Model):\n p = db.StringProperty(choices=set([\"aa\", \"bb\", \"cc\"]))\n r=db.ReferenceProperty(SecondModel)\n\nclass SecondModel(db.Model):\n r = db.ReferenceProperty(FirstModel)\n s=db.StringProperty()\n\nclass sss(webapp.RequestHandler):\n def get(self):\n #'''\n a=FirstModel()\n a.p='cc'\n a.put()\n b=SecondModel()\n b.r=a\n b.s='kkk'\n b.put()\n\n a.r=b.key()\n a.put()\n #'''\n #a=FirstModel.all().filter('p =','cc').get()\n #b=a.r\n #self.response.out.write(a.secondmodel_set.filter('r = ', a).get().s)\n self.response.out.write(b.r.p+'<br/>'+a.r.s)\n\n" ]
[ 0, -2 ]
[]
[]
[ "google_app_engine", "model", "properties", "python" ]
stackoverflow_0003003845_google_app_engine_model_properties_python.txt
Q: Encrypt and Decrypt information in a cookie I need to securely crypt and decrypt information about users ( name, surname and user_id ) in cookies. What is the best way to do this ? What encryption and decryption function do I need ? Thanks ^_^ A: It's generally a bad idea: an attacker can do chosen-text dictionary attacks if they can guess what you might be putting in the cookie, which is quite likely, and securing a universal key is harder than looking after a database containing confidential information, because there is not much in the way of an audit trail for these kind of client-side web-based attacks. If the cost of a security breach is low, then maybe you want to do this anyway. Just use a symmetric-key encryption algorithm. A: Take a look here: http://www.example-code.com/python/encryption.asp I would suggest DES or Blowfish
Encrypt and Decrypt information in a cookie
I need to securely crypt and decrypt information about users ( name, surname and user_id ) in cookies. What is the best way to do this ? What encryption and decryption function do I need ? Thanks ^_^
[ "It's generally a bad idea: an attacker can do chosen-text dictionary attacks if they can guess what you might be putting in the cookie, which is quite likely, and securing a universal key is harder than looking after a database containing confidential information, because there is not much in the way of an audit trail for these kind of client-side web-based attacks.\nIf the cost of a security breach is low, then maybe you want to do this anyway. Just use a symmetric-key encryption algorithm.\n", "Take a look here: http://www.example-code.com/python/encryption.asp\nI would suggest DES or Blowfish\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003004551_django_python.txt
Q: Django admin urls return INVALID REQUEST! - Django my admin urls are sat behind a prefix by doing the following. 1# (r'^admin/', include(admin.site.urls)), is placed within urls_core.py 2# (r'^api/', include('project.urls_core')), is palced within urls.py All admin URLs work fine except app indexes. If I go to any URL such as: /api/admin/core/ /api/admin/registration/ /api/admin/users/ /api/admin/filters/ I receive 'INVALID REQUEST' as my response. Status code is 200 (OK) though. I have never received this error message before. Does anyone have a clue? Thanks guys! A: I think some middleware, that strips the leading api/ from the url should help you: import re class URLPrefixMiddleware: def process_request(self, request): request.path = re.sub('^api/','',request.path) You shouldn't need your additional URL configuration then anymore. Put it in middleware.py in some app dir and add it to installed middleware!
Django admin urls return INVALID REQUEST! - Django
my admin urls are sat behind a prefix by doing the following. 1# (r'^admin/', include(admin.site.urls)), is placed within urls_core.py 2# (r'^api/', include('project.urls_core')), is palced within urls.py All admin URLs work fine except app indexes. If I go to any URL such as: /api/admin/core/ /api/admin/registration/ /api/admin/users/ /api/admin/filters/ I receive 'INVALID REQUEST' as my response. Status code is 200 (OK) though. I have never received this error message before. Does anyone have a clue? Thanks guys!
[ "I think some middleware, that strips the leading api/ from the url should help you:\nimport re\n\nclass URLPrefixMiddleware:\n def process_request(self, request):\n request.path = re.sub('^api/','',request.path)\n\nYou shouldn't need your additional URL configuration then anymore. Put it in middleware.py in some app dir and add it to installed middleware!\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003004736_django_django_admin_python.txt
Q: ANT doesn't get exit code return by a python script I'm currently using ant for building my java project on a Windows XP machine. I have different tasks defined in the build.xml and one of this is the exec of a Python script for analyzing the application output. I would like to make ANT failing when a particolar tag is discovered by script. I'm trying using: sys.exit(1) or os.system("EXIT 1") the second one in particular execute the console command EXIT which successfully make the building process failing if executed inside a bath file.Unfortunately ant is not able to reveal the exit code from inside the launched script and goes on normally till the end showing a BUILD SUCCESSFUL message. the script is called in this way: <exec dir="${path}/scripts" executable="python"> <arg line='log_analysis.py results.log" ' /> </exec> thanks for your help A: Try this: <exec dir="${path}/scripts" executable="python" failonerror="true"> <arg line="log_analysis.py results.log" /> </exec> Ant does not stop the build process if the command exits with a return code signaling failure by default; you have to set failonerror="true" to do that.
ANT doesn't get exit code return by a python script
I'm currently using ant for building my java project on a Windows XP machine. I have different tasks defined in the build.xml and one of this is the exec of a Python script for analyzing the application output. I would like to make ANT failing when a particolar tag is discovered by script. I'm trying using: sys.exit(1) or os.system("EXIT 1") the second one in particular execute the console command EXIT which successfully make the building process failing if executed inside a bath file.Unfortunately ant is not able to reveal the exit code from inside the launched script and goes on normally till the end showing a BUILD SUCCESSFUL message. the script is called in this way: <exec dir="${path}/scripts" executable="python"> <arg line='log_analysis.py results.log" ' /> </exec> thanks for your help
[ "Try this:\n<exec dir=\"${path}/scripts\" executable=\"python\" failonerror=\"true\">\n <arg line=\"log_analysis.py results.log\" />\n</exec>\n\nAnt does not stop the build process if the command exits with a return code signaling failure by default; you have to set failonerror=\"true\" to do that.\n" ]
[ 17 ]
[]
[]
[ "ant", "build", "python", "scripting" ]
stackoverflow_0003004057_ant_build_python_scripting.txt
Q: Is there a way to set a fixed width for the characters in HTML? Is there a way to set a fix size for the characters in HTML? That means, say … First row, 8th character is “Z” Second row’s 8th character is “A” I want to print out , when printed the “Z” has to be exactly on top of “A” *Note: I'm using the insertHtml method in QTextEdit() A: What you're asking for is called a fixed-width font. As James Hopkin remarked, HTML text in <tt> or <pre> tags is rendered with a fixed-width font. However, what you describe sounds like a table. HTML has direct support for that, with <table>, <tr> (row) and <td> (data/cell). Don't bother with fixed-width fonts; just put your A and the Z in the second <td> of their rows. A: Put the text in <tt> tags (or <pre> around a whole paragraph of text).
Is there a way to set a fixed width for the characters in HTML?
Is there a way to set a fix size for the characters in HTML? That means, say … First row, 8th character is “Z” Second row’s 8th character is “A” I want to print out , when printed the “Z” has to be exactly on top of “A” *Note: I'm using the insertHtml method in QTextEdit()
[ "What you're asking for is called a fixed-width font. As James Hopkin remarked, HTML text in <tt> or <pre> tags is rendered with a fixed-width font. \nHowever, what you describe sounds like a table. HTML has direct support for that, with <table>, <tr> (row) and <td> (data/cell). Don't bother with fixed-width fonts; just put your A and the Z in the second <td> of their rows.\n", "Put the text in <tt> tags (or <pre> around a whole paragraph of text).\n" ]
[ 3, 0 ]
[]
[]
[ "pyqt4", "python", "qtextedit" ]
stackoverflow_0003005063_pyqt4_python_qtextedit.txt
Q: encrypting passwords in a python conf file on a windows platform I have a script running on a remote machine. db info is stored in a configuration file. I want to be able to encrypt the password in the conf text so that no one can just read the file and gain access to the database. This is my current set up: My conf file sensitive info is encoded with base64 module. The main script then decodes the info. I have compiled the script using py2exe to make it a bit harder to see the code. My question is: Is there a better way of doing this? I know that base64 is not a very safe way of encrypting. Is there a way to encode using a key? I also know that py2exe can be reversed engineered very easily and the key could be found. Any other thoughts? I am also running this script on a windows machine, so any modules that are suggested should be able to run in a windows environment with ease. I know there are several other posts on this topic but I have not found one with a windows solution, or at least one that is will explained. A: If you want to be able to get back the password (instead you should hash it), you could always salt it for extra measures. But that wouldn't be much help if the user can get the salt out of the executable. Really the best way would be to not let them access the database at all. Use a web service or a server on your DB machine. A: Honestly I would use some other back-end. AxCrypt has command line switches. You can then easily write a wrapper in Python (if you don't want to use AxCrypt itself). Of course if you want a fairly simple way that may be more secure if applied properly, you can use XOR encryption - it's really easy to do such a thing with Python. Just make sure to take into account the weaknesses and strengths. But if you're confident enough that you can make a secure(??) key, it might work for you. However, the AxCrypt solution is probably just as easy and likely to be stronger. Just keep in mind that nothing is really unbreakable, it's really a question of how long it will take them to break it.
encrypting passwords in a python conf file on a windows platform
I have a script running on a remote machine. db info is stored in a configuration file. I want to be able to encrypt the password in the conf text so that no one can just read the file and gain access to the database. This is my current set up: My conf file sensitive info is encoded with base64 module. The main script then decodes the info. I have compiled the script using py2exe to make it a bit harder to see the code. My question is: Is there a better way of doing this? I know that base64 is not a very safe way of encrypting. Is there a way to encode using a key? I also know that py2exe can be reversed engineered very easily and the key could be found. Any other thoughts? I am also running this script on a windows machine, so any modules that are suggested should be able to run in a windows environment with ease. I know there are several other posts on this topic but I have not found one with a windows solution, or at least one that is will explained.
[ "If you want to be able to get back the password (instead you should hash it), you could always salt it for extra measures. But that wouldn't be much help if the user can get the salt out of the executable. \nReally the best way would be to not let them access the database at all. Use a web service or a server on your DB machine.\n", "Honestly I would use some other back-end. AxCrypt has command line switches. You can then easily write a wrapper in Python (if you don't want to use AxCrypt itself).\nOf course if you want a fairly simple way that may be more secure if applied properly, you can use XOR encryption - it's really easy to do such a thing with Python. Just make sure to take into account the weaknesses and strengths. But if you're confident enough that you can make a secure(??) key, it might work for you.\nHowever, the AxCrypt solution is probably just as easy and likely to be stronger. Just keep in mind that nothing is really unbreakable, it's really a question of how long it will take them to break it.\n" ]
[ 0, 0 ]
[]
[]
[ "encryption", "passwords", "python", "windows" ]
stackoverflow_0003005632_encryption_passwords_python_windows.txt
Q: Problem with TCP server in Twisted I'm trying to make a simple TCP server using Twisted ,which can do some interaction between diffirent client connections.The main code is as below: #!/usr/bin/env python from twisted.internet import protocol, reactor from time import ctime #global variables PORT = 22334 connlist = {} #store all the connections ids = {} #map the from-to relationships class TSServerProtocol(protocol.Protocol): def dataReceived(self, data): from_id,to_id = data.split('|') #get the IDs from standard client input,which looks like "from_id|to_id" if self.haveConn(from_id): #try to store new connections' informations pass else: self.setConn(from_id) self.setIds(from_id,to_id) if to_id in self.csids.keys(): self.connlist[to_id].transport.write(\ "you get a message now!from %s \n" % from_id) #if the to_id target found,push him a message.doesn't work as expected def setConn(self,sid): connlist[sid] = self #some other functions factory = protocol.Factory() factory.protocol = TSServerProtocol print 'waiting from connetction...' reactor.listenTCP(PORT, factory) reactor.run() As the comments mentioned,if a new client connection comes,I'll store its connection handle in a global varaible connlist which is like connlist = {a_from_id:a_conObj,b_from_id:b_conObj,....} and also parse the input then map its from-to information in ids.Then I check whether there's a key in the ids matches current "to_id".if does,get the connection handle using connlist[to_id] and push a message to the target connection.But it doesn't work.The message only shows in a same connection.Hope someone can show me some directions about this. Thanks! A: Each time a TCP connection is made, Twisted will create a unique instance of TSServerProtocol to handle that connection. So, you'll only ever see 1 connection in TSServerProtocol. Normally, this is what you want but Factories can be extended to do the connection tracking you're attempting to do here. Specifically, you can subclass Factory and override the buildProtocol() method to track instances of TSServerProtocol. The interrelationship between all the classes in Twisted takes a little time to learn and get used to. In particular, this piece of the standard Twisted documentation should be your best friend for the next while ;-)
Problem with TCP server in Twisted
I'm trying to make a simple TCP server using Twisted ,which can do some interaction between diffirent client connections.The main code is as below: #!/usr/bin/env python from twisted.internet import protocol, reactor from time import ctime #global variables PORT = 22334 connlist = {} #store all the connections ids = {} #map the from-to relationships class TSServerProtocol(protocol.Protocol): def dataReceived(self, data): from_id,to_id = data.split('|') #get the IDs from standard client input,which looks like "from_id|to_id" if self.haveConn(from_id): #try to store new connections' informations pass else: self.setConn(from_id) self.setIds(from_id,to_id) if to_id in self.csids.keys(): self.connlist[to_id].transport.write(\ "you get a message now!from %s \n" % from_id) #if the to_id target found,push him a message.doesn't work as expected def setConn(self,sid): connlist[sid] = self #some other functions factory = protocol.Factory() factory.protocol = TSServerProtocol print 'waiting from connetction...' reactor.listenTCP(PORT, factory) reactor.run() As the comments mentioned,if a new client connection comes,I'll store its connection handle in a global varaible connlist which is like connlist = {a_from_id:a_conObj,b_from_id:b_conObj,....} and also parse the input then map its from-to information in ids.Then I check whether there's a key in the ids matches current "to_id".if does,get the connection handle using connlist[to_id] and push a message to the target connection.But it doesn't work.The message only shows in a same connection.Hope someone can show me some directions about this. Thanks!
[ "Each time a TCP connection is made, Twisted will create a unique instance of TSServerProtocol to handle that connection. So, you'll only ever see 1 connection in TSServerProtocol. Normally, this is what you want but Factories can be extended to do the connection tracking you're attempting to do here. Specifically, you can subclass Factory and override the buildProtocol() method to track instances of TSServerProtocol. The interrelationship between all the classes in Twisted takes a little time to learn and get used to. In particular, this piece of the standard Twisted documentation should be your best friend for the next while ;-) \n" ]
[ 3 ]
[]
[]
[ "python", "tcp", "twisted" ]
stackoverflow_0003004227_python_tcp_twisted.txt
Q: Are there any builds of Unladen Swallow available? I realise there aren't any official ones, but I was hoping I could grab an unofficial one from somewhere? I'm running 32-bit Windows XP on x86 hardware (Core 2 Duo). A: For the time being, there are no official Windows binaries, so you have to build them on your own. Download a release from here, and the instructions for building are here: BuildingOnWindows. A quick Google search suggests that there aren't any others who've followed this procedure and published the results.
Are there any builds of Unladen Swallow available?
I realise there aren't any official ones, but I was hoping I could grab an unofficial one from somewhere? I'm running 32-bit Windows XP on x86 hardware (Core 2 Duo).
[ "For the time being, there are no official Windows binaries, so you have to build them on your own.\nDownload a release from here, and the instructions for building are here: BuildingOnWindows.\nA quick Google search suggests that there aren't any others who've followed this procedure and published the results.\n" ]
[ 1 ]
[]
[]
[ "python", "unladen_swallow" ]
stackoverflow_0002818899_python_unladen_swallow.txt
Q: Correct way to protect a private API Key when versioning a python application on a public git repo I would like to open-source a python project on Github but it contains an API key that should not be distributed. I guess there's something better than removing the key each time a "push" is committed to the repo. Imagine a simplified foomodule.py : import urllib2 API_KEY = 'XXXXXXXXX' urllib2.urlopen("http://example.com/foo?id=123%s" % API_KEY ).read() What i'm thinking is: Move the API_KEY in a second key.py module importing it on foomodule.py; i would then add key.py on .gitignore file. Same as 1. but using ConfigParser Do you know any good programmatic way to handle this scenario? A: One way would be to make it an explicit part of the interface. Make it an argument for your object constructors, for example. Or require the client to extend your class and provide a method, returning the key. It sucks when one needs to edit your module before she can use it. A: have a versioned template key_template.py: domain = 'example.com' API_KEY = Check it out to local machine, fill sensitive fields (such as API_KEY) and save as key.py. Ignore key.py in your version-control software. It really doesn't matter if you keep it in Python files or use ConfigParser. Automatic way might be to auto-merge on update with the existing key.py file.
Correct way to protect a private API Key when versioning a python application on a public git repo
I would like to open-source a python project on Github but it contains an API key that should not be distributed. I guess there's something better than removing the key each time a "push" is committed to the repo. Imagine a simplified foomodule.py : import urllib2 API_KEY = 'XXXXXXXXX' urllib2.urlopen("http://example.com/foo?id=123%s" % API_KEY ).read() What i'm thinking is: Move the API_KEY in a second key.py module importing it on foomodule.py; i would then add key.py on .gitignore file. Same as 1. but using ConfigParser Do you know any good programmatic way to handle this scenario?
[ "One way would be to make it an explicit part of the interface. Make it an argument for your object constructors, for example. Or require the client to extend your class and provide a method, returning the key.\nIt sucks when one needs to edit your module before she can use it.\n", "have a versioned template key_template.py:\ndomain = 'example.com'\nAPI_KEY = \n\nCheck it out to local machine, fill sensitive fields (such as API_KEY) and save as key.py. Ignore key.py in your version-control software. It really doesn't matter if you keep it in Python files or use ConfigParser.\nAutomatic way might be to auto-merge on update with the existing key.py file.\n" ]
[ 1, 1 ]
[]
[]
[ "configuration", "python", "version_control" ]
stackoverflow_0003006132_configuration_python_version_control.txt
Q: Django message doesn't expire My code in the view: from django.contrib import messages messages.add_message(request, messages.INFO, 'Hello world.') I don't want to show this code to the user the second time if he/she refreshes again. How do I go about doing that? Messages don't seem to have any sort of expiry setting. There is documentation here: http://docs.djangoproject.com/en/1.2/ref/contrib/messages/#expiration-of-messages A: Messages are cleared as soon as you iterate messages (which should be available from RequestContext). So step one is making sure you're displaying messages! If you want to hold-off on displaying messages for a certain page, you'll perhaps want to investigate punching things into session but it's getting a bit messy for my liking. I can't think of any good reasons to delay the message for the next pageload. If you are displaying them and your messages are hanging on longer than you expect, perhaps you're re-adding them after they're being displayed. Try putting timestamps into your messages and you'll see if when they were written.
Django message doesn't expire
My code in the view: from django.contrib import messages messages.add_message(request, messages.INFO, 'Hello world.') I don't want to show this code to the user the second time if he/she refreshes again. How do I go about doing that? Messages don't seem to have any sort of expiry setting. There is documentation here: http://docs.djangoproject.com/en/1.2/ref/contrib/messages/#expiration-of-messages
[ "Messages are cleared as soon as you iterate messages (which should be available from RequestContext).\nSo step one is making sure you're displaying messages! If you want to hold-off on displaying messages for a certain page, you'll perhaps want to investigate punching things into session but it's getting a bit messy for my liking. I can't think of any good reasons to delay the message for the next pageload.\nIf you are displaying them and your messages are hanging on longer than you expect, perhaps you're re-adding them after they're being displayed. Try putting timestamps into your messages and you'll see if when they were written.\n" ]
[ 5 ]
[]
[]
[ "django", "frameworks", "messages", "python", "session" ]
stackoverflow_0003006041_django_frameworks_messages_python_session.txt
Q: Random Loss of precision in Python ReadLine() We have a process which takes a very large csv (1.6GB) and breaks it down into pieces (in this case 3). This runs nightly and normally doesn't give us any problems. When it ran last night, however, the first of the output files had lost precision on the numeric fields in the data. The active ingredient in the script are the lines: while lineCounter <= chunk: oOutFile.write(oInFile.readline()) lineCounter = lineCounter + 1 and the normal output might be something like StringField1; StringField2; StringField3; StringField4; 1000000; StringField5; 0.000054454 etc. On this one occasion and in this one output file the numeric fields were all output with 6 zeros at the end i.e. StringField1; StringField2; StringField3; StringField4; 1000000.000000; StringField5; 0.000000 We are using Python v2.6 (and don't want to upgrade unless we really have to) but we can't afford to lose this data. Does anyone have any idea why this might have happened? If the readline is doing some kind of implicit conversion is there a way to do a binary read, because we really just want this data to pass through untouched? It is very wierd to us that this only affected one of the output files generated by the same script, and when it was rerun the output was as expected. thanks Jack (readlines method referenced in below thread) f = open(filename) lines = 0 buf_size = 1024 * 1024 read_f = f.read # loop optimization buf = read_f(buf_size) while buf: lines += buf.count('\n') buf = read_f(buf_size) return lines A: .readline() doesn't do anything with the content of the line, certainly not with numbers, so it's definitely not the culprit. Thanks for giving more info, but this still looks very mysterious to me as neither function should be causing such a change. You didn't open the output in Excel, by any chance? Sometimes Excel does weird things and interprets stuff in an unexpected way. Grasping at straws here... (As an aside, I don't see the big optimization potential in read_f = f.read :))
Random Loss of precision in Python ReadLine()
We have a process which takes a very large csv (1.6GB) and breaks it down into pieces (in this case 3). This runs nightly and normally doesn't give us any problems. When it ran last night, however, the first of the output files had lost precision on the numeric fields in the data. The active ingredient in the script are the lines: while lineCounter <= chunk: oOutFile.write(oInFile.readline()) lineCounter = lineCounter + 1 and the normal output might be something like StringField1; StringField2; StringField3; StringField4; 1000000; StringField5; 0.000054454 etc. On this one occasion and in this one output file the numeric fields were all output with 6 zeros at the end i.e. StringField1; StringField2; StringField3; StringField4; 1000000.000000; StringField5; 0.000000 We are using Python v2.6 (and don't want to upgrade unless we really have to) but we can't afford to lose this data. Does anyone have any idea why this might have happened? If the readline is doing some kind of implicit conversion is there a way to do a binary read, because we really just want this data to pass through untouched? It is very wierd to us that this only affected one of the output files generated by the same script, and when it was rerun the output was as expected. thanks Jack (readlines method referenced in below thread) f = open(filename) lines = 0 buf_size = 1024 * 1024 read_f = f.read # loop optimization buf = read_f(buf_size) while buf: lines += buf.count('\n') buf = read_f(buf_size) return lines
[ ".readline() doesn't do anything with the content of the line, certainly not with numbers, so it's definitely not the culprit. \nThanks for giving more info, but this still looks very mysterious to me as neither function should be causing such a change. You didn't open the output in Excel, by any chance? Sometimes Excel does weird things and interprets stuff in an unexpected way. Grasping at straws here...\n(As an aside, I don't see the big optimization potential in read_f = f.read :))\n" ]
[ 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003006378_file_io_python.txt
Q: Python class decorator and maximum recursion depth exceeded I try define class decorator. I have problem with __init__ method in decorated class. If __init__ method invokes super the RuntimeError maximum recursion depth exceeded is raised. Code example: def decorate(cls): class NewClass(cls): pass return NewClass @decorate class Foo(object): def __init__(self, *args, **kwargs): super(Foo, self).__init__(*args, **kwargs) What am I doing wrong? Thanks, Michał Edit 1 Thanks to Mike Boers answer I realized that correct question is what should I do to achive that super(Foo, self) point to proper class. I have also two limitation. I want invoke Foo.__init__ method and I can't change Foo class definition. Edit 2 I have solved this problem. I modify decorator function body. I don't return new class. Instead of I wrap methods of orginal class. A: Remember that a decorator is simply syntactic sugar for: >>> Foo = decorate(Foo) So in this case the name Foo actually refers to the NewClass class. Within the Foo.__init__ method you are in fact asking for the super __init__ of NewClass, which is Foo.__init__ (which is what is currently running). Thus, your Foo.__init__ keeps receiving its own __init__ to call, and you end up in an infinite recursion. A: You need to override NewClass.__init__ to prevent recursion, because NewClass.__init__ is Foo.__init__ and it keeps calling itself. def decorate(cls): class NewClass(cls): def __init__(self): pass return NewClass New idea: How about not subclassing it? Maybe monkey patching is your friend? def decorate(cls): old_do_something = cls.do_something def new_do_something(self): print "decorated", old_do_something(self) cls.do_something = new_do_something return cls @decorate class Foo(object): def __init__(self, *args, **kwargs): super(Foo, self).__init__(*args, **kwargs) def do_something(self): print "Foo" f = Foo() f.do_something()
Python class decorator and maximum recursion depth exceeded
I try define class decorator. I have problem with __init__ method in decorated class. If __init__ method invokes super the RuntimeError maximum recursion depth exceeded is raised. Code example: def decorate(cls): class NewClass(cls): pass return NewClass @decorate class Foo(object): def __init__(self, *args, **kwargs): super(Foo, self).__init__(*args, **kwargs) What am I doing wrong? Thanks, Michał Edit 1 Thanks to Mike Boers answer I realized that correct question is what should I do to achive that super(Foo, self) point to proper class. I have also two limitation. I want invoke Foo.__init__ method and I can't change Foo class definition. Edit 2 I have solved this problem. I modify decorator function body. I don't return new class. Instead of I wrap methods of orginal class.
[ "Remember that a decorator is simply syntactic sugar for:\n>>> Foo = decorate(Foo)\n\nSo in this case the name Foo actually refers to the NewClass class. Within the Foo.__init__ method you are in fact asking for the super __init__ of NewClass, which is Foo.__init__ (which is what is currently running).\nThus, your Foo.__init__ keeps receiving its own __init__ to call, and you end up in an infinite recursion. \n", "You need to override NewClass.__init__ to prevent recursion, because NewClass.__init__ is Foo.__init__ and it keeps calling itself.\ndef decorate(cls):\n class NewClass(cls):\n def __init__(self):\n pass\n return NewClass\n\n\nNew idea:\nHow about not subclassing it? Maybe monkey patching is your friend?\ndef decorate(cls):\n old_do_something = cls.do_something\n def new_do_something(self):\n print \"decorated\",\n old_do_something(self)\n\n cls.do_something = new_do_something\n return cls\n\n@decorate\nclass Foo(object):\n def __init__(self, *args, **kwargs):\n super(Foo, self).__init__(*args, **kwargs)\n\n def do_something(self):\n print \"Foo\"\n\nf = Foo()\nf.do_something()\n\n" ]
[ 5, 5 ]
[]
[]
[ "class", "decorator", "python" ]
stackoverflow_0003005945_class_decorator_python.txt