void writeheader(int type, int contin) /* **-------------------------------------------------------------- ** Input: type = table type ** contin = table continuation flag ** Output: none ** Purpose: writes column headings for output report tables **-------------------------------------------------------------- */ { char s[MAXLINE+1],s1[MAXLINE+1],s2[MAXLINE+1],s3[MAXLINE+1]; int i,n; /* Move to next page if < 11 lines remain on current page. */ if (Rptflag && LineNum+11 > (long)PageSize) { while (LineNum < (long)PageSize) writeline(" "); } writeline(" "); /* Hydraulic Status Table */ if (type == STATHDR) { sprintf(s,FMT49); if (contin) strcat(s,t_CONTINUED); writeline(s); fillstr(s,'-',70); writeline(s); } /* Energy Usage Table */ if (type == ENERHDR) { if (Unitsflag == SI) strcpy(s1,t_perM3); else strcpy(s1,t_perMGAL); sprintf(s,FMT71); if (contin) strcat(s,t_CONTINUED); writeline(s); fillstr(s,'-',63); writeline(s); sprintf(s,FMT72); writeline(s); sprintf(s,FMT73,s1); writeline(s); fillstr(s,'-',63); writeline(s); } /* Node Results Table */ if (type == NODEHDR) { if (Tstatflag == RANGE) sprintf(s,FMT76,t_DIFFER); else if (Tstatflag != SERIES) sprintf(s,FMT76,TstatTxt[Tstatflag]); else if (Dur == 0) sprintf(s,FMT77); else sprintf(s,FMT78,clocktime(Atime,Htime)); if (contin) strcat(s,t_CONTINUED); writeline(s); n = 15; sprintf(s2,"%15s",""); strcpy(s,t_NODEID); sprintf(s3,"%-15s",s); for (i=ELEV; i<QUALITY; i++) if (Field[i].Enabled == TRUE) { n += 10; sprintf(s,"%10s",Field[i].Name); strcat(s2,s); sprintf(s,"%10s",Field[i].Units); strcat(s3,s); } if (Field[QUALITY].Enabled == TRUE) { n += 10; sprintf(s,"%10s",ChemName); strcat(s2,s); sprintf(s,"%10s",ChemUnits); strcat(s3,s); } fillstr(s1,'-',n); writeline(s1); writeline(s2); writeline(s3); writeline(s1); } /* Link Results Table */ if (type == LINKHDR) { if (Tstatflag == RANGE) sprintf(s,FMT79,t_DIFFER); else if (Tstatflag != SERIES) sprintf(s,FMT79,TstatTxt[Tstatflag]); else if (Dur == 0) sprintf(s,FMT80); else sprintf(s,FMT81,clocktime(Atime,Htime)); if (contin) strcat(s,t_CONTINUED); writeline(s); n = 15; sprintf(s2,"%15s",""); strcpy(s,t_LINKID); sprintf(s3,"%-15s",s); for (i=LENGTH; i<=FRICTION; i++) if (Field[i].Enabled == TRUE) { n += 10; sprintf(s,"%10s",Field[i].Name); strcat(s2,s); sprintf(s,"%10s",Field[i].Units); strcat(s3,s); } fillstr(s1,'-',n); writeline(s1); writeline(s2); writeline(s3); writeline(s1); } } /* End of writeheader */
void * handle (void * arg) { sid_t sid; lid_t lid; uid_t uid; char *cmd_line; char *cmd_str, *lid_str, *uid_str; char *path; off_t pos; size_t cmd_len; char userdata[USERDATA_MAX + 1]; char *errstr; errstr = NULL; sd_t *sd = NULL; cb_arg_t *cb_arg = NULL; sd = (sd_t *) malloc (sizeof (sd_t)); if (sd == NULL) return NULL; sd->cli = *((int *) arg); pthread_mutex_init (&sd->mutex, NULL); cb_arg = (cb_arg_t *) malloc (sizeof (cb_arg_t)); if (cb_arg == NULL) { free (sd); return NULL; } cb_arg->arg = (void *) sd; sid = session_create (&readlink_cb, cb_arg); for (;;) { if ((cmd_line = readline (sd->cli)) == NULL) break; pthread_mutex_lock (&sd->mutex); pos = 0; cmd_len = strlen (cmd_line); for (pos = 0; cmd_line[pos] !=' ' && pos < cmd_len; pos ++); cmd_line[pos] = 0; cmd_str = cmd_line; int i; for (i = pos; cmd_line[i] != ' ' && i < cmd_len; i++); cmd_line[i] = 0; strncpy(userdata, cmd_line + pos + 1, USERDATA_MAX); userdata[USERDATA_MAX] = '\0'; pos += strlen(userdata) + 1; if (strcmp (cmd_str, GETLINK_CMD) == 0) { lid = session_getlink (sid); if (lid > 0) { char * ret = (char *) malloc (strlen(GETLINK_CMD) + strlen (mount_path) + 128); if (ret == NULL) goto error; sprintf (ret, "%s %s %s %d %s/%d/%d", GETLINK_CMD, userdata, OK_CMD, lid, mount_path, sid, lid); writeline (sd->cli, ret, strlen (ret), LF); free (ret); goto done; } else goto error; } else if (strcmp (cmd_str, SETLINK_CMD) == 0) { if (pos + 1 >= cmd_len) goto error; lid_str = cmd_line + (pos + 1); for (;cmd_line[pos] != ' ' && pos < cmd_len; pos ++); cmd_line[pos] = 0; lid = atoi (lid_str); if (pos + 1 >= cmd_len) goto error; path = cmd_line + (pos + 1); /* * TODO: sanitize path */ int rv; rv = session_setlink (sid, lid, path); if (rv != 0) { errstr = session_err_strs[rv]; printf ("%s\n", errstr); goto error; } char * ret = (char *) malloc (strlen(SETLINK_CMD) + strlen (OK_CMD) + 2); if (ret == NULL) goto error; sprintf (ret, "%s %s %s", SETLINK_CMD, userdata, OK_CMD); writeline (sd->cli, ret, strlen (ret), LF); free (ret); } else if (strcmp (cmd_str, SETUID_CMD) == 0) { if (pos + 1 >= cmd_len) goto error; uid_str = cmd_line + (pos + 1); for (;cmd_line[pos] != ' ' && pos < cmd_len; pos ++); cmd_line[pos] = 0; uid = atoi (uid_str); if (session_setuid (sid, uid) != 0) goto error; char * ret = (char *) malloc (strlen(SETUID_CMD) + strlen (OK_CMD) + 2); if (ret == NULL) goto error; sprintf (ret, "%s %s %s", SETUID_CMD, userdata, OK_CMD); writeline (sd->cli, ret, strlen (ret), LF); free (ret); } done: if (cmd_line != NULL) free (cmd_line); pthread_mutex_unlock (&sd->mutex); continue; error: if (!errstr) errstr = ""; char errbuf[1024]; snprintf(errbuf, 1024, "%s %s", ERROR_CMD, errstr); writeline (sd->cli, errbuf, strlen (errbuf), LF); goto done; } session_destroy (sid); free (cb_arg); free (sd); return NULL; }
static int at_send_command_full_nolock (const char *command, ATCommandType type, const char *responsePrefix, const char *smspdu, long long timeoutMsec, ATResponse **pp_outResponse) { int err = 0; #ifndef USE_NP struct timespec ts; #endif /*USE_NP*/ if(sp_response != NULL) { err = AT_ERROR_COMMAND_PENDING; goto error; } err = writeline (command); if (err < 0) { goto error; } s_type = type; s_responsePrefix = responsePrefix; s_smsPDU = smspdu; sp_response = at_response_new(); #ifndef USE_NP if (timeoutMsec != 0) { setTimespecRelative(&ts, timeoutMsec); } #endif /*USE_NP*/ while (sp_response->finalResponse == NULL && s_readerClosed == 0) { if (timeoutMsec != 0) { #ifdef USE_NP err = pthread_cond_timeout_np(&s_commandcond, &s_commandmutex, timeoutMsec); #else err = pthread_cond_timedwait(&s_commandcond, &s_commandmutex, &ts); #endif /*USE_NP*/ } else { err = pthread_cond_wait(&s_commandcond, &s_commandmutex); } if (err == ETIMEDOUT) { err = AT_ERROR_TIMEOUT; goto error; } } if (pp_outResponse == NULL) { at_response_free(sp_response); } else { /* line reader stores intermediate responses in reverse order */ reverseIntermediates(sp_response); *pp_outResponse = sp_response; } sp_response = NULL; if(s_readerClosed > 0) { err = AT_ERROR_CHANNEL_CLOSED; goto error; } err = 0; error: clearPendingCommand(); return err; }
int getpumpparams(void) /* **------------------------------------------------------------- ** Input: none ** Output: returns error code ** Purpose: computes & checks pump curve parameters **-------------------------------------------------------------- */ { int i, j = 0, k, m, n = 0; double a,b,c, h0 = 0.0, h1 = 0.0, h2 = 0.0, q1 = 0.0, q2 = 0.0; for (i=1; i<=Npumps; i++) { k = Pump[i].Link; if (Pump[i].Ptype == CONST_HP) /* Constant Hp pump */ { Pump[i].H0 = 0.0; Pump[i].R = -8.814*Link[k].Km; Pump[i].N = -1.0; Pump[i].Hmax = BIG; /* No head limit */ Pump[i].Qmax = BIG; /* No flow limit */ Pump[i].Q0 = 1.0; /* Init. flow = 1 cfs */ continue; } /* Set parameters for pump curves */ else if (Pump[i].Ptype == NOCURVE) /* Pump curve specified */ { j = Pump[i].Hcurve; /* Get index of head curve */ if (j == 0) { /* Error: No head curve */ sprintf(Msg,ERR226,Link[k].ID); writeline(Msg); return(200); } n = Curve[j].Npts; if (n == 1) /* Only a single h-q point */ { /* supplied so use generic */ Pump[i].Ptype = POWER_FUNC; /* power function curve. */ q1 = Curve[j].X[0]; h1 = Curve[j].Y[0]; h0 = 1.33334*h1; q2 = 2.0*q1; h2 = 0.0; } else if (n == 3 && Curve[j].X[0] == 0.0) /* 3 h-q points supplied with */ { /* shutoff head so use fitted */ Pump[i].Ptype = POWER_FUNC; /* power function curve. */ h0 = Curve[j].Y[0]; q1 = Curve[j].X[1]; h1 = Curve[j].Y[1]; q2 = Curve[j].X[2]; h2 = Curve[j].Y[2]; } else Pump[i].Ptype = CUSTOM; /* Else use custom pump curve.*/ /* Compute shape factors & limits of power function pump curves */ if (Pump[i].Ptype == POWER_FUNC) { if (!powercurve(h0,h1,h2,q1,q2,&a,&b,&c)) { /* Error: Invalid curve */ sprintf(Msg,ERR227,Link[k].ID); writeline(Msg); return(200); } else { Pump[i].H0 = -a; Pump[i].R = -b; Pump[i].N = c; Pump[i].Q0 = q1; Pump[i].Qmax = pow((-a/b),(1.0/c)); Pump[i].Hmax = h0; } } } /* Assign limits to custom pump curves */ if (Pump[i].Ptype == CUSTOM) { for (m=1; m<n; m++) { if (Curve[j].Y[m] >= Curve[j].Y[m-1]) { /* Error: Invalid curve */ sprintf(Msg,ERR227,Link[k].ID); writeline(Msg); return(200); } } Pump[i].Qmax = Curve[j].X[n-1]; Pump[i].Q0 = (Curve[j].X[0] + Pump[i].Qmax)/2.0; Pump[i].Hmax = Curve[j].Y[0]; } } /* Next pump */ return(0); }
int main (int argc, char ** argv) { char grp_name [PFS_NAME_LEN]; char sd_owner [PFS_NAME_LEN]; char sd_name [PFS_NAME_LEN]; int pfsd_sd = -1; struct hostent *he; struct sockaddr_in pfsd_addr; unsigned short pfsd_port; char * in_buf; if (argc != 5) { printf ("usage : pfs_add_sd port grp_name sd_owner sd_name\n"); exit (-1); } if (strlen (argv[2]) > PFS_NAME_LEN - 1 && strlen (argv[3]) > PFS_NAME_LEN - 1 && strlen (argv[4]) > PFS_NAME_LEN - 1) { printf ("grp_name, sd_owner, sd_name must be %d character max\n", PFS_NAME_LEN - 1); } strncpy (grp_name, argv[2], PFS_NAME_LEN); strncpy (sd_owner, argv[3], PFS_NAME_LEN); strncpy (sd_name, argv[4], PFS_NAME_LEN); pfsd_port = atoi (argv[1]); /* * We try to connect to the local pfsd server. */ if ((pfsd_sd = socket (AF_INET, SOCK_STREAM, 0)) < 0) goto error; if ((he = gethostbyname ("localhost")) == NULL) goto error; bzero (&pfsd_addr, sizeof (pfsd_addr)); pfsd_addr.sin_family = AF_INET; pfsd_addr.sin_port = htons (pfsd_port); pfsd_addr.sin_addr = *((struct in_addr *) he->h_addr); if (connect(pfsd_sd, (struct sockaddr *)&pfsd_addr, sizeof (pfsd_addr)) < 0) goto error; writeline (pfsd_sd, ADD_SD, strlen (CREAT_GRP)); writeline (pfsd_sd, grp_name, strlen (grp_name)); writeline (pfsd_sd, sd_owner, strlen (sd_owner)); writeline (pfsd_sd, sd_name, strlen (sd_name)); in_buf = readline (pfsd_sd); if (in_buf == NULL) goto error; printf ("received : %s\n", in_buf); if (strcmp (in_buf, OK) != 0) { free (in_buf); goto error; } free (in_buf); writeline (pfsd_sd, CLOSE, strlen (CLOSE)); close (pfsd_sd); printf ("sd %s.%s added to group %s.\n", sd_owner, sd_name, grp_name); return 0; error: printf ("could not add sd.\n"); return -1; }
int main(int argc, char *argv[]) { int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; char buffer[256]; struct timeval tv; fd_set read_set, write_set; if (argc < 3) { fprintf(stderr,"usage %s hostname port\n", argv[0]); exit(0); } portno = atoi(argv[2]); /* Create a socket point */ sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("ERROR opening socket"); exit(1); } server = gethostbyname(argv[1]); if (server == NULL) { fprintf(stderr,"ERROR, no such host\n"); exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); /* Now connect to the server */ if (connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0) { perror("ERROR connecting"); exit(1); } struct pollfd fds[2]; fds[0].fd = STDIN_FILENO; fds[1].fd = sockfd; fds[0].events = POLLIN; fds[1].events = POLLIN | POLLRDHUP; int poll_result; while (1 && !sig_term) { poll_result = poll(fds, 2, 1000 * 3); if (fds[1].revents & POLLRDHUP) { break; } if (fds[1].revents & POLLIN) { bzero(buffer,256); readline(sockfd, buffer, 256); if (strcmp(buffer, "[ECHO_OFF]\r\n") == 0) { echo_off(); continue; } if (strcmp(buffer, "[ECHO_ON]\r\n") == 0) { echo_on(); continue; } fputs(buffer, stdout); } if (fds[0].revents & POLLIN) { bzero(buffer,256); readline(STDIN_FILENO, buffer, 256); writeline(sockfd, buffer, strlen(buffer)); } } shutdown(sockfd, SHUT_RDWR); return 0; }
void AuxClientThread::transmit( const Bscript::BObjectImp* value ) { std::string tmp = _uoexec->auxsvc_assume_string ? value->getStringRep() : value->pack(); writeline( _sck, tmp ); }
int handle_grp_stat (int cli_sd) { char out_buf[512]; char * in_buf; char grp_id [PFS_ID_LEN]; struct pfs_group * grp; struct pfs_sd * sd; int i; in_buf = readline (cli_sd); if (in_buf == NULL) goto error; strncpy (grp_id, in_buf, PFS_ID_LEN); free (in_buf); writeline (cli_sd, OK, strlen (OK)); pfs_mutex_lock (&pfsd->pfs->group_lock); grp = pfsd->pfs->group; while (grp != NULL) { if (strncmp (in_buf, grp->grp_id, PFS_ID_LEN) == 0) goto found; grp = grp->next; } writeline (cli_sd, "0", 1); goto done; found: sprintf (out_buf, "%d", grp->sd_cnt); writeline (cli_sd, out_buf, strlen (out_buf)); sd = grp->sd; while (sd != NULL) { writeline (cli_sd, sd->sd_id, PFS_ID_LEN); writeline (cli_sd, sd->sd_owner, strlen (sd->sd_owner)); writeline (cli_sd, sd->sd_name, strlen (sd->sd_name)); sprintf (out_buf, "%d", sd->sd_sv->len); writeline (cli_sd, out_buf, strlen (out_buf)); for (i = 0; i < sd->sd_sv->len; i ++) { writeline (cli_sd, sd->sd_sv->sd_id[i], PFS_ID_LEN); sprintf (out_buf, "%llu", sd->sd_sv->value[i]); writeline (cli_sd, out_buf, strlen (out_buf)); } sd = sd->next; } done: pfs_mutex_unlock (&pfsd->pfs->group_lock); return 0; error: return -1; }
int handle_online (int cli_sd) { char * in_buf; struct pfsd_sd * new_sd; struct pfsd_sd * sd; new_sd = (struct pfsd_sd *) malloc (sizeof (struct pfsd_sd)); memset (new_sd, 0, sizeof (struct pfsd_sd)); in_buf = readline (cli_sd); if (in_buf == NULL) goto error; new_sd->tun_conn = (uint8_t) atoi (in_buf); free (in_buf); in_buf = readline (cli_sd); if (in_buf == NULL) goto error; new_sd->tun_port = atoi (in_buf); free (in_buf); in_buf = readline (cli_sd); if (in_buf == NULL) goto error; sprintf (new_sd->sd_id, in_buf, PFS_ID_LEN); free (in_buf); in_buf = readline (cli_sd); if (in_buf == NULL) goto error; strncpy (new_sd->sd_owner, in_buf, PFS_NAME_LEN); free (in_buf); in_buf = readline (cli_sd); if (in_buf == NULL) goto error; strncpy (new_sd->sd_name, in_buf, PFS_NAME_LEN); free (in_buf); /* Received an sd connection, we add it to pfsd->sd */ pfs_mutex_lock (&pfsd->sd_lock); sd = pfsd->sd; while (sd != NULL) { if (strncmp (new_sd->sd_id, sd->sd_id, PFS_ID_LEN) == 0 && sd->tun_conn == new_sd->tun_conn) { sd->tun_port = new_sd->tun_port; free (new_sd); goto done; } sd = sd->next; } new_sd->next = pfsd->sd; pfsd->sd = new_sd; pfsd->sd_cnt ++; pfsd->update = 1; done: pfs_mutex_unlock (&pfsd->sd_lock); #ifdef DEBUG printf ("*** HANDLE_ONLINE : %s:%s : %.*s ", new_sd->sd_owner, new_sd->sd_name, PFS_ID_LEN, new_sd->sd_id); if (new_sd->tun_conn == LAN_CONN) printf ("(LAN:"); if (new_sd->tun_conn == BTH_CONN) printf ("(BTH:"); printf ("%d)\n", new_sd->tun_port); #endif writeline (cli_sd, OK, strlen (OK)); return 0; error: return -1; }
size_t BasisOptimize(int* usedZeroedSpecies, bool doFormRxn, MultiPhase* mphase, std::vector<size_t>& orderVectorSpecies, std::vector<size_t>& orderVectorElements, vector_fp& formRxnMatrix) { // Get the total number of elements defined in the multiphase object size_t ne = mphase->nElements(); // Get the total number of species in the multiphase object size_t nspecies = mphase->nSpecies(); // Perhaps, initialize the element ordering if (orderVectorElements.size() < ne) { orderVectorElements.resize(ne); iota(orderVectorElements.begin(), orderVectorElements.end(), 0); } // Perhaps, initialize the species ordering if (orderVectorSpecies.size() != nspecies) { orderVectorSpecies.resize(nspecies); iota(orderVectorSpecies.begin(), orderVectorSpecies.end(), 0); } if (BasisOptimize_print_lvl >= 1) { writelog(" "); writeline('-', 77); writelog(" --- Subroutine BASOPT called to "); writelog("calculate the number of components and "); writelog("evaluate the formation matrix\n"); if (BasisOptimize_print_lvl > 0) { writelog(" ---\n"); writelog(" --- Formula Matrix used in BASOPT calculation\n"); writelog(" --- Species | Order | "); for (size_t j = 0; j < ne; j++) { size_t jj = orderVectorElements[j]; writelog(" {:>4.4s}({:1d})", mphase->elementName(jj), j); } writelog("\n"); for (size_t k = 0; k < nspecies; k++) { size_t kk = orderVectorSpecies[k]; writelog(" --- {:>11.11s} | {:4d} |", mphase->speciesName(kk), k); for (size_t j = 0; j < ne; j++) { size_t jj = orderVectorElements[j]; double num = mphase->nAtoms(kk,jj); writelogf("%6.1g ", num); } writelog("\n"); } writelog(" --- \n"); } } // Calculate the maximum value of the number of components possible. It's // equal to the minimum of the number of elements and the number of total // species. size_t nComponents = std::min(ne, nspecies); size_t nNonComponents = nspecies - nComponents; // Set this return variable to false *usedZeroedSpecies = false; // Create an array of mole numbers vector_fp molNum(nspecies,0.0); mphase->getMoles(molNum.data()); // Other workspace DenseMatrix sm(ne, ne); vector_fp ss(ne, 0.0); vector_fp sa(ne, 0.0); if (formRxnMatrix.size() < nspecies*ne) { formRxnMatrix.resize(nspecies*ne, 0.0); } // For debugging purposes keep an unmodified copy of the array. vector_fp molNumBase = molNum; double molSave = 0.0; size_t jr = 0; // Top of a loop of some sort based on the index JR. JR is the current // number of component species found. while (jr < nComponents) { // Top of another loop point based on finding a linearly independent // species size_t k = npos; while (true) { // Search the remaining part of the mole number vector, molNum for // the largest remaining species. Return its identity. kk is the raw // number. k is the orderVectorSpecies index. size_t kk = max_element(molNum.begin(), molNum.end()) - molNum.begin(); size_t j; for (j = 0; j < nspecies; j++) { if (orderVectorSpecies[j] == kk) { k = j; break; } } if (j == nspecies) { throw CanteraError("BasisOptimize", "orderVectorSpecies contains an error"); } if (molNum[kk] == 0.0) { *usedZeroedSpecies = true; } // If the largest molNum is negative, then we are done. if (molNum[kk] == USEDBEFORE) { nComponents = jr; nNonComponents = nspecies - nComponents; break; } // Assign a small negative number to the component that we have // just found, in order to take it out of further consideration. molSave = molNum[kk]; molNum[kk] = USEDBEFORE; // CHECK LINEAR INDEPENDENCE WITH PREVIOUS SPECIES // Modified Gram-Schmidt Method, p. 202 Dalquist // QR factorization of a matrix without row pivoting. size_t jl = jr; for (j = 0; j < ne; ++j) { size_t jj = orderVectorElements[j]; sm(j, jr) = mphase->nAtoms(kk,jj); } if (jl > 0) { // Compute the coefficients of JA column of the the upper // triangular R matrix, SS(J) = R_J_JR (this is slightly // different than Dalquist) R_JA_JA = 1 for (j = 0; j < jl; ++j) { ss[j] = 0.0; for (size_t i = 0; i < ne; ++i) { ss[j] += sm(i, jr) * sm(i, j); } ss[j] /= sa[j]; } // Now make the new column, (*,JR), orthogonal to the previous // columns for (j = 0; j < jl; ++j) { for (size_t i = 0; i < ne; ++i) { sm(i, jr) -= ss[j] * sm(i, j); } } } // Find the new length of the new column in Q. // It will be used in the denominator in future row calcs. sa[jr] = 0.0; for (size_t ml = 0; ml < ne; ++ml) { sa[jr] += pow(sm(ml, jr), 2); } // IF NORM OF NEW ROW .LT. 1E-3 REJECT if (sa[jr] > 1.0e-6) { break; } } // REARRANGE THE DATA if (jr != k) { if (BasisOptimize_print_lvl >= 1) { size_t kk = orderVectorSpecies[k]; writelogf(" --- %-12.12s", mphase->speciesName(kk)); size_t jj = orderVectorSpecies[jr]; writelogf("(%9.2g) replaces %-12.12s", molSave, mphase->speciesName(jj)); writelogf("(%9.2g) as component %3d\n", molNum[jj], jr); } std::swap(orderVectorSpecies[jr], orderVectorSpecies[k]); } // If we haven't found enough components, go back and find some more jr++; } if (! doFormRxn) { return nComponents; } // EVALUATE THE STOICHIOMETRY // // Formulate the matrix problem for the stoichiometric // coefficients. CX + B = 0 // // C will be an nc x nc matrix made up of the formula vectors for the // components. Each component's formula vector is a column. The rows are the // elements. // // n RHS's will be solved for. Thus, B is an nc x n matrix. // // BIG PROBLEM 1/21/99: // // This algorithm makes the assumption that the first nc rows of the formula // matrix aren't rank deficient. However, this might not be the case. For // example, assume that the first element in FormulaMatrix[] is argon. // Assume that no species in the matrix problem actually includes argon. // Then, the first row in sm[], below will be identically zero. bleh. // // What needs to be done is to perform a rearrangement of the ELEMENTS -> // i.e. rearrange, FormulaMatrix, sp, and gai, such that the first nc // elements form in combination with the nc components create an invertible // sm[]. not a small project, but very doable. // // An alternative would be to turn the matrix problem below into an ne x nc // problem, and do QR elimination instead of Gauss-Jordan elimination. // // Note the rearrangement of elements need only be done once in the problem. // It's actually very similar to the top of this program with ne being the // species and nc being the elements!! sm.resize(nComponents, nComponents); for (size_t k = 0; k < nComponents; ++k) { size_t kk = orderVectorSpecies[k]; for (size_t j = 0; j < nComponents; ++j) { size_t jj = orderVectorElements[j]; sm(j, k) = mphase->nAtoms(kk, jj); } } for (size_t i = 0; i < nNonComponents; ++i) { size_t k = nComponents + i; size_t kk = orderVectorSpecies[k]; for (size_t j = 0; j < nComponents; ++j) { size_t jj = orderVectorElements[j]; formRxnMatrix[j + i * ne] = - mphase->nAtoms(kk, jj); } } // // Use LU factorization to calculate the reaction matrix solve(sm, formRxnMatrix.data(), nNonComponents, ne); if (BasisOptimize_print_lvl >= 1) { writelog(" ---\n"); writelogf(" --- Number of Components = %d\n", nComponents); writelog(" --- Formula Matrix:\n"); writelog(" --- Components: "); for (size_t k = 0; k < nComponents; k++) { size_t kk = orderVectorSpecies[k]; writelogf(" %3d (%3d) ", k, kk); } writelog("\n --- Components Moles: "); for (size_t k = 0; k < nComponents; k++) { size_t kk = orderVectorSpecies[k]; writelogf("%-11.3g", molNumBase[kk]); } writelog("\n --- NonComponent | Moles | "); for (size_t i = 0; i < nComponents; i++) { size_t kk = orderVectorSpecies[i]; writelogf("%-11.10s", mphase->speciesName(kk)); } writelog("\n"); for (size_t i = 0; i < nNonComponents; i++) { size_t k = i + nComponents; size_t kk = orderVectorSpecies[k]; writelogf(" --- %3d (%3d) ", k, kk); writelogf("%-10.10s", mphase->speciesName(kk)); writelogf("|%10.3g|", molNumBase[kk]); // Print the negative of formRxnMatrix[]; it's easier to interpret. for (size_t j = 0; j < nComponents; j++) { writelogf(" %6.2f", - formRxnMatrix[j + i * ne]); } writelog("\n"); } writelog(" "); writeline('-', 77); } return nComponents; } // basopt()
void ElemRearrange(size_t nComponents, const vector_fp& elementAbundances, MultiPhase* mphase, std::vector<size_t>& orderVectorSpecies, std::vector<size_t>& orderVectorElements) { size_t nelements = mphase->nElements(); // Get the total number of species in the multiphase object size_t nspecies = mphase->nSpecies(); if (BasisOptimize_print_lvl > 0) { writelog(" "); writeline('-', 77); writelog(" --- Subroutine ElemRearrange() called to "); writelog("check stoich. coefficient matrix\n"); writelog(" --- and to rearrange the element ordering once\n"); } // Perhaps, initialize the element ordering if (orderVectorElements.size() < nelements) { orderVectorElements.resize(nelements); for (size_t j = 0; j < nelements; j++) { orderVectorElements[j] = j; } } // Perhaps, initialize the species ordering. However, this is dangerous, as // this ordering is assumed to yield the component species for the problem if (orderVectorSpecies.size() != nspecies) { orderVectorSpecies.resize(nspecies); for (size_t k = 0; k < nspecies; k++) { orderVectorSpecies[k] = k; } } // If the elementAbundances aren't input, just create a fake one based on // summing the column of the stoich matrix. This will force elements with // zero species to the end of the element ordering. vector_fp eAbund(nelements,0.0); if (elementAbundances.size() != nelements) { for (size_t j = 0; j < nelements; j++) { eAbund[j] = 0.0; for (size_t k = 0; k < nspecies; k++) { eAbund[j] += fabs(mphase->nAtoms(k, j)); } } } else { copy(elementAbundances.begin(), elementAbundances.end(), eAbund.begin()); } vector_fp sa(nelements,0.0); vector_fp ss(nelements,0.0); vector_fp sm(nelements*nelements,0.0); // Top of a loop of some sort based on the index JR. JR is the current // number independent elements found. size_t jr = 0; while (jr < nComponents) { // Top of another loop point based on finding a linearly independent // element size_t k = nelements; while (true) { // Search the element vector. We first locate elements that are // present in any amount. Then, we locate elements that are not // present in any amount. Return its identity in K. size_t kk; for (size_t ielem = jr; ielem < nelements; ielem++) { kk = orderVectorElements[ielem]; if (eAbund[kk] != USEDBEFORE && eAbund[kk] > 0.0) { k = ielem; break; } } for (size_t ielem = jr; ielem < nelements; ielem++) { kk = orderVectorElements[ielem]; if (eAbund[kk] != USEDBEFORE) { k = ielem; break; } } if (k == nelements) { // When we are here, there is an error usually. // We haven't found the number of elements necessary. if (BasisOptimize_print_lvl > 0) { writelogf("Error exit: returning with nComponents = %d\n", jr); } throw CanteraError("ElemRearrange", "Required number of elements not found."); } // Assign a large negative number to the element that we have // just found, in order to take it out of further consideration. eAbund[kk] = USEDBEFORE; // CHECK LINEAR INDEPENDENCE OF CURRENT FORMULA MATRIX // LINE WITH PREVIOUS LINES OF THE FORMULA MATRIX // Modified Gram-Schmidt Method, p. 202 Dalquist // QR factorization of a matrix without row pivoting. size_t jl = jr; // Fill in the row for the current element, k, under consideration // The row will contain the Formula matrix value for that element // with respect to the vector of component species. (note j and k // indices are flipped compared to the previous routine) for (size_t j = 0; j < nComponents; ++j) { size_t jj = orderVectorSpecies[j]; kk = orderVectorElements[k]; sm[j + jr*nComponents] = mphase->nAtoms(jj,kk); } if (jl > 0) { // Compute the coefficients of JA column of the the upper // triangular R matrix, SS(J) = R_J_JR (this is slightly // different than Dalquist) R_JA_JA = 1 for (size_t j = 0; j < jl; ++j) { ss[j] = 0.0; for (size_t i = 0; i < nComponents; ++i) { ss[j] += sm[i + jr*nComponents] * sm[i + j*nComponents]; } ss[j] /= sa[j]; } // Now make the new column, (*,JR), orthogonal to the // previous columns for (size_t j = 0; j < jl; ++j) { for (size_t i = 0; i < nComponents; ++i) { sm[i + jr*nComponents] -= ss[j] * sm[i + j*nComponents]; } } } // Find the new length of the new column in Q. // It will be used in the denominator in future row calcs. sa[jr] = 0.0; for (size_t ml = 0; ml < nComponents; ++ml) { double tmp = sm[ml + jr*nComponents]; sa[jr] += tmp * tmp; } // IF NORM OF NEW ROW .LT. 1E-6 REJECT if (sa[jr] > 1.0e-6) { break; } } // REARRANGE THE DATA if (jr != k) { if (BasisOptimize_print_lvl > 0) { size_t kk = orderVectorElements[k]; writelog(" --- "); writelogf("%-2.2s", mphase->elementName(kk)); writelog("replaces "); kk = orderVectorElements[jr]; writelogf("%-2.2s", mphase->elementName(kk)); writelogf(" as element %3d\n", jr); } std::swap(orderVectorElements[jr], orderVectorElements[k]); } // If we haven't found enough components, go back and find some more jr++; }; }
int inittanks() /* **--------------------------------------------------------------- ** Input: none ** Output: returns error code ** Purpose: initializes volumes in non-cylindrical tanks **--------------------------------------------------------------- */ { int i,j,n; float a; int errcode = 0, levelerr; for (j=1; j<=Ntanks; j++) { /* Skip reservoirs */ if (Tank[j].A == 0.0) continue; /* Check for valid lower/upper tank levels */ levelerr = 0; if (Tank[j].H0 > Tank[j].Hmax || Tank[j].Hmin > Tank[j].Hmax || Tank[j].H0 < Tank[j].Hmin ) levelerr = 1; /* Check that tank heights are within volume curve */ i = Tank[j].Vcurve; if (i > 0) { n = Curve[i].Npts - 1; if (Tank[j].Hmin < Curve[i].X[0] || Tank[j].Hmax > Curve[i].X[n] ) levelerr = 1; } /* Report error in levels if found */ if (levelerr) { sprintf(Msg,ERR225,Node[Tank[j].Node].ID); writeline(Msg); errcode = 200; } /* Else if tank has a volume curve, */ else if (i > 0) { /* Find min., max., and initial volumes from curve */ Tank[j].Vmin = interp(Curve[i].Npts,Curve[i].X, Curve[i].Y,Tank[j].Hmin); Tank[j].Vmax = interp(Curve[i].Npts,Curve[i].X, Curve[i].Y,Tank[j].Hmax); Tank[j].V0 = interp(Curve[i].Npts,Curve[i].X, Curve[i].Y,Tank[j].H0); /* Find a "nominal" diameter for tank */ a = (Curve[i].Y[n] - Curve[i].Y[0])/ (Curve[i].X[n] - Curve[i].X[0]); Tank[j].A = sqrt(4.0*a/PI); } } return(errcode); } /* End of inittanks */
int disconnected() /* **------------------------------------------------------------------- ** Input: None ** Output: Returns number of disconnected nodes ** Purpose: Tests current hydraulic solution to see if any closed ** links have caused the network to become disconnected. **------------------------------------------------------------------- */ { int i, j; int count, mcount; int errcode = 0; int *nodelist; char *marked; /* Allocate memory for node list & marked list */ nodelist = (int *) calloc(Nnodes+1,sizeof(int)); marked = (char *) calloc(Nnodes+1,sizeof(char)); ERRCODE(MEMCHECK(nodelist)); ERRCODE(MEMCHECK(marked)); if (errcode) return(0); /* Place tanks on node list and marked list */ for (i=1; i<=Ntanks; i++) { j = Njuncs + i; nodelist[i] = j; marked[j] = 1; } /* Place junctions with negative demands on the lists */ mcount = Ntanks; for (i=1; i<=Njuncs; i++) { if (D[i] < 0.0) { mcount++; nodelist[mcount] = i; marked[i] = 1; } } /* Mark all nodes that can be connected to tanks */ /* and count number of nodes remaining unmarked. */ marknodes(mcount,nodelist,marked); j = 0; count = 0; for (i=1; i<=Njuncs; i++) { if (!marked[i] && D[i] != 0.0) /* Skip if no demand */ { count++; if (count <= MAXCOUNT && Messageflag) { sprintf(Msg,WARN03a,Node[i].ID,clocktime(Atime,Htime)); writeline(Msg); } j = i; /* Last unmarked node */ } } /* Report number of unmarked nodes and find closed link */ /* on path from node j back to a tank. */ if (count > 0 && Messageflag) { if (count > MAXCOUNT) { sprintf(Msg, WARN03b, count-MAXCOUNT, clocktime(Atime,Htime)); writeline(Msg); } getclosedlink(j,marked); } /* Free allocated memory */ free(nodelist); free(marked); return(count); } /* End of disconnected() */
int writehydwarn(int iter, double relerr) /* **-------------------------------------------------------------- ** Input: iter = # iterations to find hydraulic solution ** Output: warning flag code ** Purpose: writes hydraulic warning message to report file ** ** Note: Warning conditions checked in following order: ** 1. System balanced but unstable ** 2. Negative pressures ** 3. FCV cannot supply flow or PRV/PSV cannot maintain pressure ** 4. Pump out of range ** 5. Network disconnected ** 6. System unbalanced **-------------------------------------------------------------- */ { int i,j; char flag = 0; char s; //(2.00.11 - LR) /* Check if system unstable */ if (iter > MaxIter && relerr <= Hacc) { sprintf(Msg,WARN02,clocktime(Atime,Htime)); if (Messageflag) writeline(Msg); flag = 2; } /* Check for negative pressures */ for (i=1; i<=Njuncs; i++) { if (H[i] < Node[i].El && D[i] > 0.0) { sprintf(Msg,WARN06,clocktime(Atime,Htime)); if (Messageflag) writeline(Msg); flag = 6; break; } } /* Check for abnormal valve condition */ for (i=1; i<=Nvalves; i++) { j = Valve[i].Link; if (S[j] >= XFCV) { sprintf(Msg,WARN05,LinkTxt[Link[j].Type],Link[j].ID, StatTxt[S[j]],clocktime(Atime,Htime)); if (Messageflag) writeline(Msg); flag = 5; } } /* Check for abnormal pump condition */ for (i=1; i<=Npumps; i++) { j = Pump[i].Link; s = S[j]; //(2.00.11 - LR) if (S[j] >= OPEN) //(2.00.11 - LR) { //(2.00.11 - LR) if (Q[j] > K[j]*Pump[i].Qmax) s = XFLOW; //(2.00.11 - LR) if (Q[j] < 0.0) s = XHEAD; //(2.00.11 - LR) } //(2.00.11 - LR) if (s == XHEAD || s == XFLOW) //(2.00.11 - LR) { sprintf(Msg,WARN04,Link[j].ID,StatTxt[s], //(2.00.11 - LR) clocktime(Atime,Htime)); if (Messageflag) writeline(Msg); flag = 4; } } /* Check if system is unbalanced */ if (iter > MaxIter && relerr > Hacc) { sprintf(Msg,WARN01,clocktime(Atime,Htime)); if (ExtraIter == -1) strcat(Msg,t_HALTED); if (Messageflag) writeline(Msg); flag = 1; } /* Check for disconnected network */ /* & update global warning flag */ if (flag > 0) { disconnected(); Warnflag = flag; } return(flag); } /* End of writehydwarn */
int main (int argc, char *argv[]) { char sname[40], line[256], writebuf[256]; char config_file[MAX_PATH_LEN]; quitflag = 0; NATEMODE = 0; starttime = time (NULL); /* parse command args here */ config_read(CONFIG_FILE); #ifndef NOFORK if (fork ()) exit (0); #endif signal (SIGHUP, (void *) gotsignal); signal (SIGINT, (void *) gotsignal); signal (SIGILL, (void *) gotsignal); signal (SIGFPE, (void *) gotsignal); signal (SIGBUS, (void *) gotsignal); #if 0 signal (SIGSEGV, (void *) gotsignal); #endif signal (SIGPIPE, (void *) gotsignal); signal (SIGTERM, (void *) gotsignal); signal (SIGUSR1, (void *) gotsignal); signal (SIGUSR2, (void *) gotsignal); signal (SIGWINCH, (void *) (gotsignal2)); /* heehee */ if ((ssock = open ("/dev/tty", O_RDONLY)) >= 0) { ioctl (ssock, TIOCNOTTY); close (ssock); } srandom ((unsigned) time (NULL)); getpush = 1; readusers (); strcpy (sname, DEFAULTSERVER); strcpy (mynick, DEFAULTNICK); strcpy (mychan, HOMECHAN); setbuf (stdout, NULL); setbuf (stderr, NULL); setjmp (my_env); #ifdef DEBUG printf ("Setup environment stuff\n"); #endif /* DEBUG */ do { if ((ssock = connectserver (sname)) < 0) { sleep (60); } else { #ifdef DEBUG printf ("Connected to server %s\n", sname); #endif /* DEBUG */ writeline ("PING td0"); #ifdef DEBUG printf ("Sent PING\n"); #endif readline (line); #ifdef DEBUG printf ("Received PONG\n"); #endif /* DEBUG */ sprintf(writebuf, "USER %s * * :%s", LOGINNAME, IRCUSER); writeline(writebuf); nick (mynick); sprintf (line, "MODE %s +i", mynick); writeline (line); join (mychan); setjmp (my_env2); waitforstuff (); #ifdef DEBUG printf (stderr, "Connection got closed!\n"); #endif close (ssock); } } while (!quitflag); #ifdef DEBUG printf ("Boom, I'm dead!\n"); #endif /* DEBUG */ close (ssock); checkufile(); exit (0); }
int handle_offline (int cli_sd) { char * in_buf; struct pfsd_sd * prev; struct pfsd_sd * next; char sd_id [PFS_ID_LEN]; uint8_t tun_conn; in_buf = readline (cli_sd); if (in_buf == NULL) goto error; tun_conn = (uint8_t) atoi (in_buf); free (in_buf); in_buf = readline (cli_sd); if (in_buf == NULL) goto error; sprintf (sd_id, in_buf, PFS_ID_LEN); free (in_buf); /* Received an sd disconnection, we remove it */ pfs_mutex_lock (&pfsd->sd_lock); prev = NULL; next = pfsd->sd; while (next != NULL) { if (strncmp (sd_id, next->sd_id, PFS_ID_LEN) == 0 && tun_conn == next->tun_conn) { #ifdef DEBUG printf ("*** HANDLE_OFFLINE : %s:%s : %.*s ", next->sd_owner, next->sd_name, PFS_ID_LEN, next->sd_id); if (next->tun_conn == LAN_CONN) printf ("(LAN:"); if (next->tun_conn == BTH_CONN) printf ("(BTH:"); printf ("%d)\n", next->tun_port); #endif if (prev == NULL) { pfsd->sd = next->next; free (next); next = pfsd->sd; pfsd->sd_cnt --; continue; } else { prev->next = next->next; free (next); next = prev->next; pfsd->sd_cnt --; continue; } } prev = next; next = next->next; } pfs_mutex_unlock (&pfsd->sd_lock); writeline (cli_sd, OK, strlen (OK)); return 0; error: return -1; }
/** * Internal send_command implementation. * Doesn't lock or call the timeout callback. * * timeoutMsec == 0 means infinite timeout. */ static int at_send_command_full_nolock (const char *command, ATCommandType type, const char *responsePrefix, const char *smspdu, long long timeoutMsec, ATResponse **pp_outResponse) { int err = AT_NOERROR; struct atcontext *ac = getAtContext(); /* Default to NULL, to allow caller to free securely even if * no response will be set below */ if (pp_outResponse != NULL) *pp_outResponse = NULL; /* FIXME This is to prevent future problems due to calls from other threads; should be revised. */ while (pthread_mutex_trylock(&ac->requestmutex) == EBUSY) pthread_cond_wait(&ac->requestcond, &ac->commandmutex); if(ac->response != NULL) { err = AT_ERROR_COMMAND_PENDING; goto finally; } ac->type = type; ac->responsePrefix = responsePrefix; ac->smsPDU = smspdu; ac->response = at_response_new(); if (ac->response == NULL) { err = AT_ERROR_MEMORY_ALLOCATION; goto finally; } err = writeline (command); if (err != AT_NOERROR) goto finally; while (ac->response->finalResponse == NULL && ac->readerClosed == 0) { if (timeoutMsec != 0) err = pthread_cond_timeout_np(&ac->commandcond, &ac->commandmutex, timeoutMsec); else err = pthread_cond_wait(&ac->commandcond, &ac->commandmutex); if (err == ETIMEDOUT) { err = AT_ERROR_TIMEOUT; goto finally; } } if (ac->response->success == 0) { err = at_get_error(ac->response); } if (pp_outResponse == NULL) at_response_free(ac->response); else { /* Line reader stores intermediate responses in reverse order. */ reverseIntermediates(ac->response); *pp_outResponse = ac->response; } ac->response = NULL; if(ac->readerClosed > 0) { err = AT_ERROR_CHANNEL_CLOSED; goto finally; } finally: clearPendingCommand(); pthread_cond_broadcast(&ac->requestcond); pthread_mutex_unlock(&ac->requestmutex); return err; }
int handle_updt (int cli_sd) { struct pfs_updt * updt = NULL; char * file_path = NULL; char * in_buf; int len; int b_done; int b_left; int b_tot; int fd; char buf[4096]; int retval; struct stat st_buf; int progress; updt = net_read_updt (cli_sd); if (updt == NULL) goto error; /* Do we need data. */ if (updt->ver->type == PFS_DIR) { file_path = pfs_mk_dir_path (pfsd->pfs, updt->ver->dst_id); if (stat (file_path, &st_buf) != 0) pfs_create_dir_with_id (pfsd->pfs, updt->ver->dst_id); free (file_path); file_path = NULL; goto done; } if (updt->ver->type == PFS_SML || updt->ver->type == PFS_FIL) { file_path = pfs_mk_file_path (pfsd->pfs, updt->ver->dst_id); if (stat (file_path, &st_buf) == 0) { free (file_path); goto done; } } else goto done; writeline (cli_sd, GET_DATA, strlen (GET_DATA)); in_buf = readline (cli_sd); if (in_buf == NULL) goto error; len = atoi (in_buf); free (in_buf); if ((fd = open (file_path, O_CREAT | O_WRONLY | O_APPEND | O_TRUNC)) < 0) goto error; fchmod (fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); b_left = len; b_done = 0; b_tot = len; len = 1; progress = 0; while (b_left > 0 && len > 0) { len = read (cli_sd, buf, ((b_left > 4096) ? 4096 : b_left)); writen (fd, buf, len); b_done += len; b_left -= len; if (((b_done * 100) / b_tot) >= (progress + 10) || ((b_done * 100) / b_tot) == 100) { progress = (b_done * 100) / b_tot; #ifdef DEBUG printf ("*** RCVD %s : %d/100\n", updt->name, progress); #endif } sprintf (buf, "%d", b_done); writeline (cli_sd, buf, strlen (buf)); } if (b_left != 0) { close (fd); unlink (file_path); goto error; } close (fd); free (file_path); file_path = NULL; done: retval = pfs_set_entry (pfsd->pfs, updt->grp_id, updt->dir_id, updt->name, updt->reclaim, updt->ver, 1); if (retval != 0 && retval != -2) { goto error; } pfs_free_updt (updt); writeline (cli_sd, OK, strlen (OK)); return 0; error: if (updt != NULL) pfs_free_updt (updt); if (file_path != NULL) free (file_path); return -1; }
void mastermind(int sd) /* Die Spiel-Funktion */ { int rc; int play; char buffer[MAXLEN]; char playername[MAXLEN]; char tmp[MAXLEN]; char opponentplayer[MAXLEN]; char secret[MAXLEN]; fd_set bereit; int gamerounds; /* stdout ungepuffert, damit write(1,..) und printf() genutzt werden können */ setbuf(stdout, NULL); printf("Client gestartet\n"); if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { perror("signal SIGPIPE"); exit(1); } /* Warten auf den Start der Kommunikation */ while(1) { struct timeval zeit; FD_ZERO(&bereit); FD_SET( sd, &bereit); /* Aktualisierungsintervall */ zeit.tv_sec = 0; zeit.tv_usec = 500000; rc = select(sd + 1, &bereit, NULL, NULL, &zeit); if (rc < 0) { if (errno != EINTR) { perror("select"); exit(1); } continue; } if (rc == 0) { write(1, ".", 1); continue; } printf("\n"); break; } /* Der Socket ist nun bereit zur Kommunikation */ /* Begrüßung vom Server empfangen */ if(empfangen(sd, buffer, MAXLEN) <= 0) { exit(1); } /* Auf Fehler überprüfen */ if (strcasecmp(buffer, "hallo\n") != 0) { perror("No Hallo"); exit(1); } /* Ausgabe auf Bildschirm */ writeline(1, buffer); /* Hallo mit ok bestätigen */ ok(sd); printf("Bitte einen Spielernamen angeben: "); while(1) { fd_set bereit; FD_ZERO(&bereit); FD_SET( 0, &bereit); FD_SET(sd, &bereit); rc = select(MAX( 0, sd) + 1 , &bereit, NULL, NULL, NULL); if (rc < 0) { if (errno == EINTR) continue; perror("select"); exit(1); } if (rc == 0) continue; if (FD_ISSET(sd, &bereit)) { /* Erst einmal empfangen (kann auch EOF sein!) */ if (empfangen( sd, buffer, MAXLEN) <= 0) { /* Server ist nicht mehr erreichbar - Ende der Kommunikation */ break; } if (strcasecmp(buffer, "quit\n") == 0) { exit(1); } if ( write(1, buffer, strlen(buffer)) < 0 ) { perror("write"); exit(1); } continue; } if (FD_ISSET(0, &bereit)) { /* von Eingabe lesen */ rc = readline(0, buffer, MAXLEN-1); if (rc < 0) { /* Fehler -> Ausgabe */ perror("readline"); exit(1); } *(buffer+rc) = (char) 0; /* String erstellen */ /* Prüfen ob gültiger Name eingegeben wurde */ /* Prüfen ob quit eingegeben wurde */ if (strcasecmp(buffer, "quit\n") == 0) { printf("Bitte einen gültigen Spielernamen angeben: "); continue; } /* Prüfen auf Länge */ if (strlen(buffer) == 1) { printf("Bitte einen gültigen Spielernamen angeben: "); continue; } /* Prüfen auf blanks im Namen */ if( sscanf(buffer,"%s%s", playername, tmp) != 1) { printf("Bitte einen gültigen Spielernamen angeben: "); continue; } printf("Angegebener Name: %s", playername); /* Namen senden */ str_senden(sd, "NAME: ", playername, rc); break; } } /* Warten auf "OK" vom Server (Gegenspieler) */ waitforserverreply(sd,1); if(empfangen(sd, buffer, MAXLEN) <= 0) { exit(1); } /* Auf Fehler überprüfen */ if (strcasecmp(buffer, "ok\n") != 0) { perror("not OK"); exit(1); } /* Warten auf Gegenspielername */ waitforserverreply(sd,0); if(empfangen(sd, buffer, MAXLEN) <= 0) { exit(1); } /* Auf Fehler überprüfen */ if (strncasecmp(buffer, "name:", 5) != 0) { perror("not name"); exit(1); } /* mit "OK" bestaetigen */ ok(sd); /* Speichern des Gegenspielernamens */ if( sscanf(buffer, "%*s %s", opponentplayer) < 0) { perror("not name"); exit(1); } /* Namen des Gegenspielers ausgeben */ printf("Dein Gegenspieler heisst: %s\n", opponentplayer); /* Warten auf Anzahl der Runden */ waitforserverreply(sd,0); if(empfangen(sd, buffer, MAXLEN) <= 0) { exit(1); } /* Auf Fehler überprüfen */ if (strncasecmp(buffer, "runden:", 5) != 0) { perror("not rounds"); exit(1); } /* mit "OK" bestaetigen */ ok(sd); /* Speichern der Rundenzahl */ if( sscanf(buffer, "%*s %d", &gamerounds) < 0) { perror("not rounds"); exit(1); } /* dem Spieler die Rundenanzahl mitteilen */ printf("Es sind %d Runden angesetzt.\n", gamerounds); /* Geheimzahl einlesen */ printf("Bitte geben Sie eine 4-stellige Geheimzahl ein: "); /* Die 1. Runde beginnt hier */ play = 1; while(play) { while(1) { fd_set bereit; FD_ZERO(&bereit); FD_SET( 0, &bereit); FD_SET(sd, &bereit); rc = select(MAX( 0, sd) + 1 , &bereit, NULL, NULL, NULL); if (rc < 0) { if (errno == EINTR) continue; perror("select"); exit(1); } if (rc == 0) continue; if (FD_ISSET(sd, &bereit)) { /* Erst einmal empfangen (kann auch EOF sein!) */ if (empfangen( sd, buffer, MAXLEN) <= 0) { /* Server ist nicht mehr erreichbar - Ende der Kommunikation */ break; } if (strcasecmp(buffer, "quit\n") == 0) { exit(1); } if ( write(1, buffer, strlen(buffer)) < 0 ) { perror("write"); exit(1); } continue; } if (FD_ISSET(0, &bereit)) { rc = readline(0, secret, 5); if (rc < 0) { /* Fehler -> Ausgabe */ perror("readline"); exit(1); } /* War die Eingabe eine Zahl? */ if ( secret[4] != '\n' ) { printf("Das war keine 4-stellige Zahl!"); printf("Bitte geben Sie eine 4-stellige Geheimzahl ein: "); continue; } } printf("ok\n"); *(secret+rc-1) = (char) 0; /* String erstellen */ if (strcasecmp(secret, "quit\n") == 0) break; /* Geheimzahl senden */ str_senden(sd, "GEHEIMZAHL: ", secret, rc); /* Fehlerabfrage keine Zahl?*/ break; } waitforserverreply(sd,1); if(empfangen(sd, buffer, MAXLEN) <= 0) { exit(1); } printf("%s\n",buffer); if (strcasecmp(buffer, "ok\n") != 0) { perror("not ok"); exit(1); } waitforserverreply(sd,0); if(empfangen(sd, buffer, MAXLEN) <= 0) { exit(1); } printf("%s\n",buffer); if (strcasecmp(buffer, "start\n") != 0) { perror("not start"); exit(1); } printf("ok start\n"); /* mit "OK" bestaetigen */ ok(sd); printf("ok ok\n"); play = runde(sd); } }
int handle_add_sd (int cli_sd) { char * in_buf; char sd_owner[PFS_NAME_LEN]; char sd_name[PFS_NAME_LEN]; char grp_id [PFS_ID_LEN]; char grp_name [PFS_NAME_LEN]; char sd_id [PFS_ID_LEN]; int tun_port = -1; uint8_t tun_conn = 100; struct pfsd_sd * sd; int tun_sd = -1; struct hostent *he; struct sockaddr_in tun_addr; memset (grp_name, 0, PFS_NAME_LEN); in_buf = readline (cli_sd); if (in_buf == NULL) goto error; strncpy (grp_name, in_buf, PFS_NAME_LEN); free (in_buf); memset (sd_owner, 0, PFS_NAME_LEN); in_buf = readline (cli_sd); if (in_buf == NULL) goto error; strncpy (sd_owner, in_buf, PFS_NAME_LEN); free (in_buf); memset (sd_name, 0, PFS_NAME_LEN); in_buf = readline (cli_sd); if (in_buf == NULL) goto error; strncpy (sd_name, in_buf, PFS_NAME_LEN); free (in_buf); /* Go fetch the grp_id. */ if (pfs_get_grp_id (pfsd->pfs, grp_name, grp_id) != 0) goto error; /* Go fetch the id. */ pfs_mutex_lock (&pfsd->sd_lock); sd = pfsd->sd; while (sd != NULL) { if (strncmp (sd_owner, sd->sd_owner, PFS_NAME_LEN) == 0 && strncmp (sd_name, sd->sd_name, PFS_NAME_LEN) == 0 && sd->tun_conn < tun_conn) { tun_port = sd->tun_port; tun_conn = sd->tun_conn; strncpy (sd_id, sd->sd_id, PFS_ID_LEN); } sd = sd->next; } if (tun_port == -1) { pfs_mutex_unlock (&pfsd->sd_lock); goto error; } pfs_mutex_unlock (&pfsd->sd_lock); /* * We try to connect to the sd. */ if ((tun_sd = socket (AF_INET, SOCK_STREAM, 0)) < 0) goto error; if ((he = gethostbyname ("localhost")) == NULL) goto error; bzero (&tun_addr, sizeof (tun_addr)); tun_addr.sin_family = AF_INET; tun_addr.sin_port = htons (tun_port); tun_addr.sin_addr = *((struct in_addr *) he->h_addr); if (connect(tun_sd, (struct sockaddr *)&tun_addr, sizeof (tun_addr)) < 0) goto error; in_buf = readline (tun_sd); if (in_buf == NULL) goto error; if (strcmp (in_buf, OK) != 0) goto error; free (in_buf); writeline (tun_sd, ADD_GRP, strlen (ADD_GRP)); writeline (tun_sd, grp_name, strlen (grp_name)); writeline (tun_sd, grp_id, PFS_ID_LEN); writeline (tun_sd, pfsd->pfs->sd_id, PFS_ID_LEN); if (pfs_group_add_sd (pfsd->pfs, grp_id, sd_id, sd_owner, sd_name) != 0) goto error; /* * We do not propagate data here. * For now we keep all log updates. */ /* * We update the remote grp_sate. */ in_buf = readline (tun_sd); if (in_buf == NULL) goto error; if (strcmp (in_buf, GRP_STAT) != 0) { free (in_buf); goto error; } free (in_buf); handle_grp_stat (tun_sd); in_buf = readline (tun_sd); if (in_buf == NULL) goto error; if (strcmp (in_buf, OK) != 0) { free (in_buf); goto error; } free (in_buf); writeline (tun_sd, CLOSE, strlen (CLOSE)); close (tun_sd); /* We add the sd to our local state. */ pfsd->update = 1; writeline (cli_sd, OK, strlen (OK)); return 0; error: if (tun_sd != -1) close (tun_sd); return -1; }
int readdata() /* **-------------------------------------------------------------- ** Input: none ** Output: returns error code ** Purpose: reads contents of input data file **-------------------------------------------------------------- */ { char line[MAXLINE+1], /* Line from input data file */ wline[MAXLINE+1]; /* Working copy of input line */ int sect,newsect, /* Data sections */ errcode = 0, /* Error code */ inperr,errsum; /* Error code & total error count */ /* Allocate input buffer */ X = (double *) calloc(MAXTOKS, sizeof(double)); ERRCODE(MEMCHECK(X)); if (!errcode) { /* Initialize number of network components */ Ntitle = 0; Nnodes = 0; Njuncs = 0; Ntanks = 0; Nlinks = 0; Npipes = 0; Npumps = 0; Nvalves = 0; Ncontrols = 0; Nrules = 0; Ncurves = MaxCurves; Npats = MaxPats; PrevPat = NULL; PrevCurve = NULL; sect = -1; errsum = 0; /* Read each line from input file. */ while (fgets(line,MAXLINE,InFile) != NULL) { /* Make copy of line and scan for tokens */ strcpy(wline,line); Ntokens = gettokens(wline); /* Skip blank lines and comments */ if (Ntokens == 0) continue; if (*Tok[0] == ';') continue; /* Check if max. length exceeded */ if (strlen(line) >= MAXLINE) { sprintf(Msg,ERR214); writeline(Msg); writeline(line); errsum++; } /* Check if at start of a new input section */ if (*Tok[0] == '[') { newsect = findmatch(Tok[0],SectTxt); if (newsect >= 0) { sect = newsect; if (sect == _END) break; continue; } else { inperrmsg(201,sect,line); errsum++; break; } } /* Otherwise process next line of input in current section */ else { inperr = newline(sect,line); if (inperr > 0) { inperrmsg(inperr,sect,line); errsum++; } } /* Stop if reach end of file or max. error count */ if (errsum == MAXERRS) break; } /* End of while */ /* Check for errors */ if (errsum > 0) errcode = 200; } /* Check for unlinked nodes */ if (!errcode) errcode = unlinked(); /* Get pattern & curve data from temp. lists */ if (!errcode) errcode = getpatterns(); if (!errcode) errcode = getcurves(); if (!errcode) errcode = getpumpparams(); /* Free input buffer */ free(X); return(errcode); } /* End of readdata */
void * handle_client (void * sd_arg) { int cli_sd; int ret; fd_set fdmask; struct timeval timeout; char * buf; cli_sd = ((struct sd_arg *) sd_arg)->sd; free (sd_arg); while (1) { /* Handle timeouts. */ FD_ZERO(&fdmask); FD_SET(cli_sd, &fdmask); timeout.tv_sec = 0; timeout.tv_usec = TIMEOUT; ret = select (cli_sd + 1, &fdmask, NULL, NULL, &timeout); if (ret == 0) goto done; buf = readline (cli_sd); if (buf == NULL) goto error; if (strcmp (GRP_STAT, buf) == 0) { #ifdef DEBUG printf ("*** HANDLE_CLIENT : cmd %s\n", GRP_STAT); #endif if (handle_grp_stat (cli_sd) != 0) goto error; } else if (strcmp (ONLINE, buf) == 0) { if (handle_online (cli_sd) != 0) goto error; } else if (strcmp (OFFLINE, buf) == 0) { if (handle_offline (cli_sd) != 0) goto error; } else if (strcmp (UPDT, buf) == 0) { #ifdef DEBUG printf ("*** HANDLE_CLIENT : cmd %s\n", UPDT); #endif if (handle_updt (cli_sd) != 0) goto error; } else if (strcmp (ADD_SD, buf) == 0) { #ifdef DEBUG printf ("*** HANDLE_CLIENT : cmd %s\n", ADD_SD); #endif if (handle_add_sd (cli_sd) != 0) goto error; } else if (strcmp (ADD_GRP, buf) == 0) { #ifdef DEBUG printf ("*** HANDLE_CLIENT : cmd %s\n", ADD_GRP); #endif if (handle_add_grp (cli_sd) != 0) goto error; } else if (strcmp (LIST_SD, buf) == 0) { #ifdef DEBUG printf ("*** HANDLE_CLIENT : cmd %s\n", LIST_SD); #endif if (handle_list_sd (cli_sd) != 0) goto error; } else if (strcmp (CREAT_GRP, buf) == 0) { #ifdef DEBUG printf ("*** HANDLE_CLIENT : cmd %s\n", CREAT_GRP); #endif if (handle_creat_grp (cli_sd) != 0) goto error; } else { free (buf); goto done; } free (buf); } error: writeline (cli_sd, ERROR, strlen (ERROR)); #ifdef DEBUG printf ("*** ERROR\n"); #endif close (cli_sd); done: return 0; }
int getcurves(void) /* **----------------------------------------------------------- ** Input: none ** Output: returns error code ** Purpose: retrieves curve data from temporary linked list **----------------------------------------------------------- */ { int i,j; double x; SFloatlist *fx, *fy; STmplist *c; /* Start at head of curve list */ c = Curvelist; /* Traverse list of curves */ while (c != NULL) { i = c->i; if (i >= 1 && i <= MaxCurves) { /* Save curve ID */ strcpy(Curve[i].ID, c->ID); /* Check that curve has data points */ if (Curve[i].Npts <= 0) { sprintf(Msg,ERR230,c->ID); writeline(Msg); return(200); } /* Allocate memory for curve data */ Curve[i].X = (double *) calloc(Curve[i].Npts, sizeof(double)); Curve[i].Y = (double *) calloc(Curve[i].Npts, sizeof(double)); if (Curve[i].X == NULL || Curve[i].Y == NULL) return(101); /* Traverse list of x,y data */ x = BIG; fx = c->x; fy = c->y; j = Curve[i].Npts - 1; while (fx != NULL && fy != NULL && j >= 0) { /* Check that x data is in ascending order */ if (fx->value >= x) { sprintf(Msg,ERR230,c->ID); writeline(Msg); return(200); } x = fx->value; /* Save x,y data in Curve structure */ Curve[i].X[j] = fx->value; fx = fx->next; Curve[i].Y[j] = fy->value; fy = fy->next; j--; } } c = c->next; } return(0); }
void VCS_PROB::prob_report(int print_lvl) { m_printLvl = print_lvl; // Printout the species information: PhaseID's and mole nums if (m_printLvl > 0) { writeline('=', 80, true, true); writeline('=', 20, false); plogf(" VCS_PROB: PROBLEM STATEMENT "); writeline('=', 31); writeline('=', 80); plogf("\n"); if (prob_type == 0) { plogf("\tSolve a constant T, P problem:\n"); plogf("\t\tT = %g K\n", T); double pres_atm = PresPA / 1.01325E5; plogf("\t\tPres = %g atm\n", pres_atm); } else { throw CanteraError("VCS_PROB::prob_report", "Unknown problem type"); } plogf("\n"); plogf(" Phase IDs of species\n"); plogf(" species phaseID phaseName "); plogf(" Initial_Estimated_Moles Species_Type\n"); for (size_t i = 0; i < nspecies; i++) { vcs_VolPhase* Vphase = VPhaseList[PhaseID[i]]; plogf("%16s %5d %16s", SpName[i], PhaseID[i], Vphase->PhaseName); if (iest >= 0) { plogf(" %-10.5g", w[i]); } else { plogf(" N/A"); } if (SpeciesUnknownType[i] == VCS_SPECIES_TYPE_MOLNUM) { plogf(" Mol_Num"); } else if (SpeciesUnknownType[i] == VCS_SPECIES_TYPE_INTERFACIALVOLTAGE) { plogf(" Voltage"); } else { plogf(" "); } plogf("\n"); } // Printout of the Phase structure information writeline('-', 80, true, true); plogf(" Information about phases\n"); plogf(" PhaseName PhaseNum SingSpec GasPhase " " EqnState NumSpec"); plogf(" TMolesInert TKmoles\n"); for (size_t iphase = 0; iphase < NPhase; iphase++) { vcs_VolPhase* Vphase = VPhaseList[iphase]; std::string EOS_cstr = string16_EOSType(Vphase->m_eqnState); plogf("%16s %5d %5d %8d ", Vphase->PhaseName, Vphase->VP_ID_, Vphase->m_singleSpecies, Vphase->m_gasPhase); plogf("%16s %8d %16e ", EOS_cstr, Vphase->nSpecies(), Vphase->totalMolesInert()); if (iest >= 0) { plogf("%16e\n", Vphase->totalMoles()); } else { plogf(" N/A\n"); } } plogf("\nElemental Abundances: "); plogf(" Target_kmol ElemType ElActive\n"); double fac = 1.0; if (m_VCS_UnitsFormat == VCS_UNITS_MKS) { fac = 1.0; } for (size_t i = 0; i < ne; ++i) { writeline(' ', 26, false); plogf("%-2.2s", ElName[i]); plogf("%20.12E ", fac * gai[i]); plogf("%3d %3d\n", m_elType[i], ElActive[i]); } plogf("\nChemical Potentials: "); if (m_VCS_UnitsFormat == VCS_UNITS_UNITLESS) { plogf("(unitless)"); } else if (m_VCS_UnitsFormat == VCS_UNITS_KCALMOL) { plogf("(kcal/gmol)"); } else if (m_VCS_UnitsFormat == VCS_UNITS_KJMOL) { plogf("(kJ/gmol)"); } else if (m_VCS_UnitsFormat == VCS_UNITS_KELVIN) { plogf("(Kelvin)"); } else if (m_VCS_UnitsFormat == VCS_UNITS_MKS) { plogf("(J/kmol)"); } plogf("\n"); plogf(" Species (phase) " " SS0ChemPot StarChemPot\n"); for (size_t iphase = 0; iphase < NPhase; iphase++) { vcs_VolPhase* Vphase = VPhaseList[iphase]; Vphase->setState_TP(T, PresPA); for (size_t kindex = 0; kindex < Vphase->nSpecies(); kindex++) { size_t kglob = Vphase->spGlobalIndexVCS(kindex); plogf("%16s ", SpName[kglob]); if (kindex == 0) { plogf("%16s", Vphase->PhaseName); } else { plogf(" "); } plogf("%16g %16g\n", Vphase->G0_calc_one(kindex), Vphase->GStar_calc_one(kindex)); } } writeline('=', 80, true, true); writeline('=', 20, false); plogf(" VCS_PROB: END OF PROBLEM STATEMENT "); writeline('=', 24); writeline('=', 80); plogf("\n"); } }
int VCS_SOLVE::vcs_elem_rearrange(double* const aw, double* const sa, double* const sm, double* const ss) { size_t ncomponents = m_numComponents; if (m_debug_print_lvl >= 2) { plogf(" "); writeline('-', 77); plogf(" --- Subroutine elem_rearrange() called to "); plogf("check stoich. coefficient matrix\n"); plogf(" --- and to rearrange the element ordering once\n"); } // Use a temporary work array for the element numbers // Also make sure the value of test is unique. bool lindep = true; double test = -1.0E10; while (lindep) { lindep = false; for (size_t i = 0; i < m_nelem; ++i) { test -= 1.0; aw[i] = m_elemAbundancesGoal[i]; if (test == aw[i]) { lindep = true; } } } // Top of a loop of some sort based on the index JR. JR is the current // number independent elements found. size_t jr = 0; while (jr < ncomponents) { size_t k; // Top of another loop point based on finding a linearly independent // species while (true) { // Search the remaining part of the mole fraction vector, AW, for // the largest remaining species. Return its identity in K. k = m_nelem; for (size_t ielem = jr; ielem < m_nelem; ielem++) { if (m_elementActive[ielem] && aw[ielem] != test) { k = ielem; break; } } if (k == m_nelem) { throw CanteraError("vcs_elem_rearrange", "Shouldn't be here. Algorithm misfired."); } // Assign a large negative number to the element that we have just // found, in order to take it out of further consideration. aw[k] = test; // CHECK LINEAR INDEPENDENCE OF CURRENT FORMULA MATRIX LINE WITH // PREVIOUS LINES OF THE FORMULA MATRIX // // Modified Gram-Schmidt Method, p. 202 Dalquist QR factorization of // a matrix without row pivoting. size_t jl = jr; // Fill in the row for the current element, k, under consideration // The row will contain the Formula matrix value for that element // from the current component. for (size_t j = 0; j < ncomponents; ++j) { sm[j + jr*ncomponents] = m_formulaMatrix(j,k); } if (jl > 0) { // Compute the coefficients of JA column of the the upper // triangular R matrix, SS(J) = R_J_JR (this is slightly // different than Dalquist) R_JA_JA = 1 for (size_t j = 0; j < jl; ++j) { ss[j] = 0.0; for (size_t i = 0; i < ncomponents; ++i) { ss[j] += sm[i + jr*ncomponents] * sm[i + j*ncomponents]; } ss[j] /= sa[j]; } // Now make the new column, (*,JR), orthogonal to the previous // columns for (size_t j = 0; j < jl; ++j) { for (size_t i = 0; i < ncomponents; ++i) { sm[i + jr*ncomponents] -= ss[j] * sm[i + j*ncomponents]; } } } // Find the new length of the new column in Q. It will be used in // the denominator in future row calcs. sa[jr] = 0.0; for (size_t ml = 0; ml < ncomponents; ++ml) { sa[jr] += pow(sm[ml + jr*ncomponents], 2); } // IF NORM OF NEW ROW .LT. 1E-6 REJECT if (sa[jr] > 1.0e-6) { break; } } // REARRANGE THE DATA if (jr != k) { if (m_debug_print_lvl >= 2) { plogf(" --- %-2.2s(%9.2g) replaces %-2.2s(%9.2g) as element %3d\n", m_elementName[k], m_elemAbundancesGoal[k], m_elementName[jr], m_elemAbundancesGoal[jr], jr); } vcs_switch_elem_pos(jr, k); std::swap(aw[jr], aw[k]); } // If we haven't found enough components, go back and find some more. jr++; } return VCS_SUCCESS; }
int StringFile::writeline(char *arg1, float arg2, int indent) { sprintf(string1, "%s %f\n", arg1, arg2); writeline(string1, indent); return 0; }
/*-------------------------------------------------------------------------- Function Name: hexout Purpose: Prints a number in base 16 to the parameter FILE stream Description: Goal is achieved via delegating to the baseout function. Input: number: the number to display. stream: where to display, likely stdout or stderr. Result: Number in base 16 is displayed. No return value. --------------------------------------------------------------------------*/ void hexout (unsigned int number, FILE * stream) { /* Output "0x" for hexidecimal. */ writeline ("0x", stream); baseout (number, HEX, stream); }
int StringFile::writeline(char *arg1, Freq arg2, int indent) { sprintf(string1, "%s %d\n", arg1, arg2.freq); writeline(string1, indent); return 0; }
int main (int argc, char *const* argv) { MyRec element; /* to store in the stack */ MyRec * retval; /* to retrieve from the stack */ Stack * main_stack; /* the list/stack to test */ int option; /* each command line option */ long command; /* stack command entered by user */ long status; /* return status of stack functions */ /* initialize debug states */ set_debug_off(); /* check command line options for debug display */ while ((option = getopt (argc, argv, "x")) != EOF) { switch (option) { case 'x': set_debug_on(); break; } } /* allocate and initialize */ main_stack = new_Stack(copy_MyRec, delete_MyRec, write_MyRec); while (1) { command = 0; /* initialize command, need for loops */ writeline ("\nThe commands are:\n"); writeline (" is(e)mpty, "); writeline ("(i)nsert, "); writeline ("(p)op, "); newline (); writeline (" (a)dvance pre, advance (n)ext, "); newline (); writeline (" (r)emove, "); writeline ("(t)op, "); writeline ("p(u)sh, (v)iew, "); newline (); writeline (" (w)rite, (W)rite_reverse,"); newline (); writeline ("\nPlease enter a command: "); command = fgetc (stdin); if (command == EOF) /* are we done? */ break; clrbuf (command); /* get rid of extra characters */ switch (command) { /* process commands */ case 'a': /* advance pre */ advance_pre_List (main_stack); break; case 'n': /* advance next */ advance_next_List (main_stack); break; case 'e': /* isempty */ if (isempty_Stack (main_stack)) writeline ("\nStack is empty."); else writeline ("\nStack is not empty."); break; case 'i': /* insert */ writeline ( "\nPlease enter a number to insert into list: "); element.xxx = decin (); clrbuf (0); /* get rid of extra characters */ status = insert (main_stack, &element, from_where ()); if (! status) fprintf (stderr, "\nWARNING: insert FAILED\n"); break; case 'p': /* pop */ retval = (MyRec *) pop (main_stack); if (! retval) fprintf (stderr, "\nWARNING: pop FAILED\n"); else { element = *retval; writeline ( "\nNumber popped from the stack is: "); write_MyRec (&element, stdout); delete_MyRec (&retval); } break; case 'r': /* remove */ retval = (MyRec *) remove_List (main_stack, from_where ()); if (! retval) fprintf (stderr, "\nWARNING: remove FAILED\n"); else { element = *retval; writeline ( "\nNumber removed from list is: "); write_MyRec (&element, stdout); delete_MyRec (&retval); } break; case 't': /* top */ retval = (MyRec *) top (main_stack); if (! retval) fprintf (stderr, "\nWARNING: top FAILED\n"); else { element = *retval; writeline ( "\nNumber at top of the stack is: "); write_MyRec (&element, stdout); } break; case 'u': /* push */ writeline ( "\nPlease enter a number to push to stack: "); element.xxx = decin (); clrbuf (0); /* get rid of extra characters */ status = push (main_stack, &element); if (! status) fprintf (stderr, "\nWARNING: push FAILED\n"); break; case 'v': /* view */ retval = (MyRec *) view (main_stack, from_where ()); if (! retval) fprintf (stderr, "\nWARNING: view FAILED\n"); else { element = *retval; writeline ( "\nNumber viewed from the list is: "); write_MyRec (&element, stdout); } break; case 'w': /* write */ writeline ("\nThe Stack contains:\n"); write_Stack (main_stack, stderr); newline (); break; case 'W': /* write */ writeline ("\nThe Stack contains (in reverse):\n"); write_reverse_List (main_stack, stderr); newline (); break; } } delete_Stack (&main_stack); /* deallocate stack */ newline (); return 0; }
void writelinktable(Pfloat *x) /* **--------------------------------------------------------------- ** Input: x = pointer to link results for current time ** Output: none ** Purpose: writes link results for current time to report file **--------------------------------------------------------------- */ { int i,j,k; char s[MAXLINE+1],s1[16]; double y[MAXVAR]; /* Write table header */ writeheader(LINKHDR,0); /* For each link: */ for (i=1; i<=Nlinks; i++) { /* Place results for each link variable in y */ y[LENGTH] = Link[i].Len*Ucf[LENGTH]; y[DIAM] = Link[i].Diam*Ucf[DIAM]; for (j=FLOW; j<=FRICTION; j++) y[j] = *((x[j-FLOW])+i); /* Check if link gets reported on */ if ((Linkflag == 1 || Link[i].Rpt) && checklimits(y,DIAM,FRICTION)) { /* Check if new page needed */ if (LineNum == (long)PageSize) writeheader(LINKHDR,1); /* Add link ID and each reported field to string s */ sprintf(s,"%-15s",Link[i].ID); for (j=LENGTH; j<=FRICTION; j++) { if (Field[j].Enabled == TRUE) { if (j == STATUS) { if (y[j] <= CLOSED) k = CLOSED; else if (y[j] == ACTIVE) k = ACTIVE; else k = OPEN; sprintf(s1, "%10s", StatTxt[k]); } /*** Updated 6/24/02 ***/ else { if (fabs(y[j]) > 1.e6) sprintf(s1, "%10.2e", y[j]); else sprintf(s1, "%10.*f", Field[j].Precision, y[j]); } /*** End of update ***/ strcat(s, s1); } } /* Note if link is a pump or valve */ if ( (j = Link[i].Type) > PIPE) { strcat(s, " "); strcat(s, LinkTxt[j]); } /* Write results for link */ writeline(s); } } writeline(" "); }