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: Is it possible in python to define functions outside of a programs main namespace and add them for easy access like a .h file in c? I don't want to really define my own PyObject. I want to have functions available for use within a program, but I don't have a need for class instances and don't want to prefix the f...
Is it possible in python to define functions outside of a programs main namespace and add them for easy access like a .h file in c?
I don't want to really define my own PyObject. I want to have functions available for use within a program, but I don't have a need for class instances and don't want to prefix the function call with the name of the module import. As an example of what I don't want import coke coke.make(data) Now an example of what ...
[ "You want:\nfrom coke import *\nmake(data)\n\nor to import individual functions or classes:\nfrom coke import make, make2\n\n", "Let your users do what they want to do:\nimport coke\ncoke.make()\n\nor\nfrom coke import make\nmake()\n\nor \nfrom coke import *\nmake()\n\nYou can't stop them, so don't fret about it....
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005710289_python.txt
Q: Python syntax for IF/THEN Compared to PHP I have a this code in PHP: if($id = $this->ci->srr->check_faca_indiv($name)) { return $id; } elseif($id = $this->_addIndiv($name)) { return $id; } else { return null; I use this basic structure all over the place and it may not be great, but it's what I'm use...
Python syntax for IF/THEN Compared to PHP
I have a this code in PHP: if($id = $this->ci->srr->check_faca_indiv($name)) { return $id; } elseif($id = $this->_addIndiv($name)) { return $id; } else { return null; I use this basic structure all over the place and it may not be great, but it's what I'm used to. The functions basically try to do some si...
[ "something like:\nreturn checkIndiv(name) or addIndiv(name)\n\n", "The basic problem with your code is that the final branch serves no purpose. Even in your PHP example it basically says:\nif (null) return null;\n\nYou can reduce everything to:\nindiv_id = checkIndiv(name)\nif indiv_id:\n return indiv_id\nelse...
[ 5, 2 ]
[]
[]
[ "if_statement", "php", "python", "syntax" ]
stackoverflow_0005710209_if_statement_php_python_syntax.txt
Q: defaults of method python Is there a cleaner way to get the defaults of a method than using the inspect module? I'd like to do this: class C(object): def __init__(self,Type='generic',X=5,Y=500): defaults=getDefaults() #not sure about this line typeDefaults_X={'short':'1','long':'10'} ty...
defaults of method python
Is there a cleaner way to get the defaults of a method than using the inspect module? I'd like to do this: class C(object): def __init__(self,Type='generic',X=5,Y=500): defaults=getDefaults() #not sure about this line typeDefaults_X={'short':'1','long':'10'} typeDefaults_Y={'large':2000,'sma...
[ "It's not really clear to me what you are trying to do. But in the method, variable already has the specified default value. But it seems to me that you would be better off not using formal default arguments in this case.\nclass C(object):\n\n def __init__(self, Type='generic', X=None, Y=None):\n X = X or...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005710451_python.txt
Q: Python socket only accepting local connections Server: import socket host = "" port = 4242 backlog = 5 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog) client, address = s.accept() while 1: data = client.recv(size) if data: client.send(data)...
Python socket only accepting local connections
Server: import socket host = "" port = 4242 backlog = 5 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog) client, address = s.accept() while 1: data = client.recv(size) if data: client.send(data) print(data.decode("utf-8")) Client: import...
[ "Sounds like host='' is defaulting to bind to localhost (127.0.0.1) under Win 7 (I don't have access to a Win 7 machine at the moment). \nTo make your server reachable on all (IPv4) interfaces on the host, this should work on Linux, Windows, Mac, etc:\nhost = '0.0.0.0'\ns.bind((host, 8080))\n\nTo verify which addr...
[ 8, 0 ]
[]
[]
[ "python", "sockets", "windows" ]
stackoverflow_0005710443_python_sockets_windows.txt
Q: Overriding basic signals (SIGINT, SIGQUIT, SIGKILL??) in Python I'm writing a program that adds normal UNIX accounts (i.e. modifying /etc/passwd, /etc/group, and /etc/shadow) according to our corp's policy. It also does some slightly fancy stuff like sending an email to the user. I've got all the code working, but...
Overriding basic signals (SIGINT, SIGQUIT, SIGKILL??) in Python
I'm writing a program that adds normal UNIX accounts (i.e. modifying /etc/passwd, /etc/group, and /etc/shadow) according to our corp's policy. It also does some slightly fancy stuff like sending an email to the user. I've got all the code working, but there are three pieces of code that are very critical, which update ...
[ "There is no real way to make your script really save. Of course you can ignore signals and catch a keyboard interrupt using try: except: but it is up to your application to be idempotent against such interrupts and it must be able to resume operations after dealing with an interrupt at some kind of savepoint. \nTh...
[ 3 ]
[]
[]
[ "linux", "python", "signals" ]
stackoverflow_0005711745_linux_python_signals.txt
Q: PyCUDA Passing variable by value to kernel Should be simple enough; I literally want to send an int to the a SourceModule kernel declaration, where the C function __global__......(int value,.....) with the value being declared and called... value = 256 ... ... func(value,...) But I'm getting a variety of errors ...
PyCUDA Passing variable by value to kernel
Should be simple enough; I literally want to send an int to the a SourceModule kernel declaration, where the C function __global__......(int value,.....) with the value being declared and called... value = 256 ... ... func(value,...) But I'm getting a variety of errors from pycuda that I'm using the wrong type.
[ "The standard PyCUDA function interface requires argument have numpy dtypes, because it internally does mapping to C types under the hood. So for scalar arguments which are passed by value, you need to \"cast\" to a suitable numpy dtype first. Something like\nvalue = 256\nva = numpy.int32(value)\n\nfunc(va)\n\nshou...
[ 9 ]
[]
[]
[ "cuda", "gpgpu", "pycuda", "python" ]
stackoverflow_0005710690_cuda_gpgpu_pycuda_python.txt
Q: sqlalchemy - Performance issues with too many methods/attributes? I have been using sqlalchemy for a few years now in replacement for Django models. I have found it very convenient to have custom methods attached to these models i.e. class Widget(Base): __tablename__ = 'widgets' id = Column(Integer, pri...
sqlalchemy - Performance issues with too many methods/attributes?
I have been using sqlalchemy for a few years now in replacement for Django models. I have found it very convenient to have custom methods attached to these models i.e. class Widget(Base): __tablename__ = 'widgets' id = Column(Integer, primary_key=True) name = Column(Unicode(100)) def get_slug(self...
[ "You would not have any performance hit when loading the objects from the database using SA using just a session.query(...).\nAnd you definitely should not move any methods out to any helper function for the sake of performance, as in doing so you would basically destroy the object oriented paradigm of your model.\...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0005710364_python_sqlalchemy.txt
Q: How can I find a table after a text string using BeautifulSoup in Python? I am trying to extract data from several web pages which are not uniform in how they display their tables. I need to write code that will search for a text string and then go to the table immediately following that specific text string. Th...
How can I find a table after a text string using BeautifulSoup in Python?
I am trying to extract data from several web pages which are not uniform in how they display their tables. I need to write code that will search for a text string and then go to the table immediately following that specific text string. Then I want to extract the contents of that table. Here's what I've got so far: ...
[ "The error is due to the fact that findAllNext is a method of Tag objects, but foundtext is a ResultSet object, which is a list of matching tags or strings. You could iterate through the each of the tags in foundtext, but depending on your needs it might be sufficient to use find, which returns only the first matc...
[ 10 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0005711483_beautifulsoup_python_web_scraping.txt
Q: A Deduplication DB schema with sqlalchemy - How to represent a group with ORM semantics? I'm trying to create a simple representation for an entity deduplication schema using mysql, and using sqlalchemy for programmatic access. I'm trying to achieve a specific effect which I think is kind of a self-referential que...
A Deduplication DB schema with sqlalchemy - How to represent a group with ORM semantics?
I'm trying to create a simple representation for an entity deduplication schema using mysql, and using sqlalchemy for programmatic access. I'm trying to achieve a specific effect which I think is kind of a self-referential query but i'm not sure: Essentially I have an 'entities' table (with unique entity_id) and an ass...
[ "You really should not do it using a Query, as if you configure the relationships properly you will get this automatically. Assuming that you use entity_group table solely to store the relationship and nothing else, you should just configure many-to-many relationship as documented. Fully working example should help...
[ 0 ]
[]
[]
[ "deduplication", "python", "sqlalchemy" ]
stackoverflow_0005700661_deduplication_python_sqlalchemy.txt
Q: How do i add a python package path during runtime Here is a scenario, i hope you can help me with. I have python unit tests in /home/k/PR-TEST/Pr/test kahmed@qatools:~/PR-TEST/Pr-test$ ls _apache.py archive clienttest decorators.py fakeTecoreClient.py fixtures.pyc psqlharness.py servertest testh...
How do i add a python package path during runtime
Here is a scenario, i hope you can help me with. I have python unit tests in /home/k/PR-TEST/Pr/test kahmed@qatools:~/PR-TEST/Pr-test$ ls _apache.py archive clienttest decorators.py fakeTecoreClient.py fixtures.pyc psqlharness.py servertest testhelp.pyc testutils.pyc apache_server.py cache commo...
[ "If you cannot (or do not want to) modify PYTHONPATH before you start the program, you can modify sys.path during runtime to achive similar functionality.\nBut in this case you will need to wrap the call to nosetests script. Also please check that you do not have case-sensitivity issue with your package being calle...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005712460_python.txt
Q: How do you model a state with three values? I have something which can be in three states (say) Open, Closed, Running I will try to model it via one of the two ways, is_open = Boolean(default=False) is_running = Boolean(default=False) and Disallow the state (say) is_running=True, is_open = False in application co...
How do you model a state with three values?
I have something which can be in three states (say) Open, Closed, Running I will try to model it via one of the two ways, is_open = Boolean(default=False) is_running = Boolean(default=False) and Disallow the state (say) is_running=True, is_open = False in application code. I can also try state=Char(choices=("O", "C",...
[ "The simplest way to handle this in Python is to use string constants. We did exactly that when adding inspect.getgeneratorstate() to Python 3.2. The possible return values from that function are:\nGEN_CREATED = 'GEN_CREATED'\nGEN_RUNNING = 'GEN_RUNNING'\nGEN_SUSPENDED = 'GEN_SUSPENDED'\nGEN_CLOSED = 'GEN_CLOSED'\n...
[ 3, 1, 0, 0, 0 ]
[ "Depending on your language, you may be able to use an enum:\nenum DoohickyState\n{\n Open,\n Closed,\n Running\n}\n\n" ]
[ -1 ]
[ "data_modeling", "modeling", "models", "python" ]
stackoverflow_0005703612_data_modeling_modeling_models_python.txt
Q: Count, index out of range I have this code to return a number but I get the error: IndexError: index out of range: 0 with the return. nbus=1 users = [] for i in range(nb): ind = (int(nbus)-1) ind= ind +1 return users[ind] Do you know why? Thanks A: You never append to users, therefore it contains no...
Count, index out of range
I have this code to return a number but I get the error: IndexError: index out of range: 0 with the return. nbus=1 users = [] for i in range(nb): ind = (int(nbus)-1) ind= ind +1 return users[ind] Do you know why? Thanks
[ "You never append to users, therefore it contains no elements and has no valid indexes.\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0005712760_python.txt
Q: python class, that takes in a couple of variables i would like to write a class that takes in a couple of variables in the form of (variableName, value). However variable names are only known at runtime and also the number of args are known at runtime. In my class, i have an object where i want to set those parama...
python class, that takes in a couple of variables
i would like to write a class that takes in a couple of variables in the form of (variableName, value). However variable names are only known at runtime and also the number of args are known at runtime. In my class, i have an object where i want to set those paramaters. So what i need to loop over all variables and set...
[ "You can do:\nclass C(object):\n def __init__(self, **kwargs):\n for (variableName, value) in kwargs.items():\n # setattr(), etc.\n\nwhich you would call with C(x=3, y=123,…).\nIf you really want to use a [variableName, value,…] list of arguments, you can do:\nclass C(object):\n def __init__...
[ 5 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0005712918_python_variables.txt
Q: empty dictionary as default value for keyword argument in python function: dictionary seems to not be initialised to {} on subsequent calls? Here's a function. My intent is to use keyword argument defaults to make the dictionary an empty dictionary if it is not supplied. >>> def f( i, d={}, x=3 ) : ... d[i] = ...
empty dictionary as default value for keyword argument in python function: dictionary seems to not be initialised to {} on subsequent calls?
Here's a function. My intent is to use keyword argument defaults to make the dictionary an empty dictionary if it is not supplied. >>> def f( i, d={}, x=3 ) : ... d[i] = i*i ... x += i ... return x, d ... >>> f( 2 ) (5, {2: 4}) But when I next call f, I get: >>> f(3) (6, {2: 4, 3: 9}) It looks like the k...
[ ">>> def f(i, d=None, x=3):\n... if not d:\n... d={}\n... d[i] = i*i\n... x += i\n... return x,d\n... \n>>> f(2)\n(5, {2: 4})\n>>> f(3)\n(6, {3: 9})\n>>> \n\n" ]
[ 4 ]
[]
[]
[ "dictionary", "keyword_argument", "python", "scope" ]
stackoverflow_0005712904_dictionary_keyword_argument_python_scope.txt
Q: Regex search return result or empty I learn Python, and bumped into interesting thing: I try to write lambda-function, which will search the pattern in the string, and return result if found matching, otherwise empty string. What I already have wrote: >>> b = lambda x: re.search("_\w+_", x).group(0) if re.search("...
Regex search return result or empty
I learn Python, and bumped into interesting thing: I try to write lambda-function, which will search the pattern in the string, and return result if found matching, otherwise empty string. What I already have wrote: >>> b = lambda x: re.search("_\w+_", x).group(0) if re.search("_\w+_", x) is not None else '' If my str...
[ "Don't write it at all.\n>>> re.findall(\"_\\\\w+_\", 'sdsd _sdsd_ sdsd sdsd _sssssssss_')\n['_sdsd_', '_sssssssss_']\n>>> re.findall(\"_\\\\w+_\", '')\n[]\n\n" ]
[ 9 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005713066_python_regex.txt
Q: Basic fetching of a URL's HTML body with Python 3.x I'm a Python newbie. I have been a little confused by the differences between the old urllib and urllib2 in Python 2.x and the new urllib in Python 3, and among other things I'm not sure when data needs to be encoded before being sent to urlopen. I have been tryi...
Basic fetching of a URL's HTML body with Python 3.x
I'm a Python newbie. I have been a little confused by the differences between the old urllib and urllib2 in Python 2.x and the new urllib in Python 3, and among other things I'm not sure when data needs to be encoded before being sent to urlopen. I have been trying to fetch the html body of a url, using a POST so that ...
[ "The GIF89a means that the server is sending you an image.\nAlso, you shouldn't be brute-force decoding with UTF-8 anyway; you should look at the response headers to figure out which encoding to use.\n" ]
[ 2 ]
[]
[]
[ "python", "url", "urllib2" ]
stackoverflow_0005713183_python_url_urllib2.txt
Q: Using a variable from another function python Hey there, this is a very fundamental concept and I've looked it up and global variables are not working for me. I need to use the variable score which is in the function main in another function called judgment, so based on the score of the trivia, I can tell the user...
Using a variable from another function python
Hey there, this is a very fundamental concept and I've looked it up and global variables are not working for me. I need to use the variable score which is in the function main in another function called judgment, so based on the score of the trivia, I can tell the user how they did (which is why I called the judgment f...
[ "You are calling judgement(score) out of the scope of your main() function. The score variable is local in that function. Just indent that line to match the function indentation.\nIn Python, indentation has syntactical meaning, so you are not \"calling judgment function at the very bottom of main\" but before the m...
[ 3, 2 ]
[]
[]
[ "global_variables", "python", "variables" ]
stackoverflow_0005713371_global_variables_python_variables.txt
Q: Help in constructing a GQL query for a one to many relationship A] Problem Summary: I have one to many data models in my project. I need help constructing a query to get the “many” side data object based on the key of the “one” side data object. Please refer to "EDIT#1" for the code that has worked, but still inef...
Help in constructing a GQL query for a one to many relationship
A] Problem Summary: I have one to many data models in my project. I need help constructing a query to get the “many” side data object based on the key of the “one” side data object. Please refer to "EDIT#1" for the code that has worked, but still inefficient. B] Problem details: 1] I have “UserReportedCountry” (one) to...
[ "Your last query looks correct and I don't see any problem of inefficiency on it; in fact querying by_key_name is pretty fast and efficient.\nI think you have room of improvement on your normalized RDMBS oriented Models design instead; since GAE does not support JOINS, after the get_data_for_users_country_and_city ...
[ 1 ]
[]
[]
[ "django", "django_models", "google_app_engine", "python" ]
stackoverflow_0005710368_django_django_models_google_app_engine_python.txt
Q: Passing python objects across interpreters I would like to exchange objects between two python interpreters working on the same (and different ) machines. Is there a mechanism to achieve the same? ~Vijay To be more specific: I have few processes running on same (and different) machine(s). Few of these processes ...
Passing python objects across interpreters
I would like to exchange objects between two python interpreters working on the same (and different ) machines. Is there a mechanism to achieve the same? ~Vijay To be more specific: I have few processes running on same (and different) machine(s). Few of these processes produce objects which are consumed by the other ...
[ "Use the pickle module of Python in order to serialize/deserialize an object state:\nhttp://docs.python.org/library/pickle.html\n", "Generally, you need to serialize the object. In Python that means pickle and unpickle. You can pickle an object on one side, transfer it somehow (socket, etc.) the other and unpickl...
[ 5, 5 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0005713586_multithreading_python.txt
Q: Django Module, App and Import Question - object has no attribute 'form' I have a signup form that needs to be loaded for every page of my site if the user is a guest. I figured the easiest way to do this would be to create a "signup" app/module and have the form variable defined in the init.py so it was automatic...
Django Module, App and Import Question - object has no attribute 'form'
I have a signup form that needs to be loaded for every page of my site if the user is a guest. I figured the easiest way to do this would be to create a "signup" app/module and have the form variable defined in the init.py so it was automatically initiated on every view, assuming I imported the module. However, I'm h...
[ "I would just point out that the way you're doing it is an extremely bad idea. You have one instance of the form across every request: that's always going to be dangerous, allowing the possibility of information leakage across requests. Don't do it.\nInstead, use the built-in mechanism that Django has to do this fo...
[ 2, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005710492_django_python.txt
Q: Can the nested try except block in python be simplified everyone, my python code is something like this: try: foo1() except FooError1: try: foo2() except FooError2: dosth() raise raisesth() I wonder if there is a try-except support for multi conditions or compound conditions in python,...
Can the nested try except block in python be simplified
everyone, my python code is something like this: try: foo1() except FooError1: try: foo2() except FooError2: dosth() raise raisesth() I wonder if there is a try-except support for multi conditions or compound conditions in python, thus my code could be simplified as: try: foo1() fo...
[ "I suggest you to read python documentation.\nI assume you want dosth called if foo1() or foo2() raise an exception you want to handle in dosth(), like in your second code block.\ntry:\n foo1() \n foo2()\nexcept (FooError1, FooError2):\n dosth()\nraise raisesth()\n\nAs you may ask a and condition in your e...
[ 1, 1 ]
[]
[]
[ "python", "try_catch" ]
stackoverflow_0005713564_python_try_catch.txt
Q: Accessing key field into Django Template How can I access key field of model into django template? A: **key** should be the name of the attribute you are expecting to find in the blockedsoftwares_list So, assuming your blockedsoftwares_listcontain a list of key (then the choice of the variable name is not explic...
Accessing key field into Django Template
How can I access key field of model into django template?
[ "**key** should be the name of the attribute you are expecting to find in the blockedsoftwares_list\nSo, assuming your blockedsoftwares_listcontain a list of key (then the choice of the variable name is not explicit), you want to check that the key field of the current software is not in the blocked software key li...
[ 0, 0 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0005714462_django_templates_google_app_engine_python.txt
Q: Help me understand why Unicode only works sometimes with Python Here's a little program: #!/usr/bin/env python # -*- encoding: utf-8 -*- print('abcd kΩ ☠ °C √Hz µF ü ☃ ♥') print(u'abcd kΩ ☠ °C √Hz µF ü ☃ ♥') On Ubuntu, Gnome terminal, IPython does what I would expect: In [6]: run Unicodetest.py abcd kΩ ☠ °C √H...
Help me understand why Unicode only works sometimes with Python
Here's a little program: #!/usr/bin/env python # -*- encoding: utf-8 -*- print('abcd kΩ ☠ °C √Hz µF ü ☃ ♥') print(u'abcd kΩ ☠ °C √Hz µF ü ☃ ♥') On Ubuntu, Gnome terminal, IPython does what I would expect: In [6]: run Unicodetest.py abcd kΩ ☠ °C √Hz µF ü ☃ ♥ abcd kΩ ☠ °C √Hz µF ü ☃ ♥ I get the same output if I ente...
[ "I/O in Python (and most other languages) is based on bytes. When you write a byte string (str in 2.x, bytes in 3.x) to a file, the bytes are simply written as-is. When you write a Unicode string (unicode in 2.x, str in 3.x) to a file, the data needs to be encoded to a byte sequence.\nFor a further explanation of...
[ 11, 2, 0, 0, 0 ]
[]
[]
[ "ipython", "python", "ubuntu", "unicode", "windows_7" ]
stackoverflow_0005695421_ipython_python_ubuntu_unicode_windows_7.txt
Q: Why "except Exception" doesn't catch SystemExit? isinstance(SystemExit(1), Exception) evals to True, but this snippet prints "caught by bare except SystemExit(1,)". try: sys.exit(0) except Exception, e: print 'caught by except Exception', str(e) except: print 'caught by bare except', repr(sys.exc_info(...
Why "except Exception" doesn't catch SystemExit?
isinstance(SystemExit(1), Exception) evals to True, but this snippet prints "caught by bare except SystemExit(1,)". try: sys.exit(0) except Exception, e: print 'caught by except Exception', str(e) except: print 'caught by bare except', repr(sys.exc_info()[1]) My testing environment is Python 2.6.
[ "isinstance(SystemExit(1), Exception)\nis False on Python 2.6. Exception hierarchy in this version of Python was changed since Python 2.4. \nE.g. KeyboardInterrupt is not subclass of Exception any more.\nSee more info http://docs.python.org/release/2.6.6/library/exceptions.html#exception-hierarchy\n", "SystemExit...
[ 13, 11, 8 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0005714525_exception_handling_python.txt
Q: Scheduling Timeouts in Python I have a bunch of sockets I read and write asynchronously. I want to execute code in case the remote peer does not react within a given time. I do not want a Timer objects as each of those runs in a different thread. Also, running a scheduler in a separate thread that handles the time...
Scheduling Timeouts in Python
I have a bunch of sockets I read and write asynchronously. I want to execute code in case the remote peer does not react within a given time. I do not want a Timer objects as each of those runs in a different thread. Also, running a scheduler in a separate thread that handles the timeouts seems infeasible due to schedu...
[ "Read about Twisted Matrix.\n" ]
[ 2 ]
[]
[]
[ "multithreading", "python", "sockets", "timeout" ]
stackoverflow_0005714952_multithreading_python_sockets_timeout.txt
Q: Python/Numpy What's it called / how do you represent that operation where you multiply each element of two vectors? For example, suppose I have: x = array([1, 2, 3]) y = array([4, 5, 6]) Standard "array multiplication" in python does z = x * y = array([4, 10, 18]). In matlab, to get the same effect, you do *. IIR...
Python/Numpy What's it called / how do you represent that operation where you multiply each element of two vectors?
For example, suppose I have: x = array([1, 2, 3]) y = array([4, 5, 6]) Standard "array multiplication" in python does z = x * y = array([4, 10, 18]). In matlab, to get the same effect, you do *. IIRC. What is this operation called, and which symbol is used to represent it?
[ "It is the Hadamard product represented with an open circle:\nhttp://en.wikipedia.org/wiki/Matrix_multiplication#Hadamard_product\n", "It seems to me you are after the expression S = sum_i( x_i * y_i)? That is called the inner product. From numpy documentation: \nfrom numpy import *\nx = array([1,2,3])\ny = arra...
[ 6, 1, 1, 0 ]
[]
[]
[ "arrays", "math", "matlab", "numpy", "python" ]
stackoverflow_0005713524_arrays_math_matlab_numpy_python.txt
Q: passing \n (new line) on stdout throught sys argument This is elementary I guess: Let's consider this snippet: for i in range(3): sys.stdout.write(str(i) + '\n') out: 0 1 2 and this: for i in range(3): sys.stdout.write(str(i) + sys.argv[1]) out (after passing \n as argument): 0\n1\n2\n So, how can I pa...
passing \n (new line) on stdout throught sys argument
This is elementary I guess: Let's consider this snippet: for i in range(3): sys.stdout.write(str(i) + '\n') out: 0 1 2 and this: for i in range(3): sys.stdout.write(str(i) + sys.argv[1]) out (after passing \n as argument): 0\n1\n2\n So, how can I pass new-line as argument?
[ "sys.stdout.write(str(i) + sys.argv[1].decode(\"string_escape\"))\n" ]
[ 8 ]
[]
[]
[ "python", "stdout" ]
stackoverflow_0005715414_python_stdout.txt
Q: Print values at specific time with Tkinter I've written a command-base program and it works properly. Since I'd like to add some graphical interface, I prepared a simple one with Tkinter. But the line which contains "scheduler.run", it locks my application and I can't get any error code. def do_deneme(p): etik...
Print values at specific time with Tkinter
I've written a command-base program and it works properly. Since I'd like to add some graphical interface, I prepared a simple one with Tkinter. But the line which contains "scheduler.run", it locks my application and I can't get any error code. def do_deneme(p): etiket_run1["text"] = etiket_run1["text"] + str(p) +...
[ "Tkinter is single-threaded. It appears that your scheduler sleeps until it is time to run something, so while it is sleeping your GUI will lock up. \nThe proper way to run something in the future or on a schedule with Tkinter is to call after which uses the event loop to schedule something to run after a set amou...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0005714936_python_tkinter.txt
Q: Pickle a django query? Is it possible to pickle or somehow store a django query in the database? This won`t work : u = User.objects.all import cPickle pickled_query = cPickle.dumps(u) # and store the pickled_query in a db-field. Any thoughts? Updated: import cPickle class CustomData(models.Model): name = mo...
Pickle a django query?
Is it possible to pickle or somehow store a django query in the database? This won`t work : u = User.objects.all import cPickle pickled_query = cPickle.dumps(u) # and store the pickled_query in a db-field. Any thoughts? Updated: import cPickle class CustomData(models.Model): name = models.CharField(max_length = ...
[ "There's documentation for that. Basically, pickle the query attribute if you want to recreate the SQL query, and pickle the whole queryset if you want to pickle a snapshot of the current results.\nYour example would do the latter, if you pickled the result of all() instead of the bound method.\n" ]
[ 7 ]
[]
[]
[ "django", "pickle", "python" ]
stackoverflow_0005715479_django_pickle_python.txt
Q: How do I reintroduce South to my Django project? I'm in the classic position of the novice coder, where in hindsight I'd do many things differently if I were starting my project over. I used South relatively early in my project, ran into some problems due to my lack of knowledge, and abandoned it, removing it fro...
How do I reintroduce South to my Django project?
I'm in the classic position of the novice coder, where in hindsight I'd do many things differently if I were starting my project over. I used South relatively early in my project, ran into some problems due to my lack of knowledge, and abandoned it, removing it from installed apps, and syncing the DB. I then learned ...
[ "South creates a table in your database to track migrations that have been applied. The table is south_migrationhistory. You probably want to either drop the table (and re-sync your db) or delete it's contents.\nI imagine at the moment south thinks that it's applied migration that it hasn't, which may be confusin...
[ 3 ]
[]
[]
[ "django", "django_south", "postgresql", "python", "reinstall" ]
stackoverflow_0005715320_django_django_south_postgresql_python_reinstall.txt
Q: libVLC function media_player_new() throws Segmentation Fault media_player_new() throws segmentation fault. import vlc ins=vlc.Instance() player=ins.media_player_new() Here is where it crashes: Thread 0 Crashed: Dispatch queue: com.apple.main-thread 0 libvlc.dylib 0x000000010059aa78 libvlc_media_player_new + ...
libVLC function media_player_new() throws Segmentation Fault
media_player_new() throws segmentation fault. import vlc ins=vlc.Instance() player=ins.media_player_new() Here is where it crashes: Thread 0 Crashed: Dispatch queue: com.apple.main-thread 0 libvlc.dylib 0x000000010059aa78 libvlc_media_player_new + 24 libvlc.dylib is in the place where script is looking: /Applica...
[ "Launch Python in 32 bit modes by running export VERSIONER_PYTHON_PREFER_32_BIT=yes This is not an ideal solution, but it works for me.\nApplying these patches will fix the issue for real: http://trac.videolan.org/vlc/ticket/4686\n" ]
[ 2 ]
[]
[]
[ "libvlc", "python", "segmentation_fault", "vlc" ]
stackoverflow_0004901669_libvlc_python_segmentation_fault_vlc.txt
Q: Valgrind on Python2.4 : Huge amount of memory 'possibly lost' I have written some code which works without errors. The code uses MySQLdb for (frequent) database access and uses 4 different databases. Also a couple of log files are generated and logging module is used. The real worry is that when running Valgrind, ...
Valgrind on Python2.4 : Huge amount of memory 'possibly lost'
I have written some code which works without errors. The code uses MySQLdb for (frequent) database access and uses 4 different databases. Also a couple of log files are generated and logging module is used. The real worry is that when running Valgrind, i get the following ==7840== LEAK SUMMARY: ==7840== definitely l...
[ "Python uses own memory allocator on top of malloc which causes problems when using valgrind. See Misc/README.valgrind for detailed explanation. Assuming you are not going to rebuild Python the solution is to use Misc/valgrind-python.supp as suppression file and uncomment the lines in it that suppress the warnings ...
[ 5 ]
[]
[]
[ "memory_leaks", "mysql", "python", "python_2.4", "valgrind" ]
stackoverflow_0005715801_memory_leaks_mysql_python_python_2.4_valgrind.txt
Q: How can I control access to a shared resource when using mod_wsgi? In mod_wsgi, web requests may be handled by python interpreters in different processes. I have a shared resource to which access needs to be synchronized. (This resource is not a database.) Python's multiprocessing has lots of good synchronization ...
How can I control access to a shared resource when using mod_wsgi?
In mod_wsgi, web requests may be handled by python interpreters in different processes. I have a shared resource to which access needs to be synchronized. (This resource is not a database.) Python's multiprocessing has lots of good synchronization primitives, but all seem to rely on the primitives being shared at spawn...
[ "A couple options are posix_ipc and using file locks. I'm not thrilled about these solutions, since it seems that there should be a built-in mod_wsgi or python library approach to cross-process (without sharing a common parent process) synchronization.\nHere's a file-locking implementation:\nfrom contextlib import ...
[ 3 ]
[]
[]
[ "mod_wsgi", "multiprocessing", "python", "synchronization" ]
stackoverflow_0005710836_mod_wsgi_multiprocessing_python_synchronization.txt
Q: Django 1.1 to Django 1.3 I have read the Django book, but for the old version 1.1. Other than rereading the book for the updated version, what is the quickest way to get up to date with the new and the deprecated features? I know I can look at the changelog, but I was looking for some more detailed resources, mayb...
Django 1.1 to Django 1.3
I have read the Django book, but for the old version 1.1. Other than rereading the book for the updated version, what is the quickest way to get up to date with the new and the deprecated features? I know I can look at the changelog, but I was looking for some more detailed resources, maybe some blog posts.
[ "What you are looking for is posts explaining in much more detail each feature. Djangoadvent did has it for 1.2.\nBy the time 1.3 came out, many of these people who wrote these posts last time around, got busy with their (new founded) startups (via YC'11)!\nYou can refer the release notes tho':\nDjango 1.3 release ...
[ 6, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005716115_django_python.txt
Q: python hcluster, distance matrix and condensed distance matrix I'm using the module hcluster to calculate a dendrogram from a distance matrix. My distance matrix is an array of arrays generated like this: import hcluster import numpy as np mols = (..a list of molecules) distMatrix = np.zeros((10, 10)) for i in ...
python hcluster, distance matrix and condensed distance matrix
I'm using the module hcluster to calculate a dendrogram from a distance matrix. My distance matrix is an array of arrays generated like this: import hcluster import numpy as np mols = (..a list of molecules) distMatrix = np.zeros((10, 10)) for i in range(0,10): for j in range(0,10): sim = OETanimoto...
[ "I knocked up a quick random example similar to yours and experienced the same problem.\nIn the docstring it does say :\nPerforms hierarchical/agglomerative clustering on the\n condensed distance matrix y. y must be a :math:{n \\choose 2} sized\n vector where n is the number of original observations paired\n ...
[ 2 ]
[]
[]
[ "distance", "hcluster", "python" ]
stackoverflow_0005714595_distance_hcluster_python.txt
Q: Boost.python overloaded constructor for numpy array and python list Given a C++ class exposed with Boost.Python, how do I expose two constructors: one that takes a numpy array, and another that takes a python list? A: I'm not a 100% on what you mean, but I'm assuming that you want to have a constructor taking a...
Boost.python overloaded constructor for numpy array and python list
Given a C++ class exposed with Boost.Python, how do I expose two constructors: one that takes a numpy array, and another that takes a python list?
[ "I'm not a 100% on what you mean, but I'm assuming that you want to have a constructor taking a Python list and another one taking a numpy array. There are a couple of ways to go about this. The easiest way is by using the make_constructor function and overloading it:\nusing boost;\nusing boost::python;\n\nshared...
[ 5 ]
[]
[]
[ "boost_python", "python" ]
stackoverflow_0005713795_boost_python_python.txt
Q: Question about python and classes I have a base class and a few derived in Python: class Base: def Foo(self): pass # First derived class class Der1(Base): def OwnFoo(self): # Do something 1 def OwnFoo2(self): # Do something 2 def Foo(self): # Do something 3 # Second derived c...
Question about python and classes
I have a base class and a few derived in Python: class Base: def Foo(self): pass # First derived class class Der1(Base): def OwnFoo(self): # Do something 1 def OwnFoo2(self): # Do something 2 def Foo(self): # Do something 3 # Second derived class class Der2(Base): def OwnFoo(se...
[ "Since you can't change the inheritance structure, make a helper class that contains the common code and include it by composition rather than inheritance.\n# Common code goes in this new class\nclass DerHelper:\n def __init__(self, parent):\n self._parent = parent\n def OwnFoo(self):\n print 'D...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "class", "function", "python" ]
stackoverflow_0005716919_class_function_python.txt
Q: isinstance of bool? in Python, i'd like to check to make sure a command line argument is of type bool before I use it in a conditional statement. this: isinstance(sys.argv[2], bool) is coming back false. What's the right way to do this? A: All command line arguments are strings. Please refine what you want. If y...
isinstance of bool?
in Python, i'd like to check to make sure a command line argument is of type bool before I use it in a conditional statement. this: isinstance(sys.argv[2], bool) is coming back false. What's the right way to do this?
[ "All command line arguments are strings. Please refine what you want.\nIf you want to check for the argument true, check if sys.argv[2] equals 'true'.\n", "As nightcracker said, command line arguments are strings.\nYou can use sys.argv[2] in ('True', 'False').\n" ]
[ 7, 6 ]
[]
[]
[ "boolean", "isinstance", "python" ]
stackoverflow_0005717738_boolean_isinstance_python.txt
Q: Python multiline regex + multi entries reading a file in one go //Last modified: Sat, Apr 16, 2011 09:55:04 AM //Codeset: ISO-8859-1 fileInfo "version" "20x64"; createNode newnode -n "a_SET"; addAttr -ci true -k true -sn "connections" -ln "connections" -dt "string"; setAttr -l on -k off ".tx"; setAttr ...
Python multiline regex + multi entries reading a file in one go
//Last modified: Sat, Apr 16, 2011 09:55:04 AM //Codeset: ISO-8859-1 fileInfo "version" "20x64"; createNode newnode -n "a_SET"; addAttr -ci true -k true -sn "connections" -ln "connections" -dt "string"; setAttr -l on -k off ".tx"; setAttr -l on -k off ".ty"; setAttr -l on -k off ".sz"; setAttr -l on...
[ "You can use regexp positive lookahead to split the groups: \n(yourGroupSeparator)(.*?)(?=yourGroupSeparator|\\Z)\n\nIn your example:\nimport re\n\nlines = open(\"e:/temp/test.txt\").read()\nmatches = re.findall(r'createNode newnode \\-n (\\\"._SET\\\");(.*?)(?=createNode|\\Z)', lines, re.MULTILINE + re.DOTALL);\n\...
[ 3, 0, 0 ]
[]
[]
[ "file", "match", "multiline", "python", "regex" ]
stackoverflow_0005686262_file_match_multiline_python_regex.txt
Q: Python Clutter: Know when a timeline is done? Is there any way to know when a timeline has finished in Python-Clutter, so that I can do something and then run another timeline? Can I use .join() on it like timers in PyGTK? A: Turns out there's a signal - "completed".
Python Clutter: Know when a timeline is done?
Is there any way to know when a timeline has finished in Python-Clutter, so that I can do something and then run another timeline? Can I use .join() on it like timers in PyGTK?
[ "Turns out there's a signal - \"completed\".\n" ]
[ 2 ]
[]
[]
[ "clutter", "python" ]
stackoverflow_0004596908_clutter_python.txt
Q: Does configuring django's setting.TIME_ZONE affect datetime.datetime.now()? The documentation says: http://docs.djangoproject.com/en/dev/ref/settings/#time-zone Note that this is the time zone to which Django will convert all dates/times -- not necessarily the timezone of the server. For example, one serv...
Does configuring django's setting.TIME_ZONE affect datetime.datetime.now()?
The documentation says: http://docs.djangoproject.com/en/dev/ref/settings/#time-zone Note that this is the time zone to which Django will convert all dates/times -- not necessarily the timezone of the server. For example, one server may serve multiple Django-powered sites, each with a separate time-zone se...
[ "Much to my surprise, it does appear to.\nweb81:~/webapps/dominicrodger2/dominicrodger$ python2.5 manage.py shell\nPython 2.5.4 (r254:67916, Aug 5 2009, 12:42:40)\n[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n(InteractiveConsole)...
[ 6, 1 ]
[]
[]
[ "datetime", "django", "python" ]
stackoverflow_0001570339_datetime_django_python.txt
Q: Python String parsing: filenames with spaces This probably isn't the most common filename parsing problem, but I have a program that displays a list of files in the following format: Filename.ext Location Some examples would be sampleFile.jpg C:\Images\my jpgs another file.bmp C:\Images\myBmps The filename and t...
Python String parsing: filenames with spaces
This probably isn't the most common filename parsing problem, but I have a program that displays a list of files in the following format: Filename.ext Location Some examples would be sampleFile.jpg C:\Images\my jpgs another file.bmp C:\Images\myBmps The filename and the location is separated by a single space. As sho...
[ "I'd probably uses a regex for grabbing anything that started with a drive letter to the end of the line, something like:\n import re\n matchWinPaths = re.compile(\"^.*([A-Z]:\\\\.+$)\")\n\nthen match each line with\n matches = re.match(line, matchWinPaths)\n winPath = matches.group(1)\n\n", "Do you have periods ...
[ 2, 1, 1 ]
[]
[]
[ "filenames", "python", "string_parsing", "windows" ]
stackoverflow_0005718368_filenames_python_string_parsing_windows.txt
Q: 'unicode' object has no attribute 'value1' If I have a list of objects in views.py, such as: myobjects=model.objects.all() then I get the values of a field of the objects: times=myobjects.values_list(‘time’, flat=True) and then I want to set attribute to each object of the list times: for mytime in times: my...
'unicode' object has no attribute 'value1'
If I have a list of objects in views.py, such as: myobjects=model.objects.all() then I get the values of a field of the objects: times=myobjects.values_list(‘time’, flat=True) and then I want to set attribute to each object of the list times: for mytime in times: mytime.value1=myobjects.filter(time=mytime).values...
[ "myobjects.values_list() returns a list of unicode values, not objects. If you need to augment the values with values from your queryset, you might consider returning a dictionary of values instead of the values_list...\ntimes = myobjects.values('time')\n\nfor mytime in times:\n mytime.update({'my_key' : myobjec...
[ 3, 1 ]
[]
[]
[ "attributes", "django", "object", "python" ]
stackoverflow_0005718133_attributes_django_object_python.txt
Q: C++ string parsing (python style) I love how in python I can do something like: points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers ...
C++ string parsing (python style)
I love how in python I can do something like: points = [] for line in open("data.txt"): a,b,c = map(float, line.split(',')) points += [(a,b,c)] Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas How can this be don...
[ "I`d do something like this:\nifstream f(\"data.txt\");\nstring str;\nwhile (getline(f, str)) {\n Point p;\n sscanf(str.c_str(), \"%f, %f, %f\\n\", &p.x, &p.y, &p.z); \n points.push_back(p);\n}\n\nx,y,z must be floats.\nAnd include:\n#include <iostream>\n#include <fstream>\n\n", "All these good examples ...
[ 24, 17, 17, 14, 7, 4, 3, 1, 1, 1 ]
[]
[]
[ "c++", "parsing", "python", "string", "text_files" ]
stackoverflow_0000536148_c++_parsing_python_string_text_files.txt
Q: 'return' with not-None expression list returns 'None' I'm currently working on XML (SVG) traversing and have the next problem: my function always return None after if currNode.parentNode is rootNode:, though, as you can see in the code below, I've explicitly set return to 'flag', which is non-empty string. The mos...
'return' with not-None expression list returns 'None'
I'm currently working on XML (SVG) traversing and have the next problem: my function always return None after if currNode.parentNode is rootNode:, though, as you can see in the code below, I've explicitly set return to 'flag', which is non-empty string. The most interesting part here is that print('...') prints three d...
[ "I suspect the problem is with the following part of your code:\n elif currNode.parentNode.nextSibling is None:\n print('<--')\n currNode = currNode.parentNode\n relsLookup(currNode, rootNode)\n\nDid you mean to say:\n elif currNode.parentNode.nextSibling is None:\n ...
[ 6, 2, 2 ]
[]
[]
[ "python", "return" ]
stackoverflow_0005715251_python_return.txt
Q: Why can't I search through the dictionary I created (Python)? In this program I am making a dictionary from a plain text file, basically I count the amount a word occurs in a document, the word becomes the key and the amount of time it occurs is the value. I can create the dictionary but then I cannot search throu...
Why can't I search through the dictionary I created (Python)?
In this program I am making a dictionary from a plain text file, basically I count the amount a word occurs in a document, the word becomes the key and the amount of time it occurs is the value. I can create the dictionary but then I cannot search through the dictionary. Here is my updated code with your guys' input. I...
[ "Your approach is very complicated (and syntactically wrong, at least in your posted code sample). \nAlso, you're rebinding the built-in name dict which is problematic, too.\nFurthermore, this functionality is already built-in in Python:\nfrom collections import defaultdict\n\ndef readFile(fileHandle):\n d = def...
[ 4, 3, 1, 0 ]
[]
[]
[ "dictionary", "function", "python" ]
stackoverflow_0005714231_dictionary_function_python.txt
Q: Joining split list into a list I'm trying to take a split up list and join them into another list. For example, I have this list: ['T', 'e', 's', 't', '\n', 'List', '\n'] Now I want to join these so it looks like ['Test', 'List'] How can I do this? A: I'm afraid that your question is a little underspecified,...
Joining split list into a list
I'm trying to take a split up list and join them into another list. For example, I have this list: ['T', 'e', 's', 't', '\n', 'List', '\n'] Now I want to join these so it looks like ['Test', 'List'] How can I do this?
[ "I'm afraid that your question is a little underspecified, as S. Lott comments, but it looks as if you just want to join all the strings together and then split where there are newlines - the following works for your example, and could be easily modified for other requirements:\n>>>> ''.join(['T', 'e', 's', 't', '\...
[ 7, 4 ]
[]
[]
[ "join", "list", "python", "split", "string" ]
stackoverflow_0005719006_join_list_python_split_string.txt
Q: Running eventlet server in bottle framework i see something like this in bottle.py version 0.9. Does that means. i can run bottle server as a eventlet server. class EventletServer(ServerAdapter): """ Untested """ def run(self, handler): from eventlet import wsgi, listen wsgi.server(listen((self.host, self....
Running eventlet server in bottle framework
i see something like this in bottle.py version 0.9. Does that means. i can run bottle server as a eventlet server. class EventletServer(ServerAdapter): """ Untested """ def run(self, handler): from eventlet import wsgi, listen wsgi.server(listen((self.host, self.port)), handler )
[ "Atlast figured out. how to run bottle server as eventlet in bottle framework.Just should pass the argument server='' inside run. list of supported servers Server adapters in bottle\nrun(server='eventlet',host='localhost', port=8080, reloader=True)\n\n" ]
[ 3 ]
[]
[]
[ "bottle", "eventlet", "python" ]
stackoverflow_0005717825_bottle_eventlet_python.txt
Q: How to convert a .pyc to a .exe file I want to create the Windows executable file of my project, but I don't want to share the source code. I use Linux, but py2exe doesn't work on Linux. Is there a py2exe alternative for Linux? A: I'd use cx_freeze. I've tried py2exe, and it doesn't handle dependencies as well a...
How to convert a .pyc to a .exe file
I want to create the Windows executable file of my project, but I don't want to share the source code. I use Linux, but py2exe doesn't work on Linux. Is there a py2exe alternative for Linux?
[ "I'd use cx_freeze.\nI've tried py2exe, and it doesn't handle dependencies as well as cx_freeze. Best of all, it's cross-platform! I've made Windows and Linux binaries with it, so I can confirm it works properly.\nHere's a little tutorial to get you started: http://www.blog.pythonlibrary.org/2010/08/12/a-cx_freeze-...
[ 7, 1 ]
[]
[]
[ "executable", "py2exe", "python" ]
stackoverflow_0005719111_executable_py2exe_python.txt
Q: Parse Java Source Files with Python I have a bunch of Java source files. I need to write a python script that goes through the source files and identifies all string literals and their location. The problem is the strings could be in a couple of different forms such as: String literal - "Hello World" Combination ...
Parse Java Source Files with Python
I have a bunch of Java source files. I need to write a python script that goes through the source files and identifies all string literals and their location. The problem is the strings could be in a couple of different forms such as: String literal - "Hello World" Combination of literals - "Hello" + "World" I have c...
[ "Using re module is the quickest solution. \nyou can use re.finditer() which returns each matched regex with the content and position\n>>> for m in re.finditer(r\"\\w+ly\", text):\n... print '%02d-%02d: %s' % (m.start(), m.end(), m.group(0))\n\n", "Another option is PLY, which is a pure-python lex / yacc. It ...
[ 3, 2, 2 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0005718862_parsing_python_regex.txt
Q: renaming file prefixes and filetypes In python 2.7, how would I go about renaming any .bat files in my current directory to a file called 1.txt? (ex) If these are the files in my directory: [test.txt, abc.exe, dkckx.bat, 123.vbs], how could I rename the dkckx.bat to 1.txt? thx in advance. A: Check the python doc...
renaming file prefixes and filetypes
In python 2.7, how would I go about renaming any .bat files in my current directory to a file called 1.txt? (ex) If these are the files in my directory: [test.txt, abc.exe, dkckx.bat, 123.vbs], how could I rename the dkckx.bat to 1.txt? thx in advance.
[ "Check the python documentation for the rename function.\nAnd may be glob will be helpful too.\n", "os.path has everything you'd need for filename manipulation. glob can search for files:\nimport os, glob\n\ni = 1\n\nfor f in glob.glob('*'):\n if os.path.splitext(os.path.split(f)[-1])[-1].lower() == '.bat':\n ...
[ 3, 0 ]
[]
[]
[ "python", "rename", "scripting" ]
stackoverflow_0005719214_python_rename_scripting.txt
Q: Convert string to datetime in django? i want to display time in 12 hour format in django templates as iam storing time data in a charecter eg('18:30:00') field how to convert this string time data to date in django/python? A: If you absolutely must do this, use time.strptime. It would be a better idea not to sto...
Convert string to datetime in django?
i want to display time in 12 hour format in django templates as iam storing time data in a charecter eg('18:30:00') field how to convert this string time data to date in django/python?
[ "If you absolutely must do this, use time.strptime. It would be a better idea not to store structured data in a string if you can avoid it, though.\n", "Within Django's templates you can use the date Template Filter:\n{{ value|date:\"h:i:s a\" }} # '18:30:00' would appear as 6:30:00 p.m.\n{{ value|date:\"g:i:s...
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005719296_django_python.txt
Q: How would I make it so (if Sector[1]=="l" and BRCTerritories[1]==".":) brings up all the results in the table? print 'Content-Type: application/vnd.google-earth.kml+xml' print 'Content-Disposition: attachment; filename=BRC_Services.kml\n' import _mssql import cgi fs = cgi.FieldStorage() BRCTerritories=str(fs['BR...
How would I make it so (if Sector[1]=="l" and BRCTerritories[1]==".":) brings up all the results in the table?
print 'Content-Type: application/vnd.google-earth.kml+xml' print 'Content-Disposition: attachment; filename=BRC_Services.kml\n' import _mssql import cgi fs = cgi.FieldStorage() BRCTerritories=str(fs['BRCTerritories'].value) Sector=str(fs['Sector'].value) if BRCTerritories[1]==".": menusearch = {"BRC_Area":BRCTer...
[ "Change the base string to this:\nquery='SELECT * FROM dbo.Services where 1=1' \n\nNow you don't need the where initialization based on \"if addition=1\" logic; you can just iterate all menu search terms as \"And\".\nTest if the criteria are the given sentinel values, if so empty the set of menusearch terms, so no...
[ 0 ]
[]
[]
[ "python", "sql", "sql_server_2008" ]
stackoverflow_0005719172_python_sql_sql_server_2008.txt
Q: Working with strings in python elif data.find('PRIVMSG') != -1: message = ':'.join(data.split (':')[2:]) if message.lower().find('code') == -1: nick = data.split('!')[ 0 ].replace(':',' ') destination = ''.join (data.split(':')[:2]).split (' ')[-2] function = messag...
Working with strings in python
elif data.find('PRIVMSG') != -1: message = ':'.join(data.split (':')[2:]) if message.lower().find('code') == -1: nick = data.split('!')[ 0 ].replace(':',' ') destination = ''.join (data.split(':')[:2]).split (' ')[-2] function = message.split( )[0] print nick +...
[ "this is the minimal example that shows the problem: \n data = \".topic 1 2 3 4 5 6 7 8 9 10\"\n arg = data.split()\n args = ''\n for index,item in enumerate(arg):\n if index > 3:\n if args == '':\n args = item\n else:\n args += ' ...
[ 2, 0, 0 ]
[]
[]
[ "irc", "python", "string" ]
stackoverflow_0005708488_irc_python_string.txt
Q: MD5 hash discrepancy between Python and PHP? I'm trying to create a checksum of a binary file (flv/f4v, etc) to verify the contents of the file between the server and client computers. The application that's running on the client computer is python-based, while the server is using PHP. PHP code is as follows: $fh...
MD5 hash discrepancy between Python and PHP?
I'm trying to create a checksum of a binary file (flv/f4v, etc) to verify the contents of the file between the server and client computers. The application that's running on the client computer is python-based, while the server is using PHP. PHP code is as follows: $fh = fopen($filepath, 'rb'); $contents = fread($fh, ...
[ "I would rather assume that the base64 implementations differ.\nEDIT\nPHP:\nphp -r 'var_dump(base64_encode(str_repeat(\"x\", 10)));'\nstring(16) \"eHh4eHh4eHh4eA==\"\n\nPython (Note the trailing newline):\n>>> (\"x\" * 10).encode('base64')\n'eHh4eHh4eHh4eA==\\n'\n\n", "PHP and python use different base64 flavors:...
[ 25, 14, 4, 4 ]
[]
[]
[ "md5", "php", "python" ]
stackoverflow_0005719471_md5_php_python.txt
Q: Python or R! - draw histograms for specified raster files I have two raster files (one with big cell size and second with much smaller.) I have written a Python script which splits these files into pieces limited by bigger cells. Now I want to draw a histogram for cell values and add value (for example as a line) ...
Python or R! - draw histograms for specified raster files
I have two raster files (one with big cell size and second with much smaller.) I have written a Python script which splits these files into pieces limited by bigger cells. Now I want to draw a histogram for cell values and add value (for example as a line) from the bigger cell. Unfortunately I don't know how to do it i...
[ "Without more information, all I can tell you is to look into matplotlib, specifically the hist() function. \nhttp://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.hist\n", "In R, it's much the same as in Python: \nhist(data) \n\nThere is a useful introduction to the raster package in the vignet...
[ 2, 1 ]
[]
[]
[ "histogram", "python", "r", "statistics" ]
stackoverflow_0005716147_histogram_python_r_statistics.txt
Q: Detecting imported objects Given the source code of a Python file, I would like to detect all imported objects. For example, given this source: import mymod from mymod2 import obj1, obj2, obj3 from mymod3 import aobj I want to get: [('mymod2', 'obj1', 'obj2', 'obj3'), ('mymod3', 'aobj')] I have already tried thi...
Detecting imported objects
Given the source code of a Python file, I would like to detect all imported objects. For example, given this source: import mymod from mymod2 import obj1, obj2, obj3 from mymod3 import aobj I want to get: [('mymod2', 'obj1', 'obj2', 'obj3'), ('mymod3', 'aobj')] I have already tried this regex: r'from (?P<mod>[_\w\d]+...
[ "A better tool than regular expressions is the ast module that comes with Python. To find all from ... import statements in the outermost scope of a.py and print all imported names, you could use\nimport ast\ncode = open(\"a.py\").read()\nfor node in ast.parse(code).body:\n if isinstance(node, ast.ImportFrom):\...
[ 8, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005719620_python_regex.txt
Q: Error importing MySQLdb for Python on Mac OS X I've spent what feels like forever running down MySQL blogs and SO questions trying to figure out how to install a MySQL server and MySQLdb for Python on my Mac OS 10.6.7. I think I got the MySQL server installed through MacPorts(which took an eternity), but I can't ...
Error importing MySQLdb for Python on Mac OS X
I've spent what feels like forever running down MySQL blogs and SO questions trying to figure out how to install a MySQL server and MySQLdb for Python on my Mac OS 10.6.7. I think I got the MySQL server installed through MacPorts(which took an eternity), but I can't import MySQLdb (downloaded from here) with Python. H...
[ "The second link in your question kind of contains the answer, but there is so much extra information mucked in that's unnecessary...\nSimply make sure you have the following bin: /usr/local/mysql/bin/mysql_config\nAnd then when installing MySQLdb all you need to do is change mysql_config.path in setup_posix.py to:...
[ 1 ]
[]
[]
[ "macos", "mysql", "python" ]
stackoverflow_0005719738_macos_mysql_python.txt
Q: convert string to datetime in python Possible Duplicate: Convert string to datetime in django? how to convert time string like '18:30:00' into datetime in python? A: Use the datetime.datetime.strptime() method A: My post in Daniweb: Date string to date object, seconds to readable string You seem to only con...
convert string to datetime in python
Possible Duplicate: Convert string to datetime in django? how to convert time string like '18:30:00' into datetime in python?
[ "Use the datetime.datetime.strptime() method\n", "My post in Daniweb:\nDate string to date object, seconds to readable string \nYou seem to only consider time part, it is trivial to convert by simple split.\n", "http://docs.python.org/library/time.html#time.strptime\nThat is the best way to do it\n" ]
[ 2, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005719580_django_python.txt
Q: How can i parse the return value(s) from python -c "import mypackage" Case # 1 : No values are returned , means success Case # 2: get error: Traceback (most recent call last): File "", line 1, in ImportError: No module named mypackage A: In short, don't. In longer, if you need to detect what packages are ins...
How can i parse the return value(s) from python -c "import mypackage"
Case # 1 : No values are returned , means success Case # 2: get error: Traceback (most recent call last): File "", line 1, in ImportError: No module named mypackage
[ "In short, don't.\nIn longer, if you need to detect what packages are installed, at least do something like:\ntry:\n import mypkg\n print \"can import\"\nexcept:\n import \"can't import\"\n\nOr check the return value:\n\n$ python -c \"import foo\" 2> /dev/null; echo $?\n1\n$ python -c \"import sys\" 2> /de...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005718858_python.txt
Q: Django based video asset review system I've been asked to develop a video review system. it would need multiple levels of permissions e.g. internal review, client review. notes(comments) on all the submissions. revisions of the video assets. searching of video assets. publishing these video assets will need to ...
Django based video asset review system
I've been asked to develop a video review system. it would need multiple levels of permissions e.g. internal review, client review. notes(comments) on all the submissions. revisions of the video assets. searching of video assets. publishing these video assets will need to be done from the commandline. because it wou...
[ "Django will do this just fine. There are a coulpe revision control apps out there, a quick google search turned up this: Django-Revision as far as command-line usage you can write your own management commands.\n" ]
[ 0 ]
[]
[]
[ "django", "pipeline", "python" ]
stackoverflow_0005720115_django_pipeline_python.txt
Q: How to cache value returned by method, which is dependent on attributes of other classes? Simplified code (no caching) First a piece of simplified code, which I'll use to explain the problem. def integrate(self, function, range): # this is just a naive integration function to show that # function needs to ...
How to cache value returned by method, which is dependent on attributes of other classes?
Simplified code (no caching) First a piece of simplified code, which I'll use to explain the problem. def integrate(self, function, range): # this is just a naive integration function to show that # function needs to be called many times sum = 0 for x in range(range): sum += function(x) * 1 ...
[ "The fundamental problem is one that you've already identified: you're trying to memoize a function that accepts mutable arguments. This problem is very closely related to the reason python dicts don't accept mutable built-ins as keys. \nIt's also a problem that's very simple to fix. Write a function that only acce...
[ 2, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0005718941_oop_python.txt
Q: Django - How to make a form for a model's foreign keys? Here's what I'm trying to do. I'm wondering if someone can suggest a good approach: models.py: class Color(models.Model): name = models.CharField(... class Speed(models.Model): name = models.CharField(... class Dog(models.Model): name = models....
Django - How to make a form for a model's foreign keys?
Here's what I'm trying to do. I'm wondering if someone can suggest a good approach: models.py: class Color(models.Model): name = models.CharField(... class Speed(models.Model): name = models.CharField(... class Dog(models.Model): name = models.CharField(... color = models.ForeignKey(Color... spee...
[ "I don't think you want to use a ModelForm here. It will never be valid without some hackery, since you won't have found or created the dog object before calling is_valid().\nInstead, I'd just use a regular form, and then override the save method of DogRequest to find or create the dog.\nUpdate: Responding to the f...
[ 21 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0005720287_django_django_forms_django_models_django_views_python.txt
Q: Update app engine entity How to update existing record in app engine. A: As long as an entity has a key defined it will be updated on put(): record = Record(value='foo') # This creates a new record record.put() record.value = 'shmoo' # This updates it record.put() key = record.key() record2 = Record.get(key) r...
Update app engine entity
How to update existing record in app engine.
[ "As long as an entity has a key defined it will be updated on put():\nrecord = Record(value='foo')\n# This creates a new record\nrecord.put()\n\nrecord.value = 'shmoo'\n# This updates it\nrecord.put()\n\nkey = record.key()\nrecord2 = Record.get(key)\nrecord2.value = 'bar'\n# Yet again this updates the same record\n...
[ 41, 2, 1, -3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005066357_google_app_engine_python.txt
Q: Django tests failing after migrating to 1.2.5 - primary key issue for child model I have a model ThreadedComment that inherits from model Object. ThreadedComment does not have a unique primary key of its own, relying on Object's promary key ("ID"). This is how the model is constructed: class Object(models.Model): ...
Django tests failing after migrating to 1.2.5 - primary key issue for child model
I have a model ThreadedComment that inherits from model Object. ThreadedComment does not have a unique primary key of its own, relying on Object's promary key ("ID"). This is how the model is constructed: class Object(models.Model): permalink = models.CharField(max_length=128) status = models.IntegerField() ...
[ "This turned out to be a django bug. Details here: http://code.djangoproject.com/ticket/12728 \nAnd here is our temporary workaround: https://bitbucket.org/filmaster/filmaster-test/changeset/afbac905cf63 \n", "I can't reproduce it on trunk or 1.2.3; I created a fresh project with app 'threadedcomments' and the mo...
[ 4, 0, 0 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0005554390_django_postgresql_python.txt
Q: Specific Disadvantages of PHP compared to Python via code examples? There appears to be an overwhelming acceptance that php is a "poorly designed" language as compared to python. As I have limited experience I am not able to fully understand this conceptually or practically...I'm still in the "Php works fine so fa...
Specific Disadvantages of PHP compared to Python via code examples?
There appears to be an overwhelming acceptance that php is a "poorly designed" language as compared to python. As I have limited experience I am not able to fully understand this conceptually or practically...I'm still in the "Php works fine so far" camp...but id like to be educated. I am specifically interested in the...
[ "The PythonVsPhp page on the PythonInfo Wiki has an excellent summary of the differences along with some heated retorts and counter-retorts.\n" ]
[ 4 ]
[]
[]
[ "php", "python" ]
stackoverflow_0005720724_php_python.txt
Q: Can I use zipimport to ship a embedded python? Currently, I'm deploying a full python distribution (the original python 2.7 msi) with my app. Which is an embedded web server made with delphi. Reading this, I wonder if is possible to embed the necessary python files with my app, to decrease load files and avoid con...
Can I use zipimport to ship a embedded python?
Currently, I'm deploying a full python distribution (the original python 2.7 msi) with my app. Which is an embedded web server made with delphi. Reading this, I wonder if is possible to embed the necessary python files with my app, to decrease load files and avoid conflict with several python versions. I have previous ...
[ "zipimport should work just fine for you -- I'm not familiar with Python for Delphi, but I doubt it disables that functionality (an embedding application can do that, but it's an unusual choice). Just remember that what you can zip up and import directly are the Python-coded modules (or just their corresponding .p...
[ 3, 0 ]
[]
[]
[ "delphi", "embedded_language", "freepascal", "python" ]
stackoverflow_0003199707_delphi_embedded_language_freepascal_python.txt
Q: Signing a SimpleDB request I'm trying to make an API call to Amazon's SimpleDB service with Python. As an example, I'm using the simplest request there is to make, ListDomains. No matter what I try, however, the response is always "The request signature we calculated does not match the signature you provided." Thi...
Signing a SimpleDB request
I'm trying to make an API call to Amazon's SimpleDB service with Python. As an example, I'm using the simplest request there is to make, ListDomains. No matter what I try, however, the response is always "The request signature we calculated does not match the signature you provided." This is the string I'm signing (as ...
[ "A key issue is that you have to properly URL encode all of the HTTP parameter values.\nThe following documentation has disappeared from the SimpleDB docs, but can be found in the SQS docs and is still very relevant to SimpleDB:\n\nDo not URL encode any of the\n unreserved characters that RFC 3986\n defines.\nThe...
[ 2, 0 ]
[]
[]
[ "amazon_simpledb", "python" ]
stackoverflow_0005721228_amazon_simpledb_python.txt
Q: PyCUDA Memory Addressing: Memory offset? I've got a large chunk of generated data (A[i,j,k]) on the device, but I only need one 'slice' of A[i,:,:], and in regular CUDA this could be easily accomplished with some pointer arithmetic. Can the same thing be done within pycuda? i.e cuda.memcpy_dtoh(h_iA,d_A+(i*strid...
PyCUDA Memory Addressing: Memory offset?
I've got a large chunk of generated data (A[i,j,k]) on the device, but I only need one 'slice' of A[i,:,:], and in regular CUDA this could be easily accomplished with some pointer arithmetic. Can the same thing be done within pycuda? i.e cuda.memcpy_dtoh(h_iA,d_A+(i*stride)) Obviously this is completely wrong since ...
[ "The pyCUDA gpuArray class supports slicing of 1D arrays, but not higher dimensions that require a stride (although it is coming). You can, however, get access to the underlying pointer in a multidimensional gpuArray from the gpuarray member, which is a pycuda.driver.DeviceAllocation type, and the size information ...
[ 2, 0 ]
[]
[]
[ "addressing", "cuda", "pycuda", "python", "relative_addressing" ]
stackoverflow_0005720376_addressing_cuda_pycuda_python_relative_addressing.txt
Q: Python TCP socket doesn't close? Maybe someone here will have a response for this thing which is just driving me insane. To make it simple, I'm making a kind of proxy. Whenever it receives something, it forwards everything to a server, and sends back the response. So there is one socket always listening on port 45...
Python TCP socket doesn't close?
Maybe someone here will have a response for this thing which is just driving me insane. To make it simple, I'm making a kind of proxy. Whenever it receives something, it forwards everything to a server, and sends back the response. So there is one socket always listening on port 4557 for clients, and for each incoming ...
[ "First I'm sorry that I currently have not the time to actually run and test your code.\nBut the idea came to my mind, that your problem might actually have something todo with using blocking mode vs. non-blocking mode on the socket. In that case you should checkout the \"socket\" module help in the python document...
[ 7 ]
[]
[]
[ "python", "sockets", "tcp" ]
stackoverflow_0005720233_python_sockets_tcp.txt
Q: Django data not showing I am building a website just for fun of learning programming more fully, but have run into an issue. I am trying to make a status update area of the user homepage where the latest status update for the current user will display up top of their page(like Facebook). However the function I hav...
Django data not showing
I am building a website just for fun of learning programming more fully, but have run into an issue. I am trying to make a status update area of the user homepage where the latest status update for the current user will display up top of their page(like Facebook). However the function I have made to retrieve the data i...
[ "list[1:] will return elements from 1 to the end. So your status variable is not a single status but a list of statuses and a list does not have the attribute status_id\nto get the last one use [-1]\nUpdate:\nYou can also use django function latest(http://docs.djangoproject.com/en/dev/ref/models/querysets/#latest)\...
[ 1, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005721843_django_python.txt
Q: Does Python do slice-by-reference on strings? I want to know if when I do something like a = "This could be a very large string..." b = a[:10] a new string is created or a view/iterator is returned A: Python does slice-by-copy, meaning every time you slice (except for very trivial slices, such as a[:]), it cop...
Does Python do slice-by-reference on strings?
I want to know if when I do something like a = "This could be a very large string..." b = a[:10] a new string is created or a view/iterator is returned
[ "Python does slice-by-copy, meaning every time you slice (except for very trivial slices, such as a[:]), it copies all of the data into a new string object.\nAccording to one of the developers, this choice was made because\n\nThe [slice-by-reference] approach is more complicated, harder to implement\n and may lead...
[ 63, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005722006_python_string.txt
Q: Setting up a Python development environment on Windows Yes, I've searched. So after spending about 4-5 hours struggling just to get Python files running, I recently stumbled over the solution to get it running through the environment variables like this: cmd -> python -> Python starts, yay yay Since it didn't work...
Setting up a Python development environment on Windows
Yes, I've searched. So after spending about 4-5 hours struggling just to get Python files running, I recently stumbled over the solution to get it running through the environment variables like this: cmd -> python -> Python starts, yay yay Since it didn't work to do it through the command line and similar I had to do i...
[ "When you say\n\nable to type 'python test.py'\n\nI'm not sure exactly what you mean. Normally when the Python interpreter runs, it looks in the current directory for any source file that is named on the command line (unless you specifically name a location for the source file, as you've discovered). It seems from ...
[ 2, 2 ]
[]
[]
[ "development_environment", "python", "windows" ]
stackoverflow_0005721948_development_environment_python_windows.txt
Q: Python imaplib display certificate key I want imaplib to display the md5 (or SHA) key of an IMAP Server Certificate to make sure, that there's no MITM (I don't trust the CA, so verifying the chain isn't enough in this case). Displaying the whole certificate would also be okay. I'd appreciate any help!! Chris A: ...
Python imaplib display certificate key
I want imaplib to display the md5 (or SHA) key of an IMAP Server Certificate to make sure, that there's no MITM (I don't trust the CA, so verifying the chain isn't enough in this case). Displaying the whole certificate would also be okay. I'd appreciate any help!! Chris
[ "You can use the M2Crypto package to parse the full SSL certificate from the IMAP connection's SSL socket. Here is an example:\nimport imaplib\nfrom M2Crypto import X509\n\ncn = imaplib.IMAP4_SSL('imap.gmail.com', 993)\nsock = cn.ssl()\ndata = sock.getpeercert(1)\ncert = X509.load_cert_string(data, X509.FORMAT_DER...
[ 2, 0 ]
[]
[]
[ "certificate", "imaplib", "python", "security", "ssl" ]
stackoverflow_0005720519_certificate_imaplib_python_security_ssl.txt
Q: Overriding a python instance method in a external library I've written a context manager for a database connection. I would like to override a method from an external class ('execute' in cx_oracle.Cursor), to drop any extraneous bind variables before passing the query to the database (or else they result in a Data...
Overriding a python instance method in a external library
I've written a context manager for a database connection. I would like to override a method from an external class ('execute' in cx_oracle.Cursor), to drop any extraneous bind variables before passing the query to the database (or else they result in a DatabaseError). The issue of why they would be there to begin with...
[ "If you use a __getattr__ method, rather than __getattribute__, you don't have to special case the names in your own class. It only looks at __getattr__ if it can't find the attribute by the normal means.\nSomething like:\ndef __getattr__(self, name):\n return getattr(self.curs, name)\n\nYou'll need to change cl...
[ 1 ]
[]
[]
[ "cx_oracle", "overriding", "python" ]
stackoverflow_0005720809_cx_oracle_overriding_python.txt
Q: Is there a long polling framework in PHP/Apache analagous to Tornado? Is there something like the Tornado framework written in PHP or any examples of how to tie it (Tornado or another reliable framework) in to a site already built on PHP/MYSQL/Apache? A: at eyeOS we have developed our entire long polling stack u...
Is there a long polling framework in PHP/Apache analagous to Tornado?
Is there something like the Tornado framework written in PHP or any examples of how to tie it (Tornado or another reliable framework) in to a site already built on PHP/MYSQL/Apache?
[ "at eyeOS we have developed our entire long polling stack using php/mysql/apache.\nWe use mysql memory tables for message exchanging, and some tricks at php level.\neyeOS is open source so you can view/modify/reuse the code under the terms of the AGPL3 license.\nThe code is here:\nhttps://code.eyeos.org/trunk/eyeos...
[ 1 ]
[]
[]
[ "comet", "long_polling", "php", "python", "tornado" ]
stackoverflow_0005722435_comet_long_polling_php_python_tornado.txt
Q: Unit testing: Does it make sense to test parent object methods? Let's say I am using a framework that has a class called Animal. class Animal(object): def speak(self): logging.info(self.sound) I have to subclass this object in order to use it and it might look something like this: class Dog(Animal): ...
Unit testing: Does it make sense to test parent object methods?
Let's say I am using a framework that has a class called Animal. class Animal(object): def speak(self): logging.info(self.sound) I have to subclass this object in order to use it and it might look something like this: class Dog(Animal): def __init__(self): self.sound = 'Woof Woof' The way I se...
[ "No, make sure the parent object is tested properly (with mocking if necessary) and test the sub-objects methods separately. This fits with the encapsulation concept (making matters local).\nIf you don't, a large project with many classes will drain all your coding resources for no added value.\n", "In your simpl...
[ 5, 3, 1 ]
[]
[]
[ "django", "python", "tdd", "unit_testing" ]
stackoverflow_0005722003_django_python_tdd_unit_testing.txt
Q: Run linux script on received emails I have written a small little script that looks up a work on wikipedia and then prints the result to the command line. I want to be able to email that word to my server and then have my server email me the results back. So far I have a new user named 'wiki' where the e-mails ar...
Run linux script on received emails
I have written a small little script that looks up a work on wikipedia and then prints the result to the command line. I want to be able to email that word to my server and then have my server email me the results back. So far I have a new user named 'wiki' where the e-mails are being sent to. I am receiving the e-mai...
[ "Depending on you mailserver (e.g. postfix) you may need to configure it to allow piping mail. Most often, using ~/.procmailrc is easiest.\n", "This is what I did to take care of my problem...\n\nI scrapped my bash script, and wrote the same function in python. I used python because of its email parsing functiona...
[ 0, 0 ]
[]
[]
[ "aliases", "email", "linux", "python" ]
stackoverflow_0005709846_aliases_email_linux_python.txt
Q: Is it possible to refer to the current list's length from inside the index? I'd like to say something like: [1, 2, 3, 4][len/2] where len refers to the length of this unnamed list. Is there a way to do this in python? A: To answer your question, you cannot do this without having the list exist beforehand. Howeve...
Is it possible to refer to the current list's length from inside the index?
I'd like to say something like: [1, 2, 3, 4][len/2] where len refers to the length of this unnamed list. Is there a way to do this in python?
[ "To answer your question, you cannot do this without having the list exist beforehand. However you can simply do:\n>>> l = [1,2,3,4]\n>>> l[len(l)/2]\n3\n\n", "I don't think that something like that is possible out of the box. But the more pythonic way is anyway to make your idea more explizit. Why not write it l...
[ 7, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005722419_python.txt
Q: Latest from each x in django I have 2 tables in my db: Category ( Id Name) Post ( Id Name Content Category (PK)) I need to get the latest post from each category into a html-table. I've tried to slice the object in the view file, with [:1], but then I only get the latest post. I've also tried to slic...
Latest from each x in django
I have 2 tables in my db: Category ( Id Name) Post ( Id Name Content Category (PK)) I need to get the latest post from each category into a html-table. I've tried to slice the object in the view file, with [:1], but then I only get the latest post. I've also tried to slice the for-loop in the template fil...
[ "from django.shortcuts import render\nfrom my_project.models import Category\n\ndef my_view(request):\n categories = Category.objects.all().select_related(depth=1)\n return render(request, 'your_template.html', {'categories' : categories})\n\n#your_template.html\n<table>\n {% for c in categories %}\n <t...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005722664_django_python.txt
Q: check for os.system() reply I like using the system() command from the os module. Is there a way to check if the command gives me a reply or not ? I have code to terminate the command if it doesn't finish in x seconds but I want to improve it to terminate it if it does not reply in x seconds. thanks ! A: This d...
check for os.system() reply
I like using the system() command from the os module. Is there a way to check if the command gives me a reply or not ? I have code to terminate the command if it doesn't finish in x seconds but I want to improve it to terminate it if it does not reply in x seconds. thanks !
[ "This depends what you mean with \"reply\". os.system() returns the exit status of the command (which is an int, typically 0 for success). If this is not enough, have a look at the subprocess module.\n", "You didn't say what OS you are running on. Alas, it is different for Windows and Linux. Here's what I do:\nim...
[ 4, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005722609_linux_python.txt
Q: gio: check if volume is mounted I'm doing something like: mo = gio.MountOperation() mo.connect('ask-password', ask_password_cb) location = gio.File("ssh://leon@concepts.tim-online.nl/home/leon/test.txt") location.mount_enclosing_volume(mo, callbackz) loop = gobject.MainLoop() loop.run() But if the volume is al...
gio: check if volume is mounted
I'm doing something like: mo = gio.MountOperation() mo.connect('ask-password', ask_password_cb) location = gio.File("ssh://leon@concepts.tim-online.nl/home/leon/test.txt") location.mount_enclosing_volume(mo, callbackz) loop = gobject.MainLoop() loop.run() But if the volume is already mounted it throws a gio.Error. ...
[ "Maybe you can do something like this:\nif location.find_enclosing_mount() == None\n location.mount_enclosing_volume(mo, callbackz) \n\n", "I found two snippets of code on Nullege that seem to do the trick:\ntry:\n retval = gfile.mount_enclosing_volume_finish(result)\nexcept gio.Error, e:\n # If we run th...
[ 1, 0 ]
[]
[]
[ "gio", "gnome", "python" ]
stackoverflow_0005709454_gio_gnome_python.txt
Q: How to create an increasing counter of ranges? In a script I'm running, there is a memory leak issue (due to the proprietary software being used) that prevents a script for running for more than about 325k iterations. To get around this, I created a list of values for it to iterate through in a for loop like so: ...
How to create an increasing counter of ranges?
In a script I'm running, there is a memory leak issue (due to the proprietary software being used) that prevents a script for running for more than about 325k iterations. To get around this, I created a list of values for it to iterate through in a for loop like so: squery = ['OBJECTID >=0 AND OBJECTID <=300000', 'O...
[ "squery =\n['OBJECTID>=%s AND OBJECTID<=%s' % (i*300k+(i!=0),(i+1)*300k) for i in range(0,3)]\n\n(300k = 300 000 and number of intervals is in range(0,*3*))\n", "Just for completeness, a generator would also solve this problem nicely:\ndef generator_function(n):\n for i in range(0,n):\n yield ('OBJECTID...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005722468_python.txt
Q: Django - Remove "Currently" In An Image Edit Form and Replace It With The Actual Image When editing an object that has an image field, you are presented with the current image path and the standard file upload field. What I want to do is to be able to replace the shown path(the "Currently: /pathtoimage.jpg" with t...
Django - Remove "Currently" In An Image Edit Form and Replace It With The Actual Image
When editing an object that has an image field, you are presented with the current image path and the standard file upload field. What I want to do is to be able to replace the shown path(the "Currently: /pathtoimage.jpg" with the actual image. How do I do this? Thanks in advance!
[ "If you are talking about a form in Django's admin you could override the AdminImageWidget.\nThere are few snippets and posts that explain the details:\n\nDjango simple admin ImageField thumbnail\nImageField for admin with thumbnail\nAdmin Image Widget\n\nFor regular forms you should take a look at django-form-util...
[ 8 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005722899_django_django_forms_python.txt
Q: Best open source CMS for developers to customize and add dynamic pages and content I want to build websites for multiple customers and want to take advantage of features that come with typical CMSs. But on top of that I need to do lots of customization like: Writing my own templates on top of any existing templat...
Best open source CMS for developers to customize and add dynamic pages and content
I want to build websites for multiple customers and want to take advantage of features that come with typical CMSs. But on top of that I need to do lots of customization like: Writing my own templates on top of any existing templates to show the data in a form more suitable for these sites. Extract some of the data fr...
[ "Two highly versatile and configurable CMSs I have used:\n\nWolf CMS - PHP-based, makes PHP directly accessible in backend; \"templating\" is simply (X)HTML + CSS + PHP calls for content; highly extensible.\nSymphony CMS - XML + PHP based; XSLT makes it possible to manipulate site content in creative ways.\n\nSo, n...
[ 4, 2, 2, 2, 1, 0 ]
[]
[]
[ "content_management_system", "django", "php", "python", "wordpress" ]
stackoverflow_0005603962_content_management_system_django_php_python_wordpress.txt
Q: call Cython function from C++ I have a C++ library that has a Python wrapper (written with SWIG). This library allows executing small user-defined code (a callback), such as element-wise operations on a vector. I.e. instead of just a + you can do whatever arbitrary binary function. Right now this is accomplished b...
call Cython function from C++
I have a C++ library that has a Python wrapper (written with SWIG). This library allows executing small user-defined code (a callback), such as element-wise operations on a vector. I.e. instead of just a + you can do whatever arbitrary binary function. Right now this is accomplished by accepting a callable Python objec...
[ "The trick with cython is in using the keyword public\ncdef public double cython_function( double value, double value2 ):\n return value + value2\n\nThen the command cythonize <your_file.pyx> along with <your_file.c> will create header <your_file.h> that you can include.\nAlternatively, you can create the heade...
[ 17, 2, 0 ]
[]
[]
[ "c++", "callback", "cython", "python" ]
stackoverflow_0005710441_c++_callback_cython_python.txt
Q: python CLI-like variable dump When I use python in interactive shell I can easily dump variables by just calling their names. >>> x = b'\xA5' >>> x '\xa5' >>> print x ▒ As you can see, the behavior is different than print's behavior. How do I emulate this CLI-like variable dump in normal scripts? A: Use the re...
python CLI-like variable dump
When I use python in interactive shell I can easily dump variables by just calling their names. >>> x = b'\xA5' >>> x '\xa5' >>> print x ▒ As you can see, the behavior is different than print's behavior. How do I emulate this CLI-like variable dump in normal scripts?
[ "Use the repr() builtin function:\n>>> x = '\\xa5'\n>>> print repr(x)\n'\\xa5'\n\n", ">>> x = b'\\xA5'\n>>> print repr(x)\n'\\xa5'\n\n", "Every class can specialize their representation using the __repr__ special method.\nFor example: \n>>> class Banana:\n... def __repr__(self):\n... return \"Fr...
[ 5, 2, 1 ]
[]
[]
[ "command_line_interface", "python" ]
stackoverflow_0005723424_command_line_interface_python.txt
Q: MYSQL and python error I want to insert data in MYSQL database using python here my code import MySQLdb #connect to db db= MySQLdb.connect(host= "localhost", user="root", passwd="newpassword", db="new_schema") #setup cursor cursor = db.cursor() #create anooog1 table curs...
MYSQL and python error
I want to insert data in MYSQL database using python here my code import MySQLdb #connect to db db= MySQLdb.connect(host= "localhost", user="root", passwd="newpassword", db="new_schema") #setup cursor cursor = db.cursor() #create anooog1 table cursor.execute("DROP TABLE IF EX...
[ "Your error is because you've created a table with no primary key.\nUse this statement (or similar):\nsql = \"\"\"CREATE TABLE try (COL1 INT, COL2 INT, PRIMARY KEY (COL1))\"\"\"\n\nHere we specify that COL1 is to be the primary key for the table. Modify as you need to suit your requirements.\nIf you wanted to add a...
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0005723414_mysql_python.txt
Q: Calling class attribute without creating an instance to that class I would like to initialize a class, then call an attribute which was set during the initialization, but without creating another instance. As a test example: class t1: def __init__(self, skipInit=False): if not skipInit: pri...
Calling class attribute without creating an instance to that class
I would like to initialize a class, then call an attribute which was set during the initialization, but without creating another instance. As a test example: class t1: def __init__(self, skipInit=False): if not skipInit: print 'Initialized' self.var = 123456 else: ...
[ "There's nothing called t1.var, so of course you can't access it. var is an attribute of a t1 instance; it doesn't exist on the class. Since you can have any number of instances of t1, there's no way for an instance method of t2 to know which t1 instance it should look for the attribute var in without you telling i...
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005723042_python.txt
Q: Editing related models in profile form using django-profiles I'm using django-profiles in my app, as it gives me a few simple views that helps me get where I want to go, faster. However, I have one problem. Given the models below, how can I create a form for editing a profile that includes all the fields on UserPr...
Editing related models in profile form using django-profiles
I'm using django-profiles in my app, as it gives me a few simple views that helps me get where I want to go, faster. However, I have one problem. Given the models below, how can I create a form for editing a profile that includes all the fields on UserProfile, the first_name, last_name and email fields from User, and o...
[ "that's quite a contortion to cram two modelforms into the same form. Choices:\n\nMake your own view. You could utilize the short-circuit, first-come-first-serve nature of django urls to pirate that one.\nBring django-profiles into your own version control and hack it to your heart's content without the constrain...
[ 1, 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003644498_django_django_forms_python.txt
Q: Is There a Way to Autogenerate Dependencies Tree in Makefile? Abstract question: I'm programming a mid-size C++/C program that's highly modularized. It has a common interface, which allows you to drop in a number of different sources with the same function declarations, but different implementations and get execu...
Is There a Way to Autogenerate Dependencies Tree in Makefile?
Abstract question: I'm programming a mid-size C++/C program that's highly modularized. It has a common interface, which allows you to drop in a number of different sources with the same function declarations, but different implementations and get executables with different functionalities. I'm working out a make syste...
[ "Yes, if you are using GCC! Here is some of a Makefile I have in a current project (for all real uses, I'll put this under public domain, have fun).\nCC=$(CROSS)gcc -c -g -Wall -Werror -ansi -pedantic $(DEFINES) -I./include\n\n%.o: %.c .d/%.d\n # Your build code here\n\n.d/%.d: %.c\n @$(CC) -MM $< -MF $@\n\n-...
[ 0 ]
[ "One way to simplify the build is skip dependencies. Just recompile everything every time. Only if the build has to be done many times, or it takes a \"long time\", the definition of which depends on the use, and the dependencies change a lot, does it make sense to do a detailed dependency build.\n" ]
[ -3 ]
[ "c", "compilation", "makefile", "python" ]
stackoverflow_0005723719_c_compilation_makefile_python.txt
Q: Compute shadow length using PyEphem I am using PyEphem and want to calculate the length of a shadow (assume a stick of unit length is planted in the ground). The length will be given by cot(phi), where phi is the solar elevation angle (please correct me if I'm wrong). I'm not sure what field to use on the Sun? In ...
Compute shadow length using PyEphem
I am using PyEphem and want to calculate the length of a shadow (assume a stick of unit length is planted in the ground). The length will be given by cot(phi), where phi is the solar elevation angle (please correct me if I'm wrong). I'm not sure what field to use on the Sun? In the example below, I'm using the angle al...
[ "\nwhat field to use on the Sun? \n\nThe sun.alt is correct. alt is an altitude above horizon; together with an azimuth east of north they define an apparent position relative to horizon.\nYour calculations are almost correct. You've forgot to supply an observer: sun = ephem.Sun(o).\n\n\nI don't know how to interpr...
[ 10 ]
[]
[]
[ "astronomy", "pyephem", "python", "shadow" ]
stackoverflow_0005720633_astronomy_pyephem_python_shadow.txt
Q: Google App Engine - Python appication: find relationship among nodes I have following model: class Relations(db.Model): name = db.StringProperty() events = db.StringListProperty(required = True) and following Relations data: name = direct events = [node_A,event_B], name = inverse events = [node_A,node_G]...
Google App Engine - Python appication: find relationship among nodes
I have following model: class Relations(db.Model): name = db.StringProperty() events = db.StringListProperty(required = True) and following Relations data: name = direct events = [node_A,event_B], name = inverse events = [node_A,node_G], name = direct events = [node_A,node_H], name = inverse events = [node_A...
[ "If I understand correctly, something like this could work:\nquery = Relations.all()\nquery.filter('events =', node)\n\ndirect_list = []\ninverse_list = []\n\nfor relation in query:\n relation.events.remove(node)\n if relation.name == 'direct':\n direct_list.extend(relation.events)\n else:\n inverse_list.e...
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005719371_google_app_engine_python.txt
Q: Better way to write a JSON file to a DB? Here's the scenario: -I'm using embed.ly's oembed service to pull metadata about user submitted links (more info about that service: http://api.embed.ly/docs/oembed) -I use this content to generate previews of content on my site -When I submit a URL to embed.ly the service ...
Better way to write a JSON file to a DB?
Here's the scenario: -I'm using embed.ly's oembed service to pull metadata about user submitted links (more info about that service: http://api.embed.ly/docs/oembed) -I use this content to generate previews of content on my site -When I submit a URL to embed.ly the service gives me back a JSON file containing the metad...
[ "Given that the valid keys are defined in embedly's repsonse documentation you can make your code a bit more maintaininable by specifying the list of supported response keys and your translations in one place, reducing the amount of redundant code.\nFor example:\n# embed.ly keys which map 1:1 with your database rec...
[ 0 ]
[]
[]
[ "django", "embed", "json", "python" ]
stackoverflow_0005722305_django_embed_json_python.txt
Q: Issues with data sharing between processes I'm rather new to Python and I'm working on a multiprocessing example script. The code is ~100 lines long, so you can find it here - http://pastie.org/1813365 It's a simple game that occurs on square fields - they are represented as matrices(list containing x nested lis...
Issues with data sharing between processes
I'm rather new to Python and I'm working on a multiprocessing example script. The code is ~100 lines long, so you can find it here - http://pastie.org/1813365 It's a simple game that occurs on square fields - they are represented as matrices(list containing x nested lists of x elements each). A separate game field is...
[ "Ok, your problem doesn't have anything to do with multiprocessing. If you look at your data class definition(you should capitalize your class names, it's pythonic that way), all the variables you are creating are class variables. You want them to be in an __init__ method and defined as self.foo=1 so that they are ...
[ 2 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0005723508_multiprocessing_python.txt
Q: IRC Bot - flood protection (python) if data.find('PRIVMSG') != -1: nick = data.split('!')[ 0 ].replace(':','') text = '' if data.count(text) >= 200: sck.send('KICK ' + " " + chan + " :" 'flooding' + '\r\n') I'm trying to code a flood protection for the bot, I want it to kick a user if he ...
IRC Bot - flood protection (python)
if data.find('PRIVMSG') != -1: nick = data.split('!')[ 0 ].replace(':','') text = '' if data.count(text) >= 200: sck.send('KICK ' + " " + chan + " :" 'flooding' + '\r\n') I'm trying to code a flood protection for the bot, I want it to kick a user if he enters more then 200 characters, how can ...
[ "As far as I remember, the colon is a reserved character in the IRC protocol. That is, the first colon in a server message denotes the start of user-supplied data (that's also why \":\" is not allowed in nicks/channel names). Hence, it suffices to search for the first colon and calculate the length of the remaining...
[ 0 ]
[]
[]
[ "irc", "python", "string" ]
stackoverflow_0005723839_irc_python_string.txt
Q: Behavior of PYTHONPATH vs PERL5LIB So behaviour of python path is different from PERL5LIB which makes it a little difficult to partition libraries into different repos. Let me describe how it works in PERL: If the directory structure is as follows: project/lib/bar/foo.pm common/lib/bar/baz.pm now PERL5LIB is set t...
Behavior of PYTHONPATH vs PERL5LIB
So behaviour of python path is different from PERL5LIB which makes it a little difficult to partition libraries into different repos. Let me describe how it works in PERL: If the directory structure is as follows: project/lib/bar/foo.pm common/lib/bar/baz.pm now PERL5LIB is set to 'project/lib:common/lib' in my perl sc...
[ "Your first problem is that you're trying to force a Perl paradigm into Python. Your second problem is that you don't seem to understand how the Python namespace system works. You can't have the same package imported twice into the global namespace. It just doesn't work like that.\nPython is going to use the first ...
[ 3 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0005723998_perl_python.txt
Q: Try Except in Python I want to take a path for a file, open the file and read the data within it. Upon doing so, I would like to count the number of occurrences of each letter in the alphabet. Of what I have read and heard, using try/except would be best here. I've tried my best in this, but I only managed to coun...
Try Except in Python
I want to take a path for a file, open the file and read the data within it. Upon doing so, I would like to count the number of occurrences of each letter in the alphabet. Of what I have read and heard, using try/except would be best here. I've tried my best in this, but I only managed to count the occurrences of what ...
[ "A slightly more elegant approach is this:\nfrom __future__ import with_statement\n\nfrom collections import defaultdict\n\nprint \"Enter the file path:\"\nthefile = raw_input()\n\nwith open(thefile, \"r\") as f:\n chars = defaultdict(int)\n\n for line in f:\n for c in line:\n chars[c] += 1\...
[ 4, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005724371_python.txt
Q: How is the template directory set in App Engine? I'm currently keeping my templates in /projectdir/static/html/. I've begun to have enough of them that I've created a subdirectory: /projectdir/static/html/tag_request/. If I want to have a template in /tag_request/ inherit from one in /html/ how do I do it? I've r...
How is the template directory set in App Engine?
I'm currently keeping my templates in /projectdir/static/html/. I've begun to have enough of them that I've created a subdirectory: /projectdir/static/html/tag_request/. If I want to have a template in /tag_request/ inherit from one in /html/ how do I do it? I've read that with django {% extends base.html %} should be...
[ "It seems to depend on which version of Django you are using.\nIf you're using 0.96, then just this works:\n{% extends ../base.html %}\n\nIf you're using 1.2, then in theory you need to create a settings.py which sets the TEMPLATE_DIRS to /projectdir/static/html/, and then use this:\n{% extends base.html %}\n\nHowe...
[ 0 ]
[]
[]
[ "django", "django_nonrel", "google_app_engine", "python" ]
stackoverflow_0005724146_django_django_nonrel_google_app_engine_python.txt
Q: How can I store a table in a variable with each row as an element and a delimiter to distinguish columns using BeautifulSoup in Python? I want to store an html table in a variable called store. html = ['<html><body><p align="center"><table><tr><td>row1col1</td><td>row1col2</td><td>row1col3</td></tr><tr><td>row2col...
How can I store a table in a variable with each row as an element and a delimiter to distinguish columns using BeautifulSoup in Python?
I want to store an html table in a variable called store. html = ['<html><body><p align="center"><table><tr><td>row1col1</td><td>row1col2</td><td>row1col3</td></tr><tr><td>row2col1</td><td>row2col2</td><td>row2col3</td></tr></table></html>'] soup = BeautifulSoup(''.join(html)) table = soup.find('table') rows = table.fi...
[ "My guess it that you're after something like this:\nhtml = '<html><body><p align=\"center\"><table><tr><td>row1col1</td><td>row1col2</td><td>row1col3</td></tr><tr><td>row2col1</td><td>row2col2</td><td>row2col3</td></tr></table></html>'\nsoup = BeautifulSoup(html)\ntable = soup.find('table')\nrows = table.findAll('...
[ 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0005724701_beautifulsoup_python.txt