Search Results

Search found 8942 results on 358 pages for 'print r'.

Page 47/358 | < Previous Page | 43 44 45 46 47 48 49 50 51 52 53 54  | Next Page >

  • Python constructor does weird things with optional parameters

    - by christangrant
    Can you help me understand of the behaviour and implications of the python __init__ constructor. It seems like when there is an optional parameter and you try and set an existing object to a new object the optional value of the existing object is preserved and copied. Ok that was confusing... so look at an example I concocted below. In the code below I am trying to make a tree structure with nodes and possibly many children . In the first class NodeBad, the constructor has two parameters, the value and any possible children. The second class NodeGood only takes the value of the node as a parameter. Both have an addchild method to add a child to a node. When creating a tree with the NodeGood class, it works as expected. However, when doing the same thing with the NodeBad class, it seems as though a child can only be added once! The code below will result in the following output: Good Tree 1 2 3 [< 3 >] Bad Tree 1 2 2 [< 2 >, < 3 >] Que Pasa? Here is the Example: #!/usr/bin/python class NodeBad: def __init__(self, value, c=[]): self.value = value self.children = c def addchild(self, node): self.children.append(node) def __str__(self): return '< %s >' % self.value def __repr__(self): return '< %s >' % self.value class NodeGood: def __init__(self, value): self.value = value self.children = [] def addchild(self, node): self.children.append(node) def __str__(self): return '< %s >' % self.value def __repr__(self): return '< %s >' % self.value if __name__ == '__main__': print 'Good Tree' ng = NodeGood(1) # Root Node rootgood = ng ng.addchild(NodeGood(2)) # 1nd Child ng = ng.children[0] ng.addchild(NodeGood(3)) # 2nd Child print rootgood.value print rootgood.children[0].value print rootgood.children[0].children[0].value print rootgood.children[0].children print 'Bad Tree' nb = NodeBad(1) # Root Node rootbad = nb nb.addchild(NodeBad(2)) # 1st Child nb = nb.children[0] nb.addchild(NodeBad(3)) # 2nd Child print rootbad.value print rootbad.children[0].value print rootbad.children[0].children[0].value print rootbad.children[0].children

    Read the article

  • how to use @ in python.. and the @property

    - by zjm1126
    this is my code: def a(): print 'sss' @a() def b(): print 'aaa' b() and the Traceback is: sss Traceback (most recent call last): File "D:\zjm_code\a.py", line 8, in <module> @a() TypeError: 'NoneType' object is not callable so how to use the '@' thanks updated class a: @property def b(x): print 'sss' aa=a() print aa.b it print : sss None how to use @property thanks

    Read the article

  • Python and displaying HTML

    - by Tyler Seymour
    I've gotten pretty comfortable with Python and now I'm looking to make a rudimentary web application. I was somewhat scared of Django and the other Python frameworks so I went caveman on it and decided to generate the HTML myself using another Python script. Maybe this is how you do it anyways - but I'm just figuring this stuff out. I'm really looking for a tip-off on, well, what to do next. My Python script PRINTS the HTML (is this even correct? I need it to be on a webpage!), but now what? Thanks for your continued support during my learning process. One day I will post answers! -Tyler Here's my code: from SearchPhone import SearchPhone phones = ["Iphone 3", "Iphone 4", "Iphone 5","Galaxy s3", "Galaxy s2", "LG Lucid", "LG Esteem", "HTC One S", "Droid 4", "Droid RAZR MAXX", "HTC EVO", "Galaxy Nexus", "LG Optimus 2", "LG Ignite", "Galaxy Note", "HTC Amaze", "HTC Rezound", "HTC Vivid", "HTC Rhyme", "Motorola Photon", "Motorola Milestone", "myTouch slide", "HTC Status", "Droid 3", "HTC Evo 3d", "HTC Wildfire", "LG Optimus 3d", "HTC ThunderBolt", "Incredible 2", "Kyocera Echo", "Galaxy S 4g", "HTC Inspire", "LG Optimus 2x", "Samsung Gem", "HTC Evo Shift", "Nexus S", "LG Axis", "Droid 2", "G2", "Droid x", "Droid Incredible" ] print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>table of phones</title> </head> <body> </body> </html> """ #table print '<table width="100%" border="1">' for x in phones: y = SearchPhone(x) print "\t<tr>" print "\t\t<td>" + str(y[0]) + "</td>" print "\t\t<td>" + str(y[1]) + "</td>" print "\t\t<td>" + str(y[2]) + "</td>" print "\t\t<td>" + str(y[3]) + "</td>" print "\t\t<td>" + str(y[4]) + "</td>" print "\t</tr>" print "</table>

    Read the article

  • Cant overload python socket.send

    - by ralu
    Code from socket import socket class PolySocket(socket): def __init__(self,*p): print "PolySocket init" socket.__init__(self,*p) def sendall(self,*p): print "PolySocket sendall" return socket.sendall(self,*p) def send(self,*p): print "PolySocket send" return socket.send(self,*p) def connect(self,*p): print "connecting..." socket.connect(self,*p) print "connected" HOST="stackoverflow.com" PORT=80 readbuffer="" s=PolySocket() s.connect((HOST, PORT)) s.send("a") s.sendall("a") Output: PolySocket init connecting... connected PolySocket sendall As we can see, send method is not overloaded.

    Read the article

  • Pure python implementation of greenlet API

    - by Tristan
    The greenlet package is used by gevent and eventlet for asynchronous IO. It is written as a C-extension and therefore doesn't work with Jython or IronPython. If performance is of no concern, what is the easiest approach to implementing the greenlet API in pure Python. A simple example: def test1(): print 12 gr2.switch() print 34 def test2(): print 56 gr1.switch() print 78 gr1 = greenlet(test1) gr2 = greenlet(test2) gr1.switch() Should print 12, 56, 34 (and not 78).

    Read the article

  • printing the instance in Python

    - by kame
    Hello! With this code: class Complex: def __init__(self, realpart, imagpart): self.real = realpart self.imag = imagpart print self.real, self.imag class Circle: def __init__(self, radius): print "A circle wiht the radius", radius, "has the properties:" print "circumference =", 3.14*radius print "area =", 3.14*radius**2 I get this output: >>> Complex(3,2) 3 2 <__main__.Complex instance at 0x01412210> But why does he print the last line?

    Read the article

  • why my code print this when i read and write..

    - by zjm1126
    def sss(request): handle=open('b.txt','r+') handle.write("I AM NEW FILE") var=handle.read(); return HttpResponse(var) urlpatterns = patterns('', ('^$',sss), ) 1.my b.txt has nothing 2.when i run my code ,it print this : I AM NEW FILE7 ??; ??x ??v1?pZ€0 ?????8N??p? ? ?) ? ?`16?? S6??? ?? ?@ ??p? {?€1?? V ?? @+ ? ? ? ? ???`? >?) ???@? Z!x`%?p??? ?????@?`7???`? ? ???1X ??????#????€0?(Q??H??P?#? ' ?(5 ?, 7??6H? 0??+?? k%8? `? ??"?` ?? ?0?? ?????/? ????8S1`?`????0? ?`????? ?? ?? ?????@]?HE,????+?+???p? @O??? ?? 37€P6?7?@= ?? ? ?+xP?x???70? ?????? €???€ h *??x ?1???€K ? ??8? ?? ?? ?`?? @?? ????? ?€????????8(?P? ??? p(0B????????? ???? P???? ?/?+?? 9 ? ? ????1???????? ; ?€??€? `?(??? ??+ ??0?? ????6 ?1?,??? {0??? X??€D ??&?€?`? ?H{ ???Xw???? ?? ??0?0?)€Q ?? ?? ? @?????? ?XA6??? O ?0 h ?? ??? ? ? j????0? 57?7@?H+ ?? ? `?? 18? ?P ??6?0????6?? ?a ?` ????????? pG8s???@ ? ? (, ? ( ?? ?+&?????7??!0[ 0m ????@??0?????? ??? p?pZ?+?@?€\1?? 0? ?? ??? ?€;?? ??`? ? ? ????*`7?@? 6 R ?????p?????00^#? ??8? h €,h? ? ??x+ ??€37????`+?P?? 1 ? ?????*??6?? ??h: ??83 ? ????0s ????? ?p? ??????" s?( ??x Q s l??x ndies". * If value is 1, cand{{ value|pluralize:"y,ies" }} displays "1 candy". * If value is 2, cand{{ value|pluralize:"y,ies" }} displays "2 candies". u ,i u i ( RE RG R5 R3 R4 ( R R< R t singular_suffixt plural_suffix( ( s? D:\Python25\lib\site-packages\django\template\defaultfilters.pyt pluralize4 s$ c C s d d k l } | | ? S( sD Takes a phone number and converts it in to its numerical equivalent.i????( t phone2numeric( Rc R ( R R why? thanks

    Read the article

  • How can my CGI program access non-browseable files?

    - by Zerobu
    I was wondering if it was possible to read a text file that was located in a directory called "/home/user/files" I wanted to read it from my cgi-bin which is located in /home/user/cgi-bi/ Below is my code, #!/usr/bin/perl use strict; use CGI; #Virtual Directory #Steffan Harris eval { use constant PASSWORD => 'perl'; use constant UPLOAD_DIR => '/home/sharris2/files'; sub mapToFile { print chdir UPLOAD_DIR; } #This function will list all files in a directory. sub listDirectoryFiles { chdir UPLOAD_DIR; my @files = <*>; mapToFile; print<<LIST; <h2>Current Files</h2> <ul> LIST if(!$files[0]) { print" </ul>\n<em>No files in directory</em>"; } foreach(@files) { print" <li>$_</li>"; } print " </ul>\n"; } #This function generates a 404 Not Found error sub generate404 { print<<RESPONSE; Status: 404 Not Found Content-Type: text/html <html> <head><title>404 Not Found</title></head> <body> <p> <h1>404 - Not Found</h1> </p> The requested URL <b>$ENV{"HTTP_HOST"}$ENV{"REQUEST_URI"}</b> was not found on the server. </body> </html> RESPONSE exit; } #This function checks the path info to see if it matches a file in the UPLOAD_DIR directory, If it does not, then it returns a 404 error sub checkExsistence { if($ENV{"PATH_INFO"}) { chdir UPLOAD_DIR; my @files = <*>; if(!$files[0] and $ENV{"PATH_INFO"} eq "/") { return; } foreach(@files) { if($ENV{"PATH_INFO"} eq "/".$_ || $ENV{"PATH_INFO"} eq "/") { print "yes"; return; } } generate404; } } sub checkPassword { my ($password, $cgi); $cgi = new CGI; $password = $cgi->param('passwd'); unless($password eq PASSWORD) { print<<RESPONSE; Status: 200 OK Content-Type: text/html <html> <head> <title>Incorrect Password</title> </head> <body> <h1>Invalid password entered.</h1> <h3><a href="/~sharris2/cgi-bin/files/">Go Back</a></h3> </body> RESPONSE exit; } } sub upLoadFile { checkPassword; my ($uploadfile, $cgi); $cgi = new CGI; $uploadfile = $cgi->upload('uploadfile'); chdir UPLOAD_DIR; $uploadfile or die "Did not receive a file to upload"; open my $FILE, '>', UPLOAD_DIR."/$uploadfile" or die "$!"; while(<$uploadfile>) { print $FILE $_; } } #Start of main part of program my $cgi = new CGI; if(!$ENV{"PATH_INFO"}) { print $cgi->redirect('/~sharris2/cgi-bin/files/'); } checkExsistence; if($ENV{"REQUEST_METHOD"} eq "POST") { upLoadFile; } print <<"HEADERS"; Status: 200 OK Content-Type: text/html HEADERS print <<"HTML"; <html> <head> <title>Virtual Directory</title> </head> <body> HTML listDirectoryFiles; print<<HTML; <h2>Upload a new file</h2> <form method = "POST" enctype = "multipart/form-data" action = "/~sharris2/cgi-bin/files/" /> File:<input type = "file" name="uploadfile"/> <p>Password: <input type = "password" name ="passwd"/></p> <p><input type = "submit" value= "Submit File" /></p> </form> </body> </html> HTML };

    Read the article

  • Why am I getting a " instance has no attribute '__getitem__' " error?

    - by Kevin Yusko
    Here's the code: class BinaryTree: def __init__(self,rootObj): self.key = rootObj self.left = None self.right = None root = [self.key, self.left, self.right] def getRootVal(root): return root[0] def setRootVal(newVal): root[0] = newVal def getLeftChild(root): return root[1] def getRightChild(root): return root[2] def insertLeft(self,newNode): if self.left == None: self.left = BinaryTree(newNode) else: t = BinaryTree(newNode) t.left = self.left self.left = t def insertRight(self,newNode): if self.right == None: self.right = BinaryTree(newNode) else: t = BinaryTree(newNode) t.right = self.right self.right = t def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in '+-*/)': currentTree.setRootVal(eval(i)) parent = pStack.pop() currentTree = parent elif i in '+-*/': currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: print "error: I don't recognize " + i return eTree def postorder(tree): if tree != None: postorder(tree.getLeftChild()) postorder(tree.getRightChild()) print tree.getRootVal() def preorder(self): print self.key if self.left: self.left.preorder() if self.right: self.right.preorder() def inorder(tree): if tree != None: inorder(tree.getLeftChild()) print tree.getRootVal() inorder(tree.getRightChild()) class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def main(): parseData = raw_input( "Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) " ) tree = buildParseTree(parseData) print( "The post order is: ", + postorder(tree)) print( "The post order is: ", + postorder(tree)) print( "The post order is: ", + preorder(tree)) print( "The post order is: ", + inorder(tree)) main() And here is the error: Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) ( 1 + 2 ) Traceback (most recent call last): File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 108, in main() File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 102, in main tree = buildParseTree(parseData) File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 46, in buildParseTree currentTree = currentTree.getLeftChild() File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 15, in getLeftChild return root[1] AttributeError: BinaryTree instance has no attribute '__getitem__'

    Read the article

  • Jquery if visible conditional not working

    - by Wade D Ouellet
    Hey, I have a page going here that uses jQuery: http://treethink.com/services What I am trying to do is, if a slide or sub-page is shown in there, change the background colour and colour of the button. To do this I tried saying, if a certain div is shown, the background colour of a certain button changes. However, you can see there that it isn't working properly, it is changing the colour for the web one but not removing the colour change and adding a colour change on a different button when you change pages. Here is the overall code: /* Hide all pages except for web */ $("#services #web-block").show(); $("#services #print-block").hide(); $("#services #branding-block").hide(); /* When a button is clicked, show that page and hide others */ $("#services #web-button").click(function() { $("#services #web-block").show(); $("#services #print-block").hide(); $("#services #branding-block").hide(); }); $("#services #print-button").click(function() { $("#services #print-block").show(); $("#services #web-block").hide(); $("#services #branding-block").hide(); }); $("#services #branding-button").click(function() { $("#services #branding-block").show(); $("#services #web-block").hide(); $("#services #print-block").hide(); }); /* If buttons are active, disable hovering */ if ($('#services #web-block').is(":visible")) { $("#services #web-button").css("background", "#444444"); $("#services #web-button").css("color", "#999999"); } if ($('#services #print-block').is(":visible")) { $("#services #print-button").css("background", "#444444"); $("#services #print-button").css("color", "#999999"); } if ($('#services #branding-block').is(":visible")) { $("#services #branding-button").css("background", "#444444"); $("#services #branding-button").css("color", "#999999"); } Thanks, Wade

    Read the article

  • Passing arguments to commandline with directories having spaces

    - by superstar
    Hi guys, I am making a system call from perl for ContentCheck.pl and passing parameters with directories (having spaces). So I pass them in quotes, but they are not being picked up in the ContentCheck.pl file Random.pm my $call = "$perlExe $contentcheck -t $target_path -b $base_path -o $output_path -s $size_threshold"; print "\ncall: ".$call."\n"; system($call); Contentcheck.pl use vars qw($opt_t $opt_b $opt_o $opt_n $opt_s $opt_h); # initialize getopts('t:b:o:n:s:h') or do{ print "*** Error: Invalid command line option. Use option -h for help.\a\n"; exit 1}; if ($opt_h) {print $UsagePage; exit; } my $tar; if ($opt_t) {$tar=$opt_t; print "\ntarget ".$tar."\n";} else { print " in target"; print "*** Error: Invalid command line option. Use option -h for help.\a\n"; exit 1;} my $base; if ($opt_b) {$base=$opt_b;} else { print "\nin base\n"; print "*** Error: Invalid command line option. Use option -h for help.\a\n"; exit 1;} This is the output in the commandline call: D:\tools\PacketCreationTool/bin/perl/winx64/bin/perl.exe D:/tools/PacketCr eationTool/scripts/ContentCheck.pl -t "C:/Documents and Settings/pkkonath/Deskto p/saved/myMockName.TGZ" -b "input file/myMockName.TGZ" -o myMockName.validate -s 10 target C:/Documents in base *** Error: Invalid command line option. Use option -h for help. Any suggestions are welcome! Thanks.

    Read the article

  • How to poll a file in /sys

    - by Bjoern
    Hi, I am stuck reading a file in /sys/ which contains the light intensity in Lux of the ambient light sensor on my Nokia N900 phone. See thread on talk.maemo.org here I tried to use pyinotify to poll the file but this looks some kind of wrong to me since the file is alway "process_IN_OPEN", "process_IN_ACCESS" and "process_IN_CLOSE_NOWRITE" I basically want to get the changes ASAP and if something changed trigger an event, execute a class... Here's the code I tried, which works, but not as I expected (I was hoping for process_IN_MODIFY to be triggered): #!/usr/bin/env python # -*- coding: utf-8 -*- # import os, time, pyinotify import pyinotify ambient_sensor = '/sys/class/i2c-adapter/i2c-2/2-0029/lux' wm = pyinotify.WatchManager() # Watch Manager mask = pyinotify.ALL_EVENTS def action(self, the_event): value = open(the_event.pathname, 'r').read().strip() return value class EventHandler(pyinotify.ProcessEvent): def process_IN_ACCESS(self, event): print "ACCESS event:", action(self, event) def process_IN_ATTRIB(self, event): print "ATTRIB event:", action(self, event) def process_IN_CLOSE_NOWRITE(self, event): print "CLOSE_NOWRITE event:", action(self, event) def process_IN_CLOSE_WRITE(self, event): print "CLOSE_WRITE event:", action(self, event) def process_IN_CREATE(self, event): print "CREATE event:", action(self, event) def process_IN_DELETE(self, event): print "DELETE event:", action(self, event) def process_IN_MODIFY(self, event): print "MODIFY event:", action(self, event) def process_IN_OPEN(self, event): print "OPEN event:", action(self, event) #log.setLevel(10) notifier = pyinotify.ThreadedNotifier(wm, EventHandler()) notifier.start() wdd = wm.add_watch(ambient_sensor, mask) wdd time.sleep(5) notifier.stop() Thanks for any hints, suggestions and examples Kind regards Bjoern

    Read the article

  • Refresh decorator

    - by Morgoth
    I'm trying to write a decorator that 'refreshes' after being called, but where the refreshing only occurs once after the last function exits. Here is an example: @auto_refresh def a(): print "In a" @auto_refresh def b(): print "In b" a() If a() is called, I want the refresh function to be run after exiting a(). If b() is called, I want the refresh function to be run after exiting b(), but not after a() when called by b(). Here is an example of a class that does this: class auto_refresh(object): def __init__(self, f): print "Initializing decorator" self.f = f def __call__(self, *args, **kwargs): print "Before function" if 'refresh' in kwargs: refresh = kwargs.pop('refresh') else: refresh = False self.f(*args, **kwargs) print "After function" if refresh: print "Refreshing" With this decorator, if I run b() print '---' b(refresh=True) print '---' b(refresh=False) I get the following output: Initializing decorator Initializing decorator Before function In b Before function In a After function After function --- Before function In b Before function In a After function After function Refreshing --- Before function In b Before function In a After function After function So when written this way, not specifying the refresh argument means that refresh is defaulted to False. Can anyone think of a way to change this so that refresh is True when not specified? Changing the refresh = False to refresh = True in the decorator does not work: Initializing decorator Initializing decorator Before function In b Before function In a After function Refreshing After function Refreshing --- Before function In b Before function In a After function Refreshing After function Refreshing --- Before function In b Before function In a After function Refreshing After function because refresh then gets called multiple times in the first and second case, and once in the last case (when it should be once in the first and second case, and not in the last case).

    Read the article

  • change column widths in mysql query

    - by addi
    <?php // Connection Database $search = $_POST ['Search']; mysql_connect("xxxxxx", "xxxxxxxxx", "xxxxxx") or die ("Error Connecting to Database"); mysql_select_db("xxxxxx") or die('Error'); $data = mysql_query("SELECT* FROM course WHERE MATCH (CourseName, CourseDescription, CourseLeader) AGAINST ('". $search ."')") or die (mysql_error()); Print "<table border cellpadding=3>"; while($info = mysql_fetch_array( $data )) { Print "<tr>"; Print "<th>Course Name:</th> <td>".$info['CourseName'] . "</td> "; Print "<th>Course Description:</th><td>".$info['CourseDescription'] . "</td> "; Print "<th>Course Leader:</th><td>".$info['CourseLeader'] . " </td></tr>"; } Print "</table>"; ?> In my php code I print the columns CourseName, CourseDescription, CourseLeader after a search, as a resultset. CourseDescription has a lot of text, how do I print it all? is there a way to change the column widths?

    Read the article

  • small code redundancy within while-loops (doesn't feel clean)

    - by wallacoloo
    So, in Python (though I think it can be applied to many languages), I find myself with something like this quite often: the_input = raw_input("what to print?\n") while the_input != "quit": print the_input the_input = raw_input("what to print?\n") Maybe I'm being too picky, but I don't like how the line the_input = raw_input("what to print?\n") has to get repeated. It decreases maintainability and organization. But I don't see any workarounds for avoiding the duplicate code without further decreasing the problem. In some languages, I could write something like this: while ((the_input=raw_input("what to print?\n")) != "quit") { print the_input } This is definitely not Pythonic, and Python doesn't even allow for assignment within loop conditions AFAIK. This valid code fixes the redundancy, while 1: the_input = raw_input("what to print?\n") if the_input == "quit": break print the_input But doesn't feel quite right either. The while 1 implies that this loop will run forever; I'm using a loop, but giving it a fake condition and putting the real one inside it. Am I being too picky? Is there a better way to do this? Perhaps there's some language construct designed for this that I don't know of?

    Read the article

  • Python: Copying files with special characters in path

    - by erikderwikinger
    Hi is there any possibility in Python 2.5 to copy files having special chars (Japanese chars, cyrillic letters) in their path? shutil.copy cannot handle this. here is some example code: import copy, os,shutil,sys fname=os.getenv("USERPROFILE")+"\\Desktop\\testfile.txt" print fname print "type of fname: "+str(type(fname)) fname0 = unicode(fname,'mbcs') print fname0 print "type of fname0: "+str(type(fname0)) fname1 = unicodedata.normalize('NFKD', fname0).encode('cp1251','replace') print fname1 print "type of fname1: "+str(type(fname1)) fname2 = unicode(fname,'mbcs').encode(sys.stdout.encoding) print fname2 print "type of fname2: "+str(type(fname2)) shutil.copy(fname2,'C:\\') the output on a Russian Windows XP C:\Documents and Settings\+????????????\Desktop\testfile.txt type of fname: <type 'str'> C:\Documents and Settings\?????????????\Desktop\testfile.txt type of fname0: <type 'unicode'> C:\Documents and Settings\+????????????\Desktop\testfile.txt type of fname1: <type 'str'> C:\Documents and Settings\?????????????\Desktop\testfile.txt type of fname2: <type 'str'> Traceback (most recent call last): File "C:\Test\getuserdir.py", line 23, in <module> shutil.copy(fname2,'C:\\') File "C:\Python25\lib\shutil.py", line 80, in copy copyfile(src, dst) File "C:\Python25\lib\shutil.py", line 46, in copyfile fsrc = open(src, 'rb') IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\\\x80\ xa4\xac\xa8\xad\xa8\xe1\xe2\xe0\xa0\xe2\xae\xe0\\Desktop\\testfile.txt'

    Read the article

  • My QFileSystemModel doesn't work as expected in PyQt

    - by Skilldrick
    I'm learning the Qt Model/View architecture at the moment, and I've found something that doesn't work as I'd expect it to. I've got the following code (adapted from Qt Model Classes): from PyQt4 import QtCore, QtGui model = QtGui.QFileSystemModel() parentIndex = model.index(QtCore.QDir.currentPath()) print model.isDir(parentIndex) #prints True print model.data(parentIndex).toString() #prints name of current directory childIndex = model.index(0, 0, parentIndex) print model.data(childIndex).toString() rows = model.rowCount(parentIndex) print rows #prints 0 (even though the current directory has directory and file children) The question: Is this a problem with PyQt, have I just done something wrong, or am I completely misunderstanding QFileSystemModel? According to the documentation, model.rowCount(parentIndex) should return the number of children in the current directory. The QFileSystemModel docs say that it needs an instance of a Gui application, so I've also placed the above code in a QWidget as follows, but with the same result: import sys from PyQt4 import QtCore, QtGui class Widget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) model = QtGui.QFileSystemModel() parentIndex = model.index(QtCore.QDir.currentPath()) print model.isDir(parentIndex) print model.data(parentIndex).toString() childIndex = model.index(0, 0, parentIndex) print model.data(childIndex).toString() rows = model.rowCount(parentIndex) print rows def main(): app = QtGui.QApplication(sys.argv) widget = Widget() widget.show() sys.exit(app.exec_()) if __name__ == '__main__': main()

    Read the article

  • [Python] Tips for making a fraction calculator code more optimized (faster and using less memory)

    - by Logic Named Joe
    Hello Everyone, Basicly, what I need for the program to do is to act a as simple fraction calculator (for addition, subtraction, multiplication and division) for the a single line of input, for example: -input: 1/7 + 3/5 -output: 26/35 My initial code: import sys def euclid(numA, numB): while numB != 0: numRem = numA % numB numA = numB numB = numRem return numA for wejscie in sys.stdin: wyjscie = wejscie.split(' ') a, b = [int(x) for x in wyjscie[0].split("/")] c, d = [int(x) for x in wyjscie[2].split("/")] if wyjscie[1] == '+': licz = a * d + b * c mian= b * d nwd = euclid(licz, mian) konA = licz/nwd konB = mian/nwd wynik = str(konA) + '/' + str(konB) print(wynik) elif wyjscie[1] == '-': licz= a * d - b * c mian= b * d nwd = euclid(licz, mian) konA = licz/nwd konB = mian/nwd wynik = str(konA) + '/' + str(konB) print(wynik) elif wyjscie[1] == '*': licz= a * c mian= b * d nwd = euclid(licz, mian) konA = licz/nwd konB = mian/nwd wynik = str(konA) + '/' + str(konB) print(wynik) else: licz= a * d mian= b * c nwd = euclid(licz, mian) konA = licz/nwd konB = mian/nwd wynik = str(konA) + '/' + str(konB) print(wynik) Which I reduced to: import sys def euclid(numA, numB): while numB != 0: numRem = numA % numB numA = numB numB = numRem return numA for wejscie in sys.stdin: wyjscie = wejscie.split(' ') a, b = [int(x) for x in wyjscie[0].split("/")] c, d = [int(x) for x in wyjscie[2].split("/")] if wyjscie[1] == '+': print("/".join([str((a * d + b * c)/euclid(a * d + b * c, b * d)),str((b * d)/euclid(a * d + b * c, b * d))])) elif wyjscie[1] == '-': print("/".join([str((a * d - b * c)/euclid(a * d - b * c, b * d)),str((b * d)/euclid(a * d - b * c, b * d))])) elif wyjscie[1] == '*': print("/".join([str((a * c)/euclid(a * c, b * d)),str((b * d)/euclid(a * c, b * d))])) else: print("/".join([str((a * d)/euclid(a * d, b * c)),str((b * c)/euclid(a * d, b * c))])) Any advice on how to improve this futher is welcome. Edit: one more thing that I forgot to mention - the code can not make use of any libraries apart from sys.

    Read the article

  • Python: problem with tiny script to delete files

    - by Rosarch
    I have a project that used to be under SVN, but now I'm moving it to Mercurial, so I want to clear out all the .svn files. It's a little too big to do it by hand, so I decided to write a python script to do it. But it isn't working. def cleandir(dir_path): print "Cleaning %s\n" % dir_path toDelete = [] files = os.listdir(dir_path) for filedir in files: print "considering %s" % filedir # continue if filedir == '.' or filedir == '..': print "skipping %s" % filedir continue path = dir_path + os.sep + filedir if os.path.isdir(path): cleandir(path) else: print "not dir: %s" % path if 'svn' in filedir: toDelete.append(path) print "Files to be deleted:" for candidate in toDelete: print candidate print "Delete all? [y|n]" choice = raw_input() if choice == 'y': for filedir in toDelete: if os.path.isdir(filedir): os.rmdir(filedir) else: os.unlink(filedir) exit() if __name__ == "__main__": cleandir(dir) The print statements show that it's only "considering" the filedirs whose names start with ".". However, if I uncomment the continue statement, all the filedirs are "considered". Why is this? Or is there some other utility that already exists to recursively de-SVN-ify a directory tree?

    Read the article

  • Trying to run my code and compiler seems to just close after it executes [migrated]

    - by Shane
    I am trying to run a program and the compiler seems to just crash right after it executes ... i have no build errors so i am wondering what the hell is going on ... I am a bit of a novice so all help would be appreciated =). I don't know if you might have time to scan through the code but this is what i have got : using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class Student { string Fname, Lname, Program ; int Sid ; // Inputting information for students public void InputStudentInfo () { Console.WriteLine ("Please enter your first name") ; Fname = Console.ReadLine() ; Console.WriteLine ("Please enter you last name") ; Lname = Console.ReadLine() ; Console.WriteLine ("Please enter you student ID#") ; Sid = int.Parse(Console.ReadLine()) ; Console.WriteLine ("Enter the Program that you are completeing") ; Program = Console.ReadLine() ; } // Printing information for students public void PrintStudentInfo () { Console.Write (" Your name is " + Fname) ; Console.Write(" " + Lname); Console.WriteLine (" Your student identification number is " + Sid) ; Console.WriteLine (" The program you are registered for is " + Program) ; } /* public void MenuInterface() { Console.WriteLine (" 1. Input Student information" ) ; Console.WriteLine (" 2. Input Course information" ) ; Console.WriteLine (" 3. Input Grade information" ) ; Console.WriteLine (" 4. Print Course information" ) ; Console.WriteLine (" 5. Print Student information" ) ; Console.WriteLine (" 6. Print Grade information" ) ; Console.WriteLine (" 7. Print Student information including Course they are registered in and the grade obtained for that course" ) ; Console.WriteLine (" 8. Print grade info of the course in which student has achieved the highest grade" ) ; Console.WriteLine (" 0. Exit") ; Console.WriteLine (" Please select a choice from 0-8") ; accode = Console.ReadLine(); } */ } public class Course { string course1, course2, course3 ; int Stuid ; // Inputting Course Information public void InputCourseInfo () { Console.WriteLine (" Please re-enter your identification number") ; Stuid = int.Parse(Console.ReadLine()) ; Console.WriteLine (" Enter the name of your first course") ; course1 = Console.ReadLine() ; Console.WriteLine (" Enter the name of your second course") ; course2 = Console.ReadLine() ; Console.WriteLine (" Enter the name of your third course") ; course3 = Console.ReadLine() ; } // Printing Course Information public void PrintCourseInfo () { Console.WriteLine (" Your ID # is " + Stuid) ; Console.Write (" The Courses you selected are " + course1) ; Console.Write("," + course2); Console.Write(" and " + course3); } } public class Grade : Course { int Studentid ; int [] hwgrade ; int [] cwgrade ; int [] midegrade ; int [] finalegrade ; int [] totalgrade ; string coursename ; public Grade ( string cname , int Studentident , int [] homework , int [] classwork , int [] midexam , int [] finalexam) { coursename = cname ; Studentid = Studentident ; hwgrade = homework ; cwgrade = classwork ; midegrade = midexam ; finalegrade = finalexam ; } public string coname { get { return coursename ; } set { coursename = value ; } } public int Studentidenty { get { return Studentid ; } set { Studentid = value ; } } public void InputGradeInfo() { Console.WriteLine (" Please enter your Student ID" ) ; grade.Studentidenty = Console.ReadLine() ; for ( int i = 0; i < 3; i++) { Console.Writeline (" Please enter the Course name" ) ; grade.coname[i] = Console.Readline() ; Console.Writeline (" Please enter your homework grade") ; grade.hwgrade[i] = int.parse(Console.Readline()) ; // ..... } } public void CalcTotalGrade() { for (int i = 0; i < 3; i++) { grade.courseper[i] = (grade.hwgrade[i] + grade.cwgrade[i]) / 2; grade.finalper[i] = (grade.midexam[i] + grade.finalegrade[i]) / 2; grade.totalgrade[i] = (grade.courseper[i] + finalper[i]) / 2; } } public void PrintGradeInfo() { for ( int i = 0; i < 3; i++) { Console.Writeline (" Your homework grade is" + grade.hwgrade[i]) ; // ..... } } static void Main(string[] args) { int accode ; Student student = new Student() ; Course course = new Course() ; Grade grade = new Grade() ; do { Console.WriteLine(" 1. Input Student information"); Console.WriteLine(" 2. Input Course information"); Console.WriteLine(" 3. Input Grade information"); Console.WriteLine(" 4. Print Course information"); Console.WriteLine(" 5. Print Student information"); Console.WriteLine(" 6. Print Grade information"); Console.WriteLine(" 7. Print Student information including Course they are registered in and the grade obtained for that course"); Console.WriteLine(" 8. Print grade info of the course in which student has achieved the highest grade"); Console.WriteLine(" 0. Exit"); Console.WriteLine(" Please select a choice from 0-8"); accode = Console.ReadLine(); switch (accode) { case 1: student.InputStudentInfo(); break; case 2: course.InputCourseInfo(); break; case 3: grade.InputGradeInfo(); break; case 4: course.PrintCourseInfo(); break; case 5: student.PRintStudentInfo(); break; case 6: grade.PrintGradeInfo(); break; case 0: Console.WriteLine(" You have chosen to exit the program have a good day. =)"); break; } } while (accode != 0); Console.ReadKey(); } } }

    Read the article

  • Creating New Scripts Dynamically in Lua

    - by bazola
    Right now this is just a crazy idea that I had, but I was able to implement the code and get it working properly. I am not entirely sure of what the use cases would be just yet. What this code does is create a new Lua script file in the project directory. The ScriptWriter takes as arguments the file name, a table containing any arguments that the script should take when created, and a table containing any instance variables to create by default. My plan is to extend this code to create new functions based on inputs sent in during its creation as well. What makes this cool is that the new file is both generated and loaded dynamically on the fly. Theoretically you could get this code to generate and load any script imaginable. One use case I can think of is an AI that creates scripts to map out it's functions, and creates new scripts for new situations or environments. At this point, this is all theoretical, though. Here is the test code that is creating the new script and then immediately loading it and calling functions from it: function Card:doScriptWriterThing() local scriptName = "ScriptIAmMaking" local scripter = scriptWriter:new(scriptName, {"argumentName"}, {name = "'test'", one = 1}) scripter:makeFileForLoadedSettings() local loadedScript = require (scriptName) local scriptInstance = loadedScript:new("sayThis") print(scriptInstance:get_name()) --will print test print(scriptInstance:get_one()) -- will print 1 scriptInstance:set_one(10000) print(scriptInstance:get_one()) -- will print 10000 print(scriptInstance:get_argumentName()) -- will print sayThis scriptInstance:set_argumentName("saySomethingElse") print(scriptInstance:get_argumentName()) --will print saySomethingElse end Here is ScriptWriter.lua local ScriptWriter = {} local twoSpaceIndent = " " local equalsWithSpaces = " = " local newLine = "\n" --scriptNameToCreate must be a string --argumentsForNew and instanceVariablesToCreate must be tables and not nil function ScriptWriter:new(scriptNameToCreate, argumentsForNew, instanceVariablesToCreate) local instance = setmetatable({}, { __index = self }) instance.name = scriptNameToCreate instance.newArguments = argumentsForNew instance.instanceVariables = instanceVariablesToCreate instance.stringList = {} return instance end function ScriptWriter:makeFileForLoadedSettings() self:buildInstanceMetatable() self:buildInstanceCreationMethod() self:buildSettersAndGetters() self:buildReturn() self:writeStringsToFile() end --very first line of any script that will have instances function ScriptWriter:buildInstanceMetatable() table.insert(self.stringList, "local " .. self.name .. " = {}" .. newLine) table.insert(self.stringList, newLine) end --every script made this way needs a new method to create its instances function ScriptWriter:buildInstanceCreationMethod() --new() function declaration table.insert(self.stringList, ("function " .. self.name .. ":new(")) self:buildNewArguments() table.insert(self.stringList, ")" .. newLine) --first line inside :new() function table.insert(self.stringList, twoSpaceIndent .. "local instance = setmetatable({}, { __index = self })" .. newLine) --add designated arguments inside :new() self:buildNewArgumentVariables() --create the instance variables with the loaded values for key,value in pairs(self.instanceVariables) do table.insert(self.stringList, twoSpaceIndent .. "instance." .. key .. equalsWithSpaces .. value .. newLine) end --close the :new() function table.insert(self.stringList, twoSpaceIndent .. "return instance" .. newLine) table.insert(self.stringList, "end" .. newLine) table.insert(self.stringList, newLine) end function ScriptWriter:buildNewArguments() --if there are arguments for :new(), add them for key,value in ipairs(self.newArguments) do table.insert(self.stringList, value) table.insert(self.stringList, ", ") end if next(self.newArguments) ~= nil then --makes sure the table is not empty first table.remove(self.stringList) --remove the very last element, which will be the extra ", " end end function ScriptWriter:buildNewArgumentVariables() --add the designated arguments to :new() for key, value in ipairs(self.newArguments) do table.insert(self.stringList, twoSpaceIndent .. "instance." .. value .. equalsWithSpaces .. value .. newLine) end end --the instance variables need separate code because their names have to be the key and not the argument name function ScriptWriter:buildSettersAndGetters() for key,value in ipairs(self.newArguments) do self:buildArgumentSetter(value) self:buildArgumentGetter(value) table.insert(self.stringList, newLine) end for key,value in pairs(self.instanceVariables) do self:buildInstanceVariableSetter(key, value) self:buildInstanceVariableGetter(key, value) table.insert(self.stringList, newLine) end end --code for arguments passed in function ScriptWriter:buildArgumentSetter(variable) table.insert(self.stringList, "function " .. self.name .. ":set_" .. variable .. "(newValue)" .. newLine) table.insert(self.stringList, twoSpaceIndent .. "self." .. variable .. equalsWithSpaces .. "newValue" .. newLine) table.insert(self.stringList, "end" .. newLine) end function ScriptWriter:buildArgumentGetter(variable) table.insert(self.stringList, "function " .. self.name .. ":get_" .. variable .. "()" .. newLine) table.insert(self.stringList, twoSpaceIndent .. "return " .. "self." .. variable .. newLine) table.insert(self.stringList, "end" .. newLine) end --code for instance variable values passed in function ScriptWriter:buildInstanceVariableSetter(key, variable) table.insert(self.stringList, "function " .. self.name .. ":set_" .. key .. "(newValue)" .. newLine) table.insert(self.stringList, twoSpaceIndent .. "self." .. key .. equalsWithSpaces .. "newValue" .. newLine) table.insert(self.stringList, "end" .. newLine) end function ScriptWriter:buildInstanceVariableGetter(key, variable) table.insert(self.stringList, "function " .. self.name .. ":get_" .. key .. "()" .. newLine) table.insert(self.stringList, twoSpaceIndent .. "return " .. "self." .. key .. newLine) table.insert(self.stringList, "end" .. newLine) end --last line of any script that will have instances function ScriptWriter:buildReturn() table.insert(self.stringList, "return " .. self.name) end function ScriptWriter:writeStringsToFile() local fileName = (self.name .. ".lua") file = io.open(fileName, 'w') for key,value in ipairs(self.stringList) do file:write(value) end file:close() end return ScriptWriter And here is what the code provided will generate: local ScriptIAmMaking = {} function ScriptIAmMaking:new(argumentName) local instance = setmetatable({}, { __index = self }) instance.argumentName = argumentName instance.name = 'test' instance.one = 1 return instance end function ScriptIAmMaking:set_argumentName(newValue) self.argumentName = newValue end function ScriptIAmMaking:get_argumentName() return self.argumentName end function ScriptIAmMaking:set_name(newValue) self.name = newValue end function ScriptIAmMaking:get_name() return self.name end function ScriptIAmMaking:set_one(newValue) self.one = newValue end function ScriptIAmMaking:get_one() return self.one end return ScriptIAmMaking All of this is generated with these calls: local scripter = scriptWriter:new(scriptName, {"argumentName"}, {name = "'test'", one = 1}) scripter:makeFileForLoadedSettings() I am not sure if I am correct that this could be useful in certain situations. What I am looking for is feedback on the readability of the code, and following Lua best practices. I would also love to hear whether this approach is a valid one, and whether the way that I have done things will be extensible.

    Read the article

  • operator overloading of stream extraction operator in C++ help

    - by Crystal
    I'm having some trouble overloading my stream extraction operator in C++ for a hw assignment. I'm not really sure why I am getting these compile errors since I thought I was doing it right... Here is my code: Complex.h #ifndef COMPLEX_H #define COMPLEX_H class Complex { //friend ostream &operator<<(ostream &output, const Complex &complexObj) const; public: Complex(double = 0.0, double = 0.0); // constructor Complex operator+(const Complex &) const; // addition Complex operator-(const Complex &) const; // subtraction void print() const; // output private: double real; // real part double imaginary; // imaginary part }; #endif Complex.cpp #include <iostream> #include "Complex.h" using namespace std; // Constructor Complex::Complex(double realPart, double imaginaryPart) : real(realPart), imaginary(imaginaryPart) { } // addition operator Complex Complex::operator+(const Complex &operand2) const { return Complex(real + operand2.real, imaginary + operand2.imaginary); } // subtraction operator Complex Complex::operator-(const Complex &operand2) const { return Complex(real - operand2.real, imaginary - operand2.imaginary); } // Overload << operator ostream &Complex::operator<<(ostream &output, const Complex &complexObj) const { cout << '(' << complexObj.real << ", " << complexObj.imaginary << ')'; return output; // returning output allows chaining } // display a Complex object in the form: (a, b) void Complex::print() const { cout << '(' << real << ", " << imaginary << ')'; } main.cpp #include <iostream> #include "Complex.h" using namespace std; int main() { Complex x; Complex y(4.3, 8.2); Complex z(3.3, 1.1); cout << "x: "; x.print(); cout << "\ny: "; y.print(); cout << "\nz: "; z.print(); x = y + z; cout << "\n\nx = y + z: " << endl; x.print(); cout << " = "; y.print(); cout << " + "; z.print(); x = y - z; cout << "\n\nx = y - z: " << endl; x.print(); cout << " = "; y.print(); cout << " - "; z.print(); cout << endl; } Compile erros: complex.cpp(23) : error C2039: '<<' : is not a member of 'Complex' complex.h(5) : see declaration of 'Complex' complex.cpp(24) : error C2270: '<<' : modifiers not allowed on nonmember functions complex.cpp(25) : error C2248: 'Complex::real' : cannot access private member declared in class 'Complex' complex.h(13) : see declaration of 'Complex::real' complex.h(5) : see declaration of 'Complex' complex.cpp(25) : error C2248: 'Complex::imaginary' : cannot access private member declared in class 'Complex' complex.h(14) : see declaration of 'Complex::imaginary' complex.h(5) : see declaration of 'Complex' Thanks!

    Read the article

  • Unknown error sourcing a script containing 'typeset -r' wrapped in command substitution

    - by Bernard Assaf
    I wish to source a script, print the value of a variable this script defines, and then have this value be assigned to a variable on the command line with command substitution wrapping the source/print commands. This works on ksh88 but not on ksh93 and I am wondering why. $ cat typeset_err.ksh #!/bin/ksh unset _typeset_var typeset -i -r _typeset_var=1 DIR=init # this is the variable I want to print When run on ksh88 (in this case, an AIX 6.1 box), the output is as follows: $ A=$(. ./typeset_err.ksh; print $DIR) $ echo $A init When run on ksh93 (in this case, a Linux machine), the output is as follows: $ A=$(. ./typeset_err.ksh; print $DIR) -ksh: _typeset_var: is read only $ print $A ($A is undefined) The above is just an example script. The actual thing I wish to accomplish is to source a script that sets values to many variables, so that I can print just one of its values, e.g. $DIR, and have $A equal that value. I do not know in advance the value of $DIR, but I need to copy files to $DIR during execution of a different batch script. Therefore the idea I had was to source the script in order to define its variables, print the one I wanted, then have that print's output be assigned to another variable via $(...) syntax. Admittedly a bit of a hack, but I don't want to source the entire sub-script in the batch script's environment because I only need one of its variables. The typeset -r code in the beginning is the error. The script I'm sourcing contains this in order to provide a semaphore of sorts--to prevent the script from being sourced more than once in the environment. (There is an if statement in the real script that checks for _typeset_var = 1, and exits if it is already set.) So I know I can take this out and get $DIR to print fine, but the constraints of the problem include keeping the typeset -i -r. In the example script I put an unset in first, to ensure _typeset_var isn't already defined. By the way I do know that it is not possible to unset a typeset -r variable, according to ksh93's man page for ksh. There are ways to code around this error. The favorite now is to not use typeset, but just set the semaphore without typeset (e.g. _typeset_var=1), but the error with the code as-is remains as a curiosity to me, and I want to see if anyone can explain why this is happening. By the way, another idea I abandoned was to grep the variable I need out of its containing script, then print that one variable for $A to be set to; however, the variable ($DIR in the example above) might be set to another variable's value (e.g. DIR=$dom/init), and that other variable might be defined earlier in the script; therefore, I need to source the entire script to make sure I all variables are defined so that $DIR is correctly defined when sourcing.

    Read the article

< Previous Page | 43 44 45 46 47 48 49 50 51 52 53 54  | Next Page >