Search Results

Search found 19539 results on 782 pages for 'pretty print'.

Page 61/782 | < Previous Page | 57 58 59 60 61 62 63 64 65 66 67 68  | Next Page >

  • programs hangs during socket interaction

    - by herrturtur
    I have two programs, sendfile.py and recvfile.py that are supposed to interact to send a file across the network. They communicate over TCP sockets. The communication is supposed to go something like this: sender =====filename=====> receiver sender <===== 'ok' ======= receiver or sender <===== 'no' ======= receiver if ok: sender ====== file ======> receiver I've got The sender and receiver code is here: Sender: import sys from jmm_sockets import * if len(sys.argv) != 4: print "Usage:", sys.argv[0], "<host> <port> <filename>" sys.exit(1) s = getClientSocket(sys.argv[1], int(sys.argv[2])) try: f = open(sys.argv[3]) except IOError, msg: print "couldn't open file" sys.exit(1) # send filename s.send(sys.argv[3]) # receive 'ok' buffer = None response = str() while 1: buffer = s.recv(1) if buffer == '': break else: response = response + buffer if response == 'ok': print 'receiver acknowledged receipt of filename' # send file s.send(f.read()) elif response == 'no': print "receiver doesn't want the file" # cleanup f.close() s.close() Receiver: from jmm_sockets import * s = getServerSocket(None, 16001) conn, addr = s.accept() buffer = None filename = str() # receive filename while 1: buffer = conn.recv(1) if buffer == '': break else: filename = filename + buffer print "sender wants to send", filename, "is that ok?" user_choice = raw_input("ok/no: ") if user_choice == 'ok': # send ok conn.send('ok') #receive file data = str() while 1: buffer = conn.recv(1) if buffer=='': break else: data = data + buffer print data else: conn.send('no') conn.close() I'm sure I'm missing something here in the sorts of a deadlock, but don't know what it is.

    Read the article

  • Faster quadrature decoder loops with Python code

    - by Kelei
    I'm working with a BeagleBone Black and using Adafruit's IO Python library. Wrote a simple quadrature decoding function and it works perfectly fine when the motor runs at about 1800 RPM. But when the motor runs at higher speeds, the code starts missing some of the interrupts and the encoder counts start to accumulate errors. Do you guys have any suggestions as to how I can make the code more efficient or if there are functions which can cycle the interrupts at a higher frequency. Thanks, Kel Here's the code: # Define encoder count function def encodercount(term): global counts global Encoder_A global Encoder_A_old global Encoder_B global Encoder_B_old global error Encoder_A = GPIO.input('P8_7') # stores the value of the encoders at time of interrupt Encoder_B = GPIO.input('P8_8') if Encoder_A == Encoder_A_old and Encoder_B == Encoder_B_old: # this will be an error error += 1 print 'Error count is %s' %error elif (Encoder_A == 1 and Encoder_B_old == 0) or (Encoder_A == 0 and Encoder_B_old == 1): # this will be clockwise rotation counts += 1 print 'Encoder count is %s' %counts print 'AB is %s %s' % (Encoder_A, Encoder_B) elif (Encoder_A == 1 and Encoder_B_old == 1) or (Encoder_A == 0 and Encoder_B_old == 0): # this will be counter-clockwise rotation counts -= 1 print 'Encoder count is %s' %counts print 'AB is %s %s' % (Encoder_A, Encoder_B) else: #this will be an error as well error += 1 print 'Error count is %s' %error Encoder_A_old = Encoder_A # store the current encoder values as old values to be used as comparison in the next loop Encoder_B_old = Encoder_B # Initialize the interrupts - these trigger on the both the rising and falling GPIO.add_event_detect('P8_7', GPIO.BOTH, callback = encodercount) # Encoder A GPIO.add_event_detect('P8_8', GPIO.BOTH, callback = encodercount) # Encoder B # This is the part of the code which runs normally in the background while True: time.sleep(1)

    Read the article

  • Python script to delete old SVN files lacks permission

    - by Rosarch
    I'm trying to delete old SVN files from directory tree. shutil.rmtree and os.unlink raise WindowsErrors, because the script doesn't have permissions to delete them. How can I get around that? Here is the script: # Delete all files of a certain type from a direcotry import os import shutil dir = "c:\\" verbosity = 0; def printCleanMsg(dir_path): if verbosity: print "Cleaning %s\n" % dir_path def cleandir(dir_path): printCleanMsg(dir_path) toDelete = [] dirwalk = os.walk(dir_path) for root, dirs, files in dirwalk: printCleanMsg(root) toDelete.extend([root + os.sep + dir for dir in dirs if '.svn' == dir]) toDelete.extend([root + os.sep + file for file in files if 'svn' in file]) print "Items to be deleted:" for candidate in toDelete: print candidate print "Delete all %d items? [y|n]" % len(toDelete) choice = raw_input() if choice == 'y': deleted = 0 for filedir in toDelete: if os.path.exists(filedir): # could have been deleted already by rmtree try: if os.path.isdir(filedir): shutil.rmtree(filedir) else: os.unlink(filedir) deleted += 1 except WindowsError: print "WindowsError: Couldn't delete '%s'" % filedir print "\nDeleted %d/%d files." % (deleted, len(toDelete)) exit() if __name__ == "__main__": cleandir(dir) Not a single file is able to be deleted. What am I doing wrong?

    Read the article

  • AttributeError in my Python program regarding classes

    - by Axel Finkel
    I'm doing an exercise out of the Python book that involves creating a class and a subclass. I am getting the following error when I try to run the program: AttributeError: 'Customer' object has no attribute 'name', when it tries to go through this bit of code: self.name.append(name) As this is my first time dealing with classes and objects in Python, I'm sure I am making some overt mistake somewhere, but I can't seem to figure it out. I've looked over the documentation for creating classes and writing member functions, and it looks correct, but it is obviously not. I want the Customer subclass to inherit the name, address, and telephone attributes from the Person superclass, but it doesn't seem to be doing so? Here is my code: class Person: def __init__(self): self.name = None self.address = None self.telephone = None def changeName(self, name): self.name.append(name) def changeAddress(self, address): self.address.append(address) def changeTelephone(self, telephone): self.telephone.append(telephone) class Customer(Person): def __init__(self): self.customerNumber = None self.onMailingList = False def changeCustomerNumber(self, customerNumber): self.customerNumber.append(customerNumber) def changeOnMailingList(): if onMailingList == False: onMailingList == True else: onMailingList == False def main(): customer1 = Customer() name = 'Bob Smith' address = '123 Somewhere Road' telephone = '111 222 3333' customerNumber = '12345' customer1.changeName(name) customer1.changeAddress(address) customer1.changeTelephone(telephone) customer1.changeCustomerNumber(customerNumber) print("Customer name: " + customer1.name) print("Customer address: " + customer1.address) print("Customer telephone number: " + customer1.telephone) print("Customer number: " + customer1.customerNumber) print("On mailing list: " + customer1.OnMailingList) customer1.changeOnMailingList() print("On mailing list: " + customer1.OnMailingList) main()

    Read the article

  • new to lists on python

    - by user1762229
    This is my current code: while True: try: mylist = [0] * 7 for x in range(7): sales = float(input("Sales for day:")) mylist[x] = sales if sales < 0: print ("Sorry,invalid. Try again.") except: print ("Sorry, invalid. Try again.") else: break print (mylist) best = max(sales) worst = min(sales) print ("Your best day had", best, "in sales.") print ("Your worst day had", worst, "in sales.") When I run it I get this: Sales for day:-5 Sorry,invalid. Try again. Sales for day:-6 Sorry,invalid. Try again. Sales for day:-7 Sorry,invalid. Try again. Sales for day:-8 Sorry,invalid. Try again. Sales for day:-9 Sorry,invalid. Try again. Sales for day:-2 Sorry,invalid. Try again. Sales for day:-5 Sorry,invalid. Try again. [-5.0, -6.0, -7.0, -8.0, -9.0, -2.0, -5.0] Traceback (most recent call last): File "C:/Users/Si Hong/Desktop/HuangSiHong_assign9_part.py", line 45, in <module> best = max(sales) TypeError: 'float' object is not iterable I am not quite sure how to code it so that, the lists do NOT take in negative values, because I only want values 0 or greater. I am not sure how to solve the TypeError issue so that the min and max values will print as in my code My last issue is, if I want to find the average value of the seven inputs that an user puts in, how should I go about this in pulling the values out of the lists Thank you so much

    Read the article

  • Printing an Image embedded into an asp.net page. C#

    - by user1683846
    I am looking to print using C#, micorsoft visual studio, asp.net. The goal:- I am trying to print all pages in a fax document. Format:- The fax document is received as a single .tiff file with multiple pages. What needs to be done:- I need to iterate each page in the .tiff image and print them all. // This function will iterate all pages, one at a time. // protected void PrintAll_Click(object sender, EventArgs e) { // counts number of pages in the fax document.// int number = _FaxPages.Count; // for loop to iterate through each page. // for (int i = 0; i < number; i++) { string _FaxId = Page.Request["FaxId"]; _PageIndex = i; imgFax.ImageUrl = "ShowFax.ashx?n=" + _FaxId + "&f=" + _PageIndex + "&mw=750"; PrintAll.Attributes.Add("onclick", "return printing()"); } } and In my Java script I have: function printing() { window.print(); } Now the issues are: <1 The function only prints one page (the very last page of the tiff file)....and it prints the entire window and not just the embedded .tiff image in the entire web browser window. Any Ideas of how to go about just printing the .tiff embedded image instead of the entire web browser window. <2 Although my for loop iterates through the pages. The print function is only called after the loop has iterated through all the pages and stopped on the final page (say page 6/6). And then it only prints that last page (along with the rest of the contents on the browser window). This is not what I want to happen... I dont want to print all the excess material on the browser window such as buttons, links etc... I just want the embedded .tiff image from the browser window.

    Read the article

  • servlet ArrayList and HashMap problem witch result

    - by nonameplum
    Hi, I have that code List<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); Map<String, Object> item = new HashMap<String, Object>(); data.clear(); item.clear(); int i = 0; while (i < 5){    item.put("id", i);    i++;    out.println("id: " + item.get("id"));    out.println("--------------------------");    data.add(item); } for(i=0 ; i<5 ; i++){    out.println("print data[" + i + "]" + data.get(i)); } Result of that is: id: 0 -------------------------- id: 1 -------------------------- id: 2 -------------------------- id: 3 -------------------------- id: 4 -------------------------- print data[0]{id=4} print data[1]{id=4} print data[2]{id=4} print data[3]{id=4} print data[4]{id=4} Why only last element is stored?

    Read the article

  • printSoln module problem

    - by dingo_d
    Hi I found in book:Numerical Methods in engineering with Python the module run_kut5, but for that module I need module printSoln, all provided in the book. Now I cp the code, made necessary line adjustments and so. The code looks like: # -*- coding: cp1250 -*- ## module printSoln ''' printSoln(X,Y,freq). Prints X and Y returned from the differential equation solvers using printput frequency ’freq’. freq = n prints every nth step. freq = 0 prints initial and final values only. ''' def printSoln(X,Y,freq): def printHead(n): print "\n x ", for i in range (n): print " y[",i,"] ", print def printLine(x,y,n): print "%13.4e"% x,f for i in range (n): print "%13.4e"% y[i], print m = len(Y) try: n = len(Y[0]) except TypeError: n = 1 if freq == 0: freq = m printHead(n) for i in range(0,m,freq): printLine(X[i],Y[i],n) if i != m - 1: printLine(X[m - 1],Y[m - 1],n) Now, when I run the program it says: line 24, in <module> m = len(Y) NameError: name 'Y' is not defined But I cp'd from the book :\ So now when I call the run_kut module I get the same error, no Y defined in printSoln... I'm trying to figure this out but I suck :( Help, please...

    Read the article

  • JS best practice for member functions

    - by MickMalone1983
    I'm writing a little mobile games library, and I'm not sure the best practice for declaring member functions of instantiated function objects. For instance, I might create a simple object with one property, and a method to print it: function Foo(id){ this.id = id; this.print = function(){ console.log(this.id); }; }; However, a function which does not need access to 'private' members of the function does not need to be declared in the function at all. I could equally have written: function print(){ console.log(this.id); }; function Foo(id){ this.id = id; this.print = print; }; When the function is invoked through an instance of Foo, the instance becomes the context for this, so the output is the same in either case. I'm not entirely sure how memory is allocated with JS, and I can't find anything that I can understand about something this specific, but it seems to me that with the first example all members of Foo, including the print function, are duplicated each time it is instantiated - but with the second, it just gets a pointer to one, pre-declared function, which would save any more memory having to be allocated as more instances of Foo are created. Am I correct, and if I am, is there any memory/performance benefit to doing this?

    Read the article

  • Why is /dev/rfcomm0 giving PySerial problems?

    - by Travis G.
    I am connecting my Ubuntu box to a wireless readout setup over Bluetooth. I wrote a Python script to send the serial information through /dev/rfcomm0. The script connects fine and works for a few minutes, but then Python will start using 100% CPU and the messages stop flowing through. I can open rfcomm0 in a serial terminal and communicate through it by hand just fine. When I open it through a terminal it seems to work indefinitely. Also, I can swap the Bluetooth receiver for a USB cable, and change the port to /dev/ttyUSB0, and I don't get any problems over time. It seems either I'm doing something wrong with rfcomm0 or PySerial doesn't handle it well. Here's the script: import psutil import serial import string import time sampleTime = 1 numSamples = 5 lastTemp = 0 TEMP_CHAR = 't' USAGE_CHAR = 'u' SENSOR_NAME = 'TC0D' gauges = serial.Serial() gauges.port = '/dev/rfcomm0' gauges.baudrate = 9600 gauges.parity = 'N' gauges.writeTimeout = 0 gauges.open() print("Connected to " + gauges.portstr) filename = '/sys/bus/platform/devices/applesmc.768/temp2_input' def parseSensorsOutputLinux(output): return int(round(float(output) / 1000)) while(1): usage = psutil.cpu_percent(interval=sampleTime) gauges.write(USAGE_CHAR) gauges.write(chr(int(usage))) #write the first byte #print("Wrote usage: " + str(int(usage))) sensorFile = open(filename) temp = parseSensorsOutputLinux(sensorFile.read()) gauges.write(TEMP_CHAR) gauges.write(chr(temp)) #print("Wrote temp: " + str(temp)) Any thoughts? Thanks. EDIT: Here is the revised code, using Python-BlueZ instead of PySerial: import psutil import serial import string import time import bluetooth sampleTime = 1 numSamples = 5 lastTemp = 0 TEMP_CHAR = 't' USAGE_CHAR = 'u' SENSOR_NAME = 'TC0D' #gauges = serial.Serial() #gauges.port = '/dev/rfcomm0' #gauges.baudrate = 9600 #gauges.parity = 'N' #gauges.writeTimeout = 0 #gauges.open() gaugeSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) gaugeSocket.connect(('00:06:66:42:22:96', 1)) filename = '/sys/bus/platform/devices/applesmc.768/temp2_input' def parseSensorsOutputLinux(output): return int(round(float(output) / 1000)) while(1): usage = psutil.cpu_percent(interval=sampleTime) #gauges.write(USAGE_CHAR) gaugeSocket.send(USAGE_CHAR) #gauges.write(chr(int(usage))) #write the first byte gaugeSocket.send(chr(int(usage))) #print("Wrote usage: " + str(int(usage))) sensorFile = open(filename) temp = parseSensorsOutputLinux(sensorFile.read()) #gauges.write(TEMP_CHAR) gaugeSocket.send(TEMP_CHAR) #gauges.write(chr(temp)) gaugeSocket.send(chr(temp)) #print("Wrote temp: " + str(temp)) It seems either Ubuntu must be closing /dev/rfcomm0 after a certain time or my Bluetooth receiver is messing things up. Even when the BluetoothError arises, the "connected" light on the receiver stays illuminated, and it is not until I power-cycle to receiver that I can reconnect. I'm not sure how to approach this problem. It's odd that the connection would work fine for a few minutes (seemingly a random amount of time) and then seize up. In case it helps, the Bluetooth receiver is a BlueSmirf Silver from Sparkfun. Do I need to be trying to maintain the connection from the receiver end or something?

    Read the article

  • Code refactoring with Visual Studio 2010 Part-2

    - by Jalpesh P. Vadgama
    In previous post I have written about Extract Method Code refactoring option. In this post I am going to some other code refactoring features of Visual Studio 2010.  Renaming variables and methods is one of the most difficult task for a developer. Normally we do like this. First we will rename method or variable and then we will find all the references then do remaining over that stuff. This will be become difficult if your variable or method are referenced at so many files and so many place. But once you use refactor menu rename it will be bit Easy. I am going to use same code which I have created in my previous post. I am just once again putting that code here for your reference. using System; namespace CodeRefractoring { class Program { static void Main(string[] args) { string firstName = "Jalpesh"; string lastName = "Vadgama"; Print(firstName, lastName); } private static void Print(string firstName, string lastName) { Console.WriteLine(string.Format("FirstName:{0}", firstName)); Console.WriteLine(string.Format("LastName:{0}", lastName)); Console.ReadLine(); } } } Now I want to rename print method in this code. To rename the method you can select method name and then select Refactor-> Rename . Once I selected Print method and then click on rename a dialog box will appear like following. Now I am renaming this Print method to PrintMyName like following.   Now once you click OK a dialog will appear with preview of code like following. It will show preview of code. Now once you click apply. You code will be changed like following. using System; namespace CodeRefractoring { class Program { static void Main(string[] args) { string firstName = "Jalpesh"; string lastName = "Vadgama"; PrintMyName(firstName, lastName); } private static void PrintMyName(string firstName, string lastName) { Console.WriteLine(string.Format("FirstName:{0}", firstName)); Console.WriteLine(string.Format("LastName:{0}", lastName)); Console.ReadLine(); } } } So that’s it. This will work in multiple files also. Hope you liked it.. Stay tuned for more.. Till that Happy Programming.

    Read the article

  • New Process For Receiving Oracle Certification Exam Results

    - by Brandye Barrington
    On November 15, 2012, Oracle Certification exam results will be available directly from Oracle's certification portal, CertView. After completing an exam at a testing center, you will login to CertView to access and print your exam scores by selecting the See My New Exam Results Now link or the Print My New Exam Results Now link from the homepage. This will provide access to all certification and exam history in one place through Oracle, providing tighter integration with other activities at Oracle. This change in policy will also increase security around data privacy. AUTHENTICATE YOUR CERTVIEW ACCOUNT NOW One very important step you must take is to authenticate your CertView account BEFORE taking your exam. This way, if there are any issues with authorization, you have time to get these sorted out before testing. Keep in mind that it can take up to 3 business days for a CertView account to be manually authenticated, so completing this process before testing is key! You will need to create a web account at PearsonVUE prior to registering for your exam and you will need to create an Oracle Web Account prior to authenticating your CertView account. The CertView account will be available for authentication within 30 minutes of creating a Pearson VUE web account at certview.oracle.com. GETTING YOUR EXAM RESULTS FROM ORACLE Before taking the scheduled exam, you should authenticate your account at certview.oracle.com using the email address and Oracle Testing ID in your Pearson VUE profile. You will be required to have an Oracle Web Account to authenticate your CertView account. After taking the exam, you will receive an email from Oracle indicating that your exam results are available at certview.oracle.com If you have previously authenticated your CertView account, you will simply click on the link in the email, which will take you to CertView, login and select See My New Exam Results Now. If you have not authenticated your CertView account before receiving this notification email, you will be required to authenticate your CertView account before accessing your exam results. Authentication requires an Oracle Web Account user name and password and the following information from your Pearson VUE profile: email address and Oracle Testing ID. Click on the link in the email to authenticate your CertView account You will be given the option to create an Oracle Web Account if you do no already have one.  After account authentication, you will be able to login to CertView and select See My New Exam Results Now to view your exam results or Print My New Exam Results Now to print your exam results. As always, if you need assistance with your CertView account, please contact Oracle Certification Support. YOUR QUESTIONS ANSWERED More Information FAQ: Receiving Exam Scores FAQ: How Do I Log Into CertView? FAQ: How To Get Exam Results FAQ: Accessing Exam Results in CertView FAQ: How Will I Know When My Exam Results Are Available? FAQ: What If I Don't Get An Exam Results Email Alert? FAQ: How To Download and Print Exam Score Reports FAQ: What If I Think My Exam Results Are Wrong In CertView? FAQ: Is Oracle Changing The Way That Exams Are Scored?

    Read the article

  • Access forbidden 403 error in xampp

    - by Ramvignesh
    I am very new to xampp. I have made a fresh xampp install with the following commands. sudo su cd /tmp wget bit.ly/1cmyrUo -O xampp-32bit.run chmod 777 ./xampp-32bit.run sudo ./xampp-32bit.run Then I made a perl file to check whether my xampp works. The following is my sample.pl file content. #!usr/bin/perl print "content-type:text/html\n"; print(header()); use CGI qw(:standard); print(start_html()); print "Hello. I am ram"; print(end_html()); After copying my perl file from /home/vicky/desktop to /opt/lampp/cgi-bin. I started my xampp with the following command. /opt/lampp/lampp start Then I ran my sample.pl in the localhost with the help of the http://localhost/cgi-bin/sample.pl in my mozilla browser. I just got the following window. I found only answers relating to the 'new security concept error' and 'accessing virtual host issue'. I did came across an askubuntu query, a bid similar to that of mine. It had no answers but some comments. One comment suggested to change the file permissions. It directed to get help from here. It said to change the directory permission as 755 and file permission as 644 to resolve this kind of issue. When I tried to do that, I came to know that my cgi-bin directory already had 755 permission and my sample.pl had 644 permission. I have no solutions now. PostScript: I have attached the content of my /opt/lampp/apache2/conf/httpd.conf file. Hope this will help the answer-providers to understand my problem completely. Alias /bitnami/ "/opt/lampp/apache2/htdocs/" Alias /bitnami "/opt/lampp/apache2/htdocs" <Directory "/opt/lampp/apache2/htdocs"> Options Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all </Directory>

    Read the article

  • My First 5K, the recap.

    - by Chris Williams
    It was a nice day to be outside (and trust me, those aren't words you'll hear from me often.) I got to the site around 7:45, hit the pre-reg table and got my number along with a goody bag full of coupons for racing gear, a water bottle and a tshirt. Oh and a map. Stashed all that stuff in the jeep, emptied my pockets of everything but my iPhone and my jeep key, and proceeded to walk around for a bit as people started showing up and signing in. It was fairly breezy, and there was definitely a storm coming... but it was anyone's guess on when it would actually arrive. It was interesting to see everyone who was participating. If I had to guess, I would say the event was 60-70% women, with a pretty broad distribution of age... as young as 13 to well over 60 (in both genders.) I don't know exactly how many folks were there, but it was well over 300. Eventually it was time to kick things off, and everyone made their way to the start line. All of the 5k and 10k runners were mixed together, starting at the same time. All the walkers and the people with strollers or dogs were in the back. It was pretty chaotic at first, once things started, but it thinned out fairly quickly. The 10k people and the hardcore runners sped ahead of everyone else and the walkers gradually lagged behind. The 5K course was pretty nice, winding around a lake down in Eden Prairie. The 10K course overlapped most of ours, but branched off a couple times too. I didn't run the whole time, but I started the race running and I ended it running, and did a mix of walking and running along the way. I met my goals, which were a) don't ever stop and b) don't be last. The weather managed to hold out for the entire race. It never got too hot, there was a nice breeze and it was mostly overcast. Pretty much perfect in my book. About 20-30 minutes after I left, the rain came down pretty hard. I had a good time, and will most likely do more of them. We'll see.

    Read the article

  • Perl: Edit hyperlinks in nested tags that aren't on seperate lines

    - by user305801
    I have an interesting problem. I wrote the following perl script to recursively loop through a directory and in all html files for img/script/a tags do the following: Convert the entire url to lowercase Replace spaces and %20 with underscores The script works great except when an image tag in wrapped with an anchor tag. Is there a way to modify the current script to also be able to manipulate the links for nested tags that are not on separate lines? Basically if I have <a href="..."><img src="..."></a> the script will only change the link in the anchor tag but skip the img tag. #!/usr/bin/perl use File::Find; $input="/var/www/tecnew/"; sub process { if (-T and m/.+\.(htm|html)/i) { #print "htm/html: $_\n"; open(FILE,"+<$_") or die "couldn't open file $!\n"; $out = ''; while(<FILE>) { $cur_line = $_; if($cur_line =~ m/<a.*>/i) { print "cur_line (unaltered) $cur_line\n"; $cur_line =~ /(^.* href=\")(.+?)(\".*$)/i; $beg = $1; $link = html_clean($2); $end = $3; $cur_line = $beg.$link.$end; print "cur_line (altered) $cur_line\n"; } if($cur_line =~ m/(<img.*>|<script.*>)/i) { print "cur_line (unaltered) $cur_line\n"; $cur_line =~ /(^.* src=\")(.+?)(\".*$)/i; $beg = $1; $link = html_clean($2); $end = $3; $cur_line = $beg.$link.$end; print "cur_line (altered) $cur_line\n"; } $out .= $cur_line; } seek(FILE, 0, 0) or die "can't seek to start of file: $!"; print FILE $out or die "can't print to file: $1"; truncate(FILE, tell(FILE)) or die "can't truncate file: $!"; close(FILE) or die "can't close file: $!"; } } find(\&process, $input); sub html_clean { my($input_string) = @_; $input_string = lc($input_string); $input_string =~ s/%20|\s/_/g; return $input_string; }

    Read the article

  • SQLite3 table not accepting INSERT INTO statements. The table is created, and so is the database, but nothing is passed into it

    - by user1460029
    <?php try { //open the database $db = new PDO('sqlite:music.db'); $db->exec("DELETE from Music;"); $db->exec("INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Whatd I Say', 'Ray Charles', '1956');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Smells Like Teen Spirit.', 'Nirvana', '1991');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Hey Jude', 'The Beatles', '1968');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Johnny B. Goode', 'Chuck Berry', '1958');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Good Vibrations', 'The Beach Boys', '1966');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Respect', 'Aretha Franklin', '1967');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Whats Going On', 'Marvin Gaye', '1971');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Imagine', 'John Lennon', '1971');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('(I Cant Get No) Satisfaction', 'Rolling Stones', '1965');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Like A Rolling Stone', 'Bob Dylan', '1965');"); //now output the data to a simple html table... //example of specifier --> WHERE First=\'Josh\'; <-- print "<table border=1>"; print "<tr><td>Title</td><td>Author</td><td>Y.O.P.</td></tr>"; $result = $db->query('SELECT * FROM Music '); foreach($result as $row) { print "<td>".$row['Title']."</td>"; print "<td>".$row['Author']."</td>"; print "<td>".$row['ReleaseDate']."</td></tr>"; } print "</table>"; $db = NULL; } catch(PDOException $e) { print 'Exception : '.$e->getMessage(); } ?> I am not sure why nothing is being inserted into the table. The file 'music.db' exists in the right path. For the record, I can only use SQlite3, no SQL allowed. PHP is allowed, so is SQLite3.

    Read the article

  • Failed to obtain JDBC Driver for MySQL under Tomcat environment

    - by Michael Mao
    Hi all: I've been trying to obtain the Driver class for JDBC connection to MySQL. The workstation is running on Linux, Fedora 10. I have manually set up the classpath variable for Java by CLI like this: bash-3.2$ echo $CLASSPATH /home/cmao/public_html/jsp/mysql-connector-java-5.1.12-bin.jar This shows that I've added the lastest mysql connection jar archive to my CLASSPATH variable. I've created a test JSP page which can be found here And source code for this page is: <%@page language="java"%> <%@page import="java.sql.*"%> <%@page import="java.util.*"%> <html> <head> <title>UTS JDBC MySQL connection test page</title> </head> <body> <% Connection con = null; out.print("Java version is : " + System.getProperty("java.version") + "<br />"); out.print("Tomcat version is : " + application.getServerInfo() + "<br />"); out.print("Servlet version is: " + application.getMajorVersion() + "<br />"); out.print("JSP version is : " + JspFactory.getDefaultFactory().getEngineInfo().getSpecificationVersion() +"<br />"); //out.print("Java classpath is : " + System.getProperty("java.class.path")+ "<br />"); //out.print("JSP classpath is : " + appliaction.getAttribute("org.apache.catalina.jsp_classpath") + "<br />"); //out.print("Tomcat classpath is : " + System.getProperty("org.apache.tomcat.common.classpath") + "<br />"); try { Class c = Class.forName("com.mysql.jdbc.Driver"); } catch(Exception e) { out.println("Error! Failed to obtain JDBC driver for MySQL... Missing class \"com.mysql.jdbc.Driver\"<br />"); } %> </body> </html> None of those commented out line would work, various Jsper Expetions would be thrown. You can check those Error pages from the following links: classpath Error page catalina Error page tomcat Error page It seems, from my limited knowledge of JSP and Servlet, the Tomcat environment "ignores" my Java CLASSPATH? In which case I cannot configure the MySQL JDBC package to let my Servlets(a JSP is but a Servlet anyway) work. I am not sure how to fix this issue. would it be better if I use an IDE like Eclipse or NetBeans and create a real Java "web app" so that everything can be "self-configured" by the usage of a web.config XML configuration file? So that I can certainly bypass this Tomcat environment restriction? Many thanks for the suggestions in advance.

    Read the article

  • Perl: Edit hyperlinks in nested tags that aren't on separate lines

    - by user305801
    I have an interesting problem. I wrote the following perl script to recursively loop through a directory and in all html files for img/script/a tags do the following: Convert the entire url to lowercase Replace spaces and %20 with underscores The script works great except when an image tag in wrapped with an anchor tag. Is there a way to modify the current script to also be able to manipulate the links for nested tags that are not on separate lines? Basically if I have <a href="..."><img src="..."></a> the script will only change the link in the anchor tag but skip the img tag. #!/usr/bin/perl use File::Find; $input="/var/www/tecnew/"; sub process { if (-T and m/.+\.(htm|html)/i) { #print "htm/html: $_\n"; open(FILE,"+<$_") or die "couldn't open file $!\n"; $out = ''; while(<FILE>) { $cur_line = $_; if($cur_line =~ m/<a.*>/i) { print "cur_line (unaltered) $cur_line\n"; $cur_line =~ /(^.* href=\")(.+?)(\".*$)/i; $beg = $1; $link = html_clean($2); $end = $3; $cur_line = $beg.$link.$end; print "cur_line (altered) $cur_line\n"; } if($cur_line =~ m/(<img.*>|<script.*>)/i) { print "cur_line (unaltered) $cur_line\n"; $cur_line =~ /(^.* src=\")(.+?)(\".*$)/i; $beg = $1; $link = html_clean($2); $end = $3; $cur_line = $beg.$link.$end; print "cur_line (altered) $cur_line\n"; } $out .= $cur_line; } seek(FILE, 0, 0) or die "can't seek to start of file: $!"; print FILE $out or die "can't print to file: $1"; truncate(FILE, tell(FILE)) or die "can't truncate file: $!"; close(FILE) or die "can't close file: $!"; } } find(\&process, $input); sub html_clean { my($input_string) = @_; $input_string = lc($input_string); $input_string =~ s/%20|\s/_/g; return $input_string; }

    Read the article

  • Compare array in loop

    - by user3626084
    I have 2 arrays with different sizes, in some cases one array can have more elements than the other array. However, I always need to compare the arrays using the same id. I need to get the other value with the same id in the other array I have tried this, but the problem happens when I compare the two arrays in a loop when the other array has more elements than one, because duplicate the loop and data , and it does not work. Here is what I've tried: <?php /// Actual Data Arrays /// $data_1=array("a1-fruits","b1-apple","c1-banana","d1-chocolate","e1-pear"); $data_2=array("b1-cars","e1-eggs"); /// for ($i=0;$i<count($data_1);$i++) { /// Explode ID $data_1 /// $exp_id=explode("-",$data_1[$i]); /// for ($h=0;$h<count($data_2);$h++) { /// Explode ID $data_2 /// $exp_id2=explode("-",$data_2[$h]); /// if ($exp_id[0]=="".$exp_id2[0]."") { print "".$data_2[$h].""; print "<br>"; } else { print "".$data_1[$i].""; print "<br>"; } /// } /// } ?> I want the following values : "a1-fruits" "b1-cars" "c1-banana" "d1-chocolate" "e1-eggs" Yet, I get this (which isn't what I want): a1-fruits a1-fruits b1-cars b1-apple c1-banana c1-banana d1-chocolate d1-chocolate e1-pear e1-eggs I tried everything I know and try to understand how I can do this because I don't understand how to compare these two arrays. The other problem is when one size has more elements than the other, the comparison always gives an error. I FIND THE SOLUTION TO THIS AND WORKING IN ALL : <?php /// Actual Data Arrays /// $data_1=array("a1-fruits","b1-apple","c1-banana","d1-chocolate","e1-pear"); $data_2=array("b1-cars","e1-eggs","d1-chocolate2"); /// for ($i=0;$i<count($data_1);$i++) { $show="bad"; /// Explode ID $data_1 /// $exp_id=explode("-",$data_1[$i]); /// for ($h=0;$h<count($data_2);$h++) { /// Explode ID $data_2 /// $exp_id2=explode("-",$data_2[$h]); /// if ($exp_id2[0]=="".$exp_id[0]."") { $show="ok"; print "".$data_2[$h]."<br>"; } /// } if ($show=="bad") { print "".$data_1[$i].""; print "<br>"; } /// } ?>

    Read the article

  • Is this the correct way to build a Perl hash that utilizes arrays?

    - by Structure
    This is the first time I have manipulated hashes and arrays in this way -- and it is working. Basically, for every key there are multiple values that I want to record and then print out in the form "key -- value -- value -- val..." My code is as follows. I am surprised that it works, so concerned that it works "by mistake". Is this the correct way to accomplish this task, or is there a more efficient or appropriate method? while ($source =~ m/(regex)/g) { #Get all key names from source $listkey = $1; #Set current list key to the current regex result. $list{$listkey} = ++$i unless $list{$listkey}; #Add the key to the hash unless it already exists. $list{$listkey} = [] unless exists $list{$listkey}; #Add an array for the hash unless the hash already exists. while ($loopcount==0) { if ($ifcount==0) { $listvalue=result_of_some_function_using_list_key; #Get the first list value from the list key. $ifcount++; #Increment so we only get the first list value once. } else { $listvalue=result_of_some_function_using_list_value; #Update the last list value. } if ($listvalue) { #If the function returned a value... push @{$list{$listkey}}, $listvalue; #...then add the value to the hash array for the key. } else { #There are no more values and we need a new key. $listkey=0; #Reset variable. $domain=0; #Reset variable. $loopcount++; #Increment loop counter to exit loop. } } $ifcount=0; #Reset count variable so the next listvalue can be generated from the new key. $loopcount=0; #Reset count variable so another loop can begin for a new key. } foreach $listkey (keys %list) { #For each key in the hash. print "$listkey --> "; #Print the key. @values = @{$list{$listkey}}; #Reference the arrays of the hash. print join ' --> ', @values; #Print the values. print "\n"; #Print new line. }

    Read the article

  • factory class, wrong number of arguments being passed to subclass constructor

    - by Hugh Bothwell
    I was looking at Python: Exception in the separated module works wrong which uses a multi-purpose GnuLibError class to 'stand in' for a variety of different errors. Each sub-error has its own ID number and error format string. I figured it would be better written as a hierarchy of Exception classes, and set out to do so: class GNULibError(Exception): sub_exceptions = 0 # patched with dict of subclasses once subclasses are created err_num = 0 err_format = None def __new__(cls, *args): print("new {}".format(cls)) # DEBUG if len(args) and args[0] in GNULibError.sub_exceptions: print(" factory -> {} {}".format(GNULibError.sub_exceptions[args[0]], args[1:])) # DEBUG return super(GNULibError, cls).__new__(GNULibError.sub_exceptions[args[0]], *(args[1:])) else: print(" plain {} {}".format(cls, args)) # DEBUG return super(GNULibError, cls).__new__(cls, *args) def __init__(self, *args): cls = type(self) print("init {} {}".format(cls, args)) # DEBUG self.args = args if cls.err_format is None: self.message = str(args) else: self.message = "[GNU Error {}] ".format(cls.err_num) + cls.err_format.format(*args) def __str__(self): return self.message def __repr__(self): return '{}{}'.format(type(self).__name__, self.args) class GNULibError_Directory(GNULibError): err_num = 1 err_format = "destination directory does not exist: {}" class GNULibError_Config(GNULibError): err_num = 2 err_format = "configure file does not exist: {}" class GNULibError_Module(GNULibError): err_num = 3 err_format = "selected module does not exist: {}" class GNULibError_Cache(GNULibError): err_num = 4 err_format = "{} is expected to contain gl_M4_BASE({})" class GNULibError_Sourcebase(GNULibError): err_num = 5 err_format = "missing sourcebase argument: {}" class GNULibError_Docbase(GNULibError): err_num = 6 err_format = "missing docbase argument: {}" class GNULibError_Testbase(GNULibError): err_num = 7 err_format = "missing testsbase argument: {}" class GNULibError_Libname(GNULibError): err_num = 8 err_format = "missing libname argument: {}" # patch master class with subclass reference # (TO DO: auto-detect all available subclasses instead of hardcoding them) GNULibError.sub_exceptions = { 1: GNULibError_Directory, 2: GNULibError_Config, 3: GNULibError_Module, 4: GNULibError_Cache, 5: GNULibError_Sourcebase, 6: GNULibError_Docbase, 7: GNULibError_Testbase, 8: GNULibError_Libname } This starts out with GNULibError as a factory class - if you call it with an error number belonging to a recognized subclass, it returns an object belonging to that subclass, otherwise it returns itself as a default error type. Based on this code, the following should be exactly equivalent (but aren't): e = GNULibError(3, 'missing.lib') f = GNULibError_Module('missing.lib') print e # -> '[GNU Error 3] selected module does not exist: 3' print f # -> '[GNU Error 3] selected module does not exist: missing.lib' I added some strategic print statements, and the error seems to be in GNULibError.__new__: >>> e = GNULibError(3, 'missing.lib') new <class '__main__.GNULibError'> factory -> <class '__main__.GNULibError_Module'> ('missing.lib',) # good... init <class '__main__.GNULibError_Module'> (3, 'missing.lib') # NO! ^ why? I call the subclass constructor as subclass.__new__(*args[1:]) - this should drop the 3, the subclass type ID - and yet its __init__ is still getting the 3 anyway! How can I trim the argument list that gets passed to subclass.__init__?

    Read the article

  • Testing IPP Printing with ipptool

    - by senloe
    I'm trying to send an IPP print job using the ipptool. Using the sample .test files, I can send commands to the printer, but I am unable to successfully use the print-job.test file. Here's an example using ipptool. c:\...>ipptool -v ipp://name.local.:631/ipp/printer print-job.test ipptool: Filename "$filename" on line 21 cannot be read. ipptool: Filename mapped to "". It looks like it's failing resolving the variable $filename within the test file so I attempted to hardcode this value in the test file. In this case I get no error, but still no print. Does anybody have any experience using ipptool to test ipp printing?

    Read the article

  • Application losing Printer within Terminal Services for remote users

    - by Richard
    Question: What I need to do is have a permanent link to a printer, normally only accessible through Terminal Services (Printer Redirect), to allow Sage Line 50 layouts to see that printer persistently, even after users have disconnected and reconnected to the Terminal Services session? Although the printer is accessible each time a user connects to the Sage Server via Terminal Services, it is given a different session number and therefore the Sage Layout sees it as a different printer. History behind question: Users using Terminal Services connecting to a Sage Server on a different site Using Sage Line 50 v 15 on that Server Users want to print invoices (sage layouts) locally Sage Server cannot see the users local printers, to get around this user uses the Print redirect features of Terminal Services The individual reports can be edited to point to a specific printer by default. This means the user just has to select an invoice and click print, then select the layout/report wanted and it auto prints that invoice to the default printer specified. The problem occurs because the layouts are edited to point to the users local printer "Ricoh 1018d (session#)", note the "(session#)" as this is the users local printer being redirected through the terminal services session. Users are able to print using the sage layouts once the default printer is setup within the layout and saved, but as soon as the users disconnects from the Terminal Services session and then reconnect in the morning go to print, it has lost the connection to that printer. I understand why its failed, because that the printer is on a per session basis and the layout would not be able to hold on to the connection from a previous session. Thanks in advance for any assistance...

    Read the article

  • Word 2010 not printing body text on pages with images

    - by Oesor
    I've got a document exhibiting bizarre behavior -- when I print, the body text style is only displayed on pages without images. Headings, header and footer, and captions are printing on the page, along with any graphics such as border styles applied to the style, but the text itself doesn't print -- except for en dashes. The text is pretty basic -- a justified Calibri style. Images are their own style, a centered paragraph item. There's no floating image boxes or text boxes going on, everything's a paragraph style. It's not a print driver issue. I get identical behavior on both a HP and Brother laser printer. It's also not a paragraph-level style issue; I've inserted enough dummy text to move a printing paragraph on a page with no images to the next page, which has an image, and the paragraph does not print on the next page. Has anyone run into an issue like this and knows the solution?

    Read the article

  • Apache doesn't run multiple requests

    - by Reinderien
    I'm currently running this simple Python CGI script to test rudimentary IPC: #!/usr/bin/python -u import cgi, errno, fcntl, os, os.path, sys, time print("""Content-Type: text/html; charset=utf-8 <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>IPC test</title> </head> <body> """) ftempname = '/tmp/ipc-messages' master = not os.path.exists(ftempname) if master: fmode = 'w' else: fmode = 'r' print('<p>Opening file</p>') sys.stdout.flush() ftemp = open(ftempname, fmode) print('<p>File opened</p>') if master: print('<p>Operating as master</p>') sys.stdout.flush() for i in range(10): print('<p>' + str(i) + '</p>') sys.stdout.flush() time.sleep(1) ftemp.close() os.remove(ftempname) else: print('<p>Operating as a slave</p>') ftemp.close() print(""" </body> </html>""") The 'server-push' portion works; that is, for the first request, I do see piecewise updates. However, while the first request is being serviced, subsequent requests are not started, only to be started after the first request has finished. Any ideas on why, and how to fix it? Edit: I see the same non-concurrent behaviour with vanilla PHP, running this: <!doctype html> <html lang="en"> <!-- $Id: $--> <head> <meta charset="utf-8" /> <title>IPC test</title> </head> <body> <p> <?php function echofl($str) { echo $str . "</b>\n"; ob_flush(); flush(); } define('tempfn', '/tmp/emailsync'); if (file_exists(tempfn)) $perms = 'r+'; else $perms = 'w'; assert($fsync = fopen(tempfn, $perms)); assert(chmod(tempfn, 0600)); if (!flock($fsync, LOCK_EX | LOCK_NB, $wouldblock)) { assert($wouldblock); $master = false; } else $master = true; if ($master) { echofl('Running as master.'); assert(fwrite($fsync, 'content') != false); assert(sleep(5) == 0); assert(flock($fsync, LOCK_UN)); } else { echofl('Running as slave.'); echofl(fgets($fsync)); } assert(fclose($fsync)); echofl('Done.'); ?> </p> </body> </html>

    Read the article

< Previous Page | 57 58 59 60 61 62 63 64 65 66 67 68  | Next Page >