Search Results

Search found 6460 results on 259 pages for 'cpp person'.

Page 12/259 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Confused Why I am getting C1010 error?

    - by bluepixel
    I have three files: Main, slist.h and slist.cpp can be seen at http://forums.devarticles.com/c-c-help-52/confused-why-i-am-getting-c2143-and-c1010-error-259574.html I'm trying to make a program where main reads the list of student names from a file (roster.txt) and inserts all the names in a list in ascending order. This is the full class roster list (notCheckedIN). From here I will read all students who have come to write the exams, each checkin will transfer their name to another list (in ascending order) called present. The final product is notCheckedIN will contain a list of all those students that did not write the exam and present will contain the list of all students who wrote the exam Main File: // Exam.cpp : Defines the entry point for the console application. #include "stdafx.h" #include "iostream" #include "iomanip" #include "fstream" #include "string" #include "slist.h" using namespace std; void OpenFile(ifstream&); void GetClassRoster(SortList&, ifstream&); void InputStuName(SortList&, SortList&); void UpdateList(SortList&, SortList&, string); void Print(SortList&, SortList&); const string END_DATA = "EndData"; int main() { ifstream roster; SortList notCheckedIn; //students present SortList present; //student absent OpenFile(roster); if(!roster) //Make sure file is opened return 1; GetClassRoster(notCheckedIn, roster); //insert the roster list into the notCheckedIn list InputStuName(present, notCheckedIn); Print(present, notCheckedIn); return 0; } void OpenFile(ifstream& roster) //Precondition: roster is pointing to file containing student anmes //Postcondition:IF file does not exist -> exit { string fileName = "roster.txt"; roster.open(fileName.c_str()); if(!roster) cout << "***ERROR CANNOT OPEN FILE :"<< fileName << "***" << endl; } void GetClassRoster(SortList& notCheckedIN, ifstream& roster) //Precondition:roster points to file containing list of student last name // && notCheckedIN is empty //Postcondition:notCheckedIN is filled with the names taken from roster.txt in ascending order { string name; roster >> name; while(roster) { notCheckedIN.Insert(name); roster >> name; } } void InputStuName(SortList& present, SortList& notCheckedIN) //Precondition: present list is empty initially and notCheckedIN list is full //Postcondition: repeated prompting to enter stuName // && notCheckedIN will delete all names found in present // && present will contain names present // && names not found in notCheckedIN will report Error { string stuName; cout << "Enter last name (Enter EndData if none to Enter): "; cin >> stuName; while(stuName!=END_DATA) { UpdateList(present, notCheckedIN, stuName); } } void UpdateList(SortList& present, SortList& notCheckedIN, string stuName) //Precondition:stuName is assigned //Postcondition:IF stuName is present, stuName is inserted in present list // && stuName is removed from the notCheckedIN list // ELSE stuName does not exist { if(notCheckedIN.isPresent(stuName)) { present.Insert(stuName); notCheckedIN.Delete(stuName); } else cout << "NAME IS NOT PRESENT" << endl; } void Print(SortList& present, SortList& notCheckedIN) //Precondition: present and notCheckedIN contains a list of student Names present/not present //Postcondition: content of present and notCheckedIN is printed { cout << "Candidates Present" << endl; present.Print(); cout << "Candidates Absent" << endl; notCheckedIN.Print(); } Header File: //Specification File: slist.h //This file gives the specifications of a list abstract data type //List items inserted will be in order //Class SortList, structured type used to represent an ADT using namespace std; const int MAX_LENGTH = 200; typedef string ItemType; //Class Object (class instance) SortList. Variable of class type. class SortList { //Class Member - components of a class, can be either data or functions public: //Constructor //Post-condition: Empty list is created SortList(); //Const member function. Compiler error occurs if any statement within tries to modify a private data bool isEmpty() const; //Post-condition: == true if list is empty // == false if list is not empty bool isFull() const; //Post-condition: == true if list is full // == false if list is full int Length() const; //Post-condition: size of list void Insert(ItemType item); //Precondition: NOT isFull() && item is assigned //Postcondition: item is in list && Length() = Length()@entry + 1 void Delete(ItemType item); //Precondition: NOT isEmpty() && item is assigned //Postcondition: // IF items is in list at entry // first occurance of item in list is removed // && Length() = Length()@entry -1; // ELSE // list is not changed bool isPresent(ItemType item) const; //Precondition: item is assigned //Postcondition: == true if item is present in list // == false if item is not present in list void Print() const; //Postcondition: All component of list have been output private: int length; ItemType data[MAX_LENGTH]; void BinSearch(ItemType, bool&, int&) const; }; Source File: //Implementation File: slist.cpp //This file gives the specifications of a list abstract data type //List items inserted will be in order //Class SortList, structured type used to represent an ADT #include "iostream" #include "slist.h" using namespace std; // int length; // ItemType data[MAX_SIZE]; //Class Object (class instance) SortList. Variable of class type. SortList::SortList() //Constructor //Post-condition: Empty list is created { length=0; } //Const member function. Compiler error occurs if any statement within tries to modify a private data bool SortList::isEmpty() const //Post-condition: == true if list is empty // == false if list is not empty { return(length==0); } bool SortList::isFull() const //Post-condition: == true if list is full // == false if list is full { return (length==(MAX_LENGTH-1)); } int SortList::Length() const //Post-condition: size of list { return length; } void SortList::Insert(ItemType item) //Precondition: NOT isFull() && item is assigned //Postcondition: item is in list && Length() = Length()@entry + 1 // && list componenet are in ascending order of value { int index; index = length -1; while(index >=0 && item<data[index]) { data[index+1]=data[index]; index--; } data[index+1]=item; length++; } void SortList:elete(ItemType item) //Precondition: NOT isEmpty() && item is assigned //Postcondition: // IF items is in list at entry // first occurance of item in list is removed // && Length() = Length()@entry -1; // && list components are in ascending order // ELSE data array is unchanged { bool found; int position; BinSearch(item,found,position); if (found) { for(int index = position; index < length; index++) data[index]=data[index+1]; length--; } } bool SortList::isPresent(ItemType item) const //Precondition: item is assigned && length <= MAX_LENGTH && items are in ascending order //Postcondition: true if item is found in the list // false if item is not found in the list { bool found; int position; BinSearch(item,found,position); return (found); } void SortList::Print() const //Postcondition: All component of list have been output { for(int x= 0; x<length; x++) cout << data[x] << endl; } void SortList::BinSearch(ItemType item, bool found, int position) const //Precondition: item contains item to be found // && item in the list is an ascending order //Postcondition: IF item is in list, position is returned // ELSE item does not exist in the list { int first = 0; int last = length -1; int middle; found = false; while(!found) { middle = (first+last)/2; if(data[middle]<item) first = middle+1; else if (data[middle] > item) last = middle -1; else found = true; } if(found) position = middle; } I cannot get rid of the C1010 error: fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source? Is there a way to get rid of this error? When I included "stdafx.h" I received the following 32 errors (which does not make sense to me why because I referred back to my manual on how to use Class method - everything looks a.ok.) Error 1 error C2871: 'std' : a namespace with this name does not exist c:\..\slist.h 6 Error 2 error C2146: syntax error : missing ';' before identifier 'ItemType' c:\..\slist.h 8 Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\..\slist.h 8 Error 4 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\..\slist.h 8 Error 5 error C2061: syntax error : identifier 'ItemType' c:\..\slist.h 30 Error 6 error C2061: syntax error : identifier 'ItemType' c:\..\slist.h 34 Error 7 error C2061: syntax error : identifier 'ItemType' c:\..\slist.h 43 Error 8 error C2146: syntax error : missing ';' before identifier 'data' c:\..\slist.h 52 Error 9 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\..\slist.h 52 Error 10 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\..\slist.h 52 Error 11 error C2061: syntax error : identifier 'ItemType' c:\..\slist.h 53 Error 12 error C2146: syntax error : missing ')' before identifier 'item' c:\..\slist.cpp 41 Error 13 error C2761: 'void SortList::Insert(void)' : member function redeclaration not allowed c:\..\slist.cpp 41 Error 14 error C2059: syntax error : ')' c:\..\slist.cpp 41 Error 15 error C2143: syntax error : missing ';' before '{' c:\..\slist.cpp 45 Error 16 error C2447: '{' : missing function header (old-style formal list?) c:\..\slist.cpp 45 Error 17 error C2146: syntax error : missing ')' before identifier 'item' c:\..\slist.cpp 57 Error 18 error C2761: 'void SortList:elete(void)' : member function redeclaration not allowed c:\..\slist.cpp 57 Error 19 error C2059: syntax error : ')' c:\..\slist.cpp 57 Error 20 error C2143: syntax error : missing ';' before '{' c:\..\slist.cpp 65 Error 21 error C2447: '{' : missing function header (old-style formal list?) c:\..\slist.cpp 65 Error 22 error C2146: syntax error : missing ')' before identifier 'item' c:\..\slist.cpp 79 Error 23 error C2761: 'bool SortList::isPresent(void) const' : member function redeclaration not allowed c:\..\slist.cpp 79 Error 24 error C2059: syntax error : ')' c:\..\slist.cpp 79 Error 25 error C2143: syntax error : missing ';' before '{' c:\..\slist.cpp 83 Error 26 error C2447: '{' : missing function header (old-style formal list?) c:\..\slist.cpp 83 Error 27 error C2065: 'data' : undeclared identifier c:\..\slist.cpp 95 Error 28 error C2146: syntax error : missing ')' before identifier 'item' c:\..\slist.cpp 98 Error 29 error C2761: 'void SortList::BinSearch(void) const' : member function redeclaration not allowed c:\..\slist.cpp 98 Error 30 error C2059: syntax error : ')' c:\..\slist.cpp 98 Error 31 error C2143: syntax error : missing ';' before '{' c:\..\slist.cpp 103 Error 32 error C2447: '{' : missing function header (old-style formal list?) c:\..\slist.cpp 103

    Read the article

  • Distutils - Where Am I going wrong?

    - by RJBrady
    I wanted to learn how to create python packages, so I visited http://docs.python.org/distutils/index.html. For this exercise I'm using Python 2.6.2 on Windows XP. I followed along with the simple example and created a small test project: person/ setup.py person/ __init__.py person.py My person.py file is simple: class Person(object): def __init__(self, name="", age=0): self.name = name self.age = age def sound_off(self): print "%s %d" % (self.name, self.age) And my setup.py file is: from distutils.core import setup setup(name='person', version='0.1', packages=['person'], ) I ran python setup.py sdist and it created MANIFEST, dist/ and build/. Next I ran python setup.py install and it installed it to my site packages directory. I run the python console and can import the person module, but I cannot import the Person class. >>>import person >>>from person import Person Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name Person I checked the files added to site-packages and checked the sys.path in the console, they seem ok. Why can't I import the Person class. Where did I go wrong?

    Read the article

  • Ruby and public_method_defined? : strange behaviour

    - by aXon
    Hi there Whilst reading through the book "The well grounded Rubyist", I came across some strange behaviour. The idea behind the code is using one's own method_missing method. The only thing I am not able to grasp is, why this code gets executed, as I do not have any Person.all_with_* class methods defined, which in turn means that the self.public_method_defined?(attr) returns true (attr is friends and then hobbies). #!/usr/bin/env ruby1.9 class Person PEOPLE = [] attr_reader :name, :hobbies, :friends def initialize(mame) @name = name @hobbies = [] @friends = [] PEOPLE << self end def has_hobby(hobby) @hobbies << hobby end def has_friend(friend) @friends << friend end def self.method_missing(m,*args) method = m.to_s if method.start_with?("all_with_") attr = method[9..-1] if self.public_method_defined?(attr) PEOPLE.find_all do |person| person.send(attr).include?(args[0]) end else raise ArgumentError, "Can't find #{attr}" end else super end end end j = Person.new("John") p = Person.new("Paul") g = Person.new("George") r = Person.new("Ringo") j.has_friend(p) j.has_friend(g) g.has_friend(p) r.has_hobby("rings") Person.all_with_friends(p).each do |person| puts "#{person.name} is friends with #{p.name}" end Person.all_with_hobbies("rings").each do |person| puts "#{person.name} is into rings" end The output is is friends with is friends with is into rings which is really understandable, as there is nothing to be executed.

    Read the article

  • Doubt about instance creation by using Spring framework ???

    - by Arthur Ronald F D Garcia
    Here goes a command object which needs to be populated from a Spring form public class Person { private String name; private Integer age; /** * on-demand initialized */ private Address address; // getter's and setter's } And Address public class Address { private String street; // getter's and setter's } Now suppose the following MultiActionController @Component public class PersonController extends MultiActionController { @Autowired @Qualifier("personRepository") private Repository<Person, Integer> personRepository; /** * mapped To /person/add */ public ModelAndView add(HttpServletRequest request, HttpServletResponse response, Person person) throws Exception { personRepository.add(person); return new ModelAndView("redirect:/home.htm"); } } Because Address attribute of Person needs to be initialized on-demand, i need to override newCommandObject to create an instance of Person to initiaze address property. Otherwise, i will get NullPointerException @Component public class PersonController extends MultiActionController { /** * code as shown above */ @Override public Object newCommandObject(Class clazz) thorws Exception { if(clazz.isAssignableFrom(Person.class)) { Person person = new Person(); person.setAddress(new Address()); return person; } } } Ok, Expert Spring MVC and Web Flow says Options for alternate object creation include pulling an instance from a BeanFactory or using method injection to transparently return a new instance. First option pulling an instance from a BeanFactory can be written as @Override public Object newCommandObject(Class clazz) thorws Exception { /** * Will retrieve a prototype instance from ApplicationContext whose name matchs its clazz.getSimpleName() */ getApplicationContext().getBean(clazz.getSimpleName()); } But what does he want to say by using method injection to transparently return a new instance ??? Can you show how i implement what he said ??? ATT: I know this funcionality can be filled by a SimpleFormController instead of MultiActionController. But it is shown just as an example, nothing else

    Read the article

  • Sharing the same file between different projects

    - by selsine
    Hi Everyone, For version control we currently use Visual Source Safe and are thinking of migrating to another version control system (SVN, Mercurial, Git). Currently we use Visual Source Safe's "Shared" file feature quite heavily. This allows us to share code between design and runtimes of a single product, and between multiple products as well. For example: **Product One** - Design Login.cpp Login.h Helper.cpp Helper.h - Runtime Login.cpp Login.h Helper.cpp Helper.h **Product Two** - Design Login.cpp Login.h - Launcher Login.cpp Login.h - Runtime Login.cpp Login.h In this example Login.cpp and Login.h contain common code that all of our projects need, Helper.cpp and Helper.h is only used in Product One. In Visual Source Safe they are shared between the specific projects, which means that whenever the files are updated in one project they are updated in any project they are shared with. This is a simple example but hopefully it explains why we use the shared feature: to reduce the amount of duplicated code and ensure that when a bug is fixed all projects automatically have access to the new fixed code. After researching alternatives to Visual Source Safe it seems that most version control systems do not have the idea of shared files, instead they seem to use the idea of sub repositories. (http://mercurial.selenic.com/wiki/subrepos http://svnbook.red-bean.com/en/1.0/ch07s03.html) My question (after all of that) is about what the best practices for achieving this are using other version control systems? Should we restructure our projects so that two copies of the files do not exist and an include directory is used instead? e.g. Product One Design Login.cpp Login.h Runtime Login.cpp Login.h Common Helper.cpp Helper.h This still leaves what to do with Login.cpp and Logon.h Should the shared files be moved to their own repository and then compiled into a lib or dll? This would make bug fixing more time consuming as the lib projects would have to be edited and then rebuilt. Should we use externals or sub repositories? Should we combine our projects (i.e. runtime, design, and launcher) into one large project? Any help would be appreciated. We have the feeling that our project design has evolved based on the tools that we used and now that we are thinking of switching tools it's difficult for us to see how we can best modify our practices. Or maybe we are the only people are there doing this...? Also, we use Visual Studio for all of our stuff. Thanks.

    Read the article

  • Etiquette for refactoring other people's sourcecode?

    - by Prutswonder
    Our team of software developers consists of a bunch of experienced programmers with a variety of programming styles and preferences. We do not have standards for everything, just the bare necessities to prevent total chaos. Recently, I bumped into some refactoring done by a colleague. My code looked somewhat like this: public Person CreateNewPerson(string firstName, string lastName) { var person = new Person() { FirstName = firstName, LastName = lastName }; return person; } Which was refactored to this: public Person CreateNewPerson (string firstName, string lastName) { Person person = new Person (); person.FirstName = firstName; person.LastName = lastName; return person; } Just because my colleague needed to update some other method in one of the classes I wrote, he also "refactored" the method above. For the record, he's one of those developers that despises syntactic sugar and uses a different bracket placement/identation scheme than the rest of us. My question is: What is the (C#) programmer's etiquette for refactoring other people's sourcecode (both semantic and syntactic)?

    Read the article

  • Function Object in Java .

    - by Tony
    I wanna implement a javascript like method in java , is this possible ? Say , I have a Person class : public class Person { private String name ; private int age ; // constructor ,accessors are omitted } And a list with Person objects: Person p1 = new Person("Jenny",20); Person p2 = new Person("Kate",22); List<Person> pList = Arrays.asList(new Person[] {p1,p2}); I wanna implement a method like this: modList(pList,new Operation (Person p) { incrementAge(Person p) { p.setAge(p.getAge() + 1)}; }); modList receives two params , one is a list , the other is the "Function object", it loops the list ,and apply this function to every element in the list. In functional programming language,this is easy , I don't know how java do this? Maybe could be done through dynamic proxy, does that have a performance trade off?

    Read the article

  • Need help with writing test

    - by London
    I'm trying to write a test for this class its called Receiver : public void get(People person) { if(null != person) { LOG.info("Person with ID " + person.getId() + " received"); processor.process(person); }else{ LOG.info("Person not received abort!"); } } Here is the test : @Test public void testReceivePerson(){ context.checking(new Expectations() {{ receiver.get(person); atLeast(1).of(person).getId(); will(returnValue(String.class)); }}); } Note: receiver is the instance of Receiver class(real not mock), processor is the instance of Processor class(real not mock) which processes the person(mock object of People class). GetId is a String not int method that is not mistake. Test fails : unexpected invocation of person.getId() I'm using jMock any help would be appreciated. As I understood when I call this get method to execute it properly I need to mock person.getId() , and I've been sniping around in circles for a while now any help would be appreciated.

    Read the article

  • Bringing people into an Asterisk conference call

    - by Harley
    I'm using Asterisk 1.4 and am trying to work out a way to bring people into a conference call. In the ideal scenario two people would be talking and one of them would push some keys, then a phone number and then the three of them would be in a conference. From there they should be able to bring in other people as well. This seems to be what the Asterisk n-way call HOWTO is trying to do, but it doesn't work quite properly for me. Here's what happens: 1. Internal person A calls person B 2. Person A presses *0, he is given a dial tone and person B is taken to a conference room 3. Person A calls person C and they can talk, and then person A presses **. 4. Person C is brought to the conference room, but person A is disconnected. In the last step, A should be taken to the conference room as well. Here's the relevant logs, where 230 is person A, 231 is person B, 207 is person C, and 282 is the conference room.

    Read the article

  • How can a non-technical person can learn to write a spec for small projects?

    - by Joseph Turian
    How can a non-technical person learn to write specs for small projects? A friend of mine is trying to outsource some development on a statistics project. In particular, he does a lot of work in excel, and wants to outsource the creation of scripts to do what he now does by hand. However, my friend is extremely non-technical. He is poor at writing technical specs. When he does write a spec, it is written the way you would describe doing something in excel (go to this cell and then copy the value to that cell). It is also overly verbose, and does examples several times. I'm not sure if he properly describes corner cases. The first project he outsourced was a failure. I think he overdescribed some details, but underdescribed corner cases. That and/or the coder he hired didn't think through the corner cases and ask appropriate questions. I'm not sure. I got on IM with him and it took me half an hour to dig out a description that should have taken five minutes or less to describe. I wrote the scripts for him at the end, but didn't examine why his process with the coder failed. He has asked me for help. However, I refuse to get involved, because taking his spec and translating it into clear requirements is 10x more work than executing on a clearly written spec. What is the right way for him to learn? Are there resources he could use? Are there ways he can learn from small, low-pressure practice projects with coders? [edit: Most of his scripts are statistical and data processing oriented. e.g. take this column and run an average over it. Remove these rows under these conditions. So the challenge is different than spec'ing a web app.]

    Read the article

  • How can a non-technical person learn to write a spec for small projects?

    - by Joseph Turian
    How can a non-technical person learn to write specs for small projects? A friend of mine is trying to outsource some development on a statistics project. In particular, he does a lot of work in excel, and wants to outsource the creation of scripts to do what he now does by hand. However, my friend is extremely non-technical. He is poor at writing technical specs. When he does write a spec, it is written the way you would describe doing something in excel (go to this cell and then copy the value to that cell). It is also overly verbose, and does examples several times. I'm not sure if he properly describes corner cases. The first project he outsourced was a failure. I think he overdescribed some details, but underdescribed corner cases. That and/or the coder he hired didn't think through the corner cases and ask appropriate questions. I'm not sure. I got on IM with him and it took me half an hour to dig out a description that should have taken five minutes or less to describe. I wrote the scripts for him at the end, but didn't examine why his process with the coder failed. He has asked me for help. However, I refuse to get involved, because taking his spec and translating it into clear requirements is 10x more work than executing on a clearly written spec. What is the right way for him to learn? Are there resources he could use? Are there ways he can learn from small, low-pressure practice projects with coders? Most of his scripts are statistical and data processing oriented. e.g. take this column and run an average over it. Remove these rows under these conditions. So the challenge is different than spec'ing a web app.

    Read the article

  • C++ scoping error

    - by Pat Murray
    I have the following code: #include "Student.h" #include "SortedList.h" using namespace std; int main() { // points to the sorted list object SortedList *list = new SortedList; //This is line 17 // array to hold 100 student objects Student create[100]; int num = 100000; // holds different ID numbers // fills an array with 100 students of various ID numbers for (Student &x : create) { x = new Student(num); num += 100; } // insert all students into the sorted list for (Student &x : create) list->insert(&x); delete list; return 0; } And I keep getting the compile time error: main.cpp: In function ‘int main()’: main.cpp:17: error: ‘SortedList’ was not declared in this scope main.cpp:17: error: ‘list’ was not declared in this scope main.cpp:17: error: expected type-specifier before ‘SortedList’ main.cpp:17: error: expected `;' before ‘SortedList’ main.cpp:20: error: ‘Student’ was not declared in this scope main.cpp:20: error: expected primary-expression before ‘]’ token main.cpp:20: error: expected `;' before ‘create’ main.cpp:25: error: expected `;' before ‘x’ main.cpp:31: error: expected primary-expression before ‘for’ main.cpp:31: error: expected `;' before ‘for’ main.cpp:31: error: expected primary-expression before ‘for’ main.cpp:31: error: expected `)' before ‘for’ main.cpp:31: error: expected `;' before ‘x’ main.cpp:34: error: type ‘<type error>’ argument given to ‘delete’, expected pointer main.cpp:35: error: expected primary-expression before ‘return’ main.cpp:35: error: expected `)' before ‘return’ My Student.cpp and SortedList.cpp files compile just fine. They both also include .h files. I just do not understand why I get an error on that line. It seems to be a small issue though. Any insight would be appreciated. UPDATE1: I originally had .h files included, but i changed it when trying to figure out the cause of the error. The error remains with the .h files included though. UPDATE2: SortedList.h #ifndef SORTEDLIST_H #define SORTEDLIST_H #include "Student.h" /* * SortedList class * * A SortedList is an ordered collection of Students. The Students are ordered * from lowest numbered student ID to highest numbered student ID. */ class SortedList { public: SortedList(); // Constructs an empty list. SortedList(const SortedList & l); // Constructs a copy of the given student object ~SortedList(); // Destructs the sorted list object const SortedList & operator=(const SortedList & l); // Defines the assignment operator between two sorted list objects bool insert(Student *s); // If a student with the same ID is not already in the list, inserts // the given student into the list in the appropriate place and returns // true. If there is already a student in the list with the same ID // then the list is not changed and false is returned. Student *find(int studentID); // Searches the list for a student with the given student ID. If the // student is found, it is returned; if it is not found, NULL is returned. Student *remove(int studentID); // Searches the list for a student with the given student ID. If the // student is found, the student is removed from the list and returned; // if no student is found with the given ID, NULL is returned. // Note that the Student is NOT deleted - it is returned - however, // the removed list node should be deleted. void print() const; // Prints out the list of students to standard output. The students are // printed in order of student ID (from smallest to largest), one per line private: // Since Listnodes will only be used within the SortedList class, // we make it private. struct Listnode { Student *student; Listnode *next; }; Listnode *head; // pointer to first node in the list static void freeList(Listnode *L); // Traverses throught the linked list and deallocates each node static Listnode *copyList(Listnode *L); // Returns a pointer to the first node within a particular list }; #endif #ifndef STUDENT_H #define STUDENT_H Student.h #ifndef STUDENT_H #define STUDENT_H /* * Student class * * A Student object contains a student ID, the number of credits, and an * overall GPA. */ class Student { public: Student(); // Constructs a default student with an ID of 0, 0 credits, and 0.0 GPA. Student(int ID); // Constructs a student with the given ID, 0 credits, and 0.0 GPA. Student(int ID, int cr, double grPtAv); // Constructs a student with the given ID, number of credits, and GPA.\ Student(const Student & s); // Constructs a copy of another student object ~Student(); // Destructs a student object const Student & operator=(const Student & rhs); // Defines the assignment operator between two student objects // Accessors int getID() const; // returns the student ID int getCredits() const; // returns the number of credits double getGPA() const; // returns the GPA // Other methods void update(char grade, int cr); // Updates the total credits and overall GPA to take into account the // additions of the given letter grade in a course with the given number // of credits. The update is done by first converting the letter grade // into a numeric value (A = 4.0, B = 3.0, etc.). The new GPA is // calculated using the formula: // // (oldGPA * old_total_credits) + (numeric_grade * cr) // newGPA = --------------------------------------------------- // old_total_credits + cr // // Finally, the total credits is updated (to old_total_credits + cr) void print() const; // Prints out the student to standard output in the format: // ID,credits,GPA // Note: the end-of-line is NOT printed after the student information private: int studentID; int credits; double GPA; }; #endif

    Read the article

  • Writing more efficient xquery code (avoiding redundant iteration)

    - by Coquelicot
    Here's a simplified version of a problem I'm working on: I have a bunch of xml data that encodes information about people. Each person is uniquely identified by an 'id' attribute, but they may go by many names. For example, in one document, I might find <person id=1>Paul Mcartney</person> <person id=2>Ringo Starr</person> And in another I might find: <person id=1>Sir Paul McCartney</person> <person id=2>Richard Starkey</person> I want to use xquery to produce a new document that lists every name associated with a given id. i.e.: <person id=1> <name>Paul McCartney</name> <name>Sir Paul McCartney</name> <name>James Paul McCartney</name> </person> <person id=2> ... </person> The way I'm doing this now in xquery is something like this (pseudocode-esque): let $ids := distinct-terms( [all the id attributes on people] ) for $id in $ids return <person id={$id}> { for $unique-name in distinct-values ( for $name in ( [all names] ) where $name/@id=$id return $name ) return <name>{$unique-name}</name> } </person> The problem is that this is really slow. I imagine the bottleneck is the innermost loop, which executes once for every id (of which there are about 1200). I'm dealing with a fair bit of data (300 MB, spread over about 800 xml files), so even a single execution of the query in the inner loop takes about 12 seconds, which means that repeating it 1200 times will take about 4 hours (which might be optimistic - the process has been running for 3 hours so far). Not only is it slow, it's using a whole lot of virtual memory. I'm using Saxon, and I had to set java's maximum heap size to 10 GB (!) to avoid getting out of memory errors, and it's currently using 6 GB of physical memory. So here's how I'd really like to do this (in Pythonic pseudocode): persons = {} for id in ids: person[id] = set() for person in all_the_people_in_my_xml_document: persons[person.id].add(person.name) There, I just did it in linear time, with only one sweep of the xml document. Now, is there some way to do something similar in xquery? Surely if I can imagine it, a reasonable programming language should be able to do it (he said quixotically). The problem, I suppose, is that unlike Python, xquery doesn't (as far as I know) have anything like an associative array. Is there some clever way around this? Failing that, is there something better than xquery that I might use to accomplish my goal? Because really, the computational resources I'm throwing at this relatively simple problem are kind of ridiculous.

    Read the article

  • [game] How to write ::: in cpp and ??? in c#?

    - by daveny
    These questions are a kind of game, and I did not find the solution for them. It is possible to write ::: in Cpp without using "" or anything like this and the compiler will accept it. (macro-s are prohibited too) And the same is true for C# too, but in C#, you have to write ???. I think Cpp will use the :: scope operator and C# will use '? :' , but I do not know the answers to them. Any idea?

    Read the article

  • UndoRedo on Nodes

    - by Geertjan
    When a change is made to the property in the Properties Window, below, the undo/redo functionality becomes enabled: When undo/redo are invoked, e.g., via the buttons in the toolbar, the display name of the node changes accordingly. The only problem I have is that the buttons only become enabled when the Person Window is selected, not when the Properties Window is selected, which would be desirable. Here's the Person object: public class Person implements PropertyChangeListener {     private String name;     public static final String PROP_NAME = "name";     public Person(String name) {         this.name = name;     }     public String getName() {         return name;     }     public void setName(String name) {         String oldName = this.name;         this.name = name;         propertyChangeSupport.firePropertyChange(PROP_NAME, oldName, name);     }     private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);     public void addPropertyChangeListener(PropertyChangeListener listener) {         propertyChangeSupport.addPropertyChangeListener(listener);     }     public void removePropertyChangeListener(PropertyChangeListener listener) {         propertyChangeSupport.removePropertyChangeListener(listener);     }     @Override     public void propertyChange(PropertyChangeEvent evt) {         propertyChangeSupport.firePropertyChange(evt);     } } And here's the Node with UndoRedo enablement: public class PersonNode extends AbstractNode implements UndoRedo.Provider, PropertyChangeListener {     private UndoRedo.Manager manager = new UndoRedo.Manager();     private boolean undoRedoEvent;     public PersonNode(Person person) {         super(Children.LEAF, Lookups.singleton(person));         person.addPropertyChangeListener(this);         setDisplayName(person.getName());     }     @Override     protected Sheet createSheet() {         Sheet sheet = Sheet.createDefault();         Sheet.Set set = Sheet.createPropertiesSet();         set.put(new NameProperty(getLookup().lookup(Person.class)));         sheet.put(set);         return sheet;     }     @Override     public void propertyChange(PropertyChangeEvent evt) {         if (evt.getPropertyName().equals(Person.PROP_NAME)) {             firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue());         }     }     public void fireUndoableEvent(String property, Person source, Object oldValue, Object newValue) {         manager.addEdit(new MyAbstractUndoableEdit(source, oldValue, newValue));     }     @Override     public UndoRedo getUndoRedo() {         return manager;     }     @Override     public String getDisplayName() {         Person p = getLookup().lookup(Person.class);         if (p != null) {             return p.getName();         }         return super.getDisplayName();     }     private class NameProperty extends PropertySupport.ReadWrite<String> {         private Person p;         public NameProperty(Person p) {             super("name", String.class, "Name", "Name of Person");             this.p = p;         }         @Override         public String getValue() throws IllegalAccessException, InvocationTargetException {             return p.getName();         }         @Override         public void setValue(String newValue) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {             String oldValue = p.getName();             p.setName(newValue);             if (!undoRedoEvent) {                 fireUndoableEvent("name", p, oldValue, newValue);                 fireDisplayNameChange(oldValue, newValue);             }         }     }     class MyAbstractUndoableEdit extends AbstractUndoableEdit {         private final String oldValue;         private final String newValue;         private final Person source;         private MyAbstractUndoableEdit(Person source, Object oldValue, Object newValue) {             this.oldValue = oldValue.toString();             this.newValue = newValue.toString();             this.source = source;         }         @Override         public boolean canRedo() {             return true;         }         @Override         public boolean canUndo() {             return true;         }         @Override         public void undo() throws CannotUndoException {             undoRedoEvent = true;             source.setName(oldValue.toString());             fireDisplayNameChange(oldValue, newValue);             undoRedoEvent = false;         }         @Override         public void redo() throws CannotUndoException {             undoRedoEvent = true;             source.setName(newValue.toString());             fireDisplayNameChange(oldValue, newValue);             undoRedoEvent = false;         }     } } Does anyone out there know how to have the Undo/Redo functionality enabled when the Properties Window is selected?

    Read the article

  • Populate Multiple PDFs

    - by gmcalab
    I am using itextsharp to populate my PDFs. I have no issues with this. Basically what I am doing is getting the PDF and populating the fields in memory then passing back the MemoryStream to be displayed on a webpage. All this is working with a single document PDF. What I am trying to figure out now, is merging multiple PDFs into one MemoryStream. The part I cant figure out is, the documents I am populating are identical. So for example, I have a List<Person> that contains 5 persons. I want to fill out a PDF for each person and merge them all into one, in memory. Bare in mind I am going to fill out the same type of document for each person. The problem I am getting is that when I try to add a second copy of the same PDF to be filled out for the second iteration, it just overwrites the first populated PDF, since it's the same document, therefore not adding a second copy for the second Person at all. So basically if I had the 5 people, I would end up with a single page with the data of the 5th person, instead of a PDF with 5 like pages that contain the data of each person respectively. Here's some code... MemoryStream ms = ms = new MemoryStream(); PdfReader docReader = null; PdfStamper Stamper = null; List<Person> persons = new List<Person>() { new Person("Larry", "David"), new Person("Dustin", "Byfuglien"), new Person("Patrick", "Kane"), new Person("Johnathan", "Toews"), new Person("Marian", "Hossa") }; try { // Iterate thru all persons and populate a PDF for each foreach(var person in persons){ PdfCopyFields Copier = new PdfCopyFields(ms); Copier.AddDocument(GetReader("Person.pdf")); Copier.Close(); docReader = new PdfReader(ms.ToArray()); Stamper = new PdfStamper(docReader, ms); AcroFields Fields = Stamper.AcroFields; Fields.SetField("FirstName", person.FirstName); } }catch(Exception e){ // handle error }finally{ if (Stamper != null) { Stamper.Close(); } if (docReader != null) { docReader.Close(); } }

    Read the article

  • BDD for C# NUnit

    - by mjezzi
    I've been using a home brewed BDD Spec extension for writing BDD style tests in NUnit, and I wanted to see what everyone thought. Does it add value? Does is suck? If so why? Is there something better out there? Here's the source: https://github.com/mjezzi/NSpec There are two reasons I created this To make my tests easy to read. To produce a plain english output to review specs. Here's an example of how a test will look: -since zombies seem to be popular these days.. Given a Zombie, Peson, and IWeapon: namespace Project.Tests.PersonVsZombie { public class Zombie { } public interface IWeapon { void UseAgainst( Zombie zombie ); } public class Person { private IWeapon _weapon; public bool IsStillAlive { get; set; } public Person( IWeapon weapon ) { IsStillAlive = true; _weapon = weapon; } public void Attack( Zombie zombie ) { if( _weapon != null ) _weapon.UseAgainst( zombie ); else IsStillAlive = false; } } } And the NSpec styled tests: public class PersonAttacksZombieTests { [Test] public void When_a_person_with_a_weapon_attacks_a_zombie() { var zombie = new Zombie(); var weaponMock = new Mock<IWeapon>(); var person = new Person( weaponMock.Object ); person.Attack( zombie ); "It should use the weapon against the zombie".ProveBy( spec => weaponMock.Verify( x => x.UseAgainst( zombie ), spec ) ); "It should keep the person alive".ProveBy( spec => Assert.That( person.IsStillAlive, Is.True, spec ) ); } [Test] public void When_a_person_without_a_weapon_attacks_a_zombie() { var zombie = new Zombie(); var person = new Person( null ); person.Attack( zombie ); "It should cause the person to die".ProveBy( spec => Assert.That( person.IsStillAlive, Is.False, spec ) ); } } You'll get the Spec output in the output window: [PersonVsZombie] - PersonAttacksZombieTests When a person with a weapon attacks a zombie It should use the weapon against the zombie It should keep the person alive When a person without a weapon attacks a zombie It should cause the person to die 2 passed, 0 failed, 0 skipped, took 0.39 seconds (NUnit 2.5.5).

    Read the article

  • XSLT: How to remove the self-closed elment

    - by Daoming Yang
    I have a large xml file which contents a lot of self-closed tags. How could remove all them by using XSLT. eg. <?xml version="1.0" encoding="utf-8" ?> <Persons> <Person> <Name>user1</Name> <Tel /> <Mobile>123</Mobile> </Person> <Person> <Name>user2</Name> <Tel>456</Tel> <Mobile /> </Person> <Person> <Name /> <Tel>123</Tel> <Mobile /> </Person> <Person> <Name>user4</Name> <Tel /> <Mobile /> </Person> </Persons> I'm expecting the result: <?xml version="1.0" encoding="utf-8" ?> <Persons> <Person> <Name>user1</Name> <Mobile>123</Mobile> </Person> <Person> <Name>user2</Name> <Tel>456</Tel> </Person> <Person> <Tel>123</Tel> </Person> <Person> <Name>user4</Name> </Person> </Persons> Note: there are thousands of different elements, how can I programmatically remove all the self-closed tags. Another question is how to remove the empty element such as <name></name> as well. Can anyone help me on this? Many thanks.

    Read the article

  • Compiling cpp code in netbeans produce errors, how to solve it ?

    - by Rupertt Wind
    i use the netbeans with MinGW and MYSY make /debugger but when i compile a basic cpp code in it and run it it produces two erorrs this is the code runned and the output![alt text][1] box #include <iostream> void main() { cout << "Hello World!" << endl; cout << "Welcome to C++ Programming" << endl; } output is /usr/bin/make -f nbproject/Makefile-Debug.mk SUBPROJECTS= .build-conf make[1]: Entering directory `/d/Users/Home/Documents/NetBeansProjects/newApp' /usr/bin/make -f nbproject/Makefile-Debug.mk dist/Debug/MinGW-Windows/newapp.exe make[2]: Entering directory `/d/Users/Home/Documents/NetBeansProjects/newApp' mkdir -p dist/Debug/MinGW-Windows g++.exe -o dist/Debug/MinGW-Windows/newapp build/Debug/MinGW-Windows/newmain.o build/Debug/MinGW-Windows/newfile.o build/Debug/MinGW-Windows/main.o build/Debug/MinGW-Windows/newfile.o: In function `main': D:/Users/Home/Documents/NetBeansProjects/newApp/newfile.cpp:5: multiple definition of `main' build/Debug/MinGW-Windows/newmain.o:D:/Users/Home/Documents/NetBeansProjects/newApp/newmain.c:15: first defined here build/Debug/MinGW-Windows/main.o: In function `main': D:/Users/Home/Documents/NetBeansProjects/newApp/main.cpp:13: multiple definition of `main' build/Debug/MinGW-Windows/newmain.o:D:/Users/Home/Documents/NetBeansProjects/newApp/newmain.c:15: first defined here collect2: ld returned 1 exit status make[2]: *** [dist/Debug/MinGW-Windows/newapp.exe] Error 1 make[2]: Leaving directory `/d/Users/Home/Documents/NetBeansProjects/newApp' make[1]: *** [.build-conf] Error 2 make[1]: Leaving directory `/d/Users/Home/Documents/NetBeansProjects/newApp' make: *** [.build-impl] Error 2 BUILD FAILED (exit value 2, total time: 1s) how can i solve this ?

    Read the article

  • How to join two collections with LINQ

    - by JustinGreenwood
    Here is a simple and complete example of how to perform joins on two collections with LINQ. I wrote it for a friend to show him, in one simple file, the power of LINQ queries and anonymous objects. In the file below, there are two simple data classes defined: Person and Item. In the beginning of the main method, two collections are created. Note that the Item's OwnerId field reference the PersonId of a Person object. The effect of the LINQ query below is equivalent to a SQL statement looking like this: select Person.PersonName as OwnerName, Item.ItemName as OwnedItem from Person inner join Item on Item.OwnerId = Person.PersonId order by Item.ItemName desc; using System; using System.Collections.Generic; using System.Linq; namespace LinqJoinAnonymousObjects { class Program { class Person { public int PersonId { get; set; } public string PersonName { get; set; } } class Item { public string ItemName { get; set; } public int OwnerId { get; set; } } static void Main(string[] args) { // Create two collections: one of people, and another with their possessions. var people = new List<Person> { new Person { PersonId=1, PersonName="Justin" }, new Person { PersonId=2, PersonName="Arthur" }, new Person { PersonId=3, PersonName="Bob" } }; var items = new List<Item> { new Item { OwnerId=1, ItemName="Armor" }, new Item { OwnerId=1, ItemName="Book" }, new Item { OwnerId=2, ItemName="Chain Mail" }, new Item { OwnerId=2, ItemName="Excalibur" }, new Item { OwnerId=3, ItemName="Bubbles" }, new Item { OwnerId=3, ItemName="Gold" } }; // Create a new, anonymous composite result for person id=2. var compositeResult = from p in people join i in items on p.PersonId equals i.OwnerId where p.PersonId == 2 orderby i.ItemName descending select new { OwnerName = p.PersonName, OwnedItem = i.ItemName }; // The query doesn't evaluate until you iterate through the query or convert it to a list Console.WriteLine("[" + compositeResult.GetType().Name + "]"); // Convert to a list and loop through it. var compositeList = compositeResult.ToList(); Console.WriteLine("[" + compositeList.GetType().Name + "]"); foreach (var o in compositeList) { Console.WriteLine("\t[" + o.GetType().Name + "] " + o.OwnerName + " - " + o.OwnedItem); } Console.ReadKey(); } } } The output of the program is below: [WhereSelectEnumerableIterator`2] [List`1] [<>f__AnonymousType1`2] Arthur - Excalibur [<>f__AnonymousType1`2] Arthur - Chain Mail

    Read the article

  • I'm getting an error in my Java code but I can't see whats wrong with it. Help?

    - by Fraz
    The error i'm getting is in the fillPayroll() method in the while loop where it says payroll.add(employee). The error says I can't invoke add() on an array type Person but the Employee class inherits from Person so I thought this would be possible. Can anyone clarify this for me? import java.io.*; import java.util.*; public class Payroll { private int monthlyPay, tax; private Person [] payroll = new Person [1]; //Method adds person to payroll array public void add(Person person) { if(payroll[0] == null) //If array is empty, fill first element with person { payroll[payroll.length-1] = person; } else //Creates copy of payroll with new person added { Person [] newPayroll = new Person [payroll.length+1]; for(int i = 0;i<payroll.length;i++) { newPayroll[i] = payroll[i]; } newPayroll[newPayroll.length] = person; payroll = newPayroll; } } public void fillPayroll() { try { FileReader fromEmployee = new FileReader ("EmployeeData.txt"); Scanner data = new Scanner(fromEmployee); Employee employee = new Employee(); while (data.hasNextLine()) { employee.readData(data.nextLine()); payroll.add(employee); } } catch (FileNotFoundException e) { System.out.println("Error: File Not Found"); } } }

    Read the article

  • Help with Hashmaps in Java

    - by Crystal
    I'm not sure how I use get() to get my information. Looking at my book, they pass the key to get(). I thought that get() returns the object associated with that key looking at the documentation. But I must be doing something wrong here.... Any thoughts? import java.util.*; public class OrganizeThis { /** Add a person to the organizer @param p A person object */ public void add(Person p) { staff.put(p, p.getEmail()); System.out.println("Person " + p + "added"); } /** * Find the person stored in the organizer with the email address. * Note, each person will have a unique email address. * * @param email The person email address you are looking for. * */ public Person findByEmail(String email) { Person aPerson = staff.get(email); return aPerson; } private Map<Person, String> staff = new HashMap<Person, String>(); public static void main(String[] args) { OrganizeThis testObj = new OrganizeThis(); Person person1 = new Person("J", "W", "111-222-3333", "[email protected]"); testObj.add(person1); System.out.println(testObj.findByEmail("[email protected]")); } }

    Read the article

  • ASP.NET MVC - How to Unit Test boundaries in the Repository pattern?

    - by JK
    Given a basic repository interface: public interface IPersonRepository { void AddPerson(Person person); List<Person> GetAllPeople(); } With a basic implementation: public class PersonRepository: IPersonRepository { public void AddPerson(Person person) { ObjectContext.AddObject(person); } public List<Person> GetAllPeople() { return ObjectSet.AsQueryable().ToList(); } } How can you unit test this in a meaningful way? Since it crosses the boundary and physically updates and reads from the database, thats not a unit test, its an integration test. Or is it wrong to want to unit test this in the first place? Should I only have integration tests on the repository? I've been googling the subject and blogs often say to make a stub that implements the IRepository: public class PersonRepositoryTestStub: IPersonRepository { private List<Person> people = new List<Person>(); public void AddPerson(Person person) { people.Add(person); } public List<Person> GetAllPeople() { return people; } } But that doesnt unit test PersonRepository, it tests the implementation of PersonRepositoryTestStub (not very helpful).

    Read the article

  • How do I alias the scala setter method 'myvar_$(myval)' to something more pleasing when in java?

    - by feydr
    I've been converting some code from java to scala lately trying to tech myself the language. Suppose we have this scala class: class Person() { var name:String = "joebob" } Now I want to access it from java so I can't use dot-notation like I would if I was in scala. So I can get my var's contents by issuing: person = Person.new(); System.out.println(person.name()); and set it via: person = Person.new(); person.name_$eq("sallysue"); System.out.println(person.name()); This holds true cause our Person Class looks like this in javap: Compiled from "Person.scala" public class Person extends java.lang.Object implements scala.ScalaObject{ public Person(); public void name_$eq(java.lang.String); public java.lang.String name(); public int $tag() throws java.rmi.RemoteException; } Yes, I could write my own getters/setters but I hate filling classes up with that and it doesn't make a ton of sense considering I already have them -- I just want to alias the _$eq method better. (This actually gets worse when you are dealing with stuff like antlr because then you have to escape it and it ends up looking like person.name_\$eq("newname"); Note: I'd much rather have to put up with this rather than fill my classes with more setter methods. So what would you do in this situation?

    Read the article

  • How do I alias the scala setter method 'myvar_$eq(myval)' to something more pleasing when in java?

    - by feydr
    I've been converting some code from java to scala lately trying to teach myself the language. Suppose we have this scala class: class Person() { var name:String = "joebob" } Now I want to access it from java so I can't use dot-notation like I would if I was in scala. So I can get my var's contents by issuing: person = Person.new(); System.out.println(person.name()); and set it via: person = Person.new(); person.name_$eq("sallysue"); System.out.println(person.name()); This holds true cause our Person Class looks like this in javap: Compiled from "Person.scala" public class Person extends java.lang.Object implements scala.ScalaObject{ public Person(); public void name_$eq(java.lang.String); public java.lang.String name(); public int $tag() throws java.rmi.RemoteException; } Yes, I could write my own getters/setters but I hate filling classes up with that and it doesn't make a ton of sense considering I already have them -- I just want to alias the _$eq method better. (This actually gets worse when you are dealing with stuff like antlr because then you have to escape it and it ends up looking like person.name_\$eq("newname"); Note: I'd much rather have to put up with this rather than fill my classes with more setter methods. So what would you do in this situation?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >