2,646 Posted Topics
Re: I would try something like this [code=c] sys = PyImport_ImportModule( "sys"); s_out = PyObject_GetAttrString(sys, "stdout"); // new reference result = PyObject_CallMethod(s_out, "write", "s", "your data goes here"); //new ref [/code] that is to say, you execute [icode]sys.stdout.write("your data goes here")[/icode], but in C :). Don't forget to decref what must … | |
Re: You should be able to do this by invoking a shell command, which depends on your linux distribution, to list the packages installed on your computer. This command should look like [icode]rmp -qa | grep unrar[/icode] on some distributions or [icode]dpkg -list unrar[/icode] on other distributions and perhaps another command … | |
Re: It looks like your program failed to remove a file due to a permission denied on that file. Perhaps you shoud run the program as administrator. If it still fails, you could check and may be change the permissions of C:\Program Files\Plone\bin\zopepy.exe. | |
Re: This one works too, for uppercase letters [code=python] >>> def shifted(letter, shift): ... return chr(ord('A') + (ord(letter) + shift - ord('A')) % 26) ... >>> shifted('C', 3) 'F' >>> shifted('Z', 3) 'C' >>> shifted('X', 3) 'A' >>> shifted('M', 3) 'P' >>> shifted('M', -3) 'J' >>> shifted('A', -3) 'X' >>> shifted('A', … | |
Re: Well, [icode]x + y[/icode] is transformed into [icode]x.__add__(y)[/icode] if x has a __add__ method. If it doesn't, but y has a __radd__ method, it's transformed into [icode]y.__radd__(x)[/icode]. So all you need to do is to define __add__ and possibly __radd__ methods in your classes. | |
Re: You can try a statement like this one [code=python] print(''.join(s[len("SimonSays: "):] for s in open("simonfile.txt") if s.startswith("SimonSays: "))) [/code] | |
Re: Use the 'key' argument of the 'sort' method like this [code=python] def score(item): # define a score function for your list items return item[1] r =[(300, 4), (5, 6), (100, 2)] r.sort(key = score) # sort by ascending score print r """ my output --> [(100, 2), (300, 4), (5, … | |
Re: You could try [code=python] tbl_name = requst.GET['table'] try: tbl = vars()[tbl_name] except KeyError: raise # handle unknown variable case differently if you want tbl.objects.filter(title__icontains=q) [/code] It's much safer than eval because eval can run any code, so should be avoided with data coming from the web. | |
Re: The explanation is that the code in a class body is executed when a module is loaded, like code at module level, while code in a function or method is only executed when the function is called. So in your last example, the print statement is executed when you create … | |
Re: [icode]'0.0.0.0'[/icode] is suspicious. Normally, localhost is [icode]'127.0.0.1'[/icode]. | |
Re: You must NEVER remove the version of python that comes with a linux distribution, because the system uses python scripts which were written for this version of python. In the README file of the python 2.6.2 sources, I found this [code=text] Tkinter ------- The setup.py script automatically configures this when … | |
This snippet provides 2 functions to create in memory a gziped archive of a sequence of files and directories, and to extract files from this archive. These functions are similar in effect to the linux commands [icode]tar czf[/icode] and [icode]tar xzf[/icode] but instead of writing an archive file on disk, … | |
Re: I think you should work with a Subject class, each Subject instance containing the results to all the experiments and the extra data, like this [code=python] from random import randint class Subject(object): def __init__(self, sid): self.sid = sid self.results = dict() self.sex = 1 self.age_band = 1 class Experiment(object): def … | |
Re: Here is a code which uses a helper class and a few functions to implement your algorithm. Tell me if it works as you expect [code=python] # orderer.py # tested with python 2.6 and 3.1 from difflib import SequenceMatcher class Orderer(object): "Helper class for the ordering algorithm" def __init__(self): self.matcher … | |
Re: Yes there is [code=python] def search(l, key): if l: if l[0] == key: return 0 s = search(l[1:], key) if s is not False: return s + 1 return False [/code] However, the good way to do this is to use the builtin index function ! | |
Re: The value of the variable switch in the main loop is [icode]<function switch at 0x7f17ffb10c08>[/icode], so it's never equal to 'ant', 'bee' or 'car'. There are many errors in your code. You are using undefined variables in different places. First concentrate on the content of the main loop: what should … | |
Re: A closing parenthesis is missing on the previous line. Also the last line has Print instead of print. There are other errors. | |
Re: The standard module [b]code[/b] contains classes to help you write your own interpreter. Basically, you need to subclass InteractiveConsole and call its push method with lines of input. | |
Re: What is your linux distribution ? Many python modules are distributed as linux packages which you should install with your software manager. For example in Ubuntu, you should run the command [icode]sudo apt-get install python-numpy python-scipy[/icode]. In Mandriva, there are also packages python-numpy and python-scipy. | |
Re: You can use this structure [code=python] while True: theGame() if not playAgain(): break quit() [/code] | |
Re: Again, you can use a threading.Condition instance. Here is a program that works with python 2.6 and 3.1. I divided the time.sleep by a factor 10 :) [code=python] #!/usr/bin/env python from threading import Thread, Condition from contextlib import contextmanager from random import randint from time import sleep import sys @contextmanager … | |
Re: Is this what you mean ? [code=python] class Agent: def __init__(self): exec "import random" in self.__dict__ ag = Agent() print ag.random.randrange(100) # this works print random.randrange(100) # this doesn't work (random not in global namespace) [/code] You could even make a class decorator [code=python] def withrandom(cls): exec "import random" in … | |
Re: The Beautifulsoup module can parse bad html. Also if you have beautifulsoup, you can use the lxml module to parse your bad html code. | |
Re: You can use a threading.Condition object. I usually use this in a 'with' context like this [code=python] #from __future__ import with_statement # uncomment if python 2.5 from contextlib import contextmanager from threading import Condition @contextmanager def acquired(condition): condition.acquire() try: yield condition finally: condition.release() my_condition = Condition() filename = "my_file.txt" class … | |
Re: Consider this [code=python] >>> import datetime >>> value = datetime.date.today() >>> print(value) 2009-12-27 >>> value datetime.date(2009, 12, 27) [/code] When you call [icode]print(value)[/icode], the string printed is the string resulting from the call [icode]str(value)[/icode], or equivalently, the string returned by the method [icode]__str__()[/icode] of the class. On the other hand, … | |
Re: You must open the mandriva software manager (if you are using gnome, this is in the Applications menu: install and remove software). Then you type 'wx' or 'matplotlib' or 'python' in the software manager search form. Then you select the packages you need and you click on the apply button. … | |
Re: The scons program uses the same method of comparing the hash values of files to determine if they have been modified. Perhaps you could have a look in scons source code. | |
Re: You can try: [code=python] while True: user = raw_input("How many multiplications ? ") try: max_multiplications = int(user) if max_multiplications <= 0: raise ValueError else: break except ValueError: print "Please enter a positive integer" [/code] | |
Re: He means that windows must be able to find the file 'python.exe'. To set the path environment variable, [url=http://www.computerhope.com/issues/ch000549.htm]follow the steps[/url] described here to be able to edit the Path variable, then at the end of the line of this path variable, append something like [icode];C:\...[/icode] (where you replace the … | |
Re: You don't have to type all 600 ! What code would you type to create only one ? | |
Re: randrange(3) returns a random number in the set 0, 1, 2. You should replace that line with [code=python] return randrange(len(DOORS)) [/code] Other changes which seem obvious is to replace all the [icode]set([0,1,2])[/icode] by [icode]set(range(len(DOORS)))[/icode]. | |
Re: You could use [code=python] def find_dupe(L): if len(L) == 0: return False elif L[0] in L[1:]: return True else: return find_dupe(L[1:]) [/code] | |
Re: Also, the normal distribution can return negative numbers, there is nothing wrong with that. | |
Re: Many linux systems have a package named "python-numpy". You only need to install it with your software manager. Don't ask such questions without specifying your linux distribution :) | |
Re: Looking at [url=http://www.math.okstate.edu/mathdept/dynamics/dragon.html]the pictures here[/url], the algorithm seems pretty straightforward, starting with a vector of 2 points A and B [code=text] def draw_dragon(A, B, depth): if depth == 0: draw segment A, B else: compute point C draw_dragon(A, C, depth - 1) draw_dragon(B, C, depth - 1) [/code] point C … | |
Re: Did you try to put the global statement as the first statement in your method ? | |
Re: You can get the python include directory like this [code=python] >>> from distutils.sysconfig import get_python_inc >>> print(get_python_inc()) /usr/include/python2.6 [/code] Now, if you don't have Python.h, you must install a package named python-dev. Dont forget to add the option [icode]-I/usr/include/python2.6[/icode] when you invoke gcc. | |
Re: A simpler solution is to hit the button [u]Toggle Plain Text[/u] before copying the code. | |
Re: Im not sure, but I think you should wrap msg2 into a new python object yourself with [icode]SWIG_NewPointerObj[/icode]. You can put only python objects in a call to a python function. Try to google for use examples of SWIG_NewPointerObj. You must pass your c++ pointer and a swig reference to … | |
Re: I have an idea of a small and useful project: it's a robot which executes other programs (first target is python programs) using a time rule, for example it can execute a program periodically. Tasks can be registered and removed. It would have a gui interface with a task list, … | |
Re: This code IS crap. What is it supposed to do ? First bugs: getRandEntry is called before it is defined (in the while True). The for interval ... loop should be removed. Also did you create a profile named myprofile for firefox ? If you're on windows (which seems to … | |
Re: There is a little module called [url=http://www.greenteapress.com/thinkpython/swampy/lumpy.html]Lumpy[/url] which can draw diagrams in live python programs. It's mainly intended for students, and it's not exactly UML, but it may help you see the structure of your objects and classes. | |
This snippet defines a function [b]chmod[/b] which uses symbolic strings to represent the mode (eg [b]u+rwx[/b]) like the shell command 'chmod'. | |
Re: The best solution is that you do the test with 2.6. Some library modules have different names, for example html.parser in python3 is HTMLParser in 2.6, but most of your programs should run. | |
Re: Also googling L-system+python yields many links which should be checked. | |
Re: You should not write [icode]except:[/icode] clauses without targeting a specific exeption. For example if you're reading user input and you're expecting a number and the user types "hello", then float("hello") will raise a ValueError. You can catch it with [icode]except ValueError[/icode]. There are many good reasons not to use except: … | |
Re: Some info are missing in your posts: 1) What is the command that you want to run for each file ? I read a few google results about pbs scripts, and may be you want to run commands like [icode]qsub script[/icode] on the command line. So the question is how … | |
Joining together ordered sample points (xi, yi) when ths xi's are different yields a piecewise linear continuous (P1) function. This snippet defines a handy class to manipulate these functions. It allows computing the value and the slope of the function at each point, arithmetic operations, absolute value, truncation and linear … | |
Re: A similar utility for linux users, using os.stavfs (tested with py 2.6 and 3.1) [code=python] import os, sys kilo = 1024.0 mega = kilo * kilo giga = kilo * mega def fullpath(location): p = os.path.expandvars(location) p = os.path.expanduser(p) return os.path.abspath(os.path.normpath(p)) def hardpath(location): p = fullpath(location) L = [] while … | |
Re: I discovered this new editor [url=http://www.geany.org/Main/HomePage]geany[/url]. It could be worth trying. |
The End.