Using arrays in Python - problems.


,
! I've just started to use Python and its a lovely
language! I've previously programmed in Fortran 95 and have just began
to use numpy. I'm having a few problems with arrays in Python though and
wondered if someone could offer me some advice
I wrote the following Fortran code to randomly generate numbers from
a log-normal distribution for use in a Monte Carlo model:

do n=1,shotcount
F(n)=G05DEF(F_mean,F_sd)
enddo

The array F(n) is dynamically allocated earlier on and is sized with
reference to shotcount, the number of iterations the model performs. The
problem is I can't get something like this to run in Python using numpy,
and for the size of the array to be sized dynamically with reference to
the variable shotcount. I acknowledge that my knowledge of Python is
still really basic (I only started learning it a few days ago) and I'm
trying to get out of the Fortran programming mindset but I'm stuck and
don't seem to be able to get any further. If anyone could help I'd be
really grateful.
Posted On: Monday 5th of November 2012 02:13:11 AM Total Views:  209
View Complete with Replies

RELATED TOPICS OF Python Programming PROGRAMMING LANGUAGE




creating color gradients using PIL

Any ideas how we can create a color gradient using Python Imaging Library. Has any got some sample code that can give me some idea. I need to create a horizontal and vertical color gradient for a college project
VIEWS ON THIS POST

147

Posted on:

Monday 5th November 2012
View Replies!

Re: Strange problem when using re module with threads

En Thu, 01 Nov 2007 17:01:36 -0300, Wei Lee Woon escribi: > I've been getting a rather strange problem with the following > multithreaded > code (reduced to the minimum which still results in the problem): > > import threading > import re > > class hey(threading.Thread): > def run(self): > print re.compile("\d+").search("hey95you").group(); > > thlist=[] > for tech in range(2): > thlist.append(hey()) > thlist[-1].start() > > for th in thlist: > th.join() > > After saving this to a file (say "test.py"), if I try to run this from > the > console using "python test.py", it seems to work fine, but when i try to > run > it from the python interactive shell using "import test", it freezes up > (if > i don't issue the join() it is fine, though). Any ideas why this is so It's the "import lock" in action. When an import is being made, no other thread can import anything, they block waiting for the lock to be released. re.compile internally tries to import sre_parse, and blocks. Then both threads are waiting for the import lock, and the main thread is waiting in the join() call [inside the "import test" call] - a deadlock. Note that you get the same effect if you replace the re.compile(...) with a simple "import os" So, don't do blocking actions (like join()) at import time. -- Gabriel Genellina
VIEWS ON THIS POST

138

Posted on:

Monday 5th November 2012
View Replies!

Re: Releasing malloc'd memory using ctypes?

On Dec 23, 2007 12:36 PM, wrote: > I am starting to experiment with ctypes. I have a function which returns a > pointer to a struct allocated in heap memory. There is a corresponding free > function for that sort of struct, e.g.: > > from ctypes import * > > cdll.LoadLibrary("libthing.so") > c_thing = CDLL("libthing.so") > > class THING(Structure): > _fields_ = [("name", c_char_p), > ("value", c_int)] > > get_thing = c_thing.get_thing > get_thing.restype = POINTER(THING) > free_thing = c_thing.free_thing > > So I call get_thing() and get back this ctypes wrapper for a pointer to a > thing. I can extract the name and value elements from the thing instance > just fine: > > thing_p = get_thing() > thing = thing_p.contents > print thing.name, "=", thing.value > > Now I need to call free_thing. What do I pass it thing_p Some attribute > of thing_p Something else altogether The ctypes module docs seem to be > strangely silent on the question of freeing heap memory which you've > received from the underlying library's functions. > You do it just like you'd do in C, and pass the return value of get_thing. Make sure that you declare free_thing as taking a pointer so ctypes knows to do the right thing.
VIEWS ON THIS POST

187

Posted on:

Monday 5th November 2012
View Replies!

Need to open an Url and display it in a window created using Pythonwin extensions

I'm pretty new to Python and I've been searching all over the place to find a solution for this. I have a html page with some javascript in it and I need to load this page in my own window (which I will create using PythonWin). The reason for this is to have capability to control the window properties and at the same time have access to click on the "submit" buttons in the webpage.e So basically, I will open a wepage as shown below - import win32com.client import win32api import win32gui ie = win32com.client.Dispatch( "InternetExplorer.Application" ) ie.Visible = 1 ie.Navigate("http://www.microsoft.com/") And then I need to display it in a window that I will create as shown below - hwnd = CreateWindowEx(...) I will be so grateful if anyone can give me some pointers on how to go about this. Thank you for reading
VIEWS ON THIS POST

185

Posted on:

Monday 5th November 2012
View Replies!

Re: Problem using subprocess.Popen on windows

jorma kala wrote: > I get an error that I don't understand when using the subprocess module > on Windows. > I guess I'm missing out something very basic. > For instance, to execute and capture the output of the ms-dos dir > command, I tried the following: > > from subprocess import * > > p1 = Popen(["dir"], stdout=PIPE) > output = p1.communicate()[0] > > But I get a WindowsError : [Error 2] File Not Found That's because "dir" isn't an executable file in its own right, merely a subcommand of the command shell. Do this: from subprocess import * p1 = Popen ("dir", shell=True, stdout=PIPE) print p1.communicate ()[0] TJG
VIEWS ON THIS POST

153

Posted on:

Monday 5th November 2012
View Replies!

using inspect on pygtk

, I recently been trying to use the inspect module to inspect the arguments of gtk objects, such as gtk.Button. I tried like this: inspect.getargspec(gtk.Button.__init__) and get the fallowing error: File "", line 1, in File "/usr/lib/python2.5/inspect.py", line 743, in getargspec raise TypeError('arg is not a Python function') TypeError: arg is not a Python function I have been trying to do this through code so that I don't have to have a list of all possible gtk classes and their arguments.
VIEWS ON THIS POST

169

Posted on:

Monday 5th November 2012
View Replies!

Advice for editing xml file using ElementTree and wxPython

I'm a computational chemist who frequently dabbles in Python. A collaborator sent me a huge XML file that at one point was evidently modified by a now defunct java application. A sample of this file looks something like: Test File Name fileName Name of the input file water Number of Atoms natoms Number of atoms in the molecule 3 I've been playing around with parsing that file using the ElementTree functions, and writing little functions to walk the tree and print stuff out. I'd like to construct a little wxPython program to modify the values graphically, maybe using something like a TreeCtrl widget. I'm pretty sure I can figure out how to get the data into the widget. - Struct - File Name: water - Number of Atoms: 3 etc. What's confusing me is what I do when I shut down the gui and save the data back to a file. What I would like to be able to do is to update the values in the ElementTree itself, and use the .write(file) function of the elementtree to write out the file, since that ends up printing out something pretty much identical to the original xml file. If I want to do this, it seems like I need to keep a connection between the gui element and the original value in the elementtree, so I can update it. But I'm having a hard time visualizing exactly how this works. Can someone help me out here a bit If this is impossible, or too difficult, I can certainly figure out a way to dump the XML directly from the gui itself, but I worry that I'll mangle the XML in the process, which elementtree doesn't do (i.e. the null operation, parsing a file with elementtree and writing it out again doesn't change anything). Seems like this is something that's probably pretty common, modifying a data structure using a gui, so I'm hoping that someone has thought about this and has some good advice about best practices here.
VIEWS ON THIS POST

185

Posted on:

Monday 5th November 2012
View Replies!

Creating Table using Tkinter

Hi i need to make a table to store a certain data using Tkinter..I have searched on the group but i have not been able to find a solution that would work for me..The thing is that i want my table to be scrollable both horizontally and vertically and i also want to transmit the data from the table serially to a microcontroller so i also need to make sure that i am able to read all the data individually..I am writing my code on Windows..my table is dynamic that is the number of columns are fixed but the number of rows can vary that would depend on the user..Initially i ask him about the number of rows...Waiting for your replies..
VIEWS ON THIS POST

82

Posted on:

Monday 5th November 2012
View Replies!

still get a using a python script in the crontab

H! I have made a program that is checking if a program is running or not. If the program is not running then it must start the program again. in the /etc/crontab: * * * * * root /usr/sbin/ program_prgchk in the /usr/sbin/program_prgchk: /usr/local/bin/python /home/reseller/domeinaanvraag/program_prgchk.py in the program_prgchk.py: ---------------------------------------- import string import os import commands def checkifrunning(): line = string.strip(commands.getoutput("ps x -o pid,command | grep program_reseller.py | grep -v 'grep'")) pid = string.split(line,' ')[0] if pid''id = int(pid) return pid if checkifrunning()=='': os.system('/usr/sbin/program_reseller') # os.wait() # os.waitpid(checkifrunning(),0) os._exit(0) If I run the command /usr/sbin/program_prgchk everything works (no process) But when I use it in the crontab I get a process
VIEWS ON THIS POST

184

Posted on:

Monday 5th November 2012
View Replies!

Implement file download using python

, I want to implement file downloads inside an authenticated web page, such that when a user clicks a link, the server side python code connects to a ftp server, downloads a relevant file and then streams the file to the browser for the user to open it with the appropriate application. In this case it will either be a pdf or a tiff file. This function is quite similar to something like writing raw bytes to a ServletOutputStream in java to be rendered directly to the user. It would be nice if someone can provide guidance, examples on how such a task may be accomplished using python.
VIEWS ON THIS POST

140

Posted on:

Monday 5th November 2012
View Replies!

IPv6 name resolution using getaddrinfo

Hi all, To get the hostname, I can use socket.gethostbyname() but that has an inherent limitation wherein does it not support IPv6 name resolution, and getaddrinfo() should be used instead. Looking up the socket.getaddrinfo() documentation, I come to know that The getaddrinfo() function returns a list of 5-tuples with the following structure: (family, socktype, proto, canonname, sockaddr) family, socktype, proto are all integer and are meant to be passed to the socket() function. canonname is a string representing the canonical name of the host. It can be a numeric IPv4/v6 address when AI_CANONNAME is specified for a numeric host. With this information, if I try something like this: >>> for res in socket.getaddrinfo('goofy.goofy.com', None, >>> socket.AI_CANONNAME): print res (2, 1, 6, '', ('10.98.1.6', 0)) (2, 2, 17, '', ('10.98.1.6', 0)) (2, 3, 0, '', ('10.98.1.6', 0)) In the output, I see the cannoname to be always blank ''. I am not getting the IPv4 or IPv6 address as a result of using getaddrinfo(). Am I making any mistake What i am trying is a replacement function for socket.gethostbyname(hostname) which will work for both IPv4 and IPv6. # return hostbyname for either IPv4 or IPv6 address. Common function. def ipv6_gethostbyname(hostname): for res in socket.getaddrinfo(hostname,None, socket.AI_CANONNAME): fa, socktype, proto, canonname, sa = res return cannoname The above function does not seem to work. It returns blank value only.
VIEWS ON THIS POST

147

Posted on:

Monday 5th November 2012
View Replies!

problems using pythom tempfile module

, I'm trying to test the tempfile module with the following script, which basically creates a temporary file, fills the file with some test data and prints it. import tempfile t = tempfile.TemporaryFile() t.write("lalalala") t.flush() print t.read() Unfortunately, the print statement gives me an empty string. Can somebody tell me what I'm doing wrong regards Samir
VIEWS ON THIS POST

111

Posted on:

Monday 5th November 2012
View Replies!

replacing xml elements with other elements using lxml

, I'm attempting to generate a random story using xml as the document, and lxml as the parser. I want the document to be simplified before processing it further, and am very close to accomplishing my goal. Below is what I have so far. Any ideas on how to move forward The goal: read and edit xml file, replacing random elements with randomly picked content from within Completed: [x] read xml [x] access first random tag [x] pick random content within random item [o] need to replace tag with picked contents xml sample: Here is some content. Here is some random content. Here is some more random content. Here is some content. Python code: from lxml import etree from StringIO import StringIO import random theXml = "Here is some content.Here is some random content.Here is some more random content.Here is some content." f = StringIO(theXml) tree = etree.parse(f) r = tree.xpath('//random') if len(r) > 0: randInt = random.randInt(0,(len(r[0]) - 1)) randContents = r[0][randInt][0] #replace parent random tag with picked content here now that I have the contents tag randomly chosen, how do I delete the parent tag, and replace it to look like this: final xml sample (goal): Here is some content. Here is some random content. Here is some content. Any idea on how to do this So close!
VIEWS ON THIS POST

172

Posted on:

Monday 5th November 2012
View Replies!

why psyco using more memery in liunx?

Hi all: When you import psyco in python2.5, you can see the memery grow up near 40MB in linux. but the same version python and psyco, is only grow up 1MB under windows. kyo
VIEWS ON THIS POST

181

Posted on:

Monday 5th November 2012
View Replies!

"No backend servers available" using httplib

i am trying to access printing templates from avery.com and i get a message from the nsapi plugin:no backend server available.can you help me
VIEWS ON THIS POST

165

Posted on:

Monday 5th November 2012
View Replies!

programming by contract using "decorators"

In the thread I started a few days ago, I was told that "programming by contract," could be done with "decorators." I was skeptical that this was a good approach, but as an exercise, I tried to code it up in a reasonably elegant form. I'd like to think I succeeded -- and I must admit that those who told me it could be done with decorators were right. My code is shown below. It shows a function called "myfunction," and another function for testing it called "myfunction_test." More detailed explanation follows the listing. Comments and feedback are welcome, of course. #!/usr/bin/env python def contract(test, check=0): "enforce programming by contract" if check: return test def null(func): def null2(*args, **keys): return func(*args, **keys) return null2 return null def getarg(args, keys, num, name): if name in keys: return keys[name] return args[num] def myfunction_test(myfunction): "contract test for function myfunction" def test(*args, **keys): x = getarg(args, keys, 0, 'x') y = getarg(args, keys, 1, 'y') z = getarg(args, keys, 2, 'z') # preconditions would go here, if there were any result = myfunction(x, y, z) # execute function assert result == x**2 + 3 * y + z # post-condition return result return test #======================================= CheckContracts = 1 @contract(myfunction_test, CheckContracts) def myfunction(x, y, z): return x**2 + 3 * y + z print myfunction(4, z=1, y=3) ------------------- end of listing --------------------- Here's what is going on. At the bottom of the listing, you will see the definition of a function called "myfunction," followed by a call of the function. It's a trivial function, but I gave it three arguments just to test passing them out of order by keyword. Just above the definition of "myfunction" is a "decorator" called "contract," which takes two arguments. The first argument specifies the name of the self-test contract function, which is "myfunction_test" in this case. The second argument is used to enable or disable the contract tests. Note that I could have just called the decorator "myfunction_test" and omitted the "contract" decorator, but I think this form, although slightly less efficient, is more readable. It also allows the enabling/ disabling logic to be put in one function rather than having to repeat it in every contract test function. Dealing with the arguments was not a trivial matter -- at least not for me. I had to experiment a bit to get it right. The "getarg" function is simply a utility for parsing the ordered and keyword arguments. It's very simple, but if something like this already exists, please let me know.
VIEWS ON THIS POST

78

Posted on:

Monday 5th November 2012
View Replies!

Re: extract text from log file using re

On 13/09/2007, Fabian Braennstroem wrote: > me again... I should describe it better: > the result should be an array with just: > > 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04 > 3.8545e-03 1.3315e-01 11:14:10 500 > 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > > as field values. > > Fabian Braennstroem schrieb am 09/13/2007 09:09 PM: > > > > > > I would like to delete a region on a log file which has this > > kind of structure: > > > > > > #------flutest------------------------------------------------------------ > > 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > > 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > > reversed flow in 1 faces on pressure-outlet 35. > > > > Writing > > "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.cas"... > > 5429199 mixed cells, zone 29, binary. > > 11187656 mixed interior faces, zone 30, binary. > > 20004 triangular wall faces, zone 31, binary. > > 1104 mixed velocity-inlet faces, zone 32, binary. > > 133638 triangular wall faces, zone 33, binary. > > 14529 triangular wall faces, zone 34, binary. > > 1350 mixed pressure-outlet faces, zone 35, binary. > > 11714 mixed wall faces, zone 36, binary. > > 1232141 nodes, binary. > > 1232141 node flags, binary. > > Done. > > > > > > Writing > > "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.dat"... > > Done. > > > > 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 > > 8.3913e-04 3.8545e-03 1.3315e-01 11:14:10 500 > > > > reversed flow in 2 faces on pressure-outlet 35. > > 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > > > > #------------------------------------------------------------------ > > > > I have a small script, which removes lines starting with > > '(re)versed', '(i)teration' and '(t)urbulent' and put the > > rest into an array: > > > > # -- plot residuals ---------------------------------------- > > import re > > filename="flutest" > > reversed_flow=re.compile('^\ re') > > turbulent_viscosity_ratio=re.compile('^\ tu') > > iteration=re.compile('^\ \ i') > > > > begin_of_res=re.compile('>\ \ \ i') > > end_of_res=re.compile('^\ ad') > > > > begin_of_writing=re.compile('^\Writing') > > end_of_writing=re.compile('^\Done') > > > > end_number=0 > > begin_number=0 > > > > > > n = 0 > > for line in open(filename).readlines(): > > n = n + 1 > > if begin_of_res.match(line): > > begin_number=n+1 > > print "Line Number (begin): " + str(n) > > > > if end_of_res.match(line): > > end_number=n > > print "Line Number (end): " + str(n) > > > > if begin_of_writing.match(line): > > begin_w=n+1 > > print "BeginWriting: " + str(n) > > print "HALLO" > > > > if end_of_writing.match(line): > > end_w=n+1 > > print "EndWriting: " +str(n) > > > > if n > end_number: > > end_number=n > > print "Line Number (end): " + str(end_number) > > > > > > > > > > > > n = 0 > > array = [] > > array_dummy = [] > > array_mapped = [] > > > > mapped = [] > > mappe = [] > > > > n = 0 > > for line in open(filename).readlines(): > > n = n + 1 > > if (begin_number n): > > # if (begin_w n): > > if not reversed_flow.match(line) and not > > iteration.match(line) and not > > turbulent_viscosity_ratio.match(line): > > m=(line.strip().split()) > > print m > > if len(m) > 0: > > # print len(m) > > laenge_liste=len(m) > > # print len(m) > > mappe.append(m) > > > > > > #--end plot > > residuals------------------------------------------------- > > > > This works fine ; except for the region with the writing > > information: > > > > #-----writing information > > ----------------------------------------- > > Writing "/home/fb/fluent-0500.cas"... > > 5429199 mixed cells, zone 29, binary. > > 11187656 mixed interior faces, zone 30, binary. > > 20004 triangular wall faces, zone 31, binary. > > 1104 mixed velocity-inlet faces, zone 32, binary. > > 133638 triangular wall faces, zone 33, binary. > > 14529 triangular wall faces, zone 34, binary. > > 1350 mixed pressure-outlet faces, zone 35, binary. > > 11714 mixed wall faces, zone 36, binary. > > 1232141 nodes, binary. > > 1232141 node flags, binary. > > Done. > > # -------end writing information ------------------------------- > > > > Does anyone know, how I can this 'writing' stuff too The > > matchingIt occurs a lot :-( > > > > the result should be an array with just: > > > 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04 > 3.8545e-03 1.3315e-01 11:14:10 500 > 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 Sometimes Python is so simple there is a tendancy to overthink the problem Based soley on the input and output in your example and not withstanding errors from the email itself word-wrapping yours and my text: >>> print '\r\n'.join([x.strip() for x in open('c:/flutest.txt') if 'e-0' in x]) 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04 3.8545e-03 1.3315e-01 11:14:10 500 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 >>> HTH
VIEWS ON THIS POST

179

Posted on:

Monday 5th November 2012
View Replies!

3D plot of 50 lines kwing end points using VTK

does anyone know how to plot multimple lines like lets say... 50 lines each liine is defined beetween two given points using VTK. a litlle example will be ok please on python and VTK
VIEWS ON THIS POST

96

Posted on:

Monday 5th November 2012
View Replies!

using the filter function within class return error

I'm trying to use the __builtin__ filter function within a class; however, I receive the following error: NameError: global name 'MajEthnic' is not defined The line of code is: EthMaj = filter(self.MajEthnic,flist) So, I'm trying to use the MajEthnic function to filter the list flist. Any ideas
VIEWS ON THIS POST

155

Posted on:

Monday 5th November 2012
View Replies!

Re: FM synthesis using Numpy

"Joost Molenaar" wrote in message news:3657a8860708141639l7e90ebdoe844691627152e40@mail.gmail.com... | I'm trying to build a simple FM synthesizer in Python. As a beginner, | I take 'FM synthesizer' to | mean: "using a sine wave to control the frequency of another sine wave." If you don't get an answer here, try the numpy/scipy list(s)
VIEWS ON THIS POST

81

Posted on:

Monday 5th November 2012
View Replies!