Search Results

Search found 169 results on 7 pages for 'iter'.

Page 1/7 | 1 2 3 4 5 6 7  | Next Page >

  • terminate called after throwing an instance of 'std::length_error'

    - by mark
    hello all, this is my first post here. As i am newbie, the problem might be stupid. I was writing a piece of code while the following error message shown, terminate called after throwing an instance of 'std::length_error' what(): basic_string::_S_create /home/gcj/finals /home/gcj/quals where Aborted the following is the offending code especially Line 39 to Line 52. It is weired for me as this block of code is almost same as the Line64 to Line79. int main(){ std::vector<std::string> dirs, need; std::string tmp_str; std::ifstream fp_in("small.in"); std::ofstream fp_out("output"); std::string::iterator iter_substr_begin, iter_substr_end; std::string slash("/"); int T, N, M; fp_in>>T; for (int t = 0; t < T; t++){ std::cout<<" time "<< t << std::endl; fp_in >> N >> M; for (int n =0; n<N; n++){ fp_in>>tmp_str; dirs.push_back(tmp_str); tmp_str.clear(); } for (int m=0; m<M; m++){ fp_in>>tmp_str; need.push_back(tmp_str); tmp_str.clear(); } for (std::vector<std::string>::iterator iter = dirs.begin(); iter!=dirs.end(); iter++){ for (std::string::iterator iter_str = (*iter).begin()+1; iter_str<(*iter).end(); ++iter_str){ if ((*iter_str)=='/') { std::string tmp_str2((*iter).begin(), iter_str); if (find(dirs.begin(), dirs.end(), tmp_str2)==dirs.end()) { dirs.push_back(tmp_str2); } } } } for (std::vector<std::string>::iterator iter_tmp = dirs.begin(); iter_tmp!= dirs.end(); ++iter_tmp) std::cout<<*iter_tmp<<" "; dirs.clear(); std::cout<<std::endl; std::cout<<" need "<<std::endl; //processing the next for (std::vector<std::string>::iterator iter_tmp = need.begin(); iter_tmp!=need.end(); ++iter_tmp) std::cout<<*iter_tmp<<" "; std::cout<<" where "; for (std::vector<std::string>::iterator iter = need.begin(); iter!=need.end(); iter++){ for (std::string::iterator iter_str = (*iter).begin()+1; iter_str<(*iter).end(); ++iter_str){ if ((*iter_str)=='/') { std::string tmp_str2((*iter).begin(), iter_str); if (find(need.begin(), need.end(), tmp_str2)==need.end()) { need.push_back(tmp_str2); } } } } for (std::vector<std::string>::iterator iter_tmp = need.begin(); iter_tmp!= need.end(); ++iter_tmp) std::cout<<*iter_tmp<<" "; need.clear(); std::cout<<std::endl; //finish processing the next } for (std::vector<std::string>::iterator iter= dirs.begin(); iter!=dirs.end(); iter++) std::cout<<*iter<<" "; std::cout<<std::endl; for (std::vector<std::string>::iterator iter= need.begin(); iter!=need.end(); iter++) std::cout<<*iter<<" "; std::cout<<std::endl; fp_out.close(); } best regards, Mark

    Read the article

  • How do I run gtk demos?

    - by Runner
    They are located under: share\gtk-2.0\demo But none of them contains a main function, how can I make the following textscroll.c actually work: /* Text Widget/Automatic scrolling * * This example demonstrates how to use the gravity of * GtkTextMarks to keep a text view scrolled to the bottom * while appending text. */ #include <gtk/gtk.h> #include "demo-common.h" /* Scroll to the end of the buffer. */ static gboolean scroll_to_end (GtkTextView *textview) { GtkTextBuffer *buffer; GtkTextIter iter; GtkTextMark *mark; char *spaces; static int count; buffer = gtk_text_view_get_buffer (textview); /* Get "end" mark. It's located at the end of buffer because * of right gravity */ mark = gtk_text_buffer_get_mark (buffer, "end"); gtk_text_buffer_get_iter_at_mark (buffer, &iter, mark); /* and insert some text at its position, the iter will be * revalidated after insertion to point to the end of inserted text */ spaces = g_strnfill (count++, ' '); gtk_text_buffer_insert (buffer, &iter, "\n", -1); gtk_text_buffer_insert (buffer, &iter, spaces, -1); gtk_text_buffer_insert (buffer, &iter, "Scroll to end scroll to end scroll " "to end scroll to end ", -1); g_free (spaces); /* Now scroll the end mark onscreen. */ gtk_text_view_scroll_mark_onscreen (textview, mark); /* Emulate typewriter behavior, shift to the left if we * are far enough to the right. */ if (count > 150) count = 0; return TRUE; } /* Scroll to the bottom of the buffer. */ static gboolean scroll_to_bottom (GtkTextView *textview) { GtkTextBuffer *buffer; GtkTextIter iter; GtkTextMark *mark; char *spaces; static int count; buffer = gtk_text_view_get_buffer (textview); /* Get end iterator */ gtk_text_buffer_get_end_iter (buffer, &iter); /* and insert some text at it, the iter will be revalidated * after insertion to point to the end of inserted text */ spaces = g_strnfill (count++, ' '); gtk_text_buffer_insert (buffer, &iter, "\n", -1); gtk_text_buffer_insert (buffer, &iter, spaces, -1); gtk_text_buffer_insert (buffer, &iter, "Scroll to bottom scroll to bottom scroll " "to bottom scroll to bottom", -1); g_free (spaces); /* Move the iterator to the beginning of line, so we don't scroll * in horizontal direction */ gtk_text_iter_set_line_offset (&iter, 0); /* and place the mark at iter. the mark will stay there after we * insert some text at the end because it has right gravity. */ mark = gtk_text_buffer_get_mark (buffer, "scroll"); gtk_text_buffer_move_mark (buffer, mark, &iter); /* Scroll the mark onscreen. */ gtk_text_view_scroll_mark_onscreen (textview, mark); /* Shift text back if we got enough to the right. */ if (count > 40) count = 0; return TRUE; } static guint setup_scroll (GtkTextView *textview, gboolean to_end) { GtkTextBuffer *buffer; GtkTextIter iter; buffer = gtk_text_view_get_buffer (textview); gtk_text_buffer_get_end_iter (buffer, &iter); if (to_end) { /* If we want to scroll to the end, including horizontal scrolling, * then we just create a mark with right gravity at the end of the * buffer. It will stay at the end unless explicitely moved with * gtk_text_buffer_move_mark. */ gtk_text_buffer_create_mark (buffer, "end", &iter, FALSE); /* Add scrolling timeout. */ return g_timeout_add (50, (GSourceFunc) scroll_to_end, textview); } else { /* If we want to scroll to the bottom, but not scroll horizontally, * then an end mark won't do the job. Just create a mark so we can * use it with gtk_text_view_scroll_mark_onscreen, we'll position it * explicitely when needed. Use left gravity so the mark stays where * we put it after inserting new text. */ gtk_text_buffer_create_mark (buffer, "scroll", &iter, TRUE); /* Add scrolling timeout. */ return g_timeout_add (100, (GSourceFunc) scroll_to_bottom, textview); } } static void remove_timeout (GtkWidget *window, gpointer timeout) { g_source_remove (GPOINTER_TO_UINT (timeout)); } static void create_text_view (GtkWidget *hbox, gboolean to_end) { GtkWidget *swindow; GtkWidget *textview; guint timeout; swindow = gtk_scrolled_window_new (NULL, NULL); gtk_box_pack_start (GTK_BOX (hbox), swindow, TRUE, TRUE, 0); textview = gtk_text_view_new (); gtk_container_add (GTK_CONTAINER (swindow), textview); timeout = setup_scroll (GTK_TEXT_VIEW (textview), to_end); /* Remove the timeout in destroy handler, so we don't try to * scroll destroyed widget. */ g_signal_connect (textview, "destroy", G_CALLBACK (remove_timeout), GUINT_TO_POINTER (timeout)); } GtkWidget * do_textscroll (GtkWidget *do_widget) { static GtkWidget *window = NULL; if (!window) { GtkWidget *hbox; window = gtk_window_new (GTK_WINDOW_TOPLEVEL); g_signal_connect (window, "destroy", G_CALLBACK (gtk_widget_destroyed), &window); gtk_window_set_default_size (GTK_WINDOW (window), 600, 400); hbox = gtk_hbox_new (TRUE, 6); gtk_container_add (GTK_CONTAINER (window), hbox); create_text_view (hbox, TRUE); create_text_view (hbox, FALSE); } if (!gtk_widget_get_visible (window)) gtk_widget_show_all (window); else gtk_widget_destroy (window); return window; }

    Read the article

  • getline won't let me type, c++

    - by Stijn
    I try to get the name of a game the users chooses and store it in a vector. I use getline so the user can use a space. When I try to type a new game to add it won't let me. It automaticly displays me games library. Please tell me what I do wrong. Problem is at if(action == "add") Here's my code: #include <iostream> #include <string> #include <vector> #include <algorithm> #include <ctime> #include <cstdlib> using namespace std; int main() { vector<string>::const_iterator myIterator; vector<string>::const_iterator iter; vector<string> games; games.push_back("Crysis 2"); games.push_back("GodOfWar 3"); games.push_back("FIFA 12"); cout <<"Welcome to your Games Library.\n"; cout <<"\nThese are your games:\n"; for (iter = games.begin(); iter != games.end(); ++iter) { cout <<*iter <<endl; } //the loop! string action; string newGame; cout <<"\n-Type 'exit' if you want to quit.\n-Type 'add' if you want to add a game.\n-Type 'delete' if you want to delete a game.\n-Type 'find' if you want to search a game.\n-Type 'game' if you don't know what game to play.\n-Type 'show' if you want to view your library."; while (action != "exit") { cout <<"\n\nWhat do you want to do: "; cin >> action; //problem is here if (action == "add") { cout <<"\nType the name of the game you want to add: "; getline (cin, newGame); games.push_back(newGame); for (iter = games.begin(); iter != games.end(); ++iter) { cout <<*iter <<endl; } continue; } else if (action == "show") { cout <<"\nThese are your games:\n"; for (iter = games.begin(); iter != games.end(); ++iter) { cout <<*iter <<endl; } } else if (action == "delete") { cout <<"Type the name of the game you want to delete: "; cin >> newGame; getline (cin, newGame); iter = find(games.begin(), games.end(), newGame); if(iter != games.end()) { games.erase(iter); cout <<"\nGame deleted!"; } else { cout<<"\nGame not found."; } continue; } else if (action == "find") { cout <<"Which game you want to look for in your library: "; cin >> newGame; getline (cin, newGame); iter = find(games.begin(), games.end(), newGame); if (iter != games.end()) { cout << "Game found.\n"; } else { cout << "Game not found.\n"; } continue; } else if (action == "game") { srand(static_cast<unsigned int>(time(0))); random_shuffle(games.begin(), games.end()); cout << "\nWhy don't you play " << games[0]; continue; } else if (action == "quit") { cout <<"\nRemember to have fun while gaming!!\n"; break; } else { cout <<"\nCommand not found"; } } return 0; }

    Read the article

  • Making a python iterator go backwards?

    - by uberjumper
    Is there anyway to make a python list iterator to go backwards? Basically i have this class IterTest(object): def __init__(self, data): self.data = data self.__iter = None def all(self): self.__iter = iter(self.data) for each in self.__iter: mtd = getattr(self, type(each).__name__) mtd(each) def str(self, item): print item next = self.__iter.next() while isinstance(next, int): print next next = self.__iter.next() def int(self, item): print "Crap i skipped C" if __name__ == '__main__': test = IterTest(['a', 1, 2,3,'c', 17]) test.all() Running this code results in the output: a 1 2 3 Crap i skipped C I know why it gives me the output, however is there a way i can step backwards in the str() method, by one step?

    Read the article

  • accessing values in a Map container, whose values were passed on as a stream

    - by wilson88
    I am trying to get access to the object values of the objects that were sent as a stream from one class to ano ther.Aparently I can view the objects via their keys but am not so sure how to get to the values.ie Bid- values trdId,qty, price. If possible you can demostrate how I can make comparison for the prices in the containers buyers and sellers for the prices. code is as below: void Auctioneer::printTable(map bidtable) { map<int, Bid*>::const_iterator iter; cout << "\t\tBidID | TradID | Type | Qty | Price \n\n"; for(iter=bidtable.begin(); iter != bidtable.end(); iter++)//{ cout << iter->second->toString() << endl<<"\n"; //------------------------------------------------------------------------- // Creating another map for the sellers. cout<<"These are the Sellers bids\n\n"; map<int, Bid*> sellers(bidtable); sellers.erase(10);sellers.erase(11);sellers.erase(12);sellers.erase(13);sellers.erase(14); sellers.erase(15);sellers.erase(16); sellers.erase(17);sellers.erase(18);sellers.erase(19); for(iter=sellers.begin(); iter != sellers.end(); iter++) cout << iter->second->toString() << endl<<"\n"; //-------------------------------------------------------------------------- // Creating another map for the sellers. cout<<"These are the Buyers bids\n\n"; map<int, Bid*> buyers(bidtable); buyers.erase(0);buyers.erase(1);buyers.erase(2);buyers.erase(3);buyers.erase(4);buyers.erase(5); buyers.erase(6);buyers.erase(7); buyers.erase(8);buyers.erase(9); for(iter=buyers.begin(); iter != buyers.end(); iter++) //sellers.erase(10); cout << iter->second->toString() << endl<<"\n";

    Read the article

  • Chunking a List - .NET vs Python

    - by Abhijeet Patel
    Chunking a List As I mentioned last time, I'm knee deep in python these days. I come from a statically typed background so it's definitely a mental adjustment. List comprehensions is BIG in Python and having worked with a few of them I can see why. Let's say we need to chunk a list into sublists of a specified size. Here is how we'd do it in C#  static class Extensions   {       public static IEnumerable<List<T>> Chunk<T>(this List<T> l, int chunkSize)       {           if (chunkSize <0)           {               throw new ArgumentException("chunkSize cannot be negative", "chunkSize");           }           for (int i = 0; i < l.Count; i += chunkSize)           {               yield return new List<T>(l.Skip(i).Take(chunkSize));           }       }    }    static void Main(string[] args)  {           var l = new List<string> { "a", "b", "c", "d", "e", "f","g" };             foreach (var list in l.Chunk(7))           {               string str = list.Aggregate((s1, s2) => s1 + "," + s2);               Console.WriteLine(str);           }   }   A little wordy but still pretty concise thanks to LINQ.We skip the iteration number plus chunkSize elements and yield out a new List of chunkSize elements on each iteration. The python implementation is a bit more terse. def chunkIterable(iter, chunkSize):      '''Chunks an iterable         object into a list of the specified chunkSize     '''        assert hasattr(iter, "__iter__"), "iter is not an iterable"      for i in xrange(0, len(iter), chunkSize):          yield iter[i:i + chunkSize]    if __name__ == '__main__':      l = ['a', 'b', 'c', 'd', 'e', 'f']      generator = chunkIterable(l,2)      try:          while(1):              print generator.next()      except StopIteration:          pass   xrange generates elements in the specified range taking in a seed and returning a generator. which can be used in a for loop(much like using a C# iterator in a foreach loop) Since chunkIterable has a yield statement, it turns this method into a generator as well. iter[i:i + chunkSize] essentially slices the list based on the current iteration index and chunksize and creates a new list that we yield out to the caller one at a time. A generator much like an iterator is a state machine and each subsequent call to it remembers the state at which the last call left off and resumes execution from that point. The caveat to keep in mind is that since variables are not explicitly typed we need to ensure that the object passed in is iterable using hasattr(iter, "__iter__").This way we can perform chunking on any object which is an "iterable", very similar to accepting an IEnumerable in the .NET land

    Read the article

  • how to show all method and data when the object not has "__iter__" function in python..

    - by zjm1126
    i find a way : (1):the dir(object) is : a="['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_errors', '_fields', '_prefix', '_unbound_fields', 'confirm', 'data', 'email', 'errors', 'password', 'populate_obj', 'process', 'username', 'validate']" (2): b=eval(a) (3)and it became a list of all method : ['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_errors', '_fields', '_prefix', '_unbound_fields', 'confirm', 'data', 'email', 'errors', 'password', 'populate_obj', 'process', 'username', 'validate'] (3)then show the object's method,and all code is : s='' a=eval(str(dir(object))) for i in a: s+=str(i)+':'+str(object[i]) print s but it show error : KeyError: '__class__' so how to make my code running . thanks

    Read the article

  • How can I skip the current item and the next in a Python loop?

    - by uberjumper
    This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer. Is there a simple way to do something like this? lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice line.next().next() <etc> It's easy to do in C++; just increment the iterator an extra time. Is there an easy way to do that in Python? I would just like to point, out the main purpose of this question is not about "reading files and such" and skipping things. I was more looking for C++ iterator style iteration. Also the new title is kinda dumb, and i dont really think it reflects the nature of my question.

    Read the article

  • C++ like iterators in python?

    - by uberjumper
    This might be a really dumb question, however i've looked around online, etc. And have not seen a solid answer. What i was wondering, is there a simple way to do something like this? lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice line.next().next() <etc> Is there an easy way to do that in python?

    Read the article

  • Java - Iterator: "Syntax error, parameterized types are only available if source level is 5.0"

    - by Helpme
    Hi! I'm purposely targeting Java OS 1.4.2 I'm trying to use an iterator combined with apache's POI to read an excel spreadsheet. The code runs perfectly in java 1.5, but in the 1.4.2 version I get the error listed in the question subject. the code is: Iterator myIter = null; it breaks on that line of code, which is clearly at the beginning of the application. I dont understand what needs to be done to correct this issue. Please let me know if you have any insight!

    Read the article

  • C++ Using a class template argument as a template argument for another type

    - by toefel
    Hey Everyone, I'm having this problem while writing my own HashTable. It all works, but when I try to templatize the thing, it gave me errors. I recreated the problem as follows: THIS CODE WORKS: typedef double Item; class A { public: A() { v.push_back(pair<string, Item>("hey", 5.0)); } void iterate() { for(Iterator iter = v.begin(); iter != v.end(); ++iter) cout << iter->first << ", " << iter->second << endl; } private: vector<pair<string, double> > v; typedef vector< pair<string, double> >::iterator Iterator; }; THIS CODE DOES NOT: template<typename ValueType> class B { public: B(){} void iterate() { for(Iterator iter = v.begin(); iter != v.end(); ++iter) cout << iter->first << ", " << iter->second << endl; } private: vector<pair<string, ValueType> > v; typedef vector< pair<string, ValueType> >::iterator Iterator; }; the error messages: g++ -O0 -g3 -Wall -c -fmessage-length=0 -omain.o ..\main.cpp ..\main.cpp:50: error: type std::vector<std::pair<std::string, ValueType>, std::allocator<std::pair<std::string, ValueType> > >' is not derived from typeB' ..\main.cpp:50: error: ISO C++ forbids declaration of `iterator' with no type ..\main.cpp:50: error: expected `;' before "Iterator" ..\main.cpp: In member function `void B::iterate()': ..\main.cpp:44: error: `Iterator' was not declared in this scope ..\main.cpp:44: error: expected `;' before "iter" ..\main.cpp:44: error: `iter' was not declared in this scope Does anybody know why this is happening? Thanks!

    Read the article

  • Strange problem with vectors.

    - by Catalin Dumitru
    I have a really strange problem with stl vectors in which the wrong destructor is called for the right object when I call the erase method if that makes any sense. My code looks something like this: for(vector<Category>::iterator iter = this->children.begin(); iter != this->children.end(); iter++) { if((*iter).item == item) { this->children.erase(iter); return; } ------------------------- } It's just a simple function that finds the element in the vector which has some item to be searched, and removes said element from the vector. My problem is than when the erase function is called, and thus the object which the iterator is pointing at is being destroyed, the wrong destructor is being called. More specific the destructor of the last element in the vector is being called, and not of the actual object being removed. Thus the memory is being removed from the wrong object, which will still be an element in the vector, and the actual object which is removed from the vector, still has all of it's memory intact. The costructor of the object looks like this: Category::Category(const Category &from) { this->name = from.name; for(vector<Category>::const_iterator iter = from.children.begin(); iter != from.children.end(); iter++) this->children.push_back((*iter)); this->item = new QTreeWidgetItem; } And the destructor Category::~Category() { this->children.clear(); if(this->item != NULL) { QTreeWidgetItem* parent = this->item->parent(); if(parent != NULL) parent->removeChild(this->item); delete this->item; } }

    Read the article

  • How do I refactor code into a subroutine but allow for early exit?

    - by deworde
    There's a really obvious refactoring opportunity in this (working) code. bool Translations::compatibleNICodes(const Rule& rule, const std::vector<std::string>& nicodes) { bool included = false; // Loop through the ni codes. for(std::vector<std::string> iter = nicodes.begin(); iter != nicodes.end(); ++iter) { // Match against the ni codes of the rule if(rule.get_ni1() == *iter) { // If there's a match, check if the rule is include or exclude const std::string flag = rule.get_op1(); // If include, code is included unless a later rule excludes it if(flag == "INCLUDE"){ included = true; } // If exclude, code is specifically excluded else if(flag == "EXCLUDE"){ return false; } } if(rule.get_ni2() == *iter) { const std::string flag = rule.get_op2(); if(flag == "INCLUDE"){ included = true; } else if(flag == "EXCLUDE"){ return false; } } if(rule.get_ni3() == *iter) { const std::string flag = rule.get_op3(); if(flag == "INCLUDE"){ included = true; } else if(flag == "EXCLUDE"){ return false; } } if(rule.get_ni4() == *iter) { const std::string flag = rule.get_op4(); if(flag == "INCLUDE"){ included = true; } else if(flag == "EXCLUDE"){ return false; } } if(rule.get_ni5() == *iter) { const std::string flag = rule.get_op5(); if(flag == "INCLUDE"){ included = true; } else if(flag == "EXCLUDE"){ return false; } } } return included; } The problem is that I can't get around the problem that I want to exit early if it's an exclude statement. Note that I can't change the structure of the Rule class. Any advice?

    Read the article

  • Displaying map stl

    - by BSchlinker
    Declared a map early on: map<char*,char*> rtable; // used to store routing information Now I'm attempting to display the contents of the map: void Routes::viewroutes(){ typedef map<char*, char*>::const_iterator iter; for (iter=rtable.begin(); iter != rtable.end(); ++iter) { cout << iter->second << " " << iter->first << endl; } } Receiving the error "expected primary-expression before '!=' token and for '-' token. Can't seem to understand the error I'm making here. Any ideas?

    Read the article

  • java reading numbers, interpreting as octal, want interpreted as string

    - by user331401
    hello, i am having an issue, where java is reading an array list from a YAML file of numbers, or strings, and it is interpreting the numbers as octal if it has a leading 0, and no 8-9 digit. is there a way to force java to read the yaml field as a string? code: ArrayList recordrarray = (ArrayList) sect.get("recordnum"); if (recordrarray != null) { recno = join (recordrarray, " "); } HAVE ALSO TRIED: Iterator<String> iter = recordrarray.iterator(); if (iter.hasNext()) recno = " " +String.valueOf(iter.next()); System.out.println(" this recnum:" + recno); while (iter.hasNext()){ recno += ""+String.valueOf(iter.next())); System.out.println(" done recnum:" + String.valueOf(iter.next())); } the input is such: 061456 changes to 25390 061506 changes to 25414 061559 - FINE it took a while to figure out what it was doing, and apparently this is a common issue for java, ideas? thanks

    Read the article

  • String.substring(index) has stoped my thread in debug mode.

    - by Arkaha
    Hello! I work with j2me polish 2.0.7, in eclipse 3.4.2, with wtk2.5.2_01. I create control which draws text: normal, bold, and italic. The code below is parsing raw text, and search for * and _ symbols, if found than add to draw vector the text and the drawer, and it's just stops after getting second time to the line 58: String test = new String(raw_text_buff.substring(iter)); it stops in raw_text_buff.substring(iter), ONLY in debug mode.. raw text is: bla bla bla *1000* bla bla Full code: private String raw_text = "bla bla bla *1000* bla bla"; Vector draw_items = null; private void prepareText() { char open_char = 0; int open_pos = 0; Object []param = null; StringBuffer sb = new StringBuffer(); String raw_text_buff = new String(raw_text); int iter = 0; boolean was_reset = false; while(true) { char c = raw_text_buff.charAt(iter); if(iter == raw_text_buff.length() || c == '*' || c == '_') { if(sb.length() > 0) { BmFont viewer = null; String str = sb.toString(); if(open_char == '*' && null != bm_strong) { viewer = bm_strong.getViewer(str); }else if(open_char == '_' && null != bm_italic) { viewer = bm_italic.getViewer(str); }else if(null != bm_normal) { viewer = bm_normal.getViewer(str); }else { } param = new Object[2]; param[0] = str; param[1] = viewer; if(null == draw_items) draw_items = new Vector(); draw_items.addElement(param); sb = new StringBuffer(); if(open_char == 0 && (c == '*' || c=='_')) open_char = c; else open_char = 0; String test = new String(raw_text_buff.substring(iter)); // stucks here. raw_text_buff = test; iter = 0; was_reset = true; }else { open_char = c; } if(iter == raw_text_buff.length()) break; }else { sb.append(c); } ++iter; } } What I'm doing wrong?

    Read the article

  • More elegant way to make a C++ member function change different member variables based on template p

    - by Eric Moyer
    Today, I wrote some code that needed to add elements to different container variables depending on the type of a template parameter. I solved it by writing a friend helper class specialized on its own template parameter which had a member variable of the original class. It saved me a few hundred lines of repeating myself without adding much complexity. However, it seemed kludgey. I would like to know if there is a better, more elegant way. The code below is a greatly simplified example illustrating the problem and my solution. It compiles in g++. #include <vector> #include <algorithm> #include <iostream> namespace myNS{ template<class Elt> struct Container{ std::vector<Elt> contents; template<class Iter> void set(Iter begin, Iter end){ contents.erase(contents.begin(), contents.end()); std::copy(begin, end, back_inserter(contents)); } }; struct User; namespace WkNS{ template<class Elt> struct Worker{ User& u; Worker(User& u):u(u){} template<class Iter> void set(Iter begin, Iter end); }; }; struct F{ int x; explicit F(int x):x(x){} }; struct G{ double x; explicit G(double x):x(x){} }; struct User{ Container<F> a; Container<G> b; template<class Elt> void doIt(Elt x, Elt y){ std::vector<Elt> v; v.push_back(x); v.push_back(y); Worker<Elt>(*this).set(v.begin(), v.end()); } }; namespace WkNS{ template<class Elt> template<class Iter> void Worker<Elt>::set(Iter begin, Iter end){ std::cout << "Set a." << std::endl; u.a.set(begin, end); } template<> template<class Iter> void Worker<G>::set(Iter begin, Iter end){ std::cout << "Set b." << std::endl; u.b.set(begin, end); } }; }; int main(){ using myNS::F; using myNS::G; myNS::User u; u.doIt(F(1),F(2)); u.doIt(G(3),G(4)); } User is the class I was writing. Worker is my helper class. I have it in its own namespace because I don't want it causing trouble outside myNS. Container is a container class whose definition I don't want to modify, but is used by User in its instance variables. doIt<F> should modify a. doIt<G> should modify b. F and G are open to limited modification if that would produce a more elegant solution. (As an example of one such modification, in the real application F's constructor takes a dummy parameter to make it look like G's constructor and save me from repeating myself.) In the real code, Worker is a friend of User and member variables are private. To make the example simpler to write, I made everything public. However, a solution that requires things to be public really doesn't answer my question. Given all these caveats, is there a better way to write User::doIt?

    Read the article

  • Mandelbrot set not displaying properly

    - by brainydexter
    I am trying to render mandelbrot set using glsl. I'm not sure why its not rendering the correct shape. Does the mandelbrot calculation require values to be within a range for the (x,y) [ or (real, imag) ] ? Here is a screenshot: I render a quad as follows: float w2 = 6; float h2 = 5; glBegin(GL_QUADS); glVertex3f(-w2, h2, 0.0); glVertex3f(-w2, -h2, 0.0); glVertex3f(w2, -h2, 0.0); glVertex3f(w2, h2, 0.0); glEnd(); My vertex shader: varying vec3 Position; void main(void) { Position = gl_Vertex.xyz; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } My fragment shader (where all the meat is): uniform float MAXITERATIONS; varying vec3 Position; void main (void) { float zoom = 1.0; float centerX = 0.0; float centerY = 0.0; float real = Position.x * zoom + centerX; float imag = Position.y * zoom + centerY; float r2 = 0.0; float iter; for(iter = 0.0; iter < MAXITERATIONS && r2 < 4.0; ++iter) { float tempreal = real; real = (tempreal * tempreal) + (imag * imag); imag = 2.0 * real * imag; r2 = (real * real) + (imag * imag); } vec3 color; if(r2 < 4.0) color = vec3(1.0); else color = vec3( iter / MAXITERATIONS ); gl_FragColor = vec4(color, 1.0); }

    Read the article

  • C++: Is there any good way to read/write without specifically stating character type in function nam

    - by Mark L.
    I'm having a problem getting a program to read from a file based on a template, for example: bool parse(basic_ifstream<T> &file) { T ch; locale loc = file.getloc(); basic_string<T> buf; file.unsetf(ios_base::skipws); if (file.is_open()) { while (file >> ch) { if(isalnum(ch, loc)) { buf += ch; } else if(!buf.empty()) { addWord(buf); buf.clear(); } } if(!buf.empty()) { addWord(buf); } return true; } return false; } This will work when I instantiate this class with <char>, but has problems when I use <wchar_t> (clearly). Outside of the class, I'm using: for (iter = mp.begin(); iter != mp.end(); ++iter ) { cout << iter->first << setw(textwidth - iter->first.length() + 1); cout << " " << iter->second << endl; } To write all of the information from this data struct (it's a map<basic_string<T>, int>), and as predicted, cout explodes if iter->first isn't a char array. I've looked online and the consensus is to use wcout, but unfortunately, since this program requires that the template can be changed at compile time (<char> - <wchar_t>) I'm not sure how I could get away with simply choosing cout or wcout. That is, unless there way a way to read/write wide characters without changing lots of code. If this explanation sounds awkwardly complicated, let me know and I'll address it as best I can.

    Read the article

  • java: List wrapper where get()/set() is allowed but add/remove is not

    - by Jason S
    I need to wrap a List<T> with some class that allows calls to set/get but does not allow add/remove calls, so that the list remains "stuck" at a fixed length. I think I have a thin wrapper class (below) that will work, but I'm not 100% positive. Did I miss anything obvious? import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; class RestrictedListWrapper<T> implements List<T> { static <T> T fail() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } static private class IteratorWrapper<T> implements ListIterator<T> { final private ListIterator<T> iter; private IteratorWrapper(ListIterator<T> iter) { this.iter = iter; } static public <T> RestrictedListWrapper.IteratorWrapper<T> wrap(ListIterator<T> target) { return new RestrictedListWrapper.IteratorWrapper<T>(target); } @Override public void add(T e) { fail(); } @Override public boolean hasNext() { return this.iter.hasNext(); } @Override public boolean hasPrevious() { return this.iter.hasPrevious(); } @Override public T next() { return this.iter.next(); } @Override public int nextIndex() { return this.iter.nextIndex(); } @Override public T previous() { return this.iter.previous(); } @Override public int previousIndex() { return this.iter.previousIndex(); } @Override public void remove() { fail(); } @Override public void set(T e) { this.iter.set(e); } } final private List<T> list; private RestrictedListWrapper(List<T> list) { this.list = list; } static public <T> RestrictedListWrapper<T> wrap(List<T> target) { return new RestrictedListWrapper<T>(target); } @Override public boolean add(T arg0) { return fail(); } @Override public void add(int index, T element) { fail(); } @Override public boolean addAll(Collection<? extends T> arg0) { return fail(); } @Override public boolean addAll(int arg0, Collection<? extends T> arg1) { return fail(); } /** * clear() allows setting all members of the list to null */ @Override public void clear() { ListIterator<T> it = this.list.listIterator(); while (it.hasNext()) { it.set(null); it.next(); } } @Override public boolean contains(Object o) { return this.list.contains(o); } @Override public boolean containsAll(Collection<?> c) { return this.list.containsAll(c); } @Override public T get(int index) { return this.list.get(index); } @Override public int indexOf(Object o) { return this.list.indexOf(o); } @Override public boolean isEmpty() { return false; } @Override public Iterator<T> iterator() { return listIterator(); } @Override public int lastIndexOf(Object o) { return this.list.lastIndexOf(o); } @Override public ListIterator<T> listIterator() { return IteratorWrapper.wrap(this.list.listIterator()); } @Override public ListIterator<T> listIterator(int index) { return IteratorWrapper.wrap(this.list.listIterator(index)); } @Override public boolean remove(Object o) { return fail(); } @Override public T remove(int index) { fail(); return fail(); } @Override public boolean removeAll(Collection<?> c) { return fail(); } @Override public boolean retainAll(Collection<?> c) { return fail(); } @Override public T set(int index, T element) { return this.list.set(index, element); } @Override public int size() { return this.list.size(); } @Override public List<T> subList(int fromIndex, int toIndex) { return new RestrictedListWrapper<T>(this.list.subList(fromIndex, toIndex)); } @Override public Object[] toArray() { return this.list.toArray(); } @Override public <T> T[] toArray(T[] a) { return this.list.toArray(a); } }

    Read the article

  • C++: Trouble with Pointers, loop variables, and structs

    - by Rosarch
    Consider the following example: #include <iostream> #include <sstream> #include <vector> #include <wchar.h> #include <stdlib.h> using namespace std; struct odp { int f; wchar_t* pstr; }; int main() { vector<odp> vec; ostringstream ss; wchar_t base[5]; wcscpy_s(base, L"1234"); for (int i = 0; i < 4; i++) { odp foo; foo.f = i; wchar_t loopStr[1]; foo.pstr = loopStr; // wchar_t* = wchar_t ? Why does this work? foo.pstr[0] = base[i]; vec.push_back(foo); } for (vector<odp>::iterator iter = vec.begin(); iter != vec.end(); iter++) { cout << "Vec contains: " << iter->f << ", " << *(iter->pstr) << endl; } } This produces: Vec contains: 0, 52 Vec contains: 1, 52 Vec contains: 2, 52 Vec contains: 3, 52 I would hope that each time, iter->f and iter->pstr would yield a different result. Unfortunately, iter->pstr is always the same. My suspicion is that each time through the loop, a new loopStr is created. Instead of copying it into the struct, I'm only copying a pointer. The location that the pointer writes to is getting overwritten. How can I avoid this? Is it possible to solve this problem without allocating memory on the heap?

    Read the article

  • Scale image to fit text boxes around borders

    - by nispio
    I have the following plot in Matlab: The image size may vary, and so may the length of the text boxes at the top and left. I dynamically determine the strings that go in these text boxes and then create them with: [M,N] = size(img); imagesc((1:N)-0.5,(1:M)-0.5, img > 0.5); axis image; grid on; colormap([1 1 1; 0.5 0.5 0.5]); set(gca,'XColor','k','YColor','k','TickDir','out') set(gca,'XTick',1:N,'XTickLabel',cell(1,N)) set(gca,'YTick',1:N,'YTickLabel',cell(1,N)) for iter = 1:M text(-0.5, iter-0.5, sprintf(strL, br{iter,:}), ... 'FontSize',16, ... 'HorizontalAlignment','right', ... 'VerticalAlignment','middle', ... 'Interpreter','latex' ); end for iter = 1:N text(iter-0.5, -0.5, {bc{:,iter}}, ... 'FontSize',16, ... 'HorizontalAlignment','center', ... 'VerticalAlignment','bottom', ... 'Interpreter','latex' ); end where br and bc are cell arrays containing the appropriate numbers for the labels. The problem is that most of the time, the text gets clipped by the edges of the figure. I am using this as a workaround: set(gca,'Position',[0.25 0.25 0.5 0.5]); As you can see, I am simply adding a larger border around the plot so that there is more room for the text. While this scaling works for one zoom level, if I maximize my plot window I get way too much empty space, and if I shrink my plot window, I get clipping again. Is there a more intelligent way to add these labels to use the minimum amount of space while making sure that the text does not get clipped?

    Read the article

  • Why is syslog so much slower than file IO?

    - by ceving
    I wrote a simple test program to measure the performance of the syslog function. This are the results of my test system: (Debian 6.0.2 with Linux 2.6.32-5-amd64) Test Case Calls Payload Duration Thoughput [] [MB] [s] [MB/s] -------------------- ---------- ---------- ---------- ---------- syslog 200000 10.00 7.81 1.28 syslog %s 200000 10.00 9.94 1.01 write /dev/null 200000 10.00 0.03 343.93 printf %s 200000 10.00 0.13 76.29 The test program did 200000 system calls writing 50 Bytes of data during each call. Why is Syslog more than ten times slower than file IO? This is the program I used to perform the test: #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <syslog.h> #include <unistd.h> const int iter = 200000; const char msg[] = "123456789 123456789 123456789 123456789 123456789"; struct timeval t0; struct timeval t1; void start () { gettimeofday (&t0, (void*)0); } void stop () { gettimeofday (&t1, (void*)0); } void report (char *action) { double dt = (double)t1.tv_sec - (double)t0.tv_sec + 1e-6 * ((double)t1.tv_usec - (double)t0.tv_usec); double mb = 1e-6 * sizeof (msg) * iter; if (action == NULL) printf ("Test Case Calls Payload Duration Thoughput \n" " [] [MB] [s] [MB/s] \n" "-------------------- ---------- ---------- ---------- ----------\n"); else { if (strlen (action) > 20) action[20] = 0; printf ("%-20s %-10d %-10.2f %-10.2f %-10.2f\n", action, iter, mb, dt, mb / dt); } } void test_syslog () { int i; openlog ("test_syslog", LOG_PID | LOG_NDELAY, LOG_LOCAL0); start (); for (i = 0; i < iter; i++) syslog (LOG_DEBUG, msg); stop (); closelog (); report ("syslog"); } void test_syslog_format () { int i; openlog ("test_syslog", LOG_PID | LOG_NDELAY, LOG_LOCAL0); start (); for (i = 0; i < iter; i++) syslog (LOG_DEBUG, "%s", msg); stop (); closelog (); report ("syslog %s"); } void test_write_devnull () { int i, fd; fd = open ("/dev/null", O_WRONLY); start (); for (i = 0; i < iter; i++) write (fd, msg, sizeof(msg)); stop (); close (fd); report ("write /dev/null"); } void test_printf () { int i; FILE *fp; fp = fopen ("/tmp/test_printf", "w"); start (); for (i = 0; i < iter; i++) fprintf (fp, "%s", msg); stop (); fclose (fp); report ("printf %s"); } int main (int argc, char **argv) { report (NULL); test_syslog (); test_syslog_format (); test_write_devnull (); test_printf (); }

    Read the article

  • STL vector reserve() and copy()

    - by natersoz
    Greetings, I am trying to perform a copy from one vector (vec1) to another vector (vec2) using the following 2 abbreviated lines of code (full test app follows): vec2.reserve( vec1.size() ); copy(vec1.begin(), vec1.end(), vec2.begin()); While the call to vec2 sets the capacity of vector vec2, the copying of data to vec2 seems to not fill in the values from vec1 to vec2. Replacing the copy() function with calls to push_back() works as expected. What am I missing here? Thanks for your help. vectest.cpp test program followed by resulting output follows. Compiler: gcc 3.4.4 on cygwin. Nat /** * vectest.cpp */ #include <iostream> #include <vector> using namespace std; int main() { vector<int> vec1; vector<int> vec2; vec1.push_back(1); vec1.push_back(2); vec1.push_back(3); vec1.push_back(4); vec1.push_back(5); vec1.push_back(6); vec1.push_back(7); vec2.reserve( vec1.size() ); copy(vec1.begin(), vec1.end(), vec2.begin()); cout << "vec1.size() = " << vec1.size() << endl; cout << "vec1.capacity() = " << vec1.capacity() << endl; cout << "vec1: "; for( vector<int>::const_iterator iter = vec1.begin(); iter < vec1.end(); ++iter ) { cout << *iter << " "; } cout << endl; cout << "vec2.size() = " << vec2.size() << endl; cout << "vec2.capacity() = " << vec2.capacity() << endl; cout << "vec2: "; for( vector<int>::const_iterator iter = vec2.begin(); iter < vec2.end(); ++iter ) { cout << *iter << endl; } cout << endl; } output: vec1.size() = 7 vec1.capacity() = 8 vec1: 1 2 3 4 5 6 7 vec2.size() = 0 vec2.capacity() = 7 vec2:

    Read the article

  • How can I use timer to stop another thread? [on hold]

    - by Haoda Fu
    How can we stop another thread based on a timer? I was trying to use timer to stop another thread. But I didn't got a success. To better illustrate my point and for your easy to understand the key issue. I made the following sample example. Your help is really appreciated using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Timers; namespace TestCodes { public static class Program { private static Thread nT = new Thread(PrintABC); private static System.Timers.Timer aTimer; public static void Main() { aTimer = new System.Timers.Timer(1000); aTimer.Elapsed += TimerCallback; aTimer.Interval = 1000; aTimer.Enabled = true; nT.Start(); Console.ReadLine(); } private static void TimerCallback(Object o, ElapsedEventArgs e) { nT.Join(); Console.WriteLine("Complete the PrintABC"); GC.Collect(); } private static void PrintABC() { for (int iter = 1; iter < 300; iter++) { Console.WriteLine(iter+"abc"); Console.ReadKey(); //Thread.Sleep(100); } } } }

    Read the article

1 2 3 4 5 6 7  | Next Page >