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: Python Remove Comma In Dollar Amount Using Python v2, I have the user entering an amount into a string as below: RawPurchaseAmount = raw_input("Please enter purchase amount: ") PurchaseAmount = float(RawPurchaseAmount.strip().lstrip("$")) This is stripping out any blank spaces at the front of the input, and remo...
Python Remove Comma In Dollar Amount
Using Python v2, I have the user entering an amount into a string as below: RawPurchaseAmount = raw_input("Please enter purchase amount: ") PurchaseAmount = float(RawPurchaseAmount.strip().lstrip("$")) This is stripping out any blank spaces at the front of the input, and removing the $ sign if one is entered. Is ther...
[ "You could use replace to remove all commas:\n\"10,000.00\".replace(\",\", \"\")\n", ">>> import re\n>>> re.sub(\"[^\\d\\.]\", \"\", \"$1,000,000.01\")\n'1000000.01'\n\nRegular expression pattern says \"anything that isn't a number or a decimal point\". Anything matching that regex is replaced with \"\".\nYou may...
[ 46, 26, 4, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005180184_python_string.txt
Q: how to select an object from a list of objects by its attribute in python Apologies if this question has already been asked but I do not think I know the correct terminology to search for an appropriate solution through google. I would like to select an object from a list of objects by the value of it's attribute,...
how to select an object from a list of objects by its attribute in python
Apologies if this question has already been asked but I do not think I know the correct terminology to search for an appropriate solution through google. I would like to select an object from a list of objects by the value of it's attribute, for example: class Example(): def __init__(self): self.pList = [] ...
[ "One option is to use the next() built-in:\ndave = next(person for person in a.pList if person.num == 123)\n\nThis will throw StopIteration if nothing is found. You can use the two-argument form of next() to provide a default value for that case:\ndave = next(\n (person for person in a.pList if person.num == 123...
[ 21, 5, 3, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0005180092_oop_python.txt
Q: FieldError at/. Cannot resolve keyword 'textField' into field I am trying to do a filter method for my django application. I have some fields in db like, userName,designation,employeeID etc . Now i am trying to do a filtering; where there is drop down shows all the fields (name, designation, employeeID etc) and a ...
FieldError at/. Cannot resolve keyword 'textField' into field
I am trying to do a filter method for my django application. I have some fields in db like, userName,designation,employeeID etc . Now i am trying to do a filtering; where there is drop down shows all the fields (name, designation, employeeID etc) and a text area for inputing some text. The filtering should be done base...
[ "Why are you expecting django to be able to magically map a field name to the names you specify in your template? For example, there's nothing in your model called any of the items you list in your <select> options. \nI find the error very self explanatory: \n\nFieldError at /filter/ Cannot resolve\n keyword 'text...
[ 3, 2, 1 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0005179834_django_django_models_django_templates_django_views_python.txt
Q: How can I do INNER JOIN in Django in legacy database? Sorry for probably simple question but I'm a newby in Django and really confused. I have an ugly legacy tables that I can not change. It has 2 tables: class Salespersons(models.Model): id = models.IntegerField(unique=True, primary_key=True) xsin = m...
How can I do INNER JOIN in Django in legacy database?
Sorry for probably simple question but I'm a newby in Django and really confused. I have an ugly legacy tables that I can not change. It has 2 tables: class Salespersons(models.Model): id = models.IntegerField(unique=True, primary_key=True) xsin = models.IntegerField() name = models.CharField(max_length...
[ "Given your example query, are your tables actually named Salespersons/Store?\nAnyway, something like this should work:\nresults = Salespersons.objects.extra(tables=[\"Store\"],\n where=[\"\"\"Salespersons.xsin = Store.xsin\"\"\"])\n\nHowever, given the names of the tables/models it doesn't...
[ 3, 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005178215_django_django_models_python.txt
Q: Parsing JSON data with Python I receive some data from a GitHub webhook service. It contains info about recent commits in a repository. String I receive looks like this: payload = { "ref":"refs/heads/master","commits":[ {"added":[],"author":{"username":"myname","email":"my@email.com","name":"John Doe"}...
Parsing JSON data with Python
I receive some data from a GitHub webhook service. It contains info about recent commits in a repository. String I receive looks like this: payload = { "ref":"refs/heads/master","commits":[ {"added":[],"author":{"username":"myname","email":"my@email.com","name":"John Doe"},"timestamp":"2011-03-03T02:04:32-0...
[ "I would look for the first { character:\njsondata = jsondata[jsondata.index(\"{\"):]\n\n", "There's no single \"right\" way of doing it, unless you want to implement a complete JS parser. That said, the solution suggested by Thomas is more generalizable, eg. less likely to break if github decides to change the f...
[ 6, 1 ]
[]
[]
[ "google_app_engine", "json", "python" ]
stackoverflow_0005181147_google_app_engine_json_python.txt
Q: Operator precedence Consider this C# class: class Node { public Node Next; } And consider these 2 cases: Node A = new Node(); Node B = A; B=(B.Next = new Node()); and Node A = new Node(); Node B = A; B.Next = (B=new Node()); Why do they produce the same result...
Operator precedence
Consider this C# class: class Node { public Node Next; } And consider these 2 cases: Node A = new Node(); Node B = A; B=(B.Next = new Node()); and Node A = new Node(); Node B = A; B.Next = (B=new Node()); Why do they produce the same results!? (A)->(B)->Null I tho...
[ "In Python, you cannot group assignments in the way you have done. The extreme RHS value is assigned to all the identifiers towards it's left.\n>>> a = (b=42)\n File \"<stdin>\", line 1\n a = (b=42)\n ^\nSyntaxError: invalid syntax\n>>> a = b = 42\n\n>>> print a,b\n42 42\n>>> \n\nSimilar to your questi...
[ 2, 2, 2, 1 ]
[]
[]
[ "c#", "java", "operator_keyword", "operator_precedence", "python" ]
stackoverflow_0005178984_c#_java_operator_keyword_operator_precedence_python.txt
Q: Error while trying to use wmi objects (python) I'm trying to write a script which detects whether the machine that the script is run on is a virtual machine or a physical machine and I don't understand the error and how to fix it. import wmi def sys_info(): objWMIService = wmi.GetObject("winmgmts:\root\cimv2...
Error while trying to use wmi objects (python)
I'm trying to write a script which detects whether the machine that the script is run on is a virtual machine or a physical machine and I don't understand the error and how to fix it. import wmi def sys_info(): objWMIService = wmi.GetObject("winmgmts:\root\cimv2") colItems = objWMIService.ExecQuery("Select * ...
[ "Do things improve if you change:\nobjWMIService = wmi.GetObject(\"winmgmts:\\root\\cimv2\") \n\nto \nobjWMIService = wmi.GetObject(r\"winmgmts:\\root\\cimv2\") \n\nThe '\\r' sequence in '\\root' will be interpreted as a <CR> character in your code. You either have to doubleup the '\\'s to escape them so they will...
[ 6 ]
[]
[]
[ "python", "wmi" ]
stackoverflow_0005181456_python_wmi.txt
Q: Python dictionary simple way to add a new key value pair Say you have, foo = 'bar' d = {'a-key':'a-value'} And you want d = {'a-key':'a-value','foo':'bar'} e = {'foo':foo} I know you can do, d['foo'] = foo #Either of the following for e e = {'foo':foo} e = dict(foo=foo) But, in all these way to add the variabl...
Python dictionary simple way to add a new key value pair
Say you have, foo = 'bar' d = {'a-key':'a-value'} And you want d = {'a-key':'a-value','foo':'bar'} e = {'foo':foo} I know you can do, d['foo'] = foo #Either of the following for e e = {'foo':foo} e = dict(foo=foo) But, in all these way to add the variable foo to dict, I have had to use the word foo twice; once to i...
[ "you can do something like this\ndef add_dry_foo(d, namespace, fooName):\n d[fooName] = namespace[fooName]\n\nfoo = 'oh-foo'\nd = {}\nadd_dry_foo(d, locals(), 'foo')\nprint d\n\n", "You can use:\nname = 'foo'\nd[name] = vars[name]\n\nI don't see the difference between your d and e cases: both set 'foo' to the ...
[ 4, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0001721795_dictionary_python.txt
Q: How to change the face color of a plot using Matplotlib I just started using Matplotlib and am trying to change the color of the face color of a plot... if I create the figure like this: plt.figure(num=None, figsize=(5, 10), dpi=80, facecolor='y', edgecolor='k') only the boarder of the figure changes to yellow....
How to change the face color of a plot using Matplotlib
I just started using Matplotlib and am trying to change the color of the face color of a plot... if I create the figure like this: plt.figure(num=None, figsize=(5, 10), dpi=80, facecolor='y', edgecolor='k') only the boarder of the figure changes to yellow... What I would like is the boarder to be white and the plot ...
[ "Hm, you could try set_axis_bgcolor. Also, instead of using gca, try this, it's cleaner:\nfig = plt.figure(num=None, figsize=(5, 10), dpi=80, facecolor='y', edgecolor='k')\nax = fig.add_subplot(111)\nax.set_axis_bgcolor(\"y\")\nax.plot(x, y, color = 'g')\n\n", "Is this what you want?\n\n#!/usr/bin/env python\n\"\...
[ 9, 6 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005181833_matplotlib_python.txt
Q: Optimization problem in Python I need to solve a problem. I have 5 devices. They all have 4 kind of I/O types. And there is a target input/output combination. At first step, I want to find all combinations among the devices so that the total I/O number of selected devices are all equal or greater than the target v...
Optimization problem in Python
I need to solve a problem. I have 5 devices. They all have 4 kind of I/O types. And there is a target input/output combination. At first step, I want to find all combinations among the devices so that the total I/O number of selected devices are all equal or greater than the target values. Let me explain: # Devices=[nu...
[ "You can use a linear programming package like PuLP. (note this also requires you to install an LP library like GLPK).\nHere's how you would use it to solve the example you gave:\nimport pulp\n\nprob = pulp.LpProblem(\"example\", pulp.LpMinimize)\n\n# Variable represent number of times device i is used\nn1 = pulp.L...
[ 5, 3, 1 ]
[]
[]
[ "linear_programming", "optimization", "python" ]
stackoverflow_0005179889_linear_programming_optimization_python.txt
Q: eclipse, pydev, easy_install-ed eggs problem I have a problem with eclipse and easy_install'ed packages into virtualenv. If I have from sqlalchemy.ext.serializer import loads import statement and put mouse cursor on "load" I get message loads Found at: __module_not_in_the_pythonpath__ and it repeats with any...
eclipse, pydev, easy_install-ed eggs problem
I have a problem with eclipse and easy_install'ed packages into virtualenv. If I have from sqlalchemy.ext.serializer import loads import statement and put mouse cursor on "load" I get message loads Found at: __module_not_in_the_pythonpath__ and it repeats with any module on PYTHONPATH while I have not manually ad...
[ "If you add a package after configuring the interpreter in Eclipse, you need to configure the interpreter again\nSee PyDev's manual:\n\nIf you add something to your python\n installation, you need to either add\n it manually as a 'new folder' in the\n System PYTHONPATH (if it's still not\n under a folder in the...
[ 13 ]
[]
[]
[ "eclipse", "python" ]
stackoverflow_0005181160_eclipse_python.txt
Q: Re-inspection of values in a Traceback I am trying to do some elaborate re-inspection of a traceback and get actual values from the objects that are failing to return more (better?) information along with the traceback. The case scenario is in a function that I import and execute that looks like this: def foo():...
Re-inspection of values in a Traceback
I am trying to do some elaborate re-inspection of a traceback and get actual values from the objects that are failing to return more (better?) information along with the traceback. The case scenario is in a function that I import and execute that looks like this: def foo(): a = True b = False assert a == ...
[ "You can use inspect module :\ntry:\n foo()\nexcept AssertionError, e:\n import inspect\n previous_trace = inspect.trace()[1]\n frame = previous_trace[0]\n print 'value of a, b:', inspect.getargvalues(frame).locals\n\nSee http://docs.python.org/library/inspect.html#inspect.getargvalues\n" ]
[ 5 ]
[]
[]
[ "evaluate", "exception", "python" ]
stackoverflow_0005182147_evaluate_exception_python.txt
Q: sphinx, buildbot (and code coverage). how do they integrate? I have a not-so-small python package, with quite some history, documented with docstrings. During its development we introduced buildbot and later on Jenkins/Hudson. Recently I added a sphinx recipe to my buildbot.cfg, in order to collect the documenta...
sphinx, buildbot (and code coverage). how do they integrate?
I have a not-so-small python package, with quite some history, documented with docstrings. During its development we introduced buildbot and later on Jenkins/Hudson. Recently I added a sphinx recipe to my buildbot.cfg, in order to collect the documentation from the sources and keep up to date web accessible docs. so ...
[ "as stated on the sphinx.ext.coverage page, coverage is computed if one specifies the builder -b coverage.\nthe result is the file \"python.txt\", a ReST file. It is your task to integrate it in your own documentation.\n" ]
[ 3 ]
[]
[]
[ "code_coverage", "documentation_generation", "python", "python_sphinx" ]
stackoverflow_0005179010_code_coverage_documentation_generation_python_python_sphinx.txt
Q: How to update a django filter to django 1.2 with GAE Hi I got the following filter which worked with django 0.96 (GAE) and is generating code on the layout erroneoulsy with GAE + django 1.2. Now i want to update the filter so that it works with django 1.2. COuld you provide any information please kindly do so. Fil...
How to update a django filter to django 1.2 with GAE
Hi I got the following filter which worked with django 0.96 (GAE) and is generating code on the layout erroneoulsy with GAE + django 1.2. Now i want to update the filter so that it works with django 1.2. COuld you provide any information please kindly do so. Filter: def news(n): url = os.environ.get('HTTP_HOST') if...
[ "Of course it would have helped if you'd specified exactly what was \"erroneous\" about the output you're getting.\nMy guess is that it's autoescaped, as you would know if you'd read the guide to upgrading from 0.96 to 1.0. Mark the output as safe:\nfrom django.utils.safestring import mark_safe\n...\nreturn mark_sa...
[ 2 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0005182010_django_google_app_engine_python.txt
Q: Waiting on events in other requests in Twisted I have a simple Twisted server that handles requests like this (obviously, asynchronously) global SomeSharedMemory if SomeSharedMemory is None: SomeSharedMemory = LoadSharedMemory() return PickSomething(SomeSharedMemory) Where SomeSharedMemory is loaded from a da...
Waiting on events in other requests in Twisted
I have a simple Twisted server that handles requests like this (obviously, asynchronously) global SomeSharedMemory if SomeSharedMemory is None: SomeSharedMemory = LoadSharedMemory() return PickSomething(SomeSharedMemory) Where SomeSharedMemory is loaded from a database. I want to avoid loading SomeSharedMemory fro...
[ "The way your example is set up, it's hard to see how you could actually have the problem you're describing. If a second request comes in to your Twisted server before the call to LoadSharedMemory issued by the first has returned, then the second request will just wait before being processed. When it is finally h...
[ 2 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0005178212_python_twisted.txt
Q: In python, how to get a UDPServer to shutdown itself? I've created a class for a server with the declaration: class myServer(socketserver.BaseRequestHandler): def handle(self): pass And started it with: someServer = socketserver.UDPServer((HOST, PORT), myServer) someServer.serve_forever() My qu...
In python, how to get a UDPServer to shutdown itself?
I've created a class for a server with the declaration: class myServer(socketserver.BaseRequestHandler): def handle(self): pass And started it with: someServer = socketserver.UDPServer((HOST, PORT), myServer) someServer.serve_forever() My question is: how can I get the server to shutdown itself? I'v...
[ "You could use twisted. Its about the best networking lib for python, here is an example of a UDP server here is (taken from the twisted documentation) the simplest UDP server ever written;\n#!/usr/bin/env python\n\n# Copyright (c) 2001-2009 Twisted Matrix Laboratories.\n# See LICENSE for details.\n\nfrom twisted.i...
[ 1, 1, 0 ]
[]
[]
[ "python", "shutdown", "socketserver", "udp" ]
stackoverflow_0005178536_python_shutdown_socketserver_udp.txt
Q: Trouble using Vim's syn-include and syn-region to embed syntax highlighting I am trying to get Vim to syntax highlight any file that ends with extension .Rtex in the following way: All top level text is highlighted as TeX Exception: any text enclosed in \begin{python}...\end{python} is highlighted as Python I am...
Trouble using Vim's syn-include and syn-region to embed syntax highlighting
I am trying to get Vim to syntax highlight any file that ends with extension .Rtex in the following way: All top level text is highlighted as TeX Exception: any text enclosed in \begin{python}...\end{python} is highlighted as Python I am able to achieve each of these criteria individually, but unable to achieve both ...
[ "After some more study of the manual, and much more trial and error, I have finally answered my own question (a simultaneously embarrassing and sublime accomplishment), which I now preserve here for posterity.\nBasically, I think the problem is that the python highlighting wouldn't take effect because the pythonCod...
[ 20, 0 ]
[]
[]
[ "latex", "python", "syntax_highlighting", "tex", "vim" ]
stackoverflow_0005176972_latex_python_syntax_highlighting_tex_vim.txt
Q: Doubt in Python FOR cycle I'm with some doubts in a Python FOR cycle: This code works great: a, b, c, d, e, f, g, h = range(8) _ = float('inf') # a b c d e f g h W = [ [0,2,1,3,9,4,_,_], # a [_,0,4,_,3,_,_,_], # b [_,_,0,8,_,_,_,_], # c [_,_,_,0,7,_,_,_], # d [_,_,_,_,0,5,_,_], # e [_,...
Doubt in Python FOR cycle
I'm with some doubts in a Python FOR cycle: This code works great: a, b, c, d, e, f, g, h = range(8) _ = float('inf') # a b c d e f g h W = [ [0,2,1,3,9,4,_,_], # a [_,0,4,_,3,_,_,_], # b [_,_,0,8,_,_,_,_], # c [_,_,_,0,7,_,_,_], # d [_,_,_,_,0,5,_,_], # e [_,_,2,_,_,0,2,2], # f [_,_,_,...
[ "Try:\nfor k in [w for w in W[a] if w < _]:\n print 1\n\nYou need to use the if clause within a list comprehension (but as noted in the comment, this is not the optimal way to do this).\nEdit: If you are looking to learn some of the 'awesome' features of python, you could also try using itertools:\nfor k in iter...
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005183185_python.txt
Q: PHP to Python Server Pages, Sessions and EXEC I'm trying to convert this PHP to psp(python server pages). I'm at a loss with the php exec function and isset for the session variables. session_start(); if(isset($_POST["var"])){ //set session username $username = (string)$_POST["var"]; $username = trim($...
PHP to Python Server Pages, Sessions and EXEC
I'm trying to convert this PHP to psp(python server pages). I'm at a loss with the php exec function and isset for the session variables. session_start(); if(isset($_POST["var"])){ //set session username $username = (string)$_POST["var"]; $username = trim($username); $_SESSION['username'] = $username; /...
[ "I think subprocess.check_output() is the function you are looking for:\nfullname = subprocess.check_output(['/var/www/cgi-bin/resolveID.py', username])\n\nInstead of isset($array['key']) you use 'key' in array in python.\n" ]
[ 1 ]
[]
[]
[ "mod_python", "php", "python" ]
stackoverflow_0005183365_mod_python_php_python.txt
Q: Python String replace based on chars NOT in RegEx Is it possible to create a reqex that finds characters that are NOT is a specific set? Rather than Blacklisting a bunch of characters and replacing them, it would be easier for me to allow a certain set and replace characters that are not in that set. My set looks ...
Python String replace based on chars NOT in RegEx
Is it possible to create a reqex that finds characters that are NOT is a specific set? Rather than Blacklisting a bunch of characters and replacing them, it would be easier for me to allow a certain set and replace characters that are not in that set. My set looks like this: [.a-zA-Z0-9] I would like to do something li...
[ "Yes, use the ^ negation \"modifier\": r'[^.a-zA-Z0-9]'\n", "clean_filename = re.sub(r'[^.a-zA-Z0-9]', \"_\", filename)\n\n", "Try with:\nre.sub(r'[^a-zA-Z0-9]', \"_\", filename)\n\n" ]
[ 33, 4, 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005183488_python_regex.txt
Q: Running Python apps without python Hi Are there any other ways to run python application without python installed exept installing py2exe. I se that the latest update was for Python 2.7, but I need something similiar for python 3.1/3.2 A: cx_freeze can be used with python 3.x. In cx_freeze page you have a versio...
Running Python apps without python
Hi Are there any other ways to run python application without python installed exept installing py2exe. I se that the latest update was for Python 2.7, but I need something similiar for python 3.1/3.2
[ "cx_freeze can be used with python 3.x.\nIn cx_freeze page you have a version for 3.1, a windows installer for 3.2 is available from Gohlke\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005183656_python.txt
Q: Odd behaviour using a custom dict class as the __dict__ attribute of Python classes I have a class that inherits from a dictionary in order to add some custom behavior - in this case it passes each key and value to a function for validation. In the example below, the 'validation' simply prints a message. Assignmen...
Odd behaviour using a custom dict class as the __dict__ attribute of Python classes
I have a class that inherits from a dictionary in order to add some custom behavior - in this case it passes each key and value to a function for validation. In the example below, the 'validation' simply prints a message. Assignment to the dictionary works as expected, printing messages whenever items are added to the ...
[ "This is an optimization. To support metamethods on __dict__, every single instance assignment would need to check the existance of the metamethod. This is a fundamental operation--every attribute lookup and assignment--so the extra couple branches needed to check this would become overhead for the whole language...
[ 5 ]
[]
[]
[ "attributes", "magic_methods", "metaprogramming", "python" ]
stackoverflow_0005183336_attributes_magic_methods_metaprogramming_python.txt
Q: Unable to pass a variable to function I'm trying to build a function that calculates hashed for a file. The function takes to arguments, the file name and the algorithm to generate: def getHashValue(fName, Hash): f = open(fName, 'rb') hashvalue = hashlib.Hash(f.read()).hexdigest f.close() print(fName +...
Unable to pass a variable to function
I'm trying to build a function that calculates hashed for a file. The function takes to arguments, the file name and the algorithm to generate: def getHashValue(fName, Hash): f = open(fName, 'rb') hashvalue = hashlib.Hash(f.read()).hexdigest f.close() print(fName + str(Hash) + hashvalue) My problem is that...
[ "Don't use hashlib inside the function. Just take the function as a parameter and use it.\ndef getHashValue(fName,Hash):\n f = open(fName,'rb')\n hashvalue = Hash(f.read()).hexdigest\n f.close()\n print(fName + str(Hash) + hashvalue)\n\nThen when you call this function, use:\ngetHashValue(filename, hashlib....
[ 10, 0, 0, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0005184219_function_python.txt
Q: How to upload photo into UserProfile for specified user in django? I have a photo field in my UserProfile model, so any user is able to upload his photo. I was thinking that all I need is ModelForm for the UserProfile, but without User specified it will fail, of course. But if I pass the request.user as a paramete...
How to upload photo into UserProfile for specified user in django?
I have a photo field in my UserProfile model, so any user is able to upload his photo. I was thinking that all I need is ModelForm for the UserProfile, but without User specified it will fail, of course. But if I pass the request.user as a parameter into a form constructor - it won't work, too, because of the thing tha...
[ "You need to pass it an instance of a UserProfile to update.\nuploadform = ProfileUploadPhotoForm(request.POST, request.FILES,\\\n instance=request.user.userprofile)\n\nif uploadform.is_valid():\n uploadform.save()\n\n", "Problem solved!\nI forgot to add \nenctype=\"multipart/form-data\"\n\nin form attribut...
[ 1, 0 ]
[]
[]
[ "django", "forms", "python", "upload" ]
stackoverflow_0005183253_django_forms_python_upload.txt
Q: 2D mutable iterator/generator I have a NxN matrix which I want to split into non-overlap KxK block. For each block, I want to assign new values to the elements. Since this looks like a good place for a generator, I implemented: def extracted_patches(im, top_left, patch_size, grid_size): '''Extract patches in r...
2D mutable iterator/generator
I have a NxN matrix which I want to split into non-overlap KxK block. For each block, I want to assign new values to the elements. Since this looks like a good place for a generator, I implemented: def extracted_patches(im, top_left, patch_size, grid_size): '''Extract patches in row-major order following a specific...
[ "As with any variables holding a numpy array, to change the value \"pointed to\" you want to avoid assigning to the variable but assign to a slice of it. Try this:\nfor submat in output_im_it:\n submat[:] = np.random.random(patch_size)\n\nAs a response to your edit: it seems you have confused the generator obje...
[ 2 ]
[]
[]
[ "generator", "image", "iterator", "numpy", "python" ]
stackoverflow_0005184462_generator_image_iterator_numpy_python.txt
Q: Save JSON outputted from a URL to a file How would I save JSON outputted by an URL to a file? e.g from the Twitter search API (this http://search.twitter.com/search.json?q=hi) Language isn't important. edit // How would I then append further updates to EOF? edit 2// Great answers guys really, but I accepted the o...
Save JSON outputted from a URL to a file
How would I save JSON outputted by an URL to a file? e.g from the Twitter search API (this http://search.twitter.com/search.json?q=hi) Language isn't important. edit // How would I then append further updates to EOF? edit 2// Great answers guys really, but I accepted the one I thought was the most elegant.
[ "This is easy in any language, but the mechanism varies. With wget and a shell:\nwget 'http://search.twitter.com/search.json?q=hi' -O hi.json\n\nTo append:\nwget 'http://search.twitter.com/search.json?q=hi' -O - >> hi.json\n\nWith Python:\nurllib.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json')...
[ 29, 8, 7, 4, 3, 1, 1 ]
[]
[]
[ "bash", "java", "perl", "python", "ruby" ]
stackoverflow_0003040904_bash_java_perl_python_ruby.txt
Q: Import a dictionary into the current scope as variables I have a .mat file in which I put data previously processed. When I perform dict = scipy.io.loadmat('training_data.mat') I get back a dict that is like this {'encoders' : ......, 'decoders' : ........, 'stuff' : .....} I want to selectively import the encod...
Import a dictionary into the current scope as variables
I have a .mat file in which I put data previously processed. When I perform dict = scipy.io.loadmat('training_data.mat') I get back a dict that is like this {'encoders' : ......, 'decoders' : ........, 'stuff' : .....} I want to selectively import the encoders and decoders variables into my current scope. The effect ...
[ "You could import a dictionary d into the global scope using\nglobals().update(d)\n\nThe same thing is impossible for local scopes, since modifying the dictionary returned by locals() results in undefined behaviour.\nA slightly hacky trick you could use in this situation is to import the names into the dictionary o...
[ 3 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0005185054_numpy_python_scipy.txt
Q: Python: Get item from list based on input I appreciate this may not be directly possible so I would be interested how you would go about solving this problem for a general case. I have a list item that looks like this, [(array,time),(array,time)...] the array is a numpy array which can have any n by m dimensions. ...
Python: Get item from list based on input
I appreciate this may not be directly possible so I would be interested how you would go about solving this problem for a general case. I have a list item that looks like this, [(array,time),(array,time)...] the array is a numpy array which can have any n by m dimensions. This will look like array[[derivatives dimensio...
[ "If I'm understanding your question correctly, you essentially want to select indexes from a list of lists, and create new lists from that selection.\nSelecting indexes from a list of lists is fairly simple, particularly if you have a fixed number of selections:\nparts = [(item[pos1], item[pos2]) for item in list]\...
[ 1, 0 ]
[]
[]
[ "list", "numpy", "python" ]
stackoverflow_0005184817_list_numpy_python.txt
Q: Scanning for thread violations with Tkinter We are just about to finish a very large update to our application which is built with python2.5 and Tkinter and the following error has crept in sadly: alloc: invalid block: 06807CE7: 1 0 0 This application has requested the Runtime to terminate it in an unusual way. P...
Scanning for thread violations with Tkinter
We are just about to finish a very large update to our application which is built with python2.5 and Tkinter and the following error has crept in sadly: alloc: invalid block: 06807CE7: 1 0 0 This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for ...
[ "I don't know if your approach is good, as I don't know Tkinter.\nBut here's a sample of how to decorate all class methods using a metaclass.\nimport functools\n\n# This is the decorator\ndef my_decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n print 'calling', func.__name__, ...
[ 1, 0 ]
[]
[]
[ "multithreading", "python", "tkinter" ]
stackoverflow_0005177290_multithreading_python_tkinter.txt
Q: why doesn't line.split('\s') do the same as line.split()? I have a very very simple program that parses a csv file that has rows of text records whose columns are separated by a single tab character. I understand split() by default splits on whitespace so explicitly specifying a whitespace pattern isn't needed, bu...
why doesn't line.split('\s') do the same as line.split()?
I have a very very simple program that parses a csv file that has rows of text records whose columns are separated by a single tab character. I understand split() by default splits on whitespace so explicitly specifying a whitespace pattern isn't needed, but my question is why won't an explicitly specified pattern for ...
[ "Because \\t really represents a tab character in a string (like \\n is the new line character, see here a list of valid escape sequences), but \\s is a special regular expression character class for white spaces.\nstr.split[docs] does not accept regular expressions. If you want to split with regular expressions, y...
[ 10, 1, 1 ]
[]
[]
[ "python", "split" ]
stackoverflow_0005185685_python_split.txt
Q: Migrating to pip+virtualenv from setuptools So pip and virtualenv sound wonderful compared to setuptools. Being able to uninstall would be great. But my project is already using setuptools, so how do I migrate? The web sites I've been able to find so far are very vague and general. So here's an anthology of questi...
Migrating to pip+virtualenv from setuptools
So pip and virtualenv sound wonderful compared to setuptools. Being able to uninstall would be great. But my project is already using setuptools, so how do I migrate? The web sites I've been able to find so far are very vague and general. So here's an anthology of questions after reading the main web sites and trying s...
[ "Wow, that's quite a set of questions. Many of them would really deserve their own SO question with more details. I'll do my best:\n\nFirst of all, are virtualenv and pip\n supposed to be in a usable state by\n now?\n\nYes, although they don't serve everyone's needs. Pip and virtualenv (along with everything else...
[ 22, 4 ]
[]
[]
[ "matplotlib", "packaging", "pip", "python", "virtualenv" ]
stackoverflow_0004981174_matplotlib_packaging_pip_python_virtualenv.txt
Q: How can I let android emulator talk to the localhost? I'm running an android app on the emulator. This app tries to load a html file using the webview api. I also have a simple http server running on the same computer under the directory where I want to serve the request using the following python command: python ...
How can I let android emulator talk to the localhost?
I'm running an android app on the emulator. This app tries to load a html file using the webview api. I also have a simple http server running on the same computer under the directory where I want to serve the request using the following python command: python -m SimpleHTTPServer 800 However, I couldn't access this lin...
[ "Use address 10.0.2.2 instead of localhost.\n", "localhost is a short-cut to tell the \"whatever\" to talk to itself. So, you are telling the emulator to look for a web server running in the emulator.\nInstead of trying to connect to localhost, look up the IP for your computer and use that instead.\n", "Actuall...
[ 16, 0, 0 ]
[ "Best solution is not to use emulator at all. Its slow and full of bugs. Get your employer to buy a device or two.\n" ]
[ -2 ]
[ "android", "android_emulator", "python", "webview" ]
stackoverflow_0005185016_android_android_emulator_python_webview.txt
Q: Python reading 2 strings from the same line how can I read once at a time 2 strings from a txt file, that are written on the same line? e.g. francesco 10 A: Why not read just the line and split it up later? You'd have to read byte-by-byte and look for the space character, which is very inefficient. Better to re...
Python reading 2 strings from the same line
how can I read once at a time 2 strings from a txt file, that are written on the same line? e.g. francesco 10
[ "Why not read just the line and split it up later? You'd have to read byte-by-byte and look for the space character, which is very inefficient. Better to read the entire line, and then split the resulting string on the space, giving you two strings.\n", "# out is your file\nout.readline().split() # result is ['fr...
[ 1, 1, 0, 0 ]
[]
[]
[ "file", "python", "readline" ]
stackoverflow_0005185444_file_python_readline.txt
Q: Ctrl-C doesn't work with PyQt Why doesn't Ctrl+C work to break a Python program that uses PyQt? I want to debug it and get a stack trace and for some reason, this is harder to do than with C++! A: CTRL+C causes a signal to be sent to the process. Python catches the signal, and sets a global variable, some...
Ctrl-C doesn't work with PyQt
Why doesn't Ctrl+C work to break a Python program that uses PyQt? I want to debug it and get a stack trace and for some reason, this is harder to do than with C++!
[ "\nCTRL+C causes a signal to be sent to\n the process. Python catches the\n signal, and sets a global variable,\n something like CTRL_C_PRESSED = True.\n Then, whenever the Python interpreter\n gets to execute a new opcode, it sees\n the variable set and raises a\n KeybordInterrupt.\nThis means that CTRL+C w...
[ 41, 4 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0005160577_pyqt_python.txt
Q: download file in python when i want download jpeg in python with this code: def download(url, dest): s = urllib2.urlopen(url) content = s.read() s.close() d = open(dest,'w') d.write(content) d.close() the file on hdd is not readable but when i open jpeg in mozilla its ok, i am using window...
download file in python
when i want download jpeg in python with this code: def download(url, dest): s = urllib2.urlopen(url) content = s.read() s.close() d = open(dest,'w') d.write(content) d.close() the file on hdd is not readable but when i open jpeg in mozilla its ok, i am using windows and python 2.6 some solutio...
[ "You are opening the file in text mode and corrupting it. Python is interpreting certain byte sequences as EOL characters and writing them out as the appropriate EOL for that operating system. You need to tell Python to open the destination file in binary mode.\nChange d = open(dest,'w') to d = open(dest,'wb') and...
[ 8, 6, 5 ]
[]
[]
[ "download", "python" ]
stackoverflow_0005186389_download_python.txt
Q: Segmentation Fault (11) on httpd when python-ldap is initialized I'm using mod_wsgi for a Django application (OSQA) on RHEL 5 with Python 2.43 (cannot upgrade). I had the site set up and working fine, and then tried to integrate the authentication with python-ldap for accessing Active Directory attributes e.g. a u...
Segmentation Fault (11) on httpd when python-ldap is initialized
I'm using mod_wsgi for a Django application (OSQA) on RHEL 5 with Python 2.43 (cannot upgrade). I had the site set up and working fine, and then tried to integrate the authentication with python-ldap for accessing Active Directory attributes e.g. a user's name, email address etc. Apache httpd crashes with the following...
[ "Try disabling any Apache modules for auth which use LDAP. Also try disabling mod_php if being used and it is loading a LDAP extension. In short, library version conflict may be because of LDAP libraries rather than expat, so disable the other Apache modules and see if problem goes away. That will narrow it down.\n...
[ 1 ]
[]
[]
[ "apache", "expat_parser", "mod_wsgi", "python", "python_ldap" ]
stackoverflow_0005181181_apache_expat_parser_mod_wsgi_python_python_ldap.txt
Q: Add content inside html body tag i created a python script with the help of BeautifulSoup and i can get some content from a web site. Now i want with this script to place the code inside the body tag of an html file. How am i gonna do that ? thnx A: soup = BeautifulSoup(your_old_html) soup.body.insert(0, your...
Add content inside html body tag
i created a python script with the help of BeautifulSoup and i can get some content from a web site. Now i want with this script to place the code inside the body tag of an html file. How am i gonna do that ? thnx
[ "soup = BeautifulSoup(your_old_html)\nsoup.body.insert(0, your_tag)\nprint soup\n\nMore info here:\nhttp://www.crummy.com/software/BeautifulSoup/documentation.html#Adding%20a%20Brand%20New%20Element\n" ]
[ 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0005185912_beautifulsoup_python.txt
Q: Filter Foreignkey within Inlineform Hello I cant seem to filter a Foreignkey Dropdown within an Inline form. These are my classes: class Author(models.Model): name = models.CharField(max_length=50) desc = models.CharField(max_length=50) class Book(models.Model): author = models.ForeignKey(Author) ...
Filter Foreignkey within Inlineform
Hello I cant seem to filter a Foreignkey Dropdown within an Inline form. These are my classes: class Author(models.Model): name = models.CharField(max_length=50) desc = models.CharField(max_length=50) class Book(models.Model): author = models.ForeignKey(Author) title= models.CharField(max_length=50) ...
[ "I'm a little confused by your question but found it interesting. \nYou want the author dropdown on the inlines to be the selected author -- so the inline will always only have 1 choice, the current author?\nWell, normally you'd use formfield_for_foreignkey\nhttp://docs.djangoproject.com/en/dev/ref/contrib/admin/#d...
[ 7 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0005185808_django_django_admin_python.txt
Q: PyQt signal with arguments of arbitrary type / PyQt_PyObject equivalent for new-style signals I have an object that should signal that a value has changed by emitting a signal with the new value as an argument. The type of the value can change, and so I'm unsure of how to write the signal type. I know that I can a...
PyQt signal with arguments of arbitrary type / PyQt_PyObject equivalent for new-style signals
I have an object that should signal that a value has changed by emitting a signal with the new value as an argument. The type of the value can change, and so I'm unsure of how to write the signal type. I know that I can acconmplish this using old-style signals like this: self.emit(SIGNAL("valueChanged(PyQt_PyObject)"),...
[ "First, the object you're emitting from needs the signal defined as an attribute of its class:\nclass SomeClass(QObject):\n valueChanged = pyqtSignal(object) \n\nNotice the signal has one argument of type object, which should allow anything to pass through. Then, you should be able to emit the signal from withi...
[ 23, 6 ]
[]
[]
[ "pyqt", "python", "qt", "signals" ]
stackoverflow_0004523006_pyqt_python_qt_signals.txt
Q: Python GUI does not Close Child Process My work asked me to port our program (that someone else wrote) from Windows to Linux. I have been able to successfully run the Python script and the executable program that the Python script calls in Linux. The Python script creates a GUI, and the script uses the following ...
Python GUI does not Close Child Process
My work asked me to port our program (that someone else wrote) from Windows to Linux. I have been able to successfully run the Python script and the executable program that the Python script calls in Linux. The Python script creates a GUI, and the script uses the following command to close the GUI when the user is don...
[ "Does the external program read from stdin and then exit? If it does, does your close_application method call self.proc.stdout.close()?\nIf the external program doesn't exit automatically (e.g.: when it's done reading input or doing a simple task), then you may need to kill it explicitly with Popen.close() (Python ...
[ 0, 0 ]
[]
[]
[ "linux", "pygtk", "python" ]
stackoverflow_0005158737_linux_pygtk_python.txt
Q: python script execution through crontab what happens to my script in python that does not run through crontab every minute. My script has execute permissions and then calls two other scripts in python. This is the content of my crontab (#crontab -l): */1 * * * * /usr/bin/rsm/samplesMonitor.py Thank you guys. A:...
python script execution through crontab
what happens to my script in python that does not run through crontab every minute. My script has execute permissions and then calls two other scripts in python. This is the content of my crontab (#crontab -l): */1 * * * * /usr/bin/rsm/samplesMonitor.py Thank you guys.
[ "Check /var/log/syslog for errors.\nDIAGNOSTICS\n cron requires that each entry in a crontab end in a \n newline character. If the last entry in a crontab is \n missing a newline (ie, terminated by EOF), cron will \n consider the crontab (at least partially) broken. A \n warning wil...
[ 4, 1, 0, 0 ]
[]
[]
[ "cron", "crontab", "execution", "python" ]
stackoverflow_0005174080_cron_crontab_execution_python.txt
Q: Python Property Change Listener Pattern Anyone know of any easy way to track changes to a dictionary object in python? I am at a high level doing crud, so I have a couple methods that handle changing a dictionary, if the dictionary changes I want to call a function to basically do an Observer/Notify. class MyC...
Python Property Change Listener Pattern
Anyone know of any easy way to track changes to a dictionary object in python? I am at a high level doing crud, so I have a couple methods that handle changing a dictionary, if the dictionary changes I want to call a function to basically do an Observer/Notify. class MyClass(object): def update(self, item): ...
[ "You can derive from the dict class and add a callback on any changes. This requires to overwrite any methods that change the dictionary:\nclass NotifyDict(dict):\n __slots__ = [\"callback\"]\n def __init__(self, callback, *args, **kwargs):\n self.callback = callback\n dict.__init__(self, *args...
[ 15, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005186520_python.txt
Q: Sending custom PyQt signals? I'm practicing PyQt and (Q)threads by making a simple Twitter client. I have two Qthreads. Main/GUI thread. Twitter fetch thread - fetches data from Twitter every X minutes. So, every X minutes my Twitter thread downloads a new set of status updates (a Python list). I want to hand th...
Sending custom PyQt signals?
I'm practicing PyQt and (Q)threads by making a simple Twitter client. I have two Qthreads. Main/GUI thread. Twitter fetch thread - fetches data from Twitter every X minutes. So, every X minutes my Twitter thread downloads a new set of status updates (a Python list). I want to hand this list over to the Main/GUI threa...
[ "You can also do this, which is much more pythonic (and readable!).\n# create a signal equivalent to \"void someSignal(int, QWidget)\"\nsomeSignal = QtCore.pyqtSignal(int, QtGui.QWidget)\n\n# define a slot with the same signature\n@QtCore.pyqtSlot(int, QtGui.QWidget)\ndef someSlot(status, source):\n pass\n\n# co...
[ 28, 7, 7, 7, 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qthread" ]
stackoverflow_0002585442_pyqt_pyqt4_python_qthread.txt
Q: mod_python equivalent to php exec() command what is the mod_python equivalent to the php exec command? $cmd = '/var/www/scripts/test.py' + $parameter $return = exec($cmd) I've tried this but it doesn't return anything varReturn= subprocess.check_output(['/var/www/scripts/resolveID.py ', varParameters) A: Captur...
mod_python equivalent to php exec() command
what is the mod_python equivalent to the php exec command? $cmd = '/var/www/scripts/test.py' + $parameter $return = exec($cmd) I've tried this but it doesn't return anything varReturn= subprocess.check_output(['/var/www/scripts/resolveID.py ', varParameters)
[ "Capture the stdout and stderr of the subprocess:\nfrom subprocess import Popen, PIPE\n\nproc = Popen(['/var/www/scripts/resolveId.py', 'arg1', 'arg2'], stdout=PIPE, stderr=PIPE)\nstdout, stderr = proc.communicate()\n\n" ]
[ 1 ]
[]
[]
[ "exec", "mod_python", "php", "python" ]
stackoverflow_0005185958_exec_mod_python_php_python.txt
Q: Python Question about Variable Scope Rules This is a source code for Quicksort in Python I found on Wikipedia. def pivot(v, left, right): i = left for j in range(left + 1, right + 1): if v[j] < v[left]: i += 1 # .. incrementa-se i v[i], v[j] = v[j], v[i] v[i], v[left] = v...
Python Question about Variable Scope Rules
This is a source code for Quicksort in Python I found on Wikipedia. def pivot(v, left, right): i = left for j in range(left + 1, right + 1): if v[j] < v[left]: i += 1 # .. incrementa-se i v[i], v[j] = v[j], v[i] v[i], v[left] = v[left], v[i] return i def qsort(v, left, ri...
[ "It doesn't rebind a/v, it merely mutates it. You don't need to declare a name global if you're mutating the object it's bound to.\n", "In python a is passed by \"alias\" (See Jochen's comment below). Therefore, Any modifications to v will be relflected in a.\nEDIT: I fixed my wording thanks to the comments belo...
[ 6, 2, 0, 0 ]
[]
[]
[ "python", "quicksort", "scope" ]
stackoverflow_0005008191_python_quicksort_scope.txt
Q: How to write formulas contained many constants in a function while keeping their names meaningful without using global variables? I have a function which should be solved using ode solver. The problems is that it has many constants (say 100) and at the same time I don't want to put them in an array because it woul...
How to write formulas contained many constants in a function while keeping their names meaningful without using global variables?
I have a function which should be solved using ode solver. The problems is that it has many constants (say 100) and at the same time I don't want to put them in an array because it would be hard to understand the formulas (which are chemical stuff). Some part of my code in this function looks like: # Component: Calciu...
[ "On second thought, why not just use global variables? It will give you a pretty, simple, and fast result. In python globals will be restricted to the module they are defined in, so you don't have to worry about them polluting the entire program as they would in say C.\n", "If you want to avoid polluting the na...
[ 2, 1, 1 ]
[]
[]
[ "chemistry", "python" ]
stackoverflow_0005186922_chemistry_python.txt
Q: Call subprocess.Popen() when the working directory is on a UNC path, not a mapped drive I would like to run an executable that performs some processing on a dataset located on a remote filer. As part of the design, I'd like the location of the filer to be flexible and something that's passed to my python program a...
Call subprocess.Popen() when the working directory is on a UNC path, not a mapped drive
I would like to run an executable that performs some processing on a dataset located on a remote filer. As part of the design, I'd like the location of the filer to be flexible and something that's passed to my python program at runtime. I've put together the following bit of code that illustrates my problem, but using...
[ "The problem is not with Popen,, but with cmd.exe, which does not allow the working directory to be a UNC path. It just does not; try it. You may have better luck specifying shell=False on your Popen() call, assuming that whatever executable you're running can handle a UNC path, but of course if what you're trying ...
[ 6 ]
[]
[]
[ "python", "subprocess", "unc", "windows" ]
stackoverflow_0005187160_python_subprocess_unc_windows.txt
Q: Python: How to add a prefix to tags in an xml.etree.ElementTree I use the python asciimathml library to parse some asciimathml and convert it to MathML >>> from xml.etree.ElementTree import tostring >>> tostring(asciimathml.parse('sqrt 2')) '<math><mstyle><msqrt><mn>2</mn></msqrt></mstyle></math>' The only troubl...
Python: How to add a prefix to tags in an xml.etree.ElementTree
I use the python asciimathml library to parse some asciimathml and convert it to MathML >>> from xml.etree.ElementTree import tostring >>> tostring(asciimathml.parse('sqrt 2')) '<math><mstyle><msqrt><mn>2</mn></msqrt></mstyle></math>' The only trouble is I need my tags with a m: prefix. How do I change above code so I...
[ "You can rename the tag, adding the 'm:' prefix:\nimport asciimathml\nfrom xml.etree.ElementTree import tostring\n\ntree = asciimathml.parse('sqrt 2')\nfor elem in tree.getiterator():\n elem.tag = 'm:' + elem.tag\n\nprint tostring(tree)\n\nResult:\n<m:math><m:mstyle><m:msqrt><m:mn>2</m:mn></m:msqrt></m:mstyle></...
[ 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0005183343_python_xml.txt
Q: Django inheritance Please have a look: class Categorie(models.Model): id = models.AutoField('id', primary_key=True) title = models.CharField('title', max_length=800) articles = models.ManyToManyField(Article) class Article(models.Model): id = models.AutoField('id', primary_key=True) title ...
Django inheritance
Please have a look: class Categorie(models.Model): id = models.AutoField('id', primary_key=True) title = models.CharField('title', max_length=800) articles = models.ManyToManyField(Article) class Article(models.Model): id = models.AutoField('id', primary_key=True) title = models.CharField('titl...
[ "I'll start by saying that you don't need to define the 'id' field, if you don't define it then Django will add it automatically.\nSecondly, the CookRecette and NewsPaper objects are not linked to the Categorie object by any means (ForeignKey, OneToOne, OneToMany, ManyToMany) so they wouldn't be able to be accessed...
[ 1, 0 ]
[]
[]
[ "django", "model_inheritance", "python" ]
stackoverflow_0005186990_django_model_inheritance_python.txt
Q: Getting current time with timezone in python? I'm using Google App Engine with python. And I can't install third party library. I though this should work, but it actually runs without error but it returns current time timezone is not applied. What did I do wrong? from datetime import tzinfo, timedelta, datetime ...
Getting current time with timezone in python?
I'm using Google App Engine with python. And I can't install third party library. I though this should work, but it actually runs without error but it returns current time timezone is not applied. What did I do wrong? from datetime import tzinfo, timedelta, datetime class Seoul_tzinfo(tzinfo): def utcoffset(self,...
[ "You need to implement a tzinfo class with ALL the proper methods to do what you want to do.\nThe documentation says that tzinfo is an abstract class that if to be used with datetime objects needs to be made a concrete class with proper methods.\nSpecifically take a look at this from the documentation:\nclass Fixed...
[ 3, 3, 1 ]
[]
[]
[ "google_app_engine", "python", "timezone" ]
stackoverflow_0005180889_google_app_engine_python_timezone.txt
Q: How to obtain the root of a tree without parsing the entire file? I'm making an xml parser to parse xml reports from different tools, and each tool generates different reports with different tags. For example: Arachni generates an xml report with <arachni_report></arachni_report> as tree root tag. nmap generates a...
How to obtain the root of a tree without parsing the entire file?
I'm making an xml parser to parse xml reports from different tools, and each tool generates different reports with different tags. For example: Arachni generates an xml report with <arachni_report></arachni_report> as tree root tag. nmap generates an xml report with <nmaprun></nmaprun> as tree root tag. I'm trying not ...
[ "\"simple string methods\" are the root [pun intended] of all evil -- see examples below.\nUpdate 2 Code and output now show that proposed regexes also don't work very well.\nUse ElementTree. The function that you are looking for is iterparse. Enable \"start\" events. Bale out on the first iteration.\nCode:\n# codi...
[ 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "celementtree", "elementtree", "python" ]
stackoverflow_0005160965_celementtree_elementtree_python.txt
Q: Extract domain from body of email I was wondering if there is any way I could extract domain names from the body of email messages in python. I was thinking of using regular expressions, but I am not too great in writing them, and was wondering if someone could help me out. Here's a sample email body: <tr><td cols...
Extract domain from body of email
I was wondering if there is any way I could extract domain names from the body of email messages in python. I was thinking of using regular expressions, but I am not too great in writing them, and was wondering if someone could help me out. Here's a sample email body: <tr><td colspan="5"><font face="verdana" size="4" c...
[ "The cleanest way to do it is with cssselect from lxml.html and urlparse. Here is how:\nfrom lxml import html\nfrom urlparse import urlparse\ndoc = html.fromstring(html_data)\nlinks = doc.cssselect(\"a\")\ndomains = set([])\nfor link in links:\n try: href=link.attrib['href']\n except KeyError: continue\n p...
[ 2, 1, 1, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005185944_python_regex.txt
Q: Trying to parse HTML using BeautifulSoup, but it not working? I have to parse this HTML: <a href="rtsp://v8.cache2.c.youtube.com/CjgLENy73wIaLwnqnxbpjjoGIRMYESARFEIJbXYtZ29vZ2xlSARSB3Jlc3VsdHNgpq6joefRgbhNDA==/0/0/0/video.3gp"><img src="http://i.ytimg.com/vi/IQY6jukWn-o/default.jpg?w=80&amp;h=60&amp;sigh=izeIwhz4P...
Trying to parse HTML using BeautifulSoup, but it not working?
I have to parse this HTML: <a href="rtsp://v8.cache2.c.youtube.com/CjgLENy73wIaLwnqnxbpjjoGIRMYESARFEIJbXYtZ29vZ2xlSARSB3Jlc3VsdHNgpq6joefRgbhNDA==/0/0/0/video.3gp"><img src="http://i.ytimg.com/vi/IQY6jukWn-o/default.jpg?w=80&amp;h=60&amp;sigh=izeIwhz4POtPOOr-jRGrtC4qiFA" alt="video" width="80" height="60" style="borde...
[ "When you search for text you are looking for all of the NavigableString objects that match your regular expression (Which is looking for any character followed by a 3, a g and a b -- use \\.3agb if you want to match .3agb literally with a regex).\nUse soup.findAll and search for any <a> tags with an href that matc...
[ 2, 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0005187648_beautifulsoup_python.txt
Q: Python list IndexError with transfering lists to objects So I'm working on an assignment, and I've come to a obstacle I can't seem to overcome. I'm essentially designing a rudimentary Library System. I have to read in from a file the books, librarians, and patrons and parse them in to lists then to objects. I've g...
Python list IndexError with transfering lists to objects
So I'm working on an assignment, and I've come to a obstacle I can't seem to overcome. I'm essentially designing a rudimentary Library System. I have to read in from a file the books, librarians, and patrons and parse them in to lists then to objects. I've gotten the parsing to lists part down and have them ready to be...
[ "The problem is that you are assigning empty lists during every iteration. When you call ISBN[i] the list always has only one element. Therefore it fails as soon as i becomes larger than zero.\nOne way to fix it is to notice that you don't need the lists at all:\ndef _addToCollection(self):\n i = 0\n while i ...
[ 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005187919_list_python.txt
Q: I am not using QPixmap, in PyQt. but I get QPixmap: It is not safe to use pixmaps outside the GUI thread in PyQt I am using PyQt for a project. But not all of a sudden I am getting an error: QPixmap: It is not safe to use pixmaps outside the GUI thread in PyQt I am not using QPixmap anywhere in my code... pleas...
I am not using QPixmap, in PyQt. but I get QPixmap: It is not safe to use pixmaps outside the GUI thread in PyQt
I am using PyQt for a project. But not all of a sudden I am getting an error: QPixmap: It is not safe to use pixmaps outside the GUI thread in PyQt I am not using QPixmap anywhere in my code... please help. class itemCheckBtn(QtGui.QDialog): qApp = None; okCallback = None; def __init__(self,parent=None): itemChe...
[ "It looks like you are using threads, and somehow you are trying to change the GUI from some thread other than the main GUI thread (this is not allowed). This could be happening somewhat indirectly--for example your server thread calls a function on MyForm, which tries to update the itemCheckBtn. Even though the co...
[ 3 ]
[]
[]
[ "pyqt", "python", "qpixmap" ]
stackoverflow_0005187608_pyqt_python_qpixmap.txt
Q: Python 2.5 script to connect to FTP and download file I am sure this has been resolved before but I cannot seem to find a similar Q&A (newbie) Using Windows XP and Python 2.5, I m trying to use a script to connect to an FTP server and dowload files. It should be simple but following the instructions of similar scr...
Python 2.5 script to connect to FTP and download file
I am sure this has been resolved before but I cannot seem to find a similar Q&A (newbie) Using Windows XP and Python 2.5, I m trying to use a script to connect to an FTP server and dowload files. It should be simple but following the instructions of similar scripts I get the errors: ftp.login('USERNAME') File "C:\Pyt...
[ "I can't understand which library are you using. Python standard urllib2 is sufficient:\nimport urllib2, shutil\n\nftpfile = urllib2.urlopen(\"ftp://host.example.com/path/to/file\")\nlocalfile = open(\"/tmp/downloaded\", \"wb\")\nshutil.copyfileobj(ftpfile, localfile)\n\nIf you need to login (anonymous login isn't ...
[ 5, 4 ]
[ "the first trivial check would be to open an interactive session (i.e. ftp yourself to this server with the same credentials), to be sure that this is not a permission issue..\nAnother source of failure, you might need to give your username as domain\\username when connecting to a MS ftp server.\nMaybe that helps ?...
[ -1 ]
[ "ftp", "python" ]
stackoverflow_0005116491_ftp_python.txt
Q: Confusion about Python variable scope I came across some code which kind of puzzled me. Here's a minimal example which shows this: # of course, the ... are not part of the actual code some_var = {"key1":"value1" ... "keyN":"valueN"} def some_func(): v = some_var["key1"] The code works, but the fact that I can...
Confusion about Python variable scope
I came across some code which kind of puzzled me. Here's a minimal example which shows this: # of course, the ... are not part of the actual code some_var = {"key1":"value1" ... "keyN":"valueN"} def some_func(): v = some_var["key1"] The code works, but the fact that I can access some_var directly confuses me. The ...
[ "No, you just can't reassign some_var in a local scope. Consider the following:\nsome_var = {}\ndef some_func():\n # some_var[5] = 6\n some_var = {1:2}\n some_var[3] = 4\nsome_func()\nprint (repr(some_var)) # {}\n\nYou'll see the assignment in some_func actually creates a local variable which shadows the g...
[ 6, 3, 3, 2, 1, 1 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0005184117_python_scope.txt
Q: Merge and sync stdout and stderr? say I'm running an exe from a python script using: subprocess.call(cmdArgs,stdout=outf, stderr=errf) when outf and errf are file descriptors of text files. is there any way I can generate on top of it a merged and synced text file of both stdout and stderr? it should be formatted...
Merge and sync stdout and stderr?
say I'm running an exe from a python script using: subprocess.call(cmdArgs,stdout=outf, stderr=errf) when outf and errf are file descriptors of text files. is there any way I can generate on top of it a merged and synced text file of both stdout and stderr? it should be formatted with time and source(our/err). thanks
[ "It is a bit tricky, since you need to poll the stdout and stderr file descriptors of the subprocess while it's running, to get accurate timestamps. You also need to chop up the output into a list of lines so the final results can be merged and sorted easily. You could easily merge the two streams as they're read, ...
[ 4, 1 ]
[]
[]
[ "python", "stderr", "stdout", "subprocess" ]
stackoverflow_0004984549_python_stderr_stdout_subprocess.txt
Q: Unable to get Wacom events from /dev/input/event* I have created a pygtk program to monitor the keyboard status and mouse clicks across any application (i.e. not just for my application). This uses evdev by Micah Dowty which basically monitors /dev/input/event* for output and decodes the information in a way that ...
Unable to get Wacom events from /dev/input/event*
I have created a pygtk program to monitor the keyboard status and mouse clicks across any application (i.e. not just for my application). This uses evdev by Micah Dowty which basically monitors /dev/input/event* for output and decodes the information in a way that I can display the information to the user. The program ...
[ "This is due to X that take the full control of your input device, you can't read event yourself. You might have one of theses 2 issues :\n\nA \"catchall\" is actually getting your device.\nIn your /var/log/Xorg.0.log, you should see a line like :\nStantum MTP USB Controller: Applying InputClass \"evdev touchscreen...
[ 0 ]
[]
[]
[ "linux", "pygtk", "python", "wacom" ]
stackoverflow_0001860668_linux_pygtk_python_wacom.txt
Q: Python & memory mapping? Using a Linux machine, how many files can one 'mmap' using python (what is the limit)? Thanks. A: There's multiple limits in play. The first is the system-wide open files limit, /proc/sys/fs/nr_open. This is typically in the million-range. This limit may continue to be counted against pr...
Python & memory mapping?
Using a Linux machine, how many files can one 'mmap' using python (what is the limit)? Thanks.
[ "There's multiple limits in play. The first is the system-wide open files limit, /proc/sys/fs/nr_open. This is typically in the million-range.\nThis limit may continue to be counted against processes that open the file, set up the mapping, then close the file again.\nThe second is the per-process getrlimit(2) RLIMI...
[ 4, 1 ]
[]
[]
[ "linux", "python", "ubuntu" ]
stackoverflow_0005188423_linux_python_ubuntu.txt
Q: Python: Is there a way to generate xsd files based on xml examples I have a list of xml examples I would like to turn into schemas (xsd files). Exactly what the trang tool does (http://www.thaiopensource.com/relaxng/trang.html). I don't like calling trang from my script (i.e doing os.system('java -jar trang...')) ...
Python: Is there a way to generate xsd files based on xml examples
I have a list of xml examples I would like to turn into schemas (xsd files). Exactly what the trang tool does (http://www.thaiopensource.com/relaxng/trang.html). I don't like calling trang from my script (i.e doing os.system('java -jar trang...')) - is there a python package I can use instead?
[ "If you are running Jython (http://jython.org/) then you could import trang and run it internally.\n" ]
[ 0 ]
[]
[]
[ "python", "xml", "xsd" ]
stackoverflow_0003849632_python_xml_xsd.txt
Q: mechanize opening multiple pages I am using mechanize and beautifulsoup to create a python script to pull some data from a web page. The scraping works fine but the problem I am having is in moving to multiple pages. Is there a way to move between pages in mechanize in a loop? Here's what I tried Browser().follo...
mechanize opening multiple pages
I am using mechanize and beautifulsoup to create a python script to pull some data from a web page. The scraping works fine but the problem I am having is in moving to multiple pages. Is there a way to move between pages in mechanize in a loop? Here's what I tried Browser().follow_link(text_regex="Next") but it goes...
[ "How does your code \"just die\"? If it throws an exception, you can catch it and do something to handle it propery (inside your loop as is):\ntry:\n Browser.follow_link(text_regex=\"Next\")\nexcept Exception:\n print \"No more next button; terminating loop (but not dying mysteriously)\"\n break\n\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "mechanize", "python", "web_scraping" ]
stackoverflow_0005188518_beautifulsoup_mechanize_python_web_scraping.txt
Q: python, if condition on methods i have two methods New() and Edit() and another method make() that has some statements.. New() and Edit() both call make(), however there are some statements i would like to skip in make() if the calling method is new(). Take an example below def new(): make() def edit(): make(...
python, if condition on methods
i have two methods New() and Edit() and another method make() that has some statements.. New() and Edit() both call make(), however there are some statements i would like to skip in make() if the calling method is new(). Take an example below def new(): make() def edit(): make() def make(): statement 1 stat...
[ "Yes — put statement 3 in edit(). \nAlternatively, if you want other things to be able to call make() and execute statement 3, use keyword arguments to specify a default behaviour:\ndef new():\n make(skip=True)\n\ndef edit():\n make()\n # OR: make(skip=False)\n\ndef make(skip=False):\n statement 1\n statement ...
[ 4 ]
[]
[]
[ "if_statement", "methods", "python" ]
stackoverflow_0005188800_if_statement_methods_python.txt
Q: Python 2.6.2, Django 1.0.3, Windows XP, Page not found: / I'm just starting to learn Python and Django and an unable to get the most basic app working. I've setup Python, added python to the Path environment variable, installed Django using install.py script. I created an app by running the command django-admin.p...
Python 2.6.2, Django 1.0.3, Windows XP, Page not found: /
I'm just starting to learn Python and Django and an unable to get the most basic app working. I've setup Python, added python to the Path environment variable, installed Django using install.py script. I created an app by running the command django-admin.py startproject my_project updated the settings.py file for a d...
[ "To complete this question - @artran's answer of changing the port \npython manage.py runserver 8001\n\nwill work. \nWhen python runs the server, it automatically uses port 8000 (hence http://127.0.0.1:8000/). It uses this port as to not tread on the toes of other applications using localhost ports. However, you ma...
[ 2, 0, 0 ]
[]
[]
[ "django", "python", "windows" ]
stackoverflow_0001527678_django_python_windows.txt
Q: Finding a book's subject using Amazon AWS API I'm using PyAWS to access Amazon's API. I'm trying to get a book's subject. I know it has something to do with BrowseNode* but not sure how to access it. A: I don't know PyAWS but regardless, you probably want to figure out the actual response group and node you need...
Finding a book's subject using Amazon AWS API
I'm using PyAWS to access Amazon's API. I'm trying to get a book's subject. I know it has something to do with BrowseNode* but not sure how to access it.
[ "I don't know PyAWS but regardless, you probably want to figure out the actual response group and node you need for this. \nhttp://docs.amazonwebservices.com/AWSECommerceService/2010-11-01/DG/\nIf by subject, you mean a description of what it's about, the closest I can find to this at a quick glance is the MediumR...
[ 1 ]
[]
[]
[ "amazon_web_services", "python" ]
stackoverflow_0005188932_amazon_web_services_python.txt
Q: Is there any working example of "pytap" TAP emitter for Python if we look at like in example 3: #TEST SOME STUFF from TAP.Simple import * plan(3) def in_between(value, bottom, top, msg): ret = ok(((bottom = value) and (value = top)), msg) if (not ret): diag("value %s is not between %s and %s" % (...
Is there any working example of "pytap" TAP emitter for Python
if we look at like in example 3: #TEST SOME STUFF from TAP.Simple import * plan(3) def in_between(value, bottom, top, msg): ret = ok(((bottom = value) and (value = top)), msg) if (not ret): diag("value %s is not between %s and %s" % (value, bottom, top)) return ret in_between(5, 3, 10, "5 is OK."...
[ "OK , i figured it out myself, by looking at perl's TAP examples, and transposing it to fit Python\n#!/usr/bin/env python\nimport TAP\n\nok = TAP.Builder.create(3).ok\ndef hello_world():\n return \"Hello, World!\"\nok(hello_world() == \"Hello, World!\", \"First Test\")\nok(hello_world() is \"Hello, World!\", \...
[ 1 ]
[]
[]
[ "python", "tap", "unit_testing" ]
stackoverflow_0005174910_python_tap_unit_testing.txt
Q: In Python what could cause a for loop to randomly go backwards in value? What can cause an iterator to go forwards in a loop, and then backwards? This is the code I'm using to loop through the table's primary key field. The primary key is being used to populate initial values in a separate table. For loop: for row...
In Python what could cause a for loop to randomly go backwards in value?
What can cause an iterator to go forwards in a loop, and then backwards? This is the code I'm using to loop through the table's primary key field. The primary key is being used to populate initial values in a separate table. For loop: for row in sampleDB.select_fromTable(): print row[0] sampleDB.insert_toTable(...
[ "I suspect the results of this code may change depending on exactly which versions of sqlite and python are used.\nNotice that your call to c.close in the select_fromTable method should be c.close(). This is a fortunate error, since you cannot iterate over the results of the query after the cursor is closed. Howeve...
[ 4 ]
[]
[]
[ "loops", "python", "sqlite" ]
stackoverflow_0005188691_loops_python_sqlite.txt
Q: why the syntax error? Why is this: # other stuff... print str(checksum)+" "+ranswer+".0000000000" giving syntax error in Python 3, even though it works fine in Python 2.5 ? ADDED: Could anybody tell me what is the equivalent of strip(something) in python 3? Thanks,its fixed now. A: print is a function in Python...
why the syntax error?
Why is this: # other stuff... print str(checksum)+" "+ranswer+".0000000000" giving syntax error in Python 3, even though it works fine in Python 2.5 ? ADDED: Could anybody tell me what is the equivalent of strip(something) in python 3? Thanks,its fixed now.
[ "print is a function in Python3. Use it is print(...)There is not anything called strip(something). But what you might looking for is `strip() method on string objects'. It is available in Python3.\nstrip(...)\n S.strip([chars]) -> str\n\n Return a copy of the string S with leading and trailing\n whitespac...
[ 4, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0005189004_python_python_3.x.txt
Q: Can't retieve a value from a C function in a Python script but can in console I am using python (Pydev) to communicate with stepper motors with a DLL using ctypes. I am trying to retrieve the position of the motor. The thing is that if I type the script in line by line in the console it works but if I run the scri...
Can't retieve a value from a C function in a Python script but can in console
I am using python (Pydev) to communicate with stepper motors with a DLL using ctypes. I am trying to retrieve the position of the motor. The thing is that if I type the script in line by line in the console it works but if I run the script it always gives me 0. This is my code: import ctypes AC=windll.hvpositionerv2 a...
[ "My best guess: this is a timing issue. After connecting to the hardware, it takes a certain amount of time before it reports the motor position, and before that first response, you will always get 0. Try adding a 1 second sleep before AC.PositionerGetPosition.\n" ]
[ 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0005118532_ctypes_python.txt
Q: cookies.sqlite encrypted on Firefox 3.6 and above? Possible Duplicate: Accessing firefox cookies.sqlite Error [Solved] I just downloaded Firefox 3.6. I have a Python script that reads my cookies.sqlite DB but it would not work after with Firefox 3.6. It kept telling me the database was encrypted. I uninstalled...
cookies.sqlite encrypted on Firefox 3.6 and above?
Possible Duplicate: Accessing firefox cookies.sqlite Error [Solved] I just downloaded Firefox 3.6. I have a Python script that reads my cookies.sqlite DB but it would not work after with Firefox 3.6. It kept telling me the database was encrypted. I uninstalled Firefox then found version 3.5 and installed that. No...
[ "The file isn't encrypted, but it is opened with an exclusive lock as of Firefox 3.6. I suspect python is telling you the wrong reason as to why it cannot open the database file, but the version of SQLite that Firefox ships with does not have the encryption module.\n" ]
[ 2 ]
[]
[]
[ "cookies", "encryption", "firefox", "python", "sqlite" ]
stackoverflow_0005187900_cookies_encryption_firefox_python_sqlite.txt
Q: How can we compute cube-root in python with specified precision? How can we compute cube-root in python with specified precision? I would like to use the decimal class for this and my compiler is python 2.5 I tried using something like this: >>> from decimal import * >>> x=Decimal("10") >>> print x**(Decima...
How can we compute cube-root in python with specified precision?
How can we compute cube-root in python with specified precision? I would like to use the decimal class for this and my compiler is python 2.5 I tried using something like this: >>> from decimal import * >>> x=Decimal("10") >>> print x**(Decimal("1.0")/3) Traceback (most recent call last): File "<pyshell#4>"...
[ "Definitely works in 2.5.2, maybe there was a change since 2.5?\nPython 2.5.2 (r252:60911, Jan 20 2010, 21:48:48) \n[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from decimal import Decimal\n>>> x=Decimal(\"10\")\n>>> x**(Decimal(\...
[ 2, 1 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0005188803_python_python_2.6.txt
Q: Regex: how to match overlapping patterns (maybe Python specific) I have a string that looks like this: "XaXbXcX". I'm looking to match any lowercase letters surrounded by X on either side. I tried this in Python, but I'm not getting what I'm looking for: import re str = "XaXbXcX" pattern = r'X([a-z])X' matches = r...
Regex: how to match overlapping patterns (maybe Python specific)
I have a string that looks like this: "XaXbXcX". I'm looking to match any lowercase letters surrounded by X on either side. I tried this in Python, but I'm not getting what I'm looking for: import re str = "XaXbXcX" pattern = r'X([a-z])X' matches = re.findall(pattern, str) # gives me ['a', 'c']. What about b?
[ "You can use a lookbehind assertion:\npattern = r'(?<=X)([a-z])X'\n\n", "I do not know python, however this regex works i tested in gskinner too ([^(?:X)+])+.\nHope this helps you\n" ]
[ 7, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005189396_python_regex.txt
Q: Get the content of a tag with beautiful soup I have this html: <a href="/watch?gl=US&amp;client=mv-google&amp;hl=en&amp;v=0C_yXOhJxWg">Miss Black OCU 2011</a> My program reads a html file, and above is the chunk of that file. How do I extract "Miss Black OCU 2011" using BeautifulSoup in python. A: Here's a qui...
Get the content of a tag with beautiful soup
I have this html: <a href="/watch?gl=US&amp;client=mv-google&amp;hl=en&amp;v=0C_yXOhJxWg">Miss Black OCU 2011</a> My program reads a html file, and above is the chunk of that file. How do I extract "Miss Black OCU 2011" using BeautifulSoup in python.
[ "Here's a quick fix:\n>>> from BeautifulSoup import BeautifulSoup as BS\n>>> soup = BS('<a href=\"/watch?gl=US&amp;client=mv-google&amp;hl=en&amp;v=0C_yXOhJxWg\">Miss Black OCU 2011</a>')\n>>> tags = soup.findAll('a', href=True)\n>>> for tag in tags: tag.renderContents() \n'Miss Black OCU 2011'\n>>> \n\n" ]
[ 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0005189819_beautifulsoup_python.txt
Q: Python/Biomolecular Physics- Trying to code a simple stochastic simulation of a system exhibiting conditional behavior! *edited 6/17/10 I'm trying to understand how to improve my code (make it more pythonic). Also, I'm interested in writing more intuitive 'conditionals' that would describe scenarios that are commo...
Python/Biomolecular Physics- Trying to code a simple stochastic simulation of a system exhibiting conditional behavior!
*edited 6/17/10 I'm trying to understand how to improve my code (make it more pythonic). Also, I'm interested in writing more intuitive 'conditionals' that would describe scenarios that are commonplace in biochemistry. The conditional criteria in the below program I've explained in Answer #2, but I am not satisfied wit...
[ "Info on the math behind simple stochastic simulation of chemical rxns:\nTypically, processes like this are simulated as discrete events with each event occurring with probability 'P' given a specific rate constant 'k' and a number of possible events 'n' in the interval of time 'dt': P=1-e**(-kdtn). Here we are neg...
[ 1, 1, 0, 0 ]
[]
[]
[ "physics", "python", "stochastic" ]
stackoverflow_0003054038_physics_python_stochastic.txt
Q: Filtering in Django I am trying to implement a simple filter method between a choice selected from drop-down and a text field. The drop down has choices like Name, Designation,Employee ID (which are all fields in DB). There is a text field where a value for the selected choice from designation can be given. Eg: If...
Filtering in Django
I am trying to implement a simple filter method between a choice selected from drop-down and a text field. The drop down has choices like Name, Designation,Employee ID (which are all fields in DB). There is a text field where a value for the selected choice from designation can be given. Eg: If i select Designation fro...
[ "I gave the solution in your other post: \nfirst, make your choice values EXACTLY the field names you want to search.\n\n<select name=\"choices\" onsubmit=\"document.forms[0].submit()\" >\n <option value=\"\">Select A Choice</option>\n <option value=\"userName\">Name</option> \n <option value=\"designation...
[ 4, 0, 0 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0005189721_django_django_models_django_templates_django_views_python.txt
Q: Python v3 Logging I could use this code below on Python 2. I tried it on Python 3 and I got an error. Anyone could explain why? Code: import logging import logging.handlers LOG_FILENAME = 'poller.log' # Set up a specific logger with our desired output level poll_logger = logging.getLogger('pollerLog') # Add the...
Python v3 Logging
I could use this code below on Python 2. I tried it on Python 3 and I got an error. Anyone could explain why? Code: import logging import logging.handlers LOG_FILENAME = 'poller.log' # Set up a specific logger with our desired output level poll_logger = logging.getLogger('pollerLog') # Add the log message handler to...
[ "It's a bug in Python 3.1.3 (see the issue on bugs.python.org).\nSupposedly it's fixed in Python 3.2.\n" ]
[ 5 ]
[]
[]
[ "logging", "python", "python_3.x" ]
stackoverflow_0005190470_logging_python_python_3.x.txt
Q: How does a lambda function refer to its parameters in python? I am new in Python. My task was quite simple -- I need a list of functions that I can use to do things in batch. So I toyed it with some examples like fs = [lambda x: x + i for i in xrange(10)] Surprisingly, the call of [f(0) for f in fs] gave me the...
How does a lambda function refer to its parameters in python?
I am new in Python. My task was quite simple -- I need a list of functions that I can use to do things in batch. So I toyed it with some examples like fs = [lambda x: x + i for i in xrange(10)] Surprisingly, the call of [f(0) for f in fs] gave me the result like [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]. It was not what I expe...
[ "It looks a bit messy, but you can get what you want by doing something like this:\n>>> fs = [(lambda y: lambda x: x + y)(i) for i in xrange(10)]\n>>> [f(0) for f in fs]\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nNormally Python supports the \"closure\" concept similar to what you're used to in Javascript. However, for thi...
[ 10, 6, 4, 1 ]
[]
[]
[ "closures", "functional_programming", "lambda", "python" ]
stackoverflow_0005190146_closures_functional_programming_lambda_python.txt
Q: Python Work Around For 'Goto' At the moment I have a check to see if a string has specific characters in it. I am trying to find a work around for a 'Goto' function. This is what I have at the moment: chars = set('0123456789$,') if any((c in chars) for c in UserInputAmount): print 'Input accepted' else: p...
Python Work Around For 'Goto'
At the moment I have a check to see if a string has specific characters in it. I am trying to find a work around for a 'Goto' function. This is what I have at the moment: chars = set('0123456789$,') if any((c in chars) for c in UserInputAmount): print 'Input accepted' else: print 'Invalid entry. Please try aga...
[ "You don't need a goto, you just need a loop. Try this, which loops forever unless the user provides valid input:\nchars = set('0123456789$,')\n\nwhile True: # loop \"forever\"\n UserInputAmount = raw_input() # get input from user\n\n if any((c in chars) for c in UserInputAmount):\n print 'Input accep...
[ 6, 2, 2 ]
[ "goodEntry = False\nfirst = True\nchars = frozenset(\"abc\") #whatever\nvalidateEntry = lambda x: any( (c in chars) for c in inString)\n\nwhile not goodEntry:\n if not first: print \"Invalid input\"\n first = False\n print \"Enter input: \"\n inString = raw_input()\n goodEntry = validateEntry(inStri...
[ -1 ]
[ "goto", "python" ]
stackoverflow_0005190187_goto_python.txt
Q: Can a Django view return its header first? I have a particularly heavy view which may need to return a form posting to itself several times, but I need the header straight away. Is there any way for the header portion of the template to be returned first? e.g. my view returns something like: return HttpResponse(Te...
Can a Django view return its header first?
I have a particularly heavy view which may need to return a form posting to itself several times, but I need the header straight away. Is there any way for the header portion of the template to be returned first? e.g. my view returns something like: return HttpResponse(Template(' {% extends "base.html" %} {% block ...
[ "Yes, it is possible. What you need to do is capture each individual render as a string, then concatenate the strings to form the complete content of the response.\nHere is the low-level way:\nfrom django.template import Context, Template\nt1 = Template(\"My name is {{ my_name }}.\")\nc1 = Context({\"my_name\": \"...
[ 0, 0, 0 ]
[]
[]
[ "django", "python", "wsgi" ]
stackoverflow_0005189345_django_python_wsgi.txt
Q: Django South: How to use with multiple installs of codebase and one central database? I am converting an existing codebase (with several apps) to use South. My codebase is currently installed on 1 development server and 3 production servers. The development has its own database and the 3 production servers are all...
Django South: How to use with multiple installs of codebase and one central database?
I am converting an existing codebase (with several apps) to use South. My codebase is currently installed on 1 development server and 3 production servers. The development has its own database and the 3 production servers are all connected to one central database. I read the info at http://south.aeracode.org/docs/conve...
[ "No, You use it only to apply changes to the database schema. You don't need to run migrate again on Servers 2 and 3, since they are using the same db as Server 1. \n" ]
[ 2 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0005190847_django_django_south_python.txt
Q: urlib2.urlopen through proxy fails after a few calls Edit: after much fiddling, it seems urlgrabber succeeds where urllib2 fails, even when telling it close the connection after each file. Seems like there might be something wrong with the way urllib2 handles proxies, or with the way I use it ! Anyways, here is th...
urlib2.urlopen through proxy fails after a few calls
Edit: after much fiddling, it seems urlgrabber succeeds where urllib2 fails, even when telling it close the connection after each file. Seems like there might be something wrong with the way urllib2 handles proxies, or with the way I use it ! Anyways, here is the simplest possible code to retrieve files in a loop: impo...
[ "The proxy might be throttling your requests. I guess it thinks you look like a bot.\nYou could add a timeout, and see if that gets you through.\n", "You can minimize the number of connection by using the keepalive handler from the urlgrabber module. \nimport urllib2\nfrom keepalive import HTTPHandler\nkeepalive_...
[ 1, 1 ]
[]
[]
[ "authentication", "proxy", "python", "urllib2", "urlopen" ]
stackoverflow_0005118670_authentication_proxy_python_urllib2_urlopen.txt
Q: python/c++ wrapping on Snow Leopard I create a dynamic library and then using swig under snow leopard but when I import my module it returns always ImportError: No module named blabla. I've all compiled in 64 bit, download and install python 2.7 64 bit. This test library has been created with cmake, and when I was...
python/c++ wrapping on Snow Leopard
I create a dynamic library and then using swig under snow leopard but when I import my module it returns always ImportError: No module named blabla. I've all compiled in 64 bit, download and install python 2.7 64 bit. This test library has been created with cmake, and when I was with leopard 32 bit, it worked.
[ "Given that it worked on 32 bits, I would first check whether the library has 64 bits code. You can use the file command I think to check the arch in a multi-arch mach-o binary.\nIf the library is indeed 64 bits, then please give us the exact exception in python, and more importantly, a build log from cmake. Build ...
[ 0 ]
[]
[]
[ "c++", "importerror", "osx_leopard", "python", "swig" ]
stackoverflow_0005186361_c++_importerror_osx_leopard_python_swig.txt
Q: Python: Sort list using another list order, having different lengths, and without 'sorted' I'll to explain this right: I'm in an environment where I can't use python built-in functions (like 'sorted', 'set'), can't declare methods, can't make conditions (if), and can't make loops, except for: can call methods (bu...
Python: Sort list using another list order, having different lengths, and without 'sorted'
I'll to explain this right: I'm in an environment where I can't use python built-in functions (like 'sorted', 'set'), can't declare methods, can't make conditions (if), and can't make loops, except for: can call methods (but just one each time, and saving returns on another variable foo python:item.sort(); #foo varia...
[ "It's hard to answer, not knowing exactly what's allowed and what's not. But how about this O(N^2) solution?\n[x for x in correct_order if x in messed_order] + [x for x in messed_order if x not in correct_order]\n\n", "Create a Script (Python) object in your skin and use that as a function. TALES expressions are ...
[ 5, 2, 0, 0, 0 ]
[]
[]
[ "list", "plone", "python", "sorting" ]
stackoverflow_0003633288_list_plone_python_sorting.txt
Q: programming using pyclutter I am new to clutter (and pyclutter). I have been trying to use pyclutter. I haven't found any good tutorial for it so far. I mean nothin that really explains properly. I saw a couple of example programs but when I tried to use pyclutter I dint get any good results. The commands are anai...
programming using pyclutter
I am new to clutter (and pyclutter). I have been trying to use pyclutter. I haven't found any good tutorial for it so far. I mean nothin that really explains properly. I saw a couple of example programs but when I tried to use pyclutter I dint get any good results. The commands are anailable but their proper use is wha...
[ "This will not work, cause cogl is an abstraction to use OpenGL. In OpenGL world, the drawing must be done for everyframe. That's mean, your code will be executed only once, as soon as you window will flip, you'll not see the line.\nYou can create a custom actor for that, and put your instruction in the do_paint() ...
[ 1 ]
[]
[]
[ "cogl", "opengl", "python" ]
stackoverflow_0004985686_cogl_opengl_python.txt
Q: how to lock steps in buildbot I have a builder which consists of steps A, B, and C; and a second builder which consists of steps U, V, and W: How can I 'block' step U until steps A and B are finished? So basically I want that steps C and U run parallel to each other. My first idea was to introduce two interlocks, ...
how to lock steps in buildbot
I have a builder which consists of steps A, B, and C; and a second builder which consists of steps U, V, and W: How can I 'block' step U until steps A and B are finished? So basically I want that steps C and U run parallel to each other. My first idea was to introduce two interlocks, a and b: step A demands lock a, ste...
[ "Try using a Triggerable scheduler for your builder which performs steps U,V,W. In the first builder add a step Trigger after \"B\" and before \"C\".\nThis should bring you the desired behaviour ...\n" ]
[ 3 ]
[]
[]
[ "buildbot", "python" ]
stackoverflow_0004914259_buildbot_python.txt
Q: Generate the following pseudo-timestamp as workaround on limitation of flot graphing library currently, I have the following current timestamp value example in seconds. 1299196800. It means 4 March 2011 0:0:0 in Greenwich (GMT) 4 March 2011 8:0:0 in Malaysia (GMT +8) Currently, if my Python script pass in 129...
Generate the following pseudo-timestamp as workaround on limitation of flot graphing library
currently, I have the following current timestamp value example in seconds. 1299196800. It means 4 March 2011 0:0:0 in Greenwich (GMT) 4 March 2011 8:0:0 in Malaysia (GMT +8) Currently, if my Python script pass in 1299196800 to a flot graphing javascript library, it will always show Greenwich's time 4 March 2011 0...
[ "The UTC time in flot is by design: look for timestamp here, and fixing the time offset is the recommended solution. \nConsider that the flot timestamp are expressed in milliseconds, so you'll have to multiply your example offset by 1000.\nIt is not a good idea, though, to use a constant timestamp: in general you'...
[ 3, 1 ]
[]
[]
[ "flot", "python" ]
stackoverflow_0005191646_flot_python.txt
Q: How to install patches for python on Mac IDLE has the contextual menu right-click bug on mac (Tk problem) There is already a patch issued for this problem: issue 10404 I've downloaded the patch (issue10404-idle_no_context_menus.txt) - where and how do I install it? Thanks in advance. A: Find the EditorWindow.py ...
How to install patches for python on Mac
IDLE has the contextual menu right-click bug on mac (Tk problem) There is already a patch issued for this problem: issue 10404 I've downloaded the patch (issue10404-idle_no_context_menus.txt) - where and how do I install it? Thanks in advance.
[ "Find the EditorWindow.py file in your filesystem (find / -name EditorWindow.py if you're completely in the dark about where it might live); cd into it's containing directory, then run:\npatch --dry-run < ~/path/to/issue10401-idle_no_context_menus.txt\n\nIf it succeeds, take off the --dry-run and re-run the command...
[ 1, 0 ]
[]
[]
[ "macos", "patch", "python", "python_idle" ]
stackoverflow_0005192166_macos_patch_python_python_idle.txt
Q: converting object value into float in python i got timestamp returned as a tuple from rrd database i.e. info variable will contain this [(38177492.733055562, 38177482.886388876),(39370533.190833323, 40563588.018611118)] inside my code i am converting tuple (38177492.733055562,38177482.886388876) intto list us...
converting object value into float in python
i got timestamp returned as a tuple from rrd database i.e. info variable will contain this [(38177492.733055562, 38177482.886388876),(39370533.190833323, 40563588.018611118)] inside my code i am converting tuple (38177492.733055562,38177482.886388876) intto list using list function after that i am accessing eleme...
[ "What you're doing doesn't make much sense, I'm afraid - index is an index into the info list, not into val, which is one of the tuples in that list.\nAlso, you don't need to convert the list into a tuple in order to access an element of the tuple.\nYour indentation is broken in the line where the loop starts, and ...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005192033_django_python.txt
Q: Problems in uploading files with django I'm new using django. I've to upload a file and fot this I'm following the instructions present in official documentation: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/?from=olddocs my index.htlm <form action="upload_file" enctype="multipart/form-data" ...
Problems in uploading files with django
I'm new using django. I've to upload a file and fot this I'm following the instructions present in official documentation: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/?from=olddocs my index.htlm <form action="upload_file" enctype="multipart/form-data" method="POST"> {% csrf_token %} ...
[ "Are you sure that your form action is correct?\nShouldn't it be something like this instead:\n<form action=\"{% url upload_file %}\" enctype=\"multipart/form-data\" method=\"post\">\n\n", "You could perhaps output the request.method at the beginning of your method, just to be sure... after that, print form._erro...
[ 1, 0 ]
[]
[]
[ "django", "django_views", "file_upload", "python" ]
stackoverflow_0005192038_django_django_views_file_upload_python.txt
Q: Doubts in Python code I'm reading a book of Algorithms in Python, and I'm also new to Python. I can't understand this example: class Bunch(dict): def __init__(self, *args, **kwds): super(Bunch, self).__init__(*args, **kwds) self.__dict__ = self x = Bunch(name="Jayne Cobb", position="Public Rel...
Doubts in Python code
I'm reading a book of Algorithms in Python, and I'm also new to Python. I can't understand this example: class Bunch(dict): def __init__(self, *args, **kwds): super(Bunch, self).__init__(*args, **kwds) self.__dict__ = self x = Bunch(name="Jayne Cobb", position="Public Relations") print x.name Some...
[ "*args means: Collect all extra parameters without a name in this list:\ndef x(a, *args): pass\nx(1, 2, 3)\n\nassigns a=1 and args=[2,3].\n**kwargs assigns all extra parameters with a name to the dict kawrgs:\ndef x(a, **kw): pass\nx(1, b=2, c=3)\n\nassigns a=1 and kw={b=2, c=3}.\nThe code super(Bunch, self).__init...
[ 4, 3, 2 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0005192732_algorithm_python.txt
Q: Update value in SqlAlchemy many-to-many association table Given the tables below, how do I update what group a user is in? I feel like I have to be missing something obvious but I haven't found anything so far that shows how to do this. group_permission_table = Table('group_permission', metadata, Column('group...
Update value in SqlAlchemy many-to-many association table
Given the tables below, how do I update what group a user is in? I feel like I have to be missing something obvious but I haven't found anything so far that shows how to do this. group_permission_table = Table('group_permission', metadata, Column('group_name', Integer, ForeignKey('group.group_name', onupdate="CASCA...
[ "You do not need to delete anything from the M2N relation table explicitly. When you delete a user from the group.users and then commit your changes, the data in the relationship table will be updated (inserted or deleted accordingly). You can check this by logging the SQL statements with the echo=True\nengine = cr...
[ 8 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0005083696_python_sqlalchemy.txt
Q: How to use Python to send email via Microsoft Exchange Web Services API With Exchange 2007 and Exchange 2010, Microsoft has introduced Exchange Web Services. This allows to perform many operations on the Exchange server using SOAP. Example SOAP Message to Send Email Python has great SOAP libraries. I am assuming I...
How to use Python to send email via Microsoft Exchange Web Services API
With Exchange 2007 and Exchange 2010, Microsoft has introduced Exchange Web Services. This allows to perform many operations on the Exchange server using SOAP. Example SOAP Message to Send Email Python has great SOAP libraries. I am assuming I can simply use these libraries to perform operations on the Exchange server ...
[ "i would use suds for this.\ndownload and documentation: https://fedorahosted.org/suds/\nyou will have to modify the wsdl file a little bit.\ntutorial for php is located here: http://www.howtoforge.com/talking-soap-with-exchange\njust use search form here or google :)\n" ]
[ 0 ]
[]
[]
[ "exchange_server", "exchangewebservices", "python", "soap" ]
stackoverflow_0004505609_exchange_server_exchangewebservices_python_soap.txt
Q: WSDL XSD and soappy I have the following WSDL and XSD from SOAPpy import WSDL import os # you'll need to configure these two values; # see http://www.google.com/apis/ WSDLFILE = os.path.join(os.path.dirname(__file__), "getiwsAesPayment.wsdl") _server = WSDL.Proxy(WSDLFILE) print _server Which gives me the err...
WSDL XSD and soappy
I have the following WSDL and XSD from SOAPpy import WSDL import os # you'll need to configure these two values; # see http://www.google.com/apis/ WSDLFILE = os.path.join(os.path.dirname(__file__), "getiwsAesPayment.wsdl") _server = WSDL.Proxy(WSDLFILE) print _server Which gives me the error: schema.load(reade...
[ "try to include (not import) other xsd's in your wsdl\n", "or simply use SUDS :)\nIt works with newer SOAP-Standards.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "soap", "webservice_client", "wsdl" ]
stackoverflow_0004316608_python_soap_webservice_client_wsdl.txt
Q: Delete x-line paragraphs from text file with Python I have a long text file with paragraph with 6 and 7 lines each. I need to take all seven line paragraphs and write them to a file and take six line paragraphs and write them to a file. Or delete 6-line (7-line) paragraphs. Each paragraph is separated with blank ...
Delete x-line paragraphs from text file with Python
I have a long text file with paragraph with 6 and 7 lines each. I need to take all seven line paragraphs and write them to a file and take six line paragraphs and write them to a file. Or delete 6-line (7-line) paragraphs. Each paragraph is separated with blank line (or two blank lines). Text file example: Firs Name...
[ "As a welcome on stackoverflow, and because I think you have now searched more for a code , I propose you the following code.\nIt verifies that the paragraphs have not more than 7 lines and not less than 6 lines. It warns when such paragraphs exist in the source. \nYou'll remove all the prints to have a clean code,...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005188344_python.txt
Q: Randomizing an array into two arrays I have a list of numbers and I need to split into to corresponding arrays of different sizes, but that make up all the combinations of the array splitting up. For example, if I have an array a=[1,2,3,4,5] and I want to split it to one array of size 3 and the other 2. So I wa...
Randomizing an array into two arrays
I have a list of numbers and I need to split into to corresponding arrays of different sizes, but that make up all the combinations of the array splitting up. For example, if I have an array a=[1,2,3,4,5] and I want to split it to one array of size 3 and the other 2. So I was thinking of making two arrays to hold ea...
[ "This solution should be more efficient for large arrays, as it uses a set to compute the indices for the second array, and pre-allocates memory:\nimport scipy as sp\nimport itertools\n\nnumber = sp.array([53, 64, 68, 71, 77, 82, 85])\nlen_number = len(number)\n\n# number of combinations\nncomb = sp.comb(len_number...
[ 1, 0 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0005177137_numpy_python_scipy.txt
Q: Installing my sdist from PyPI puts the files in unexpected places My problem is that when I upload my Python package to PyPI, and then install it from there using pip, my app breaks because it installs my files into completely different locations than when I simply install the exact same package from a local sdist...
Installing my sdist from PyPI puts the files in unexpected places
My problem is that when I upload my Python package to PyPI, and then install it from there using pip, my app breaks because it installs my files into completely different locations than when I simply install the exact same package from a local sdist. Installing from the local sdist puts files on my system like this: /P...
[ "The data_files parameter is for data files who isn't a part of the package. You should probably use package_data instead.\nSee https://docs.python.org/3/distutils/setupscript.html#installing-package-data\nThat wouldn't install the data in site-packages/data, but in my opinion that's not where is should be installe...
[ 7 ]
[ "You can load package data with pkgutil.get_data(), it will find where exactly package data is installed.\nHere is a nice blog post about including data files in packages: Including data files into Python packages\n" ]
[ -1 ]
[ "distribute", "distutils", "pypi", "python", "setuptools" ]
stackoverflow_0005192386_distribute_distutils_pypi_python_setuptools.txt
Q: Keyboard/Mouse events on desktop / root window with pygtk (gtk.gdk) on Linux As the title states, I'm trying to capture Mouse and Keyboard events with Python-gtk. I can do this easily with python-xlib with: self.display = display.Display() self.screen = self.display.screen() self.root_window = self.sc...
Keyboard/Mouse events on desktop / root window with pygtk (gtk.gdk) on Linux
As the title states, I'm trying to capture Mouse and Keyboard events with Python-gtk. I can do this easily with python-xlib with: self.display = display.Display() self.screen = self.display.screen() self.root_window = self.screen.root self.root_window.grab_pointer(1, X.ButtonPressMask | X...
[ "Here is an example that i just did that you can base on it:\nimport gtk\n\n\ndef on_key_press(widget, data=None):\n print \"click\"\n\nif __name__ == '__main__':\n w = gtk.Window()\n\n # Connect the callback on_key_press to the signal key_press.\n w.connect(\"key_press_event\", on_key_press)\n # Mak...
[ 3, 0 ]
[]
[]
[ "gdk", "gtk", "linux", "pygtk", "python" ]
stackoverflow_0004542152_gdk_gtk_linux_pygtk_python.txt
Q: Google App Engine -- Java or Python? I noticed that this was asked in the following post. Has anyone used both and can conclusively tell me which is better? It seems like python might be a little easier to implement and faster? A: By this time, both implementations are reasonably mature and solid, and their func...
Google App Engine -- Java or Python?
I noticed that this was asked in the following post. Has anyone used both and can conclusively tell me which is better? It seems like python might be a little easier to implement and faster?
[ "By this time, both implementations are reasonably mature and solid, and their functionality is pretty similar (I don't think it's quite 100% equal yet, but, moving in that direction). So, if you already know only one of the two languages, I'd say \"just go for it\". If you already know both, you don't need my advi...
[ 17, 8, 4, 3, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "java", "python" ]
stackoverflow_0002105832_google_app_engine_java_python.txt
Q: Creating multiple dictionaries based on other dictionary values in python I have a list that contains many dictionaries. Each dictionary represents a change that has occurred within my application. The "change" dictionary has the following entries: userid: The user ID for a user ctype: A reference to a change type...
Creating multiple dictionaries based on other dictionary values in python
I have a list that contains many dictionaries. Each dictionary represents a change that has occurred within my application. The "change" dictionary has the following entries: userid: The user ID for a user ctype: A reference to a change type in my application score: A score The ctype can be one of about 12 different s...
[ "The key thing to agregate data here is to have a dictionary where each key is the userid, and each entry is the data relevant to that userid. \nfinal_data = {}\nfor entry in data:\n userid = entry[\"userid\"]\n if userid not in final_data:\n final_data[userid] = {\"userid\": userid, \"score\": 0} \n ...
[ 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005193552_dictionary_python.txt
Q: Using Django with MySQL for storing and looking up Large DNA Microarray Results I'm trying to setup a django app that allows me to store and lookup the results of a dna microarray with ~500k unique probes for a large number of subjects. The model set up I've been toying with is as follows: class Subject(models.Mod...
Using Django with MySQL for storing and looking up Large DNA Microarray Results
I'm trying to setup a django app that allows me to store and lookup the results of a dna microarray with ~500k unique probes for a large number of subjects. The model set up I've been toying with is as follows: class Subject(models.Model): name = models.CharField() class Chip(models.Model): chip_name = models....
[ "Well if you need a result (genotype) per Probe for every Subject, then a standard many-to-many intermediary table (Genotype) is going to get huge indeed.\nWith 1000 Subjects you'd have 500 million records.\nIf you could save the values for genotype field encoded/serialized in one or more columns, that would reduce...
[ 1 ]
[]
[]
[ "django", "django_models", "large_data", "python" ]
stackoverflow_0005193741_django_django_models_large_data_python.txt