void Queue::remove(DLink<VariableWithTimeStamp> *elt) { elt->content.timeStamp = -1; elt->content.incdec = NOTHING_EVENT; erase(elt, false); }
void NBNodeCont::joinNodeClusters(NodeClusters clusters, NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc) { for (NodeClusters::iterator i = clusters.begin(); i != clusters.end(); ++i) { std::set<NBNode*> cluster = *i; assert(cluster.size() > 1); Position pos; bool setTL; std::string id; TrafficLightType type; analyzeCluster(cluster, id, pos, setTL, type); if (!insert(id, pos)) { // should not fail WRITE_WARNING("Could not join junctions " + id); continue; } NBNode* newNode = retrieve(id); if (setTL) { NBTrafficLightDefinition* tlDef = new NBOwnTLDef(id, newNode, 0, type); if (!tlc.insert(tlDef)) { // actually, nothing should fail here delete tlDef; throw ProcessError("Could not allocate tls '" + id + "'."); } } // collect edges std::set<NBEdge*> allEdges; for (std::set<NBNode*>::const_iterator j = cluster.begin(); j != cluster.end(); ++j) { const EdgeVector& edges = (*j)->getEdges(); allEdges.insert(edges.begin(), edges.end()); } // remap and remove edges which are completely within the new intersection for (std::set<NBEdge*>::iterator j = allEdges.begin(); j != allEdges.end();) { NBEdge* e = (*j); NBNode* from = e->getFromNode(); NBNode* to = e->getToNode(); if (cluster.count(from) > 0 && cluster.count(to) > 0) { for (std::set<NBEdge*>::iterator l = allEdges.begin(); l != allEdges.end(); ++l) { if (e != *l) { (*l)->replaceInConnections(e, e->getConnections()); } } ec.erase(dc, e); allEdges.erase(j++); // erase does not invalidate the other iterators } else { ++j; } } // remap edges which are incoming / outgoing for (std::set<NBEdge*>::iterator j = allEdges.begin(); j != allEdges.end(); ++j) { NBEdge* e = (*j); std::vector<NBEdge::Connection> conns = e->getConnections(); const bool outgoing = cluster.count(e->getFromNode()) > 0; NBNode* from = outgoing ? newNode : e->getFromNode(); NBNode* to = outgoing ? e->getToNode() : newNode; e->reinitNodes(from, to); // re-add connections which previously existed and may still valid. // connections to removed edges will be ignored for (std::vector<NBEdge::Connection>::iterator k = conns.begin(); k != conns.end(); ++k) { e->addLane2LaneConnection((*k).fromLane, (*k).toEdge, (*k).toLane, NBEdge::L2L_USER, false, (*k).mayDefinitelyPass); } } // remove original nodes registerJoinedCluster(cluster); for (std::set<NBNode*>::const_iterator j = cluster.begin(); j != cluster.end(); ++j) { erase(*j); } } }
CellLinkedList::ReverseIterator CellLinkedList::erase(CellLinkedList::ReverseIterator pos) { Iterator it = (++pos).base(); it = erase(it); return ReverseIterator(it); }
void activate_sleeper(Creature *cr) { int state=0; int choice=0; char havedead=0; do { erase(); set_color(COLOR_WHITE,COLOR_BLACK,0); printfunds(0,1,"Money: "); move(0,0); addstr("Taking Undercover Action: What will "); addstr(cr->name); addstr(" focus on?"); printcreatureinfo(cr); makedelimiter(8,0); set_color(COLOR_WHITE,COLOR_BLACK,state=='a'); move(10,1); addstr("A - Communication and Advocacy"); set_color(COLOR_WHITE,COLOR_BLACK,state=='b'); move(11,1); addstr("B - Espionage"); set_color(COLOR_WHITE,COLOR_BLACK,state=='d'); move(12,1); addstr("C - Join the Active LCS"); set_color(COLOR_WHITE,COLOR_BLACK,0); move(20,40); addstr("Enter - Confirm Selection"); switch(state) { case 'a': set_color(COLOR_WHITE,COLOR_BLACK,cr->activity.type==ACTIVITY_NONE); move(10,40); addstr("1 - Lay Low"); set_color(COLOR_WHITE,COLOR_BLACK,cr->activity.type==ACTIVITY_SLEEPER_LIBERAL); move(11,40); addstr("2 - Advocate Liberalism"); move(12,40); if(subordinatesleft(*cr)) { set_color(COLOR_WHITE,COLOR_BLACK,cr->activity.type==ACTIVITY_SLEEPER_RECRUIT); addstr("3 - Expand Sleeper Network"); } else { set_color(COLOR_BLACK,COLOR_BLACK,1); if(cr->flag & CREATUREFLAG_BRAINWASHED) addstr("3 - [Enlightened Can't Recruit]"); else addstr("3 - [Need More Juice to Recruit]"); } break; case 'b': set_color(COLOR_WHITE,COLOR_BLACK,cr->activity.type==ACTIVITY_SLEEPER_SPY); move(10,40); addstr("1 - Uncover Secrets"); set_color(COLOR_WHITE,COLOR_BLACK,cr->activity.type==ACTIVITY_SLEEPER_EMBEZZLE); move(11,40); addstr("2 - Embezzle Funds"); set_color(COLOR_WHITE,COLOR_BLACK,cr->activity.type==ACTIVITY_SLEEPER_STEAL); move(12,40); addstr("3 - Steal Equipment"); break; } set_color(COLOR_WHITE,COLOR_BLACK,0); switch(cr->activity.type) { case ACTIVITY_NONE: move(22,3); addstr(cr->name); addstr(" will stay out of trouble."); break; case ACTIVITY_SLEEPER_LIBERAL: move(22,3); addstr(cr->name); addstr(" will build support for Liberal causes."); break; case ACTIVITY_SLEEPER_RECRUIT: if(subordinatesleft(*cr)) { move(22,3); addstr(cr->name); addstr(" will try to recruit additional sleeper agents."); } break; case ACTIVITY_SLEEPER_SPY: move(22,3); addstr(cr->name); addstr(" will snoop around for secrets and enemy plans."); break; case ACTIVITY_SLEEPER_EMBEZZLE: move(22,3); addstr(cr->name); addstr(" will embezzle money for the LCS."); break; case ACTIVITY_SLEEPER_STEAL: move(22,3); addstr(cr->name); addstr(" will steal equipment and send it to the Shelter."); break; } refresh(); int c=getch(); translategetch(c); if(c>='a'&&c<='z'){state=c;} if((c>='a'&&c<='z') || (c>='1'&&c<='9')) { choice=c; switch(state) { case 'a': switch(choice) { default: case '1':cr->activity.type=ACTIVITY_NONE;break; case '2':cr->activity.type=ACTIVITY_SLEEPER_LIBERAL;break; case '3': if(subordinatesleft(*cr)) cr->activity.type=ACTIVITY_SLEEPER_RECRUIT;break; } break; case 'b': switch(choice) { default: case '1':cr->activity.type=ACTIVITY_SLEEPER_SPY;break; case '2':cr->activity.type=ACTIVITY_SLEEPER_EMBEZZLE;break; case '3':cr->activity.type=ACTIVITY_SLEEPER_STEAL;break; } break; } } if(state=='c') { activityst oact=cr->activity; cr->activity.type=ACTIVITY_SLEEPER_JOINLCS; } if(c=='x') { cr->activity.type=ACTIVITY_NONE; break; } if(c==10||c==ESC) { break; } }while(1); }
int main(int argc, char **argv) { int i, start, end, row, diff, flag, direction; const unsigned seed = (unsigned)time((time_t *)0); #ifdef XCURSES Xinitscr(argc, argv); #else initscr(); #endif nodelay(stdscr, TRUE); noecho(); if (has_colors()) start_color(); for (i = 0; i < 8; i++) init_pair((short)i, color_table[i], COLOR_BLACK); srand(seed); flag = 0; while (getch() == ERR) /* loop until a key is hit */ { do { start = rand() % (COLS - 3); end = rand() % (COLS - 3); start = (start < 2) ? 2 : start; end = (end < 2) ? 2 : end; direction = (start > end) ? -1 : 1; diff = abs(start - end); } while (diff < 2 || diff >= LINES - 2); attrset(A_NORMAL); for (row = 0; row < diff; row++) { mvaddstr(LINES - row, row * direction + start, (direction < 0) ? "\\" : "/"); if (flag++) { myrefresh(); erase(); flag = 0; } } if (flag++) { myrefresh(); flag = 0; } explode(LINES - row, diff * direction + start); erase(); myrefresh(); } endwin(); return 0; }
/** This stops ncurses on a sweet, gentle way. */ void engine_exit() { erase(); refresh(); endwin(); }
int PX4IO_Uploader::upload(const char *filenames[]) { int ret; const char *filename = NULL; size_t fw_size; #ifndef PX4IO_SERIAL_DEVICE #error Must define PX4IO_SERIAL_DEVICE in board configuration to support firmware upload #endif /* allow an early abort and look for file first */ for (unsigned i = 0; filenames[i] != nullptr; i++) { _fw_fd = open(filenames[i], O_RDONLY); if (_fw_fd < 0) { log("failed to open %s", filenames[i]); continue; } log("using firmware from %s", filenames[i]); filename = filenames[i]; break; } if (filename == NULL) { log("no firmware found"); close(_io_fd); _io_fd = -1; return -ENOENT; } _io_fd = open(PX4IO_SERIAL_DEVICE, O_RDWR); if (_io_fd < 0) { log("could not open interface"); return -errno; } /* save initial uart configuration to reset after the update */ struct termios t_original; tcgetattr(_io_fd, &t_original); /* adjust line speed to match bootloader */ struct termios t; tcgetattr(_io_fd, &t); cfsetspeed(&t, 115200); tcsetattr(_io_fd, TCSANOW, &t); /* look for the bootloader for 150 ms */ for (int i = 0; i < 15; i++) { ret = sync(); if (ret == OK) { break; } else { usleep(10000); } } if (ret != OK) { /* this is immediately fatal */ log("bootloader not responding"); tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return -EIO; } struct stat st; if (stat(filename, &st) != 0) { log("Failed to stat %s - %d\n", filename, (int)errno); tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return -errno; } fw_size = st.st_size; if (_fw_fd == -1) { tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return -ENOENT; } /* do the usual program thing - allow for failure */ for (unsigned retries = 0; retries < 1; retries++) { if (retries > 0) { log("retrying update..."); ret = sync(); if (ret != OK) { /* this is immediately fatal */ log("bootloader not responding"); tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return -EIO; } } ret = get_info(INFO_BL_REV, bl_rev); if (ret == OK) { if (bl_rev <= BL_REV) { log("found bootloader revision: %d", bl_rev); } else { log("found unsupported bootloader revision %d, exiting", bl_rev); tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return OK; } } ret = erase(); if (ret != OK) { log("erase failed"); continue; } ret = program(fw_size); if (ret != OK) { log("program failed"); continue; } if (bl_rev <= 2) ret = verify_rev2(fw_size); else if(bl_rev == 3) { ret = verify_rev3(fw_size); } if (ret != OK) { log("verify failed"); continue; } ret = reboot(); if (ret != OK) { log("reboot failed"); tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return ret; } log("update complete"); ret = OK; break; } /* reset uart to previous/default baudrate */ tcsetattr(_io_fd, TCSANOW, &t_original); close(_fw_fd); close(_io_fd); _io_fd = -1; // sleep for enough time for the IO chip to boot. This makes // forceupdate more reliably startup IO again after update up_udelay(100*1000); return ret; }
static void slk_test(void) /* exercise the soft keys */ { int c, fmt = 1; char buf[9]; c = CTRL('l'); do { switch(c) { case CTRL('l'): erase(); attron(A_BOLD); mvaddstr(0, 20, "Soft Key Exerciser"); attroff(A_BOLD); move(2, 0); P("Available commands are:"); P(""); P("^L -- refresh screen"); P("a -- activate or restore soft keys"); P("d -- disable soft keys"); P("c -- set centered format for labels"); P("l -- set left-justified format for labels"); P("r -- set right-justified format for labels"); P("[12345678] -- set label; labels are numbered 1 through 8"); P("e -- erase stdscr (should not erase labels)"); P("s -- test scrolling of shortened screen"); P("x, q -- return to main menu"); P(""); P("Note: if activating the soft keys causes your terminal to"); P("scroll up one line, your terminal auto-scrolls when anything"); P("is written to the last screen position. The ncurses code"); P("does not yet handle this gracefully."); refresh(); /* fall through */ case 'a': slk_restore(); break; case 'e': wclear(stdscr); break; case 's': move(20, 0); while ((c = getch()) != 'Q') addch(c); break; case 'd': slk_clear(); break; case 'l': fmt = 0; break; case 'c': fmt = 1; break; case 'r': fmt = 2; break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': (void) mvaddstr(20, 0, "Please enter the label value: "); wgetnstr(stdscr, buf, 8); slk_set((c - '0'), buf, fmt); slk_refresh(); break; case 'x': case 'q': goto done; default: beep(); } } while ((c = getch()) != EOF); done: erase(); endwin(); }
vector<vector<int>> getFactors(int n) { auto ans = f(n); ans.erase(ans.begin()); return ans; }
static void color_edit(void) /* display the color test pattern, without trying to edit colors */ { int i, c, value = 0, current = 0, field = 0, usebase = 0; refresh(); for (i = 0; i < COLORS; i++) init_pair(i, COLOR_WHITE, i); do { short red, green, blue; attron(A_BOLD); mvaddstr(0, 20, "Color RGB Value Editing"); attroff(A_BOLD); for (i = 0; i < COLORS; i++) { mvprintw(2 + i, 0, "%c %-8s:", (i == current ? '>' : ' '), (i < sizeof(colors)/sizeof(colors[0]) ? colors[i] : "")); attrset(COLOR_PAIR(i)); addstr(" "); attrset(A_NORMAL); /* * Note: this refresh should *not* be necessary! It works around * a bug in attribute handling that apparently causes the A_NORMAL * attribute sets to interfere with the actual emission of the * color setting somehow. This needs to be fixed. */ refresh(); color_content(i, &red, &green, &blue); addstr(" R = "); if (current == i && field == 0) attron(A_STANDOUT); printw("%04d", red); if (current == i && field == 0) attrset(A_NORMAL); addstr(", G = "); if (current == i && field == 1) attron(A_STANDOUT); printw("%04d", green); if (current == i && field == 1) attrset(A_NORMAL); addstr(", B = "); if (current == i && field == 2) attron(A_STANDOUT); printw("%04d", blue); if (current == i && field == 2) attrset(A_NORMAL); attrset(A_NORMAL); addstr(")"); } mvaddstr(COLORS + 3, 0, "Use up/down to select a color, left/right to change fields."); mvaddstr(COLORS + 4, 0, "Modify field by typing nnn=, nnn-, or nnn+. ? for help."); move(2 + current, 0); switch (c = getch()) { case KEY_UP: current = (current == 0 ? (COLORS - 1) : current - 1); value = 0; break; case KEY_DOWN: current = (current == (COLORS - 1) ? 0 : current + 1); value = 0; break; case KEY_RIGHT: field = (field == 2 ? 0 : field + 1); value = 0; break; case KEY_LEFT: field = (field == 0 ? 2 : field - 1); value = 0; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': do { value = value * 10 + (c - '0'); c = getch(); } while (isdigit(c)); if (c != '+' && c != '-' && c != '=') beep(); else ungetch(c); break; case '+': usebase = 1; goto changeit; case '-': value = -value; usebase = 1; goto changeit; case '=': usebase = 0; changeit: color_content(current, &red, &green, &blue); if (field == 0) red = red * usebase + value; else if (field == 1) green = green * usebase + value; else if (field == 2) blue = blue * usebase + value; init_color(current, red, green, blue); break; case '?': erase(); P(" RGB Value Editing Help"); P(""); P("You are in the RGB value editor. Use the arrow keys to select one of"); P("the fields in one of the RGB triples of the current colors; the one"); P("currently selected will be reverse-video highlighted."); P(""); P("To change a field, enter the digits of the new value; they won't be"); P("echoed. Finish by typing `='; the change will take effect instantly."); P("To increment or decrement a value, use the same procedure, but finish"); P("with a `+' or `-'."); P(""); P("To quit, do `x' or 'q'"); move(LINES - 1, 0); addstr("Press any key to continue... "); (void) getch(); erase(); break; case 'x': case 'q': break; default: beep(); break; } } while (c != 'x' && c != 'q'); erase(); endwin(); }
static void getch_test(void) /* test the keypad feature */ { char buf[BUFSIZ]; unsigned int c; int incount = 0, firsttime = 0; bool blocking = TRUE; refresh(); (void) printw("Delay in 10ths of a second (<CR> for blocking input)? "); echo(); getstr(buf); noecho(); if (isdigit(buf[0])) { timeout(atoi(buf) * 100); blocking = FALSE; } c = '?'; for (;;) { if (firsttime++) { printw("Key pressed: %04o ", c); if (c >= KEY_MIN) { (void) addstr(keyname(c)); addch('\n'); } else if (c > 0x80) { if (isprint(c & ~0x80)) (void) printw("M-%c", c); else (void) printw("M-%s", unctrl(c)); addstr(" (high-half character)\n"); } else { if (isprint(c)) (void) printw("%c (ASCII printable character)\n", c); else (void) printw("%s (ASCII control character)\n", unctrl(c)); } } if (c == 'x' || c == 'q') break; if (c == '?') addstr("Type any key to see its keypad value, `q' to quit, `?' for help.\n"); while ((c = getch()) == ERR) if (!blocking) (void) printw("%05d: input timed out\n", incount++); } timeout(-1); erase(); endwin(); }
void TimeSigMap::del(int tick) { erase(tick); normalize(); }
bool OfferStream::step () { // Modifying the order or logic of these // operations causes a protocol breaking change. for(;;) { // BookTip::step deletes the current offer from the view before // advancing to the next (unless the ledger entry is missing). if (! m_tip.step()) return false; SLE::pointer const& entry (m_tip.entry()); // Remove if missing if (! entry) { erase (view()); erase (view_cancel()); continue; } // Remove if expired if (entry->isFieldPresent (sfExpiration) && entry->getFieldU32 (sfExpiration) <= m_when) { view_cancel().offerDelete (entry->getIndex()); if (m_journal.trace) m_journal.trace << "Removing expired offer " << entry->getIndex(); continue; } m_offer = Offer (entry, m_tip.quality()); Amounts const amount (m_offer.amount()); // Remove if either amount is zero if (amount.empty()) { view_cancel().offerDelete (entry->getIndex()); if (m_journal.warning) m_journal.warning << "Removing bad offer " << entry->getIndex(); m_offer = Offer{}; continue; } // Calculate owner funds // NIKB NOTE The calling code also checks the funds, how expensive is // looking up the funds twice? Amount const owner_funds (view().accountFunds ( m_offer.account(), m_offer.amount().out, fhZERO_IF_FROZEN)); // Check for unfunded offer if (owner_funds <= zero) { // If the owner's balance in the pristine view is the same, // we haven't modified the balance and therefore the // offer is "found unfunded" versus "became unfunded" if (view_cancel().accountFunds (m_offer.account(), m_offer.amount().out, fhZERO_IF_FROZEN) == owner_funds) { view_cancel().offerDelete (entry->getIndex()); if (m_journal.trace) m_journal.trace << "Removing unfunded offer " << entry->getIndex(); } else { if (m_journal.trace) m_journal.trace << "Removing became unfunded offer " << entry->getIndex(); } m_offer = Offer{}; continue; } break; } return true; }
/* function implementations */ int main(int argc, char **argv) { int ch = 0, n, eating, trick = 0; int erow, ecol; /* eat position */ int level, tricks, moves, score; WINDOW *wstat, *wpos, *wepos; /* Status and positions windows */ List *worm = NULL, *current; /* THe LiST */ int auto_mode = 0; /* Play without user interaction */ level = tricks = moves = score = 0; srand( time(NULL) ); /* check the flag for auto-mode */ if( argc == 2 && argv[1][0] == '-' && argv[1][1] == 'a' ) auto_mode = 1; initscr(); /* start of session */ curs_set(0); /* hide the cursor */ keypad(stdscr, TRUE); /* enable the function keys */ cbreak(); noecho(); nodelay(stdscr, TRUE); /* unlock getch(3) */ /* Check the terminal size */ if( LINES < MINROW || COLS < MINCOL ) { endwin(); printf("This game require a terminal size of %dx%d pixel.\n", MINROW, MINCOL); printf("Your terminal size is: %dx%d\n", LINES, COLS); return -1; } /* Create the windows */ wstat = subwin(stdscr, 3, COLS - COLS / 3, 2, COLS / 6); /* status */ wpos = subwin(stdscr, 3, 9, 2, 3); /* worm position */ wepos = subwin(stdscr, 3, 9, 2, COLS - 9 - 3); /* eat position */ /* Add the first position */ newnode(&worm, 1 + rand() % (COLS - 2), 6 + rand() % (LINES - 7)); /* start point for the eat */ erow = 6 + rand() % (LINES - 7); ecol = 1 + rand() % (COLS - 2); /* choose a random route */ route = 1 + rand() % 4; wormshow(worm, WORM, HEAD); /* put the first WORM */ mvprintw(erow, ecol, "%d", n = 1); /* put the first eat */ /* main loop */ while( (auto_mode ? getch() : (ch = getch())) != 'q' ) { /* * Auto-mode play * * NOTE: the worm can to bite himself losing the * game which will be auto-restarted again. * */ if( auto_mode ) { ch = 0; /* don't touch the user moves */ /* choose the route, if needed */ if( worm->x < erow ) { if( route != R_DOWN ) ch = 'j'; } else if( worm->x > erow ) { if( route != R_UP ) ch = 'k'; } else if( worm->y < ecol ) { if( route != R_RIGHT ) ch = 'l'; } else { if( route != R_LEFT ) ch = 'h'; } } switch(ch) { case 'h': case KEY_LEFT: route = R_LEFT; ++moves; break; case 'j': case KEY_DOWN: route = R_DOWN; ++moves; break; case 'k': case KEY_UP: route = R_UP; ++moves; break; case 'l': case KEY_RIGHT: route = R_RIGHT; ++moves; break; case 'p': case ' ': /* space bar */ /* Pause */ nodelay(stdscr, FALSE); /* lock the getch() */ mvprintw(LINES / 2, COLS / 2, "Pause!"); while( (ch = getch()) ) { if( ch == 'p' || ch == ' ' ) break; clear(); mvprintw(LINES / 2, COLS / 2, "Pause!"); } nodelay(stdscr, TRUE); /* unlock the getch() */ clear(); break; case 't': /* Tricks */ if( trick ) { nodelay(stdscr, TRUE); trick = 0; } else { nodelay(stdscr, FALSE); trick = 1; ++tricks; } break; case KEY_RESIZE: /* Terminal resize */ nodelay(stdscr, FALSE); /* Check the terminal size */ while( LINES < MINROW || COLS < MINCOL ) { clear(); mvprintw(LINES / 2, COLS / 2 - 12, "Terminal size too small!"); mvprintw(LINES / 2 + 1, COLS / 2 - 16, "Please, enlarge it and press a key"); getch(); } nodelay(stdscr, TRUE); clear(); break; } /* eof switch() */ moveworm(&worm, route); /* move the worm */ /* * Check if the "new" position is already * busy or it's out of the window. */ if( isout(worm) || isbite(worm) || (auto_mode && level >= LEVMAX) ) { if( level >= LEVMAX ) mvprintw(LINES / 2, COLS / 2 - 5, "Too fast!"); else mvprintw(LINES / 2, COLS / 2 - 5, "You lose!"); mvprintw(LINES / 2 + 1, COLS / 2 - 10, "Your scores are: %.3d", score); if( auto_mode ) { mvprintw(LINES / 2 + 3, COLS / 2 - 6, "Restarting.."); refresh(); /* reset the game */ killworm(&worm); newnode(&worm, 1 + rand() % (COLS - 2), 6 + rand() % (LINES - 7)); erow = 6 + rand() % (LINES - 7); ecol = 1 + rand() % (COLS - 2); score = level = eating = tricks = moves = 0; n = 1; sleep(2); /* leave that the user tastes the messsage :-) */ continue; } else { mvprintw(LINES / 2 + 2, COLS / 2 - 10, "Press a key to exit.."); nodelay(stdscr, FALSE); getch(); /* wait for input */ break; } } eating = n; /* needed for the wormshow() call */ /* If it's eating */ while( iseat(worm, erow, ecol) ) { /* Add a node on the top of worm (new head) */ current = worm; while( current->next != NULL ) current = current->next; newnode(¤t->next, worm->y, worm->x); /* Change the eat's position */ erow = 6 + rand() % (LINES - 7); ecol = 1 + rand() % (COLS - 2); ++n; /* Change the eat's number */ score += level + 1; /* increment the points */ /* Increase the level */ if( !(n % LEVEAT) ) { ++level; } } erase(); /* clear the screen */ box(stdscr, ACS_VLINE, ACS_HLINE); /* create the borders */ mvprintw(erow, ecol, "%d", n); /* draw the eat */ /* Show the status window (and its elemets) */ mvwprintw(stdscr, 1, COLS / 2 - 37 / 2, /* Copy */ "The Hermit worm - (C) 2006 Claudio M."); /* left */ box(wstat, ACS_VLINE, ACS_HLINE); /* status box */ mvwhline(stdscr, 5, 1, ACS_HLINE, COLS - 2); /* new top limit */ /* Show the worm position */ box(wepos, ACS_VLINE, ACS_HLINE); /* status box */ mvwprintw(stdscr, 1, 3, "Worm Curs"); mvwprintw(wepos, 1, 2, "%.2dx%.2d", erow, ecol); /* Show the eat position */ box(wpos, ACS_VLINE, ACS_HLINE); /* status box */ mvwprintw(stdscr, 1, COLS - 12, "Eat Curs"); mvwprintw(wpos, 1, 2, "%.2dx%.2d", worm->x, worm->y); /* Show the informations */ mvwprintw(wstat, 1, 3, "TS:%.2dx%.2d | " /* Terminal size */ "SL:%.2d | " /* Speed level */ "EM:%.2d | " /* Eats missing */ "UM:%.3d | " /* User moves */ "UT:%.2d | " /* User tricks */ "Ss:%.3d", /* Scores */ LINES, COLS, level + 1, LEVEAT - (n % LEVEAT), moves, tricks, score); /* * Show the whole "new" worm * NOTE: this statement is not optimized - trash statement :-) */ if( iseat(worm, erow + 1, ecol) || iseat(worm, erow - 1, ecol) || iseat(worm, erow, ecol + 1) || iseat(worm, erow, ecol - 1) ) { wormshow(worm, WORM, EATH); } else wormshow(worm, WORM, HEAD); usleep( 100000 - level * 10000 ); } endwin(); /* end of session */ puts("\nEnd of game."); return 0; } /* E0F main */
bool Foam::HashTable<T, Key, Hash>::erase(const Key& key) { return erase(find(key)); }
void mode_base(void) { short buyer=0; char forcewait,canseethings; int nonsighttime=0; int oldforcemonth=month; int length=0; int l = 0; do { forcewait=1; canseethings=0; cantseereason=CANTSEE_OTHER; if(!disbanding) { for(int p=0;p<(int)pool.size();p++) { if(pool[p]->alive&& pool[p]->align==1&& pool[p]->dating==0&& pool[p]->hiding==0&& !(pool[p]->flag & CREATUREFLAG_SLEEPER)) { if(!location[pool[p]->location]->part_of_justice_system()) { canseethings=1; if(pool[p]->clinic==0){forcewait=0;break;} } } else { if(pool[p]->dating==1 && cantseereason>CANTSEE_DATING) cantseereason=CANTSEE_DATING; else if(pool[p]->hiding!=0 && cantseereason>CANTSEE_HIDING) cantseereason=CANTSEE_HIDING; } } } else { cantseereason=CANTSEE_DISBANDING; } if(disbanding) { disbanding = show_disbanding_screen(oldforcemonth); } if(!forcewait) { if(nonsighttime>=365*4) { erase(); char str[100]; if(nonsighttime>=365*16) { strcpy(str,"How long since you've heard these sounds... times have changed."); } else if(nonsighttime>=365*8) { strcpy(str,"It has been a long time. A lot must have changed..."); } else { strcpy(str,"It sure has been a while. Things might have changed a bit."); } set_color(COLOR_WHITE,COLOR_BLACK,1); move(12,39-((strlen(str)-1)>>1)); addstr(str, gamelog); gamelog.nextMessage(); //Write out buffer to prepare for the next message. refresh(); getch(); } nonsighttime=0; } int partysize=0; int partydead=0; if(activesquad!=NULL) { for(int p=0;p<6;p++) { if(activesquad->squad[p]!=NULL)partysize++; else { if(p==buyer)buyer=0; continue; } if(!partysize) { delete activesquad; activesquad=NULL; } if(!activesquad->squad[p]->alive)partydead++; } } int safenumber=0; for(l=0;l<(int)location.size();l++)if(location[l]->is_lcs_safehouse())safenumber++; Location *loc=NULL; if(selectedsiege!=-1)loc = location[selectedsiege]; if(activesquad!=NULL && activesquad->squad[0]->location!=-1) loc = location[activesquad->squad[0]->location]; siegest *siege=NULL; if(loc) siege= &loc->siege; char sieged=0; char underattack=0; if(siege!=NULL) { sieged=siege->siege; if(sieged) underattack=siege->underattack; } char haveflag=0; if(loc) haveflag=loc->haveflag; // Count people at each location int* num_present = new int[location.size()]; for(int i=0;i<(int)location.size();i++)num_present[i]=0; for(int p=0;p<(int)pool.size();p++) { if(!pool[p]->alive)continue; // Dead people don't count if(pool[p]->align!=1)continue; // Non-liberals don't count if(pool[p]->location==-1)continue; // Vacationers don't count num_present[pool[p]->location]++; } char cannotwait=0; for(l=0;l<(int)location.size();l++) { if(!location[l]->siege.siege)continue; if(location[l]->siege.underattack) { // Allow siege if no liberals present if(num_present[l])cannotwait=1; break; } } delete[] num_present; if(!forcewait) { erase(); if(activesquad!=NULL)selectedsiege=-1; locheader(); if(selectedsiege!=-1) { printlocation(selectedsiege); if(location[selectedsiege]->can_be_upgraded()&& !location[selectedsiege]->siege.siege) { set_color(COLOR_WHITE,COLOR_BLACK,0); move(8,1); addstr("I - Invest in this location"); } } else if(activesquad!=NULL)printparty(); else makedelimiter(8,0); if(sieged) { move(8,1); if(underattack) { set_color(COLOR_RED,COLOR_BLACK,1); addstr("Under Attack"); } else { set_color(COLOR_YELLOW,COLOR_BLACK,1); addstr("Under Siege"); int stock=1; if(loc)stock=loc->compound_stores; if(!stock)addstr(" (No Food)"); } } if(haveflag) { for(int p=0;p<7;p++) { move(p+10,32); if(p<3) { set_color(COLOR_WHITE,COLOR_BLUE,1); move(p+10,32); addstr("::::::"); set_color(COLOR_WHITE,COLOR_RED,1); move(p+10,38); for(int i=0;i<10;i++)addch(CH_LOWER_HALF_BLOCK); } else { if(p<6)set_color(COLOR_WHITE,COLOR_RED,1); else set_color(COLOR_RED,COLOR_BLACK,0); for(int i=0;i<16;i++) { if(p==6)addch(CH_UPPER_HALF_BLOCK); else addch(CH_LOWER_HALF_BLOCK); } } } } set_color(COLOR_WHITE,COLOR_BLACK,0); move(18,10); addstr("--- ACTIVISM ---"); move(18,51); addstr("--- PLANNING ---"); if(partysize>0&&!underattack)set_color(COLOR_WHITE,COLOR_BLACK,0); else set_color(COLOR_BLACK,COLOR_BLACK,1); move(19,40); addstr("E - Equip Squad"); if(vehicle.size()>0&&partysize>0)set_color(COLOR_WHITE,COLOR_BLACK,0); else set_color(COLOR_BLACK,COLOR_BLACK,1); move(19,60); addstr("V - Vehicles"); if(pool.size()>0)set_color(COLOR_WHITE,COLOR_BLACK,0); else set_color(COLOR_BLACK,COLOR_BLACK,1); move(20,40); addstr("R - Review Assets and Form Squads"); if(partysize>1)set_color(COLOR_WHITE,COLOR_BLACK,0); else set_color(COLOR_BLACK,COLOR_BLACK,1); move(8,30); if(partysize>0 && !sieged) addstr("O - Reorder"); if (activesquad) { move(8,1); set_color(COLOR_WHITE,COLOR_BLACK,0); addstr(activesquad->name); addstr("-"); //in case of overlap, at least make it clear where the name ends. } if(squad.size()>1||(activesquad==NULL&&squad.size()>0))set_color(COLOR_WHITE,COLOR_BLACK,0); else set_color(COLOR_BLACK,COLOR_BLACK,1); move(8,43); addstr("TAB - Next Squad"); if(safenumber>0)set_color(COLOR_WHITE,COLOR_BLACK,0); else set_color(COLOR_BLACK,COLOR_BLACK,1); move(8,62); addstr("Z - Next Location"); set_color(COLOR_WHITE,COLOR_BLACK,0); move(21,40); addstr("L - The Status of the Liberal Agenda"); set_color(COLOR_WHITE,COLOR_BLACK,0); move(21,1); addstr("A - Activate Liberals"); set_color(COLOR_BLACK,COLOR_BLACK,1); for(int p=0;p < (int)pool.size();p++) { if(pool[p]->alive==true&& pool[p]->flag & CREATUREFLAG_SLEEPER&& pool[p]->align==ALIGN_LIBERAL&& pool[p]->hiding==false&& pool[p]->clinic==false&& pool[p]->dating==false) { set_color(COLOR_WHITE,COLOR_BLACK,0); break; } } move(21,25); addstr("B - Sleepers"); if(partysize>0) { if(activesquad->activity.type!=ACTIVITY_NONE)set_color(COLOR_WHITE,COLOR_BLACK,0); else set_color(COLOR_BLACK,COLOR_BLACK,1); } else set_color(COLOR_BLACK,COLOR_BLACK,1); move(20,1); addstr("C - Cancel this Squad's Departure"); if(sieged) { if(partysize>0)set_color(COLOR_WHITE,COLOR_BLACK,0); else { set_color(COLOR_BLACK,COLOR_BLACK,1); for(int p=0;p<(int)pool.size();p++) { if(pool[p]->location==selectedsiege) { set_color(COLOR_WHITE,COLOR_BLACK,0); break; } } } move(19,1); addstr("F - Escape/Engage"); set_color(COLOR_WHITE,COLOR_BLACK,0); move(19,23); addstr("G - Give Up"); } else { if(partysize>0)set_color(COLOR_WHITE,COLOR_BLACK,0); else set_color(COLOR_BLACK,COLOR_BLACK,1); move(19,1); addstr("F - Go forth to stop EVIL"); } //if(partysize>0&&(party_status==-1||partysize>1))set_color(COLOR_WHITE,COLOR_BLACK,0); //else set_color(COLOR_BLACK,COLOR_BLACK,1); //move(19,40); //addstr("# - Check the status of a squad Liberal"); //if(party_status!=-1)set_color(COLOR_WHITE,COLOR_BLACK,0); //else set_color(COLOR_BLACK,COLOR_BLACK,1); //move(18,40); //addstr("0 - Show the squad's Liberal status"); set_color(COLOR_WHITE,COLOR_BLACK,0); move(23,40); addstr("X - Live to fight EVIL another day"); move(23,1); if(cannotwait) { set_color(COLOR_WHITE,COLOR_BLACK,0); addstr("Cannot Wait until Siege Resolved"); } else { set_color(COLOR_WHITE,COLOR_BLACK,0); if(sieged) addstr("W - Wait out the siege"); else addstr("W - Wait a day"); if(day==monthday())addstr(" (next month)"); } set_color(COLOR_WHITE,COLOR_BLACK,0); move(22,40); addstr("S - FREE SPEECH: the Liberal Slogan"); move(22,1); if(haveflag) { if(sieged) set_color(COLOR_GREEN,COLOR_BLACK,1); else set_color(COLOR_WHITE,COLOR_BLACK,0); addstr("P - PROTEST: burn the flag"); } else { if(ledger.get_funds()>=20&&!sieged&& (selectedsiege!=-1||activesquad!=NULL))set_color(COLOR_WHITE,COLOR_BLACK,0); else set_color(COLOR_BLACK,COLOR_BLACK,1); addstr("P - PATRIOTISM: fly a flag here ($20)"); } length=strlen(slogan); set_color(COLOR_WHITE,COLOR_BLACK,1); if(haveflag)move(17,40-(length>>1)); else move(13,40-(length>>1));
inline typename result_of::erase_key<Sequence const, Key>::type erase_key(Sequence const& seq) { return erase(seq, find<Key>(seq)); }
bool show_disbanding_screen(int& oldforcemonth) { if(oldforcemonth == month) return true; for(int p=pool.size()-1;p>=0;p--) { int targetjuice=0; for(int i=0;i<(year-disbandtime)+1;i++) { targetjuice+=LCSrandom(100); } if(targetjuice>1000) { targetjuice=1000; } if(pool[p]->juice<targetjuice) { if(pool[p]->hireid!=-1 && !(pool[p]->flag & CREATUREFLAG_SLEEPER)) pool[p]->alive=0; // Kill for the purposes of disbanding all contacts below } } oldforcemonth=month; erase(); move(0,0); char num[20]; itoa(year,num,10); set_color(COLOR_WHITE,COLOR_BLACK,1); addstr(getmonth(month)); addstr(" "); addstr(num); //int y=2; set_alignment_color(exec[EXEC_PRESIDENT], true); mvaddstr(1,0,"President: "); addstr(execname[EXEC_PRESIDENT]);addstr(", "); switch(exec[EXEC_PRESIDENT]) { case -2:addstr("Arch-Conservative");break; case -1:addstr("Conservative");break; case 0:addstr("moderate");break; case 1:addstr("Liberal");break; case 2:addstr("Elite Liberal");break; } if(execterm==1)addstr(", 1st Term"); else addstr(", 2nd Term"); int housemake[5]={0,0,0,0,0}; for(int h=0;h<435;h++) housemake[house[h]+2]++; int lsum=housemake[3]+housemake[4]-housemake[0]-housemake[1]; if(lsum<=-145)set_color(COLOR_RED,COLOR_BLACK,1); else if(lsum<0)set_color(COLOR_MAGENTA,COLOR_BLACK,1); else if(lsum<145)set_color(COLOR_YELLOW,COLOR_BLACK,1); else if(housemake[4]<290)set_color(COLOR_CYAN,COLOR_BLACK,1); else set_color(COLOR_GREEN,COLOR_BLACK,1); move(2,0); addstr("House: "); itoa(housemake[4],num,10); addstr(num);addstr("Lib+, "); itoa(housemake[3],num,10); addstr(num);addstr("Lib, "); itoa(housemake[2],num,10); addstr(num);addstr("Mod, "); itoa(housemake[1],num,10); addstr(num);addstr("Cons, "); itoa(housemake[0],num,10); addstr(num);addstr("Cons+"); int senatemake[5]={0,0,0,0,0}; for(int s=0;s<100;s++) senatemake[senate[s]+2]++; lsum=senatemake[3]+senatemake[4]-senatemake[0]-senatemake[1]; if(lsum<=-33)set_color(COLOR_RED,COLOR_BLACK,1); else if(lsum<0)set_color(COLOR_MAGENTA,COLOR_BLACK,1); else if(lsum<33)set_color(COLOR_YELLOW,COLOR_BLACK,1); else if(senatemake[4]<67)set_color(COLOR_CYAN,COLOR_BLACK,1); else set_color(COLOR_GREEN,COLOR_BLACK,1); move(3,0); addstr("Senate: "); itoa(senatemake[4],num,10); addstr(num);addstr("Lib+, "); itoa(senatemake[3],num,10); addstr(num);addstr("Lib, "); itoa(senatemake[2],num,10); addstr(num);addstr("Mod, "); itoa(senatemake[1],num,10); addstr(num);addstr("Cons, "); itoa(senatemake[0],num,10); addstr(num);addstr("Cons+"); int courtmake[5]={0,0,0,0,0}; for(int s=0;s<9;s++) { courtmake[court[s]+2]++; } lsum=courtmake[3]+courtmake[4] -courtmake[0]-courtmake[1]; if(courtmake[0]>=5)set_alignment_color(ALIGN_ARCHCONSERVATIVE, true); else if(courtmake[0]+courtmake[1]>=5)set_alignment_color(ALIGN_CONSERVATIVE, true); else if(courtmake[3]+courtmake[4]<5)set_alignment_color(ALIGN_MODERATE, true); else if(courtmake[4]<5)set_alignment_color(ALIGN_LIBERAL, true); else set_alignment_color(ALIGN_ELITELIBERAL, true); mvaddstr(4,0,"Supreme Court: "); itoa(courtmake[4],num,10); addstr(num);addstr("Lib+, "); itoa(courtmake[3],num,10); addstr(num);addstr("Lib, "); itoa(courtmake[2],num,10); addstr(num);addstr("Mod, "); itoa(courtmake[1],num,10); addstr(num);addstr("Cons, "); itoa(courtmake[0],num,10); addstr(num);addstr("Cons+"); //y=0; for(int l=0;l<LAWNUM;l++) { set_alignment_color(law[l], true); move(6+l/3,l%3*30); char str[40]; getlaw(str,l); addstr(str); } set_color(COLOR_WHITE,COLOR_BLACK,0); mvaddstr(19,33,"Public Mood"); mvaddstr(21,1,"Conservative"); mvaddstr(21,66,"Liberal"); mvaddstr(22,0,"<------------------------------------------------------------------------------>"); move(22,77*publicmood(-1)/100+1); addstr("|"); mvaddstr(23,0,"R - Recreate the Liberal Crime Squad Any Other Key - Next Month"); refresh(); char c=getch(); if(c=='r') return false; else return true; }
void PrimaryTree::erase(std::string string) { root_ = erase(root_, string); }
void keypress(XEvent *ev) { XKeyEvent *e = &ev->xkey; KeySym sym = XkbKeycodeToKeysym(dpy, (KeyCode)e->keycode, 0, 0); int mod = ((e->state & ~Mod2Mask) & ~LockMask); if (mod == (ControlMask | ShiftMask)) { if (sym == XK_q) { spect->fex = 0; running = False; } if (sym == XK_j || sym == XK_Down) threshold(-0.05); else if (sym == XK_k || sym == XK_Up) threshold(0.05); else if (sym == XK_h || sym == XK_Left) sp_floor(-0.05); else if (sym == XK_l || sym == XK_Right) sp_floor(0.05); else if (sym == XK_p) play(0.1666); } else if (mod == (Mod1Mask | ShiftMask)) { if (sym == XK_p) play(0.08333); } else if (mod == ControlMask) { if (sym == XK_q) running = False; else if (sym == XK_f) series_export(); else if (sym == XK_s) screenshot(); else if (sym == XK_i) img_draw(); else if (sym == XK_j || sym == XK_Down) zoom(-0.025); else if (sym == XK_k || sym == XK_Up) zoom(0.025); else if (sym == XK_h || sym == XK_Left) return; else if (sym == XK_l || sym == XK_Right) return; else if (sym == XK_p) play(0.33); } else if (mod == Mod1Mask) { if (sym == XK_j || sym == XK_Down) eraser_cursor(-1,-1); else if (sym == XK_k || sym == XK_Up) eraser_cursor(1,1); else if (sym == XK_h || sym == XK_Left) eraser_cursor(-1,1); else if (sym == XK_l || sym == XK_Right) eraser_cursor(1,-1); else if (sym == XK_p) play(0.25); } else if (mod == ShiftMask) { if (sym == XK_j || sym == XK_Down) pt_line(-0.2,0); else if (sym == XK_k || sym == XK_Up) pt_line(0.2,0); else if (sym == XK_h || sym == XK_Left) pt_line(0,-0.2); else if (sym == XK_l || sym == XK_Right) pt_line(0,0.2); else if (sym == XK_p) play(0.5); } else if (sym == XK_j || sym == XK_Down) move(0,0.02); else if (sym == XK_k || sym == XK_Up) move(0,-0.02); else if (sym == XK_h || sym == XK_Left) move(0.02,0); else if (sym == XK_l || sym == XK_Right) move(-0.02,0); else if (sym == XK_F1) { if (fork() == 0) { close(ConnectionNumber(dpy)); fclose(stderr); fclose(stdout); execvp(conf.help_cmd[0],(char * const *)conf.help_cmd); } } else if (sym == XK_F2) { if ( (info->vis = !info->vis) ) XMapRaised(dpy,info->win); else XUnmapWindow(dpy,info->win); XFlush(dpy); } else if (sym == XK_e) { //mode = MODE_ERASE & (mode ^= MODE_ERASE); mode = (mode & MODE_ERASE ? 0 : MODE_ERASE); eraser_cursor(0,0); info->draw(info); } else if (sym == XK_c) { //mode = MODE_CROP & (mode ^= MODE_CROP); mode = (mode & MODE_CROP ? 0 : MODE_CROP); if (!(mode & MODE_CROP)) XDefineCursor(dpy, win, None); else XDefineCursor(dpy, win, XCreateFontCursor(dpy, 34)); info->draw(info); } else if (sym == XK_Escape) { mode = MODE_NULL; XDefineCursor(dpy, win, None); info->draw(info); } else if (sym == XK_p) play(1.0); else if (sym == XK_t) { conf.layers = !conf.layers; spectro_draw(); XCopyArea(dpy, buf, win, gc, 0, 0, ww, wh, 0, 0); } else if (sym == XK_u && mode & (MODE_ERASE)) erase(-1,-1); while(XCheckMaskEvent(dpy, KeyPressMask, ev)); }
/** * Make the current environment persistent * @param[in] filename where to store * @param[in] dirname what to store (all files in this dir) * @param[in] flags superblock flags (refer ENVFS_FLAGS_* macros) * @return 0 on success, anything else in case of failure * * Note: This function will also be used on the host! See note in the header * of this file. */ int envfs_save(const char *filename, const char *dirname, unsigned flags) { struct envfs_super *super; int envfd, size, ret; struct action_data data = {}; void *buf = NULL, *wbuf; struct envfs_entry *env; if (!filename) filename = default_environment_path_get(); if (!dirname) dirname = "/env"; data.writep = NULL; data.base = dirname; #ifdef __BAREBOX__ defaultenv_load(TMPDIR, 0); #endif if (flags & ENVFS_FLAGS_FORCE_BUILT_IN) { size = 0; /* force no content */ } else { /* first pass: calculate size */ recursive_action(dirname, ACTION_RECURSE, file_action, NULL, &data, 0); recursive_action("/.defaultenv", ACTION_RECURSE, file_remove_action, NULL, &data, 0); size = 0; for (env = data.env; env; env = env->next) { size += PAD4(env->size); size += sizeof(struct envfs_inode); size += PAD4(strlen(env->name) + 1); size += sizeof(struct envfs_inode_end); } } buf = xzalloc(size + sizeof(struct envfs_super)); data.writep = buf + sizeof(struct envfs_super); super = buf; super->magic = ENVFS_32(ENVFS_MAGIC); super->major = ENVFS_MAJOR; super->minor = ENVFS_MINOR; super->size = ENVFS_32(size); super->flags = ENVFS_32(flags); if (!(flags & ENVFS_FLAGS_FORCE_BUILT_IN)) { /* second pass: copy files to buffer */ env = data.env; while (env) { struct envfs_entry *next = env->next; envfs_save_inode(&data, env); free(env->buf); free(env->name); free(env); env = next; } } super->crc = ENVFS_32(crc32(0, buf + sizeof(struct envfs_super), size)); super->sb_crc = ENVFS_32(crc32(0, buf, sizeof(struct envfs_super) - 4)); envfd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); if (envfd < 0) { printf("could not open %s: %s\n", filename, errno_str()); ret = -errno; goto out1; } ret = protect(envfd, ~0, 0, 0); /* ENOSYS and EOPNOTSUPP aren't errors here, many devices don't need it */ if (ret && errno != ENOSYS && errno != EOPNOTSUPP) { printf("could not unprotect %s: %s\n", filename, errno_str()); goto out; } ret = erase(envfd, ERASE_SIZE_ALL, 0); /* ENOSYS and EOPNOTSUPP aren't errors here, many devices don't need it */ if (ret && errno != ENOSYS && errno != EOPNOTSUPP) { printf("could not erase %s: %s\n", filename, errno_str()); goto out; } size += sizeof(struct envfs_super); wbuf = buf; while (size) { ssize_t now = write(envfd, wbuf, size); if (now < 0) { ret = -errno; goto out; } wbuf += now; size -= now; } ret = protect(envfd, ~0, 0, 1); /* ENOSYS and EOPNOTSUPP aren't errors here, many devices don't need it */ if (ret && errno != ENOSYS && errno != EOPNOTSUPP) { printf("could not protect %s: %s\n", filename, errno_str()); goto out; } ret = 0; #ifdef CONFIG_NVVAR if (!strcmp(filename, default_environment_path_get())) nv_var_set_clean(); #endif out: close(envfd); out1: free(buf); #ifdef __BAREBOX__ unlink_recursive(TMPDIR, NULL); #endif return ret; }
// Removes a Node<T> from the back of the list. Simply calls erase() on // the Node<T> previous to tail. Logical error to call pop_back() on // empty list, which is handled inside erase(); void pop_back(){ erase(tail->prev); }
/* base - activate sleepers */ void activate_sleepers(void) { vector<Creature *> temppool; // Comb the pool of Liberals for sleeper agents for(int p=0;p<pool.size();p++) { // Select only sleepers that can work if(pool[p]->alive==true&& pool[p]->flag & CREATUREFLAG_SLEEPER&& pool[p]->align==ALIGN_LIBERAL&& pool[p]->hiding==false&& pool[p]->clinic==false&& pool[p]->dating==false) { temppool.push_back(pool[p]); } } if(temppool.size()==0)return; sortliberals(temppool,activesortingchoice[SORTINGCHOICE_ACTIVATESLEEPERS]); int page=0; char str[80]; do { erase(); set_color(COLOR_WHITE,COLOR_BLACK,0); printfunds(0,1,"Money: "); move(0,0); addstr("Activate Sleeper Agents"); makedelimiter(1,0); move(1,4); addstr("CODE NAME"); move(1,25); addstr("JOB"); move(1,42); addstr("SITE"); move(1,57); addstr("ACTIVITY"); int y=2; for(int p=page*9;p<temppool.size()&&p<page*9+9;p++) { set_color(COLOR_WHITE,COLOR_BLACK,0); move(y,0); addch((y-2)/2+'A');addstr(" - "); addstr(temppool[p]->name); move(y,25); getrecruitcreature(str,temppool[p]->type); addstr(str); move(y+1,6); addstr("Effectiveness: "); if(temppool[p]->infiltration > 0.8f) { set_color(COLOR_RED,COLOR_BLACK,1); } else if(temppool[p]->infiltration > 0.6f) { set_color(COLOR_MAGENTA,COLOR_BLACK,1); } else if(temppool[p]->infiltration > 0.4f) { set_color(COLOR_YELLOW,COLOR_BLACK,1); } else if(temppool[p]->infiltration > 0.2f) { set_color(COLOR_WHITE,COLOR_BLACK,1); } else if(temppool[p]->infiltration > 0.1f) { set_color(COLOR_WHITE,COLOR_BLACK,0); } else { set_color(COLOR_GREEN,COLOR_BLACK,0); } char num[10]; itoa(static_cast<int>(temppool[p]->infiltration*100),num,10); addstr(num); addstr("%"); move(y,42); set_color(COLOR_WHITE,COLOR_BLACK,0); addstr(location[temppool[p]->worklocation]->getname(true)); move(y,57); // Let's add some color here... set_activity_color(temppool[p]->activity.type); getactivity(str,temppool[p]->activity); addstr(str); y+=2; } set_color(COLOR_WHITE,COLOR_BLACK,0); move(22,0); addstr("Press a Letter to Assign an Activity."); move(23,0); addpagestr(); addstr(" T to sort people."); set_color(COLOR_WHITE,COLOR_BLACK,0); refresh(); int c=getch(); translategetch(c); //PAGE UP if((c==interface_pgup||c==KEY_UP||c==KEY_LEFT)&&page>0)page--; //PAGE DOWN if((c==interface_pgdn||c==KEY_DOWN||c==KEY_RIGHT)&&(page+1)*9<temppool.size())page++; if(c>='a'&&c<='s') { int p=page*9+(int)(c-'a'); if(p<temppool.size()) { activate_sleeper(temppool[p]); } } if(c=='t') { sorting_prompt(SORTINGCHOICE_ACTIVATESLEEPERS); sortliberals(temppool,activesortingchoice[SORTINGCHOICE_ACTIVATESLEEPERS],true); } if(c==10||c==ESC)break; }while(1); }
// Removes a Node<T> from the front of the list. Pop_front() calls erase() // on head->next. void pop_front(){ erase(head->next); }
void NBNodeCont::removeIsolatedRoads(NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tc) { UNUSED_PARAMETER(tc); // Warn of isolated edges, i.e. a single edge with no connection to another edge int edgeCounter = 0; const std::vector<std::string>& edgeNames = ec.getAllNames(); for (std::vector<std::string>::const_iterator it = edgeNames.begin(); it != edgeNames.end(); ++it) { // Test whether this node starts at a dead end, i.e. it has only one adjacent node // to which an edge exists and from which an edge may come. NBEdge* e = ec.retrieve(*it); if (e == 0) { continue; } NBNode* from = e->getFromNode(); const EdgeVector& outgoingEdges = from->getOutgoingEdges(); if (outgoingEdges.size() != 1) { // At this node, several edges or no edge start; so, this node is no dead end. continue; } const EdgeVector& incomingEdges = from->getIncomingEdges(); if (incomingEdges.size() > 1) { // At this node, several edges end; so, this node is no dead end. continue; } else if (incomingEdges.size() == 1) { NBNode* fromNodeOfIncomingEdge = incomingEdges[0]->getFromNode(); NBNode* toNodeOfOutgoingEdge = outgoingEdges[0]->getToNode(); if (fromNodeOfIncomingEdge != toNodeOfOutgoingEdge) { // At this node, an edge ends which is not the inverse direction of // the starting node. continue; } } // Now we know that the edge e starts a dead end. // Next we test if the dead end is isolated, i.e. does not lead to a junction bool hasJunction = false; EdgeVector road; NBEdge* eOld = 0; NBNode* to; std::set<NBNode*> adjacentNodes; do { road.push_back(e); eOld = e; from = e->getFromNode(); to = e->getToNode(); const EdgeVector& outgoingEdgesOfToNode = to->getOutgoingEdges(); const EdgeVector& incomingEdgesOfToNode = to->getIncomingEdges(); adjacentNodes.clear(); for (EdgeVector::const_iterator itOfOutgoings = outgoingEdgesOfToNode.begin(); itOfOutgoings != outgoingEdgesOfToNode.end(); ++itOfOutgoings) { if ((*itOfOutgoings)->getToNode() != from // The back path && (*itOfOutgoings)->getToNode() != to // A loop / dummy edge ) { e = *itOfOutgoings; // Probably the next edge } adjacentNodes.insert((*itOfOutgoings)->getToNode()); } for (EdgeVector::const_iterator itOfIncomings = incomingEdgesOfToNode.begin(); itOfIncomings != incomingEdgesOfToNode.end(); ++itOfIncomings) { adjacentNodes.insert((*itOfIncomings)->getFromNode()); } adjacentNodes.erase(to); // Omit loops if (adjacentNodes.size() > 2) { hasJunction = true; } } while (!hasJunction && eOld != e); if (!hasJunction) { edgeCounter += int(road.size()); std::string warningString = "Removed a road without junctions: "; for (EdgeVector::iterator roadIt = road.begin(); roadIt != road.end(); ++roadIt) { if (roadIt == road.begin()) { warningString += (*roadIt)->getID(); } else { warningString += ", " + (*roadIt)->getID(); } NBNode* fromNode = (*roadIt)->getFromNode(); NBNode* toNode = (*roadIt)->getToNode(); ec.erase(dc, *roadIt); if (fromNode->getIncomingEdges().size() == 0 && fromNode->getOutgoingEdges().size() == 0) { // Node is empty; can be removed erase(fromNode); } if (toNode->getIncomingEdges().size() == 0 && toNode->getOutgoingEdges().size() == 0) { // Node is empty; can be removed erase(toNode); } } WRITE_WARNING(warningString); } } if (edgeCounter > 0 && !OptionsCont::getOptions().getBool("remove-edges.isolated")) { WRITE_WARNING("Detected isolated roads. Use the option --remove-edges.isolated to get a list of all affected edges."); } }
Status parseUri(ParsedUri &result, const std::string &text) { Uri uri; if (uri.decode(text, false)) { // Turn Airbitz URI's into bitcoin URI's: if ("airbitz" == uri.scheme()) { uri.deauthorize(); auto path = uri.path(); if (0 != path.find("bitcoin/", 0)) return ABC_ERROR(ABC_CC_ParseError, "Unknown airbitz URI"); path.erase(0, 8); uri.pathSet(path); uri.schemeSet("bitcoin"); } // Check the scheme: if ("bitcoin" == uri.scheme()) { uri.deauthorize(); if (addressOk(uri.path())) result.address = uri.path(); auto query = uri.queryDecode(); bc::decode_base10(result.amountSatoshi, query["amount"], 8); result.label = query["label"]; result.message = query["message"]; result.category = query["category"]; result.ret = query["ret"]; result.paymentProto = query["r"]; } else if ("hbits" == uri.scheme()) { uri.deauthorize(); bc::ec_secret secret; ABC_CHECK(hbitsDecode(secret, uri.path())); result.wif = bc::secret_to_wif(secret, true); } else if ("bitid" == uri.scheme()) { result.bitidUri = text; } else { return ABC_ERROR(ABC_CC_ParseError, "Unknown URI scheme"); } } else if (addressOk(text)) { // This is a raw bitcoin address: result.address = text; } else if (bc::null_hash != bc::wif_to_secret(text)) { // This is a raw WIF private key: result.wif = text; } else if (minikeyOk(text)) { // This is a raw Casascius minikey: result.wif = bc::secret_to_wif(bc::minikey_to_secret(text), false); } else if (hbitsOk(text)) { // This is a raw hbits key: bc::ec_secret secret; ABC_CHECK(hbitsDecode(secret, text)); result.wif = bc::secret_to_wif(secret, true); } else { return ABC_ERROR(ABC_CC_ParseError, "Malformed bitcoin URI"); } // Private keys also have addresses: if (result.wif.size()) { const auto compressed = bc::is_wif_compressed(result.wif); const auto secret = bc::wif_to_secret(result.wif); const auto pubkey = bc::secret_to_public_key(secret, compressed); bc::payment_address address; address.set(pubkeyVersion(), bc::bitcoin_short_hash(pubkey)); result.address = address.encoded(); } return Status(); }
bool CHooks::Remove(const hookkey &key) { return (erase(key) > 0); }
// This is used when you want to swap the track or pair of // tracks in s1 with the track or pair of tracks in s2. // The complication is that the tracks are stored in a single // linked list, and pairs of tracks are marked only by a flag // in one of the tracks. void TrackList::SwapNodes(TrackNodePointer s1, TrackNodePointer s2) { // if a null pointer is passed in, we want to know about it wxASSERT(!isNull(s1)); wxASSERT(!isNull(s2)); // Deal with first track in each team Track *link; link = (*s1)->GetLink(); bool linked1 = link != nullptr; if (linked1 && !(*s1)->GetLinked()) { s1 = link->GetNode(); } link = (*s2)->GetLink(); bool linked2 = link != nullptr; if (linked2 && !(*s2)->GetLinked()) { s2 = link->GetNode(); } // Safety check... if (s1 == s2) return; // Be sure s1 is the earlier iterator if ((*s1)->GetIndex() >= (*s2)->GetIndex()) { std::swap(s1, s2); std::swap(linked1, linked2); } // Remove tracks value_type save11 = std::move(*s1), save12{}; s1 = erase(s1); if (linked1) { wxASSERT(s1 != s2); save12 = std::move(*s1), s1 = erase(s1); } const bool same = (s1 == s2); value_type save21 = std::move(*s2), save22{}; s2 = erase(s2); if (linked2) save22 = std::move(*s2), s2 = erase(s2); if (same) // We invalidated s1! s1 = s2; // Reinsert them Track *pTrack; if (save22) pTrack = save22.get(), pTrack->SetOwner(this, s1 = insert(s1, std::move(save22))); pTrack = save21.get(), pTrack->SetOwner(this, s1 = insert(s1, std::move(save21))); if (save12) pTrack = save12.get(), pTrack->SetOwner(this, s2 = insert(s2, std::move(save12))); pTrack = save11.get(), pTrack->SetOwner(this, s2 = insert(s2, std::move(save11))); // Now correct the Index in the tracks, and other things RecalcPositions(s1); UpdatedEvent(s1); ResizedEvent(s1); }
CellLinkedList::Iterator CellLinkedList::extractTo(CellLinkedList::Iterator pos, CellLinkedList & other) { Cell * c = *pos; other.append(c); return erase(pos); }
void de_zoom_map(t_env *e) { e->pad -= 1; erase(e); }