Search Results

Search found 990 results on 40 pages for 'readline'.

Page 3/40 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Sockets receiving null (Android)

    - by Henrik
    I have a android app that is communicating with a server (written in java). Between these two parts I have established a Socket connection and want to send data. The problem I am having is that sometimes, for some users, the information that reaches the server is null. This works (for all phones, all users): Server: int a = Integer.parseInt(in.readLine()); int b = Integer.parseInt(in.readLine()); int c = Integer.parseInt(in.readLine()); int d = Integer.parseInt(in.readLine()); String checksum = in.readLine(); String model = in.readLine(); String device = in.readLine(); String name = in.readLine(); Client: out.println(a); out.println(b); out.println(c); out.println(d); out.println(hash); out.println(Build.MODEL); out.println(Build.DEVICE); String name = fixName(); out.print(name); out.flush(); This does not work (for some users): Server: int a = Integer.parseInt(in.readLine()); String checksum = in.readLine(); String model = in.readLine(); String device = in.readLine(); String name = in.readLine(); String msg = in.readLine(); int version = -1; String test = "hej"; try{ test = in.readLine(); version = Integer.parseInt(test); }catch(Exception e){ e.printStackTrace(); } Client: out.println(a); out.println(hash); out.println(Build.MODEL); out.println(Build.DEVICE); String name = fixName(); if(name == null) name = "John Doe"; out.println(name); String msg = fixMsg(); if(msg == null) name = "nada"; out.println(msg); out.println(curversion); out.flush(); Sometimes, in the second case, the name, msg, and version (the string test) are null at the server side. The catch is triggered because test is null. curversion,a are ints, the rest are strings. Any ideas?

    Read the article

  • Nullpointerexcption & abrupt IOStream closure with inheritence and subclasses

    - by user1401652
    A brief background before so we can communicate on the same wave length. I've had about 8-10 university courses on programming from data structure, to one on all languages, to specific ones such as java & c++. I'm a bit rusty because i usually take 2-3 month breaks from coding. This is a personal project that I started thinking of two years back. Okay down to the details, and a specific question, I'm having problems with my mutator functions. It seems to be that I am trying to access a private variable incorrectly. The question is, am I nesting my classes too much and trying to mutate a base class variable the incorrect way. If so point me in the way of the correct literature, or confirm this is my problem so I can restudy this information. Thanks package GroceryReceiptProgram; import java.io.*; import java.util.Vector; public class Date { private int hour, minute, day, month, year; Date() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What's the hour? (Use 1-24 military notation"); hour = Integer.parseInt(keyboard.readLine()); System.out.println("what's the minute? "); minute = Integer.parseInt(keyboard.readLine()); System.out.println("What's the day of the month?"); day = Integer.parseInt(keyboard.readLine()); System.out.println("Which month of the year is it, use an integer"); month = Integer.parseInt(keyboard.readLine()); System.out.println("What year is it?"); year = Integer.parseInt(keyboard.readLine()); keyboard.close(); } catch (IOException e) { System.out.println("Yo houston we have a problem"); } } public void setHour(int hour) { this.hour = hour; } public void setHour() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What hour, use military notation?"); this.hour = Integer.parseInt(keyboard.readLine()); keyboard.close(); } catch (NumberFormatException e) { System.out.println(e.toString() + ":doesnt seem to be a number"); } catch (IOException e) { System.out.println(e.toString()); } } public int getHour() { return hour; } public void setMinute(int minute) { this.minute = minute; } public void setMinute() { try (BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in))) { System.out.println("What minute?"); this.minute = Integer.parseInt(keyboard.readLine()); } catch (NumberFormatException e) { System.out.println(e.toString() + ": doesnt seem to be a number"); } catch (IOException e) { System.out.println(e.toString() + ": minute shall not cooperate"); } catch (NullPointerException e) { System.out.println(e.toString() + ": in the setMinute function of the Date class"); } } public int getMinute() { return minute; } public void setDay(int day) { this.day = day; } public void setDay() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What day 0-6?"); this.day = Integer.parseInt(keyboard.readLine()); keyboard.close(); } catch (NumberFormatException e) { System.out.println(e.toString() + ":doesnt seem to be a number"); } catch (IOException e) { System.out.println(e.toString()); } } public int getDay() { return day; } public void setMonth(int month) { this.month = month; } public void setMonth() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What month 0-11?"); this.month = Integer.parseInt(keyboard.readLine()); keyboard.close(); } catch (NumberFormatException e) { System.out.println(e.toString() + ":doesnt seem to be a number"); } catch (IOException e) { System.out.println(e.toString()); } } public int getMonth() { return month; } public void setYear(int year) { this.year = year; } public void setYear() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What year?"); this.year = Integer.parseInt(keyboard.readLine()); keyboard.close(); } catch (NumberFormatException e) { System.out.println(e.toString() + ":doesnt seem to be a number"); } catch (IOException e) { System.out.println(e.toString()); } } public int getYear() { return year; } public void set() { setMinute(); setHour(); setDay(); setMonth(); setYear(); } public Vector<Integer> get() { Vector<Integer> holder = new Vector<Integer>(5); holder.add(hour); holder.add(minute); holder.add(month); holder.add(day); holder.add(year); return holder; } }; That is the Date class obviously, next is the other base class Location. package GroceryReceiptProgram; import java.io.*; import java.util.Vector; public class Location { String streetName, state, city, country; int zipCode, address; Location() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What is the street name"); streetName = keyboard.readLine(); System.out.println("Which state?"); state = keyboard.readLine(); System.out.println("Which city?"); city = keyboard.readLine(); System.out.println("Which country?"); country = keyboard.readLine(); System.out.println("Which zipcode?");//if not u.s. continue around this step zipCode = Integer.parseInt(keyboard.readLine()); System.out.println("What address?"); address = Integer.parseInt(keyboard.readLine()); } catch (IOException e) { System.out.println(e.toString()); } } public void setZipCode(int zipCode) { this.zipCode = zipCode; } public void setZipCode() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What zipCode?"); this.zipCode = Integer.parseInt(keyboard.readLine()); keyboard.close(); } catch (NumberFormatException e) { System.out.println(e.toString() + ":doesnt seem to be a number"); } catch (IOException e) { System.out.println(e.toString()); } } public void set() { setAddress(); setCity(); setCountry(); setState(); setStreetName(); setZipCode(); } public int getZipCode() { return zipCode; } public void setAddress(int address) { this.address = address; } public void setAddress() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What minute?"); this.address = Integer.parseInt(keyboard.readLine()); keyboard.close(); } catch (NumberFormatException e) { System.out.println(e.toString() + ":doesnt seem to be a number"); } catch (IOException e) { System.out.println(e.toString()); } } public int getAddress() { return address; } public void setStreetName(String streetName) { this.streetName = streetName; } public void setStreetName() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What minute?"); this.streetName = keyboard.readLine(); keyboard.close(); } catch (IOException e) { System.out.println(e.toString()); } } public String getStreetName() { return streetName; } public void setState(String state) { this.state = state; } public void setState() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What minute?"); this.state = keyboard.readLine(); keyboard.close(); } catch (IOException e) { System.out.println(e.toString()); } } public String getState() { return state; } public void setCity(String city) { this.city = city; } public void setCity() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What minute?"); this.city = keyboard.readLine(); keyboard.close(); } catch (IOException e) { System.out.println(e.toString()); } } public String getCity() { return city; } public void setCountry(String country) { this.country = country; } public void setCountry() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What minute?"); this.country = keyboard.readLine(); keyboard.close(); } catch (IOException e) { System.out.println(e.toString()); } } public String getCountry() { return country; } }; their parent(What is the proper name?) class package GroceryReceiptProgram; import java.io.*; public class FoodGroup { private int price, count; private Date purchaseDate, expirationDate; private Location location; private String name; public FoodGroup() { try { setPrice(); setCount(); expirationDate.set(); purchaseDate.set(); location.set(); } catch (NullPointerException e) { System.out.println(e.toString() + ": in the constructor of the FoodGroup class"); } } public void setPrice(int price) { this.price = price; } public void setPrice() { try (BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in))) { System.out.println("What Price?"); price = Integer.parseInt(keyboard.readLine()); } catch (NumberFormatException e) { System.out.println(e.toString() + ":doesnt seem to be a number"); } catch (IOException e) { System.out.println(e.toString() + ": in the FoodGroup class, setPrice function"); } catch (NullPointerException e) { System.out.println(e.toString() + ": in FoodGroup class. SetPrice()"); } } public int getPrice() { return price; } public void setCount(int count) { this.count = count; } public void setCount() { try (BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in))) { System.out.println("What count?"); count = Integer.parseInt(keyboard.readLine()); } catch (NumberFormatException e) { System.out.println(e.toString() + ":doesnt seem to be a number"); } catch (IOException e) { System.out.println(e.toString() + ": in the FoodGroup class, setCount()"); } catch (NullPointerException e) { System.out.println(e.toString() + ": in FoodGroup class, setCount"); } } public int getCount() { return count; } public void setName(String name) { this.name = name; } public void setName() { try { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What minute?"); this.name = keyboard.readLine(); } catch (IOException e) { System.out.println(e.toString()); } } public String getName() { return name; } public void setLocation(Location location) { this.location = location; } public Location getLocation() { return location; } public void setPurchaseDate(Date purchaseDate) { this.purchaseDate = purchaseDate; } public void setPurchaseDate() { this.purchaseDate.set(); } public Date getPurchaseDate() { return purchaseDate; } public void setExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; } public void setExpirationDate() { this.expirationDate.set(); } public Date getExpirationDate() { return expirationDate; } } and finally the main class, so I can get access to all of this work. package GroceryReceiptProgram; public class NewMain { public static void main(String[] args) { FoodGroup test = new FoodGroup(); } } If anyone is further interested, here is a link the UML for this. https://www.dropbox.com/s/1weigjnxih70tbv/GRP.dia

    Read the article

  • How to bind up arrow in ~/.inputrc (readline) for vim insert mode?

    - by Pawel Goscicki
    When in Readline apps with vim mode enabled in ~/.inputrc (set editing-mode vi) is there a way to bind the up arrow key? To previous history, for example. It seems I have to press ESC key first, only then it works. Here's my attempt at making it work (~/.inputrc): $if mode=vi # INSERT MODE set keymap vi-insert "\e[A": history-search-backward # up-arrow "\e[B": history-search-forward # down-arrow Also note, that when I press Ctrl+v and then <Up>, it prints ^[[A.

    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

  • Delete last 3 lines within while ((line = r.ReadLine()) != null) but not open a new text file to delete the lines?

    - by user1473672
    This is the code I've seen so far to delete last 3 lines in a text file, but it's required to determine string[] lines = File.ReadAllLines(); which is nt necessary for me to do so. string[] lines = File.ReadAllLines(@"C:\\Users.txt"); StringBuilder sb = new StringBuilder(); int count = lines.Length - 3; // except last 3 lines for (int s = 0; s < count; s++) { sb.AppendLine(lines[s]); } The code works well, but I don't wanna re-read the file as I've mentioned the streamreader above : using (StreamReader r = new StreamReader(@"C:\\Users.txt")) Im new to C#, as far as I know, after using streamreader, and if I wanna modify the lines, I have to use this : while ((line = r.ReadLine()) != null) { #sample codes inside the bracket line = line.Replace("|", ""); line = line.Replace("MY30", ""); line = line.Replace("E", ""); } So, is there any way to delete the last 3 lines in the file within the "while ((line = r.ReadLine()) != null)" ?? I have to delete lines, replace lines and a few more modications in one shot, so I can't keep opening/reading the same text file again and again to modify the lines. I hope the way I ask is understable for you guys .< Plz help me, I know the question sounds simple but I've searched so many ways to solve it but failed =( So far, my code is : using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication11 { public class Read { static void Main(string[] args) { string tempFile = Path.GetTempFileName(); using (StreamReader r = new StreamReader(@"C:\\Users\SAP Report.txt")) { using (StreamWriter sw = new StreamWrite (@"C:\\Users\output2.txt")) { string line; while ((line = r.ReadLine()) != null) { line = line.Replace("|", ""); line = line.Replace("MY30", ""); line = line.Replace("E", ""); line = System.Text.RegularExpressions.Regex.Replace(line, @"\s{2,}", " "); sw.WriteLine(line); } } } } } } Now my next task is to delete the last 3 lines in the file after these codes, and I need help on this one. Thank you.

    Read the article

  • Delete section of streamreader

    - by Luke
    I am reading a file into my program using streamreader. private void loadFile() { lstDeliveryDetails.Items.Clear(); if (!File.Exists("../../MealDeliveries.txt")) { MessageBox.Show("File not found!"); return; } using (StreamReader sr = new StreamReader("../../MealDeliveries.txt")) { //first line is delivery name string strDeliveryName = sr.ReadLine(); while (strDeliveryName != null) { //other lines Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine()); mainForm.myDeliveries.Add(d); //check for further values strDeliveryName = sr.ReadLine(); } } displayDeliveries(); } Eventually I end up with all the deliveries in the following array public static ArrayList myDeliveries = new ArrayList(); It is loaded into the listview. I select an item as follows: iDeliverySelected = lstDeliveryDetails.SelectedItems[0].Index; I am struggling to understand how I can select an item and use a delete button to remove it from the text file?

    Read the article

  • Need file read in from form load

    - by Luke
    I am using a listview, and trying to populate using a file. I need the file to be read in as soon as the form starts. private void mainForm_Load(object sender, EventArgs e) { //get file read in if (File.Exists("../../MealDeliveries.txt")) { StreamReader sr = new StreamReader("../../MealDeliveries.txt"); //first line is delivery name string strDeliveryName = sr.ReadLine(); do { //other lines Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine()); mainForm.myDeliveries.Add(d); //check for further values strDeliveryName = sr.ReadLine(); //stop if no more values } while (strDeliveryName != null); displayDeliveries(); } } Should this work?

    Read the article

  • Installing Ruby 1.8.6 via RVM on Snow Leopard

    - by Neil Middleton
    I'm trying to install ruby 1.8.6 onto Snow Leopard - but am getting some make errors: ossl_x509revoked.c: In function ‘ossl_x509revoked_new’: ossl_x509revoked.c:48: warning: passing argument 2 of ‘ASN1_dup’ from incompatible pointer type ossl_x509revoked.c: In function ‘DupX509RevokedPtr’: ossl_x509revoked.c:64: warning: passing argument 2 of ‘ASN1_dup’ from incompatible pointer type readline.c: In function ‘username_completion_proc_call’: readline.c:730: error: ‘username_completion_function’ undeclared (first use in this function) readline.c:730: error: (Each undeclared identifier is reported only once readline.c:730: error: for each function it appears in.) make[1]: *** [readline.o] Error 1 make: *** [all] Error 1 Anyone have any ideas?

    Read the article

  • Installing Ruby 1.8.6 via RVM on Snow Leopard

    - by Neil Middleton
    I'm trying to install ruby 1.8.6 onto Snow Leopard - but am getting some make errors: ossl_x509revoked.c: In function ‘ossl_x509revoked_new’: ossl_x509revoked.c:48: warning: passing argument 2 of ‘ASN1_dup’ from incompatible pointer type ossl_x509revoked.c: In function ‘DupX509RevokedPtr’: ossl_x509revoked.c:64: warning: passing argument 2 of ‘ASN1_dup’ from incompatible pointer type readline.c: In function ‘username_completion_proc_call’: readline.c:730: error: ‘username_completion_function’ undeclared (first use in this function) readline.c:730: error: (Each undeclared identifier is reported only once readline.c:730: error: for each function it appears in.) make[1]: *** [readline.o] Error 1 make: *** [all] Error 1 Anyone have any ideas?

    Read the article

  • Listview not being populated

    - by Luke
    I have put some console.writeline code in to test, but they arent appearing in the output box? public static ArrayList myDeliveries = new ArrayList(); public mainForm() { InitializeComponent(); } private void mainForm_Load(object sender, EventArgs e) { if (!File.Exists("../../MealDeliveries.txt")) { MessageBox.Show("File not found!"); return; } using (StreamReader sr = new StreamReader("../../MealDeliveries.txt")) { //first line is delivery name string strDeliveryName = sr.ReadLine(); Console.WriteLine("some tetttttttttt23423423423423423ttttttttttttttttttttttt"); while (strDeliveryName != null) { //other lines Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine()); mainForm.myDeliveries.Add(d); //check for further values strDeliveryName = sr.ReadLine(); } } displayDeliveries(); } private void displayDeliveries() { lstDeliveryDetails.Items.Clear(); Console.WriteLine("some tettttttttttttttttttttttttttttttttt"); Console.WriteLine(mainForm.myDeliveries.Count); foreach (Delivery d in mainForm.myDeliveries) { lstDeliveryDetails.Items.Add(d.DeliveryName); } } Can anyone help??

    Read the article

  • Console.WriteLine does not show up in Output window

    - by Luke
    I have put some Console.WriteLine calls in to test, but they aren't appearing in the output box? public static ArrayList myDeliveries = new ArrayList(); public mainForm() { InitializeComponent(); } private void mainForm_Load(object sender, EventArgs e) { if (!File.Exists("../../MealDeliveries.txt")) { MessageBox.Show("File not found!"); return; } using (StreamReader sr = new StreamReader("../../MealDeliveries.txt")) { //first line is delivery name string strDeliveryName = sr.ReadLine(); Console.WriteLine("some tetttttttttt23423423423423423ttttttttttttttttttttttt"); while (strDeliveryName != null) { //other lines Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine()); mainForm.myDeliveries.Add(d); //check for further values strDeliveryName = sr.ReadLine(); } } displayDeliveries(); } private void displayDeliveries() { lstDeliveryDetails.Items.Clear(); Console.WriteLine("some tettttttttttttttttttttttttttttttttt"); Console.WriteLine(mainForm.myDeliveries.Count); foreach (Delivery d in mainForm.myDeliveries) { lstDeliveryDetails.Items.Add(d.DeliveryName); } } Can anyone help??

    Read the article

  • C#: Searching through arrays

    - by Jonathan Oberhaus
    I have a dvd app that stores dvds and blu-rays, I want to search the arrays by director. Below is the code for the inventory class I have seen many different ways to do this. There seems to be some debate as the best/most efficient way to accomplish this, any suggestions? Blockquote namespace MovieInventoryApplication { class Inventory { public Bluray[] BlurayMovies; public DVD[] DVDMovies; private int blurayCount; private int dvdCount; public Inventory() { BlurayMovies = new Bluray[5]; DVDMovies = new DVD[5]; blurayCount = 0; dvdCount = 0; } public void AddBluray() { String strTitle; int intReleaseYear; int intRunningTimeMinutes; String strDirector; int intPrice; int intRegionCode; try { Console.Write("Enter a title: "); strTitle = Console.ReadLine(); Console.Write("Enter a release year: "); intReleaseYear = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the running time in minutes: "); intRunningTimeMinutes = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the directors name: "); strDirector = Console.ReadLine(); Console.Write("Enter a rental price: "); intPrice = Convert.ToInt32(Console.ReadLine()); BlurayMovies[blurayCount] = new Bluray(strTitle, intReleaseYear, intRunningTimeMinutes, strDirector, intPrice); blurayCount++; Console.Write("Enter the DVD region code: "); intRegionCode = Convert.ToInt32(Console.ReadLine()); DVDMovies[dvdCount] = new DVD(strTitle, intReleaseYear, intRunningTimeMinutes, strDirector, intPrice, intRegionCode); dvdCount++; } catch (FormatException FormatException) { Console.WriteLine(FormatException.Message); Console.WriteLine("Please enter a number in this field."); } } public void AddDVD() { String strTitle; int intReleaseYear; int intRunningTimeMinutes; String strDirector; int intPrice; int intRegionCode; try { Console.Write("Enter a title: "); strTitle = Console.ReadLine(); Console.Write("Enter a release year: "); intReleaseYear = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the running time in minutes: "); intRunningTimeMinutes = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the directors name: "); strDirector = Console.ReadLine(); Console.Write("Enter a rental price: "); intPrice = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the region code: "); intRegionCode = Convert.ToInt32(Console.ReadLine()); DVDMovies[dvdCount] = new DVD(strTitle, intReleaseYear, intRunningTimeMinutes, strDirector, intPrice, intRegionCode); dvdCount++; } catch (FormatException FormatException) { Console.WriteLine(FormatException.Message); Console.WriteLine("Please enter a number in this field."); } } public void ListAllBluray() { int position = 0; while (BlurayMovies[position] != null) { Console.WriteLine(position + " " + BlurayMovies[position].strTitle); position++; } } public void ListAllDVD() { int position = 0; while (DVDMovies[position] != null) { //position + 1 + " " + Console.WriteLine(position + " " + DVDMovies[position].strTitle); position++; } } public void BlurayInfo(int position) { Console.WriteLine("Title: {0}", DVDMovies[position].strTitle); Console.WriteLine("Release Year: {0}", DVDMovies[position].intReleaseYear); Console.WriteLine("Running Time (Minutes): {0}", DVDMovies[position].intRunningTimeMinutes); Console.WriteLine("Director: {0}", DVDMovies[position].strDirector); Console.WriteLine("Price: {0}", DVDMovies[position].intPrice); } public void DVDInfo(int position) { Console.WriteLine("Title: {0}", DVDMovies[position].strTitle); Console.WriteLine("Release Year: {0}", DVDMovies[position].intReleaseYear); Console.WriteLine("Running Time (Minutes): {0}", DVDMovies[position].intRunningTimeMinutes); Console.WriteLine("Director: {0}", DVDMovies[position].strDirector); Console.WriteLine("Price: {0}", DVDMovies[position].intPrice); Console.WriteLine("Region Code: {0}", DVDMovies[position].intRegionCode); } } }

    Read the article

  • python: creating a list inside a dictionary

    - by user1871081
    I just started using python and I'm trying to create a program that will read a file that looks like this: AAA x 111 AAB x 111 AAA x 112 AAC x 123 ... the file is 50 lines long and I'm trying to make the letters into keys in a dictionary and the numbers lists that correspond with the keys. I want the output to look like this: {AAA: ['111', '112'], AAB: ['111'], AAC: [123], ...} This is what I've tried file = open("filename.txt", "r") readline = file.readline().rstrip() while readline!= "": list = [] list = readline.split(" ") j = list.index("x") k = list[0:j] v = list[p + 1:] d = {} if k in d == False d[k] = [] d[k].append(v) else d[k].append(v) readline = file.readline().rstrip() I keep getting syntax errors on my if statement and I can't figure out what I've done wrong.

    Read the article

  • Installing ruby 1.9.1 on OS X with RVM, getting error I can't make sense of

    - by Pselus
    I'm trying to update my ruby install on Leopard to at least 1.9.1. I found a tutorial that tells me how to do it with RVM and I get as far as downloading, configuring and compiling the version I want, but during the compile I get errors. When checking the make.error.log file this is the message I get: [2010-11-07 13:43:44] make main.c: In function ‘objcdummyfunction’: main.c:19: warning: implicit declaration of function ‘objc_msgSend’ main.c: At top level: main.c:19: warning: ‘objcdummyfunction’ defined but not used eval.c: In function ‘ruby_cleanup’: eval.c:139: warning: passing argument 1 of ‘ruby_init_stack’ discards qualifiers from pointer target type gc.c: In function ‘garbage_collect_with_gvl’: gc.c:597: warning: cast from pointer to integer of different size w: illegal option -- L usage: w [hi] [user ...] make: [libruby.1.9.1.dylib] Error 1 (ignored) readline.c: In function ‘username_completion_proc_call’: readline.c:1159: error: ‘username_completion_function’ undeclared (first use in this function) readline.c:1159: error: (Each undeclared identifier is reported only once readline.c:1159: error: for each function it appears in.) make[1]: *** [readline.o] Error 1 make: *** [mkmain.sh] Error 1 I have no idea what any of that means. Help?

    Read the article

  • Comparing text files w/ Junit

    - by jon077
    I am comparing text files in junit using: public static void assertReaders(BufferedReader expected, BufferedReader actual) throws IOException { String line; while ((line = expected.readLine()) != null) { assertEquals(line, actual.readLine()); } assertNull("Actual had more lines then the expected.", actual.readLine()); assertNull("Expected had more lines then the actual.", expected.readLine()); } Is this a good way to compare text files? What is preferred?

    Read the article

  • Problem reading from the StandarOutput from ftp.exe. Possible System.Diagnostics.Process Framework b

    - by SoMoS
    Hello, I was trying some stuff executing console applications when I found this problem handling the I/O of the ftp.exe command that everybody has into the computer. Just try this code: m_process = New Diagnostics.Process() m_process.StartInfo.FileName = "ftp.exe" m_process.StartInfo.CreateNoWindow = True m_process.StartInfo.RedirectStandardInput = True m_process.StartInfo.RedirectStandardOutput = True m_process.StartInfo.UseShellExecute = False m_process.Start() m_process.StandardInput.AutoFlush = True m_process.StandardInput.WriteLine("help") MsgBox(m_process.StandardOutput.ReadLine()) MsgBox(m_process.StandardOutput.ReadLine()) MsgBox(m_process.StandardOutput.ReadLine()) MsgBox(m_process.StandardOutput.ReadLine()) This should show you the text that ftp sends you when you do that from the command line: Los comandos se pueden abreviar. Comandos: ! delete literal prompt send ? debug ls put status append dir mdelete pwd trace ascii disconnect mdir quit type bell get mget quote user binary glob mkdir recv verbose bye hash mls remotehelp cd help mput rename close lcd open rmdir Instead of that I'm getting the first line and 3 more with garbage, after that the call to ReadLine block like if there was no data available. Any hints about that?

    Read the article

  • Lotto program doesn't stop

    - by Naseyb Yaramis
    So I'm making a lotto game. You have to enter 6 lucky numbers and if they're the same as the lotto numbers then you win. Here is my code: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OefeningExaam { class Program { static void Main(string[] args) { Random getal = new Random(); int[] lottotrekking = new int[6]; Console.WriteLine("Geef je geluksgetallen in <tussen 1 en 42>"); Console.WriteLine("Geef je eerste getal in"); int getal1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Geef je tweede getal in"); int getal2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Geef je derde getal in"); int getal3 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Geef je vierde getal in"); int getal4 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Geef je vijfde getal in"); int getal5 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Geef je zesde getal in"); int getal6 = Convert.ToInt32(Console.ReadLine()); while (getal1 != lottotrekking[0] || getal2 != lottotrekking[1] || getal3 != lottotrekking[2] || getal4 != lottotrekking[3] || getal5 != lottotrekking[4] || getal5 != lottotrekking[4] || getal6 != lottotrekking[5]) { for (int i = 0; i < lottotrekking.Length; i++) { int cijfer = getal.Next(1, 43); lottotrekking[i] = cijfer; Console.WriteLine(lottotrekking[0] + "\t " + lottotrekking[1] + "\t " + lottotrekking[2] + "\t " + lottotrekking[3] + "\t " + lottotrekking[4] + "\t " + lottotrekking[5]); } } if (getal1 == lottotrekking[0] && getal2 == lottotrekking[1] && getal3 == lottotrekking[2] && getal4 == lottotrekking[3] && getal5 == lottotrekking[4] && getal5 == lottotrekking[4] && getal6 == lottotrekking[5]) { Console.WriteLine(lottotrekking[0] + " " + lottotrekking[1] + " " + lottotrekking[2] + " " + lottotrekking[3] + " " + lottotrekking[4] + " " + lottotrekking[5]); } Console.ReadLine(); } } } The problem is that the program just keeps going and doesn't stop. It's supposed to stop when the lucky numbers are the same as the lotto numbers.

    Read the article

  • Not being able to `make` in terminal on Mac OS X 10.7

    - by AlanTuring
    Hi so i am trying to install the commands wget and with-readline for use with Mac OS X's terminal. The configuration seems to work fine for both even though i am required to specify for the first one, host= i686-apple. When i get to the make part of the installation, the output is as follows. For wget: for with-readline so does anyone have any idea what's going on? Pastie links: wget: http://pastie.org/4925079 with-readline: http://pastie.org/4925083 Thanks in advance.

    Read the article

  • Tab Auto-Completion in Mac OS X when using sftp in terminal

    - by AlanTuring
    i have been getting very frustrated lately since the readline functionality has been removed from MacOSX and Tab Auto-Completion doesn't work anymore. So i was wondering if anyone knew a good alternative to use that i could install so i can tab auto-complete files when sftp'd in. I heard that with-readline is a good option for this. If so, how do i get an alias sftp = with-readline sftp to work? I would like to do the same with any other option that isn't with-readline, so i don't have to assign an alias each time i set up a session. I am using Mac OS X 10.8(Mountain Lion) with Homebrew installed. Thanks in advance to anyone who can help me.

    Read the article

  • how to speed up the code??

    - by kaushik
    i have very huge code about 600 lines plus. cant post the whole thing here. but a particular code snippet is taking so much time,leading to problems. here i post that part of code please tell me what to do speed up the processing.. please suggest the part which may be the reason and measure to improve them if this small part of code is understandable. using_data={} def join_cost(a , b): global using_data #print a #print b save_a=[] save_b=[] print 1 #for i in range(len(m)): #if str(m[i][0])==str(a): save_a=database_index[a] #for i in range(len(m)): # if str(m[i][0])==str(b): #print 'save_a',save_a #print 'save_b',save_b print 2 save_b=database_index[b] using_data[save_a[0]]=save_a s=str(save_a[1]).replace('phone','text') s=str(s)+'.pm' p=os.path.join("c:/begpython/wavnk/",s) x=open(p , 'r') print 3 for i in range(6): x.readline() k2='a' j=0 o=[] while k2 is not '': k2=x.readline() k2=k2.rstrip('\n') oj=k2.split(' ') o=o+[oj] #print o[j] j=j+1 #print j #print o[2][0] temp=long(1232332) end_time=save_a[4] #print end_time k=(j-1) for i in range(k): diff=float(o[i][0])-float(end_time) if diff<0: diff=diff*(-1) if temp>diff: temp=diff pm_row=i #print pm_row #print temp #print o[pm_row] #pm_row=3 q=[] print 4 l=str(p).replace('.pm','.mcep') z=open(l ,'r') for i in range(pm_row): z.readline() k3=z.readline() k3=k3.rstrip('\n') q=k3.split(' ') #print q print 5 s=str(save_b[1]).replace('phone','text') s=str(s)+'.pm' p=os.path.join("c:/begpython/wavnk/",s) x=open(p , 'r') for i in range(6): x.readline() k2='a' j=0 o=[] while k2 is not '': k2=x.readline() k2=k2.rstrip('\n') oj=k2.split(' ') o=o+[oj] #print o[j] j=j+1 #print j #print o[2][0] temp=long(1232332) strt_time=save_b[3] #print strt_time k=(j-1) for i in range(k): diff=float(o[i][0])-float(strt_time) if diff<0: diff=diff*(-1) if temp>diff: temp=diff pm_row=i #print pm_row #print temp #print o[pm_row] #pm_row=3 w=[] l=str(p).replace('.pm','.mcep') z=open(l ,'r') for i in range(pm_row): z.readline() k3=z.readline() k3=k3.rstrip('\n') w=k3.split(' ') #print w cost=0 for i in range(12): #print q[i] #print w[i] h=float(q[i])-float(w[i]) cost=cost+math.pow(h,2) j_cost=math.sqrt(cost) #print cost return j_cost def target_cost(a , b): a=(b+1)*3 b=(a+1)*2 t_cost=(a+b)*5/2 return t_cost r1='shht:ra_77' r2='grx_18' g=[] nodes=[] nodes=nodes+[[r1]] for i in range(len(y_in_db_format)): g=y_in_db_format[i] #print g #print g[0] g.remove(str(g[0])) nodes=nodes+[g] nodes=nodes+[[r2]] print nodes print "lenght of nodes",len(nodes) lists=[] #lists=lists+[r1] for i in range(len(nodes)): for j in range(len(nodes[i])): lists=lists+[nodes[i][j]] #lists=lists+[r2] print lists distance={} for i in range(len(lists)): if i==0: distance[str(lists[i])]=0 else: distance[str(lists[i])]=long(123231223) #print distance group_dist=[] infinity=long(123232323) for i in range(len(nodes)): distances=[] for j in range(len(nodes[i])): #distances=[] if i==0: distances=distances+[[nodes[i][j], 0]] else: distances=distances+[[nodes[i][j],infinity]] group_dist=group_dist+[distances] #print distances print "group_distances",group_dist #print "check",group_dist[0][0][1] #costs={} #for i in range(len(lists)): #if i==0: # costs[str(lists[i])]=1 #else: # costs[str(lists[i])]=get_selfcost(lists[i]) path=[] for i in range(len(nodes)): mini=[] if i!=(len(nodes)-1): #temp=long(123234324) #Now calculate the cost between the current node and each of its neighbour for k in range(len(nodes[(i+1)])): for j in range(len(nodes[i])): current=nodes[i][j] #print "current_node",current j_distance=join_cost( current , nodes[i+1][k]) #t_distance=target_cost( current , nodes[i+1][k]) t_distance=34 #print distance #print "distance between current and neighbours",distance total_distance=(.5*(float(group_dist[i][j][1])+float(j_distance))+.5*(float(t_distance))) #print "total distance between the intial_nodes and current neighbour",total_distance if int(group_dist[i+1][k][1]) > int(total_distance): group_dist[i+1][k][1]=total_distance #print "updated distance",group_dist[i+1][k][1] a=current #print "the neighbour",nodes[i+1][k],"updated the value",a mini=mini+[[str(nodes[i+1][k]),a]] print mini

    Read the article

  • Using delegates in C# (Part 2)

    - by rajbk
    Part 1 of this post can be read here. We are now about to see the different syntaxes for invoking a delegate and some c# syntactic sugar which allows you to code faster. We have the following console application. 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: Operation op1 = new Operation(Division); 9: double result = op1.Invoke(10, 5); 10: 11: Console.WriteLine(result); 12: Console.ReadLine(); 13: } 14: 15: static double Division(double x, double y) { 16: return x / y; 17: } 18: } Line 1 defines a delegate type called Operation with input parameters (double x, double y) and a return type of double. On Line 8, we create an instance of this delegate and set the target to be a static method called Division (Line 15) On Line 9, we invoke the delegate (one entry in the invocation list). The program outputs 5 when run. The language provides shortcuts for creating a delegate and invoking it (see line 9 and 11). Line 9 is a syntactical shortcut for creating an instance of the Delegate. The C# compiler will infer on its own what the delegate type is and produces intermediate language that creates a new instance of that delegate. Line 11 uses a a syntactical shortcut for invoking the delegate by removing the Invoke method. The compiler sees the line and generates intermediate language which invokes the delegate. When this code is compiled, the generated IL will look exactly like the IL of the compiled code above. 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: //shortcut constructor syntax 9: Operation op1 = Division; 10: //shortcut invoke syntax 11: double result = op1(10, 2); 12: 13: Console.WriteLine(result); 14: Console.ReadLine(); 15: } 16: 17: static double Division(double x, double y) { 18: return x / y; 19: } 20: } C# 2.0 introduced Anonymous Methods. Anonymous methods avoid the need to create a separate method that contains the same signature as the delegate type. Instead you write the method body in-line. There is an interesting fact about Anonymous methods and closures which won’t be covered here. Use your favorite search engine ;-)We rewrite our code to use anonymous methods (see line 9): 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: //Anonymous method 9: Operation op1 = delegate(double x, double y) { 10: return x / y; 11: }; 12: double result = op1(10, 2); 13: 14: Console.WriteLine(result); 15: Console.ReadLine(); 16: } 17: 18: static double Division(double x, double y) { 19: return x / y; 20: } 21: } We could rewrite our delegate to be of a generic type like so (see line 2 and line 9). You will see why soon. 1: //Generic delegate 2: public delegate T Operation<T>(T x, T y); 3:  4: public class Program 5: { 6: [STAThread] 7: static void Main(string[] args) 8: { 9: Operation<double> op1 = delegate(double x, double y) { 10: return x / y; 11: }; 12: double result = op1(10, 2); 13: 14: Console.WriteLine(result); 15: Console.ReadLine(); 16: } 17: 18: static double Division(double x, double y) { 19: return x / y; 20: } 21: } The .NET 3.5 framework introduced a whole set of predefined delegates for us including public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2); Our code can be modified to use this delegate instead of the one we declared. Our delegate declaration has been removed and line 7 has been changed to use the Func delegate type. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //Func is a delegate defined in the .NET 3.5 framework 7: Func<double, double, double> op1 = delegate (double x, double y) { 8: return x / y; 9: }; 10: double result = op1(10, 2); 11: 12: Console.WriteLine(result); 13: Console.ReadLine(); 14: } 15: 16: static double Division(double x, double y) { 17: return x / y; 18: } 19: } .NET 3.5 also introduced lambda expressions. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. We change our code to use lambda expressions. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //lambda expression 7: Func<double, double, double> op1 = (x, y) => x / y; 8: double result = op1(10, 2); 9: 10: Console.WriteLine(result); 11: Console.ReadLine(); 12: } 13: 14: static double Division(double x, double y) { 15: return x / y; 16: } 17: } C# 3.0 introduced the keyword var (implicitly typed local variable) where the type of the variable is inferred based on the type of the associated initializer expression. We can rewrite our code to use var as shown below (line 7).  The implicitly typed local variable op1 is inferred to be a delegate of type Func<double, double, double> at compile time. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //implicitly typed local variable 7: var op1 = (x, y) => x / y; 8: double result = op1(10, 2); 9: 10: Console.WriteLine(result); 11: Console.ReadLine(); 12: } 13: 14: static double Division(double x, double y) { 15: return x / y; 16: } 17: } You have seen how we can write code in fewer lines by using a combination of the Func delegate type, implicitly typed local variables and lambda expressions.

    Read the article

  • Java Port Socket Programming Error

    - by atrus-darkstone
    Hi- I have been working on a java client-server program using port sockets. The goal of this program is for the client to take a screenshot of the machine it is running on, break the RGB info of this image down into integers and arrays, then send this info over to the server, where it is reconstructed into a new image file. However, when I run the program I am experiencing the following two bugs: The first number recieved by the server, no matter what its value is according to the client, is always 49. The client only sends(or the server only receives?) the first value, then the program hangs forever. Any ideas as to why this is happening, and what I can do to fix it? The code for both client and server is below. Thanks! CLIENT: import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.*; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class ViewerClient implements ActionListener{ private Socket vSocket; private BufferedReader in; private PrintWriter out; private Robot robot; // static BufferedReader orders = null; public ViewerClient() throws Exception{ vSocket = null; in = null; out = null; robot = null; } public void setVSocket(Socket vs) { vSocket = vs; } public void setInput(BufferedReader i) { in = i; } public void setOutput(PrintWriter o) { out = o; } public void setRobot(Robot r) { robot = r; } /*************************************************/ public Socket getVSocket() { return vSocket; } public BufferedReader getInput() { return in; } public PrintWriter getOutput() { return out; } public Robot getRobot() { return robot; } public void run() throws Exception{ int speed = 2500; int pause = 5000; Timer timer = new Timer(speed, this); timer.setInitialDelay(pause); // System.out.println("CLIENT: Set up timer."); try { setVSocket(new Socket("Alex-PC", 4444)); setInput(new BufferedReader(new InputStreamReader(getVSocket().getInputStream()))); setOutput(new PrintWriter(getVSocket().getOutputStream(), true)); setRobot(new Robot()); // System.out.println("CLIENT: Established connection and IO ports."); // timer.start(); captureScreen(nameImage()); }catch(Exception e) { System.err.println(e); } } public void captureScreen(String fileName) throws Exception{ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle screenRectangle = new Rectangle(screenSize); BufferedImage image = getRobot().createScreenCapture(screenRectangle); int width = image.getWidth(); int height = image.getHeight(); int[] pixelData = new int[(width * height)]; image.getRGB(0,0, width, height, pixelData, width, height); byte[] imageData = new byte[(width * height)]; String fromServer = null; if((fromServer = getInput().readLine()).equals("READY")) { sendWidth(width); sendHeight(height); sendArrayLength((width * height)); sendImageInfo(fileName); sendImageData(imageData); } /* System.out.println(imageData.length); String fromServer = null; for(int i = 0; i < pixelData.length; i++) { imageData[i] = ((byte)pixelData[i]); } System.out.println("CLIENT: Pixel data successfully converted to byte data."); System.out.println("CLIENT: Waiting for ready message..."); if((fromServer = getInput().readLine()).equals("READY")) { System.out.println("CLIENT: Ready message recieved."); getOutput().println("SENDING ARRAY LENGTH..."); System.out.println("CLIENT: Sending array length..."); System.out.println("CLIENT: " + imageData.length); getOutput().println(imageData.length); System.out.println("CLIENT: Array length sent."); getOutput().println("SENDING IMAGE..."); System.out.println("CLIENT: Sending image data..."); for(int i = 0; i < imageData.length; i++) { getOutput().println(imageData[i]); } System.out.println("CLIENT: Image data sent."); getOutput().println("SENDING IMAGE WIDTH..."); System.out.println("CLIENT: Sending image width..."); getOutput().println(width); System.out.println("CLIENT: Image width sent."); getOutput().println("SENDING IMAGE HEIGHT..."); System.out.println("CLIENT: Sending image height..."); getOutput().println(height); System.out.println("CLIENT: Image height sent..."); getOutput().println("SENDING IMAGE INFO..."); System.out.println("CLIENT: Sending image info..."); getOutput().println(fileName); System.out.println("CLIENT: Image info sent."); getOutput().println("FINISHED."); System.out.println("Image data sent successfully."); } if((fromServer = getInput().readLine()).equals("CLOSE DOWN")) { getOutput().close(); getInput().close(); getVSocket().close(); } */ } public String nameImage() throws Exception { String dateFormat = "yyyy-MM-dd HH-mm-ss"; Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); String fileName = sdf.format(cal.getTime()); return fileName; } public void sendArrayLength(int length) throws Exception { getOutput().println("SENDING ARRAY LENGTH..."); getOutput().println(length); } public void sendWidth(int width) throws Exception { getOutput().println("SENDING IMAGE WIDTH..."); getOutput().println(width); } public void sendHeight(int height) throws Exception { getOutput().println("SENDING IMAGE HEIGHT..."); getOutput().println(height); } public void sendImageData(byte[] imageData) throws Exception { getOutput().println("SENDING IMAGE..."); for(int i = 0; i < imageData.length; i++) { getOutput().println(imageData[i]); } } public void sendImageInfo(String info) throws Exception { getOutput().println("SENDING IMAGE INFO..."); getOutput().println(info); } public void actionPerformed(ActionEvent a){ String message = null; try { if((message = getInput().readLine()).equals("PROCESSING...")) { if((message = getInput().readLine()).equals("IMAGE RECIEVED SUCCESSFULLY.")) { captureScreen(nameImage()); } } }catch(Exception e) { JOptionPane.showMessageDialog(null, "Problem: " + e); } } } SERVER: import java.awt.image.BufferedImage; import java.io.*; import java.net.*; import javax.imageio.ImageIO; /*IMPORTANT TODO: * 1. CLOSE ALL STREAMS AND SOCKETS WITHIN CLIENT AND SERVER! * 2. PLACE MAIN EXEC CODE IN A TIMED WHILE LOOP TO SEND FILE EVERY X SECONDS * */ public class ViewerServer { private ServerSocket vServer; private Socket vClient; private PrintWriter out; private BufferedReader in; private byte[] imageData; private int width; private int height; private String imageInfo; private int[] rgbData; private boolean active; public ViewerServer() throws Exception{ vServer = null; vClient = null; out = null; in = null; imageData = null; width = 0; height = 0; imageInfo = null; rgbData = null; active = true; } public void setVServer(ServerSocket vs) { vServer = vs; } public void setVClient(Socket vc) { vClient = vc; } public void setOutput(PrintWriter o) { out = o; } public void setInput(BufferedReader i) { in = i; } public void setImageData(byte[] imDat) { imageData = imDat; } public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } public void setImageInfo(String im) { imageInfo = im; } public void setRGBData(int[] rd) { rgbData = rd; } public void setActive(boolean a) { active = a; } /***********************************************/ public ServerSocket getVServer() { return vServer; } public Socket getVClient() { return vClient; } public PrintWriter getOutput() { return out; } public BufferedReader getInput() { return in; } public byte[] getImageData() { return imageData; } public int getWidth() { return width; } public int getHeight() { return height; } public String getImageInfo() { return imageInfo; } public int[] getRGBData() { return rgbData; } public boolean getActive() { return active; } public void run() throws Exception{ connect(); setActive(true); while(getActive()) { recieve(); } close(); } public void recieve() throws Exception{ String clientStatus = null; int clientData = 0; // System.out.println("SERVER: Sending ready message..."); getOutput().println("READY"); // System.out.println("SERVER: Ready message sent."); if((clientStatus = getInput().readLine()).equals("SENDING IMAGE WIDTH...")) { setWidth(getInput().read()); System.out.println("Width: " + getWidth()); } if((clientStatus = getInput().readLine()).equals("SENDING IMAGE HEIGHT...")) { setHeight(getInput().read()); System.out.println("Height: " + getHeight()); } if((clientStatus = getInput().readLine()).equals("SENDING ARRAY LENGTH...")) { clientData = getInput().read(); setImageData(new byte[clientData]); System.out.println("Array length: " + clientData); } if((clientStatus = getInput().readLine()).equals("SENDING IMAGE INFO...")) { setImageInfo(getInput().readLine()); System.out.println("Image Info: " + getImageInfo()); } if((clientStatus = getInput().readLine()).equals("SENDING IMAGE...")) { for(int i = 0; i < getImageData().length; i++) { getImageData()[i] = ((byte)getInput().read()); } } if((clientStatus = getInput().readLine()).equals("FINISHED.")) { getOutput().println("PROCESSING..."); setRGBData(new int[getImageData().length]); for(int i = 0; i < getRGBData().length; i++) { getRGBData()[i] = getImageData()[i]; } BufferedImage image = null; image.setRGB(0, 0, getWidth(), getHeight(), getRGBData(), getWidth(), getHeight()); ImageIO.write(image, "png", new File(imageInfo + ".png")); //create an image file out of the screenshot getOutput().println("IMAGE RECIEVED SUCCESSFULLY."); } } public void connect() throws Exception { setVServer(new ServerSocket(4444)); //establish server connection // System.out.println("SERVER: Connection established."); setVClient(getVServer().accept()); //accept client connection request // System.out.println("SERVER: Accepted connection request."); setOutput(new PrintWriter(vClient.getOutputStream(), true)); //set up an output channel setInput(new BufferedReader(new InputStreamReader(vClient.getInputStream()))); //set up an input channel // System.out.println("SERVER: Created IO ports."); } public void close() throws Exception { getOutput().close(); getInput().close(); getVClient().close(); getVServer().close(); } }

    Read the article

  • Non-blocking read on a stream in python.

    - by Mathieu Pagé
    Hi, I'm using the subprocess module to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-bloking or to check if there is data on the stream before I invoke .readline? I'd like this to be portable or at least work under Windows and Linux. here is how I do it for now (It's blocking on the .readline if no data is avaible): p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE) str = p.stdout.readline() Thanks for your help.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >