void run_cmd(char *cmdLine, int mode) { char *histCmd; int redirect_status; int loopback = 0; start: histCmd = strdup(cmdLine); redirect_status = check_redirection(cmdLine); if (redirect_status == REDIR_ERROR) { if (mode == BATCH_MODE) { display_full_command(histCmd); } printError(); free(cmdLine); free(histCmd); return; } char **shArgv = parseInput(cmdLine); if (mode == BATCH_MODE && shArgv[0] != NULL && loopback == 0) { display_full_command(histCmd); } int builtin = is_builtin(shArgv); if (builtin != -1 && redirect_status == REDIR_OK_REDIR) { printError(); free(cmdLine); free(shArgv); free(histCmd); return; } if(builtin == 2) { int isValid = check_re_exec(shArgv); if(isValid) { free(cmdLine); free(shArgv); free(histCmd); cmdLine = strdup(re_exec_cmd); free(re_exec_cmd); loopback = 1; goto start; } else { printError(); free(cmdLine); free(shArgv); free(histCmd); return; } } if(shArgv[0] != NULL) { add_cmd(histCmd); if(do_builtin(shArgv)) { free(histCmd); free(cmdLine); free(shArgv); return; } else { do_execute(shArgv, redirect_status == REDIR_OK_REDIR ? 1 : 0, redir_file); } } free(cmdLine); free(shArgv); free(histCmd); }
void P::buildText( Cell* cell ) { cell->addByte( 0xFA ); if( cell->textFull() ) printError( ERR1_LARGEPAGE ); }
RootNodeT * buildTree(int N, MatrixT Dorig, char **taxon) { /* \section{Initialize} Initialize main variables */ int i; RootNodeT *root; int Nleft, Nnext; /* number of Nodes left to be joined and the next index to be used */ MatrixT b=matrix(N); /* the $b_{i;j}$ matrix (eq 0.7) */ /* $q(i)$ array: value which minimizes $R(i,q(i),j)\,\forall j\ne i,q(i)$ */ int *q; int *q2; /* Second best value */ VectorT R=vector(N); /* $R(i,q(i))$ (eq 0.10) */ VectorT LLR=vector(N); /* $R(i,q(i),q2(i))$ */ VectorT Zscore=vector(N); /* $z(i,q(i))$ */ /* This auxilary matrices are globally defined in \|weighbor.h| we do this to make it simplier so we do not always have to pass these around. Note that the need to be visible here as we will be calling \|calcR| later in this function and \|calcR| needs these values */ s = matrix(N); /* $s_{ij}$ eq 0.9 */ deltaB = matrix(N); /* $\Delta b_{ij}$ eq 0.8 */ delta2B = matrix(N); /* $\Delta^2 b_{ij}$ */ if(recalcB) oldDeltaB = matrix(N); /* This will hold this orignal $N$ distances plus any distances from the $N-3$ internal nodes. Note we do not care about the root node so $N-3$ and not $N-2$ */ mD=matrix(2*N-3); /* This is the renormalization vector $c_i$ (eq 0.39) and matrix $c_{i;j}$ (eq 0.43 ver0.2.5); again it must be large enough to hold both the original and the new joined taxa N.B. \|vector| sets all elements to zero. */ vC=vector(2*N-3); /* This matrices hold the previous iterations values of $s_{ij}$, $\Delta b_{ij}$, etc. They are used to speed up the next iterations calcultions of these quantities. */ mS = matrix(2*N-3); mDelB = matrix(2*N-3); mDel2B = matrix(2*N-3); /* Init \|mS| to -1 to keep track of which entries have not yet been computed. */ for(i=0;i<2*N-3;++i) { int j; for(j=0;j<2*N-3;++j) mS[i][j] = -1.0; } /* Make a copy of the original distance matrix; embed it in the larger matrix which will hold the new distance from the added internal nodes of the tree. */ setMM(N, Dorig, mD); /* Allocate and initialize the \|q|, \|q2| and \|nodes| array. $2N-3$ nodes to hold both the original and the added nodes. */ q = (int *)malloc(N*sizeof(int)); if(!q) printError("build::buildTree:out of memory-q\n"); q2 = (int *)malloc(N*sizeof(int)); if(!q2) printError("build::buildTree:out of memory-q2\n"); nodes = (NodeT **)malloc( (2*N-3)*sizeof(NodeT *)); if(!nodes) printError("build::buildTree:out of memory-nodes"); for(i=0;i<N;++i) { nodes[i] = createNode(); nodes[i]->name = taxon[i]; nodes[i]->ind = i; } Nleft = N; Nnext = N; /* \section{Loop until 3 taxa left} While we have more than 3 nodes left do the neighbor joining algorithm. Each pass of the algorithm will join 2 nodes replacing them with one. */ while(Nleft>3) { int j, k, ip, ip2; double minR = 0, min2R = 0; NodeT *newNode, *tmpNode; double sigma_inf_i, sigma_inf_ip; double sig_r, sig_l; int jj, jjmin; double LLRp = 0, tR; /* \subsection{Calculate Residual} */ calc_q(Nleft, q, R, b, q2, LLR, Zscore); if(printLevel>2) for(k=0;k<Nleft;++k) fprintf(outfile, "q[%d]=%d R(%d,%d)=%g\n", k, q[k], k, q[k], R[k]); /* Find $i$ than minimizes $R(i,q(i))$. With the constraint that $q(q(i))=i$ first if no pair found then find the best $i$ without this constraint. Note: the \|checkQQI| flag determines if we will use the $q(q(i))=i$ constraint. Note: j will hold the next best pair */ i = -1; j = -1; if(checkQQI) { for(k=0;k<Nleft;++k) if(q[q[k]]==k) { if(R[k]<minR || i==-1) { if(printLevel>3) fprintf(outfile, "ij=%d%d k=%d q[k]=%d minR = %.16g R[k] = %.16g\n", i,j,k, q[k], minR, R[k]); j = i; min2R = minR; i = k; minR = R[k]; } else if(R[k]>minR && (R[k]<min2R || j==-1) ) { j = k; min2R = R[k]; } } } if(i==-1) /* No pair had $q(q(i))=i$ */ { if(R[0]<R[1]) { i = 0; minR = R[0]; j = 1; min2R = R[1]; } else { i = 1; minR = R[1]; j = 0; min2R = R[0]; } for(k=1;k<Nleft;++k) if(R[k]<minR) { j = i; min2R = minR; i = k; minR = R[k]; } else if(R[k] < min2R && R[k] > minR) { j = k; min2R = R[k]; } if(checkQQI && printLevel>1) fprintf(outfile, "No pair with q[q[i]]==i "); else if(q[q[i]]!=i && printLevel>1) fprintf(outfile, "The pair does not satisfy q[q[i]]==i (checking is off)" ); } ip = q[i]; ip2 = j; /* If the extended tournament option is set (-e) then run two more tournaments for (i,q[i]) to see who really wins. */ if(extendedTourn) { double minR1 = 0, minR2 = 0, tmpR, oldR=R[i]; int jmin=-1, jpmin=-1; /* First fine the j the minimizes R(i,j) */ for(j=0;j<Nleft;++j) if(j!=i && j!=q[i]) { if(j!=q2[i]) tmpR = calcR2(Nleft, i, j, q2[i]); else tmpR = calcR2(Nleft, i, j, q[i]); if(tmpR<minR1 || jmin==-1) { minR1=tmpR; jmin = j; } } /* and now the $j'$ that minimizes $R(j',q[i])$ */ for(j=0;j<Nleft;++j) if(j!=i && j!=q[i]) { if(j!=q2[i]) tmpR = calcR2(Nleft, j, q[i], q2[i]); else tmpR = calcR2(Nleft, j, q[i], i); if(tmpR<minR2 || jpmin==-1) { minR2=tmpR; jpmin = j; } } /* Now fnd which of the three is the smallest */ if(minR1<minR2 && minR1<R[i]) { ip = jmin; if(printLevel>1) fprintf(outfile, "Extended Tournament New Winner(A): (%d, %d) R=%g\n", i, ip, minR1); } else if(minR2<minR1 && minR2<R[i]) { i = jpmin; if(printLevel>1) fprintf(outfile, "Extended Tournament New Winner(B): (%d, %d) R=%g\n", i, ip, minR2); } if(printLevel>3) fprintf(outfile, "R=%g, R1=%g, R2=%g\n", oldR, minR1, minR2); } /* Find the $jj$ that minimizes $R(q(i),i,jj)$ and then print out the LLR and LLR' values. */ jjmin=-1; for(jj=0;jj<Nleft;++jj) if(jj!=i && jj!=ip && (((tR=calcR(Nleft, ip, jj, i))<LLRp) || jjmin==-1)) { jjmin = jj; LLRp = tR; } LLRp *= 0.5; if( (LLR[i]<1e-6) && (LLRp<1e-6) ) { fprintf(stderr, "warning: tie scores encountered; topology may depend on sequence order!\n"); fprintf(stderr, "taxon %s and taxon %s\n\n", nodes[i]->name, nodes[ip]->name); if(printLevel>1) { fprintf(outfile, "warning: tie scores encountered; topology may depend on sequence order!\n"); fprintf(outfile, "taxon %s and taxon %s\n\n", nodes[i]->name, nodes[ip]->name); } } if(printLevel>0) { fprintf(outfile, "\nJoin taxon %s to taxon %s (%s next best choice)\n", nodes[i]->name, nodes[ip]->name, nodes[q2[i]]->name); fprintf(outfile, " p-value = %g\n", DMAX(1.0/(exp(LLR[i])+1.0), 1.0/(exp(LLRp)+1.0))); if(printLevel>1) { fprintf(outfile,"\nJoin taxon %s to taxon %s; R=%g\n", nodes[i]->name, nodes[ip]->name, minR); if(ip2!=-1 && ip2!=i && ip2!=ip) fprintf(outfile, "Second best pair (%s, %s); R=%g\n", nodes[ip2]->name, nodes[q[ip2]]->name, min2R); else fprintf(outfile, "No second best pair\n"); } } /* Note due to the way we shuffle around nodes after joining: i->Nnext, New->i, ip<->Nleft-1, if ip is less than i and i=Nleft-1 then the new node will be in position ip not i!! But tc (the global that is suppose to point to the position of the new node for calcb) is set to i so this will screw us up. The simpliest solution is to make sure i<ip; swap if they are not. */ if(ip<i) { int tt; tt=i; i=ip; ip=tt; } /* Need to calculate the new branch lengths $\bar b_{i;i'}$ and $\bar b_{i';i}$, eq. 0.19. Note if the z-score is negative then we calculate $\phi$ eq (0.26) and use it to renormalize $d_{i,i'}$ and recompute $b_{i;i'}$ and $b_{i';i}$. */ if(Zscore[i]<0.0) { double phi_iip, dBar_iip; phi_iip = calcPhi(Nleft, i, ip); if(printLevel>2) fprintf(outfile, "Renormalizing z[%d,%d] = %g\n", i, ip, Zscore[i]); if(phi_iip>0) { dBar_iip = D(i,ip)-phi_iip; if(printLevel>2) fprintf(outfile, "phi=%g dBar_iip=%g\n", phi_iip, dBar_iip); /* renormalize the b's */ if( dBar_iip >= fabs(deltaB[i][ip]) ) b[i][ip] = (deltaB[i][ip] + dBar_iip)/2.0; else if( dBar_iip < -deltaB[i][ip] ) b[i][ip] = 0.0; else b[i][ip] = dBar_iip; if( dBar_iip >= fabs(deltaB[ip][i]) ) b[ip][i] = (deltaB[ip][i] + dBar_iip)/2.0; else if( dBar_iip < -deltaB[ip][i] ) b[ip][i] = 0.0; else b[ip][i] = dBar_iip; } } nodes[i ]->rho = b[i][ip]; nodes[ip]->rho = b[ip][i]; if(nodes[i ]->rho < 0.0) { if(printLevel>0) fprintf(outfile, "WARNING: Negative branch length %lg set to zero\n", nodes[i ]->rho); nodes[i ]->rho = 0.0; nodes[ip]->rho = D(i,ip); } else if(nodes[ip]->rho < 0.0) { if(printLevel>0) fprintf(outfile, "WARNING: Negative branch length %lg set to zero\n", nodes[ip]->rho); nodes[ip]->rho = 0.0; nodes[i ]->rho = D(i,ip); } if(printLevel>3) { fprintf(outfile, "\\bar b_[%d%d] = %g b_[%d%d]=%g\n", i, ip, nodes[i]->rho, i, ip, b[i][ip]); fprintf(outfile, "\\bar b_[%d%d] = %g b_[%d%d]=%g\n\n", ip, i, nodes[ip]->rho, ip, i, b[ip][i]); } newNode = createNode(); newNode->ind = Nnext; newNode->child_r = nodes[i]; newNode->child_l = nodes[ip]; newNode->name = nodes[i]->name; nodes[Nnext] = newNode; /* Calculate $\sigma^2_\infty(i\bar\imath)$ (eq. 0.27) for each of the joined taxa. */ sigma_inf_i = 0.0; sigma_inf_ip = 0.0; for(j=0;j<Nleft;++j) { if(j!=i && j!=ip) { sigma_inf_i += sigma_na(DMAX(b[i][ip],MINB)+C(i), DMAX(D(i,j)-b[i][ip],MINB)+C(j) ); sigma_inf_ip += sigma_na(DMAX(b[ip][i],MINB)+C(ip), DMAX(D(ip,j)-b[ip][i],MINB)+C(j) ); } } /* Add \|EPSILON| here to make the following formulae a bit simplier */ sigma_inf_i += EPSILON; sigma_inf_ip += EPSILON; /* Calculate the new distances from eq. 0.24 $$ d_{\bar\imath k} = {{(d_{ik}-b_{i;i'}+\phi_i)/\sigma^2_\infty(i\bar\imath)+ (d_{i'j}-b_{i';i}+\phi_{i'})/\sigma^2_\infty(i'\bar\imath)} \over{ {1\over\sigma^2_\infty(i'\bar\imath)} + {1\over\sigma^2_\infty(i'\bar\imath)}}} $$ where\hfill\break $i=$ \|newNode->child_r->ind|,\hfill\break $i'=$ \|newNode->child_l->ind|,\hfill\break $b_{i;i'}=$ \|newNode->child_r->rho|,\hfill\break $b_{i';i}=$ \|newNode->child_l->rho| Also calcuate the renormalization terms $c_{i;j}$ (eq 0.43 ver0.2.5) and $c_i$ */ for(j=0;j<Nleft;++j) { if(j!=i && j!=ip) { /* $1/\sigma^2_\infty(i\bar\imath)+1/\sigma^2_\infty(i'\bar\imath)$ */ double norm = 1.0/( 1.0/sigma_inf_i + 1.0/sigma_inf_ip); /* First calcuate the new distances */ D(Nnext,j) = D(j,Nnext) = norm * ( (D(i,j)-RHO(newNode->child_r))/(sigma_inf_i) + (D(ip,j)-RHO(newNode->child_l))/(sigma_inf_ip) ); if(D(Nnext,j)<0.0) D(Nnext,j) = D(j,Nnext) = 0.0; } } D(Nnext,Nnext) = 0.0; /* And now the new renormalization quantity $c_{\bar\imath}$ N.B. eq 0.30 has been rewritten from $$ {1\over{{1\over X}+{1\over Y}}} $$ to $$ {XY\over X+Y} $$ which is better behaved numerically when $X$ or $Y$ is small (and cheeper since it only has one division). */ sig_r = sigma2t(C(i)+DMAX(RHO(newNode->child_r), MINB)); sig_l = sigma2t(C(ip)+DMAX(RHO(newNode->child_l), MINB)); if(sig_r*sig_l>0.0) { C(Nnext) = sigma2tinv(sig_r*sig_l/(sig_r+sig_l)); } else C(Nnext) = sigma2tinv(0.0); if(! (C(Nnext)<=DMIN(DMAX(RHO(newNode->child_r),MINB)+C(i)+1e-14, DMAX(RHO(newNode->child_l),MINB)+C(ip)+1e-14))) { printf("C(Nnext=%d)=%g\n" "RHO_R=%g C(i=%d)=%g sig_r=%g\nRHO_L=%g C(ip=%d)=%g sig_l=%g -- %g\n", Nnext, C(Nnext), RHO(newNode->child_r), i, C(i), sig_r, RHO(newNode->child_l), ip, C(ip), sig_l, sig_r*sig_l/(sig_r+sig_l)); } assert((C(Nnext)<=DMIN(DMAX(RHO(newNode->child_r),MINB)+C(i)+1e-14, DMAX(RHO(newNode->child_l),MINB)+C(ip)+1e-14))); /* Swap $i$ node to the empty node at the end of the list and place the new node in position $i$ */ nodes[Nnext] = nodes[i]; nodes[i] = newNode; /* Swap the $ip$ node and the last node on the list this moves $ip$ to the end. When we decrease \|Nleft| by one there will be on less node and the two joined nodes $i$ and $ip$ will now be after then end (\|Nleft|) of the list */ tmpNode = nodes[ip]; nodes[ip] = nodes[Nleft-1]; nodes[Nleft-1] = tmpNode; /* In the new node set the child indecies to the new indexes of the the joined nodes. This info will be used by \|sigma2_3| in the renormalization step */ newNode->cind_r=Nnext; newNode->cind_l=Nleft-1; /* Set up the \|ta|, \|tb| and \|tc| node array indices. \|ta| and \|tb| point to the two taxa that where just joined, and \|tc| points to the newly created taxon. These globals will be used in the next call to \|calcb|. */ ta = Nnext; tb = Nleft - 1; tc = i; --Nleft; ++Nnext; /* Print out the values of the various variables */ if(printLevel>2) { int a, b; fprintf(outfile, "\nReduced d_ij=\n"); for(a=0;a<Nleft;++a) { for(b=0;b<Nleft;++b) fprintf(outfile,"%7.4lg ", D(a,b)); fprintf(outfile,"\n"); } fprintf(outfile,"\n"); } if(printLevel>3) { int a, b; for(a=0;a<Nnext;++a) { for(b=0;b<Nnext;++b) fprintf(outfile,"%7.4lg ", mD[a][b]); fprintf(outfile,"\n"); } fprintf(outfile,"\n"); fprintf(outfile, "c_i = "); for(a=0;a<Nleft;++a) { fprintf(outfile,"%7.4lg ", C(a)); } fprintf(outfile,"\n"); for(a=0;a<Nnext;++a) { fprintf(outfile,"%7.4lg ", vC[a]); } fprintf(outfile,"\n"); fprintf(outfile, "\n"); } } /* \section{Final three taxa} Now there are just three taxa left. They will join to the root node of our tree. Find their branch lengths (which we can do exactly) and set up the root node to be passed back on return from this functin. */ root = createRootNode(); if(!root) printError("build::buildTree:out of memory-root"); root->child_l = nodes[0]; root->child_m = nodes[1]; root->child_r = nodes[2]; /* Now get the root branch lengths. We can solve this exactly since we have three equations and three unknows. The equations to solve are: $$ \rho_0+\rho_1 = d_{01}, \rho_0+\rho_2 = d_{02}, \rho_1+\rho_2 = d_{12} $$ And the solution is: $$ \rho_0={1 \over 2}\left(d_{01}+d_{02}-d_{12}\right), \rho_1={1 \over 2}\left(d_{01}-d_{02}+d_{12}\right), \rho_2={1 \over 2}\left(-d_{01}+d_{02}+d_{12}\right) $$ */ root->child_l->rho = 0.5*( D(0,1)+D(0,2)-D(1,2)); root->child_m->rho = 0.5*( D(0,1)-D(0,2)+D(1,2)); root->child_r->rho = 0.5*(-D(0,1)+D(0,2)+D(1,2)); /* check for negative lengths and set to zero if found and decrease the other each by half the the negative length (note + a neg number is a decrease) */ if(root->child_l->rho < 0.0) { root->child_m->rho += 0.5*root->child_l->rho; root->child_r->rho += 0.5*root->child_l->rho; root->child_l->rho=0.0; } if(root->child_m->rho < 0.0) { root->child_l->rho += 0.5*root->child_m->rho; root->child_r->rho += 0.5*root->child_m->rho; root->child_m->rho=0.0; } if(root->child_r->rho < 0.0) { root->child_l->rho += 0.5*root->child_r->rho; root->child_m->rho += 0.5*root->child_r->rho; root->child_r->rho=0.0; } /* Clean up */ freeMatrix(mD); freeMatrix(b); freeMatrix(delta2B); freeMatrix(deltaB); if(recalcB) freeMatrix(oldDeltaB); freeMatrix(s); freeVector(R); freeVector(LLR); freeVector(Zscore); freeVector(vC); freeMatrix(mS); freeMatrix(mDelB); freeMatrix(mDel2B); free(nodes); free(q); free(q2); return(root); }
/*--------------------------------------------------------------------------*/ int sci_legendre(char *fname, void* pvApiCtx) { /* * Interface onto the (Slatec) dxleg.f code. * Scilab syntax: * * p = legendre(n, m, x [, norm_flag] ) * * x is a vector with mnx elements (it is better to * have a row vector but this is not forced) * * n : a non negative int scalar (or a vector of such * int regularly speced with an increment of 1) * m : same constraints than for n * * n and m may not be both vectors * * norm_flag : optional. When it is present and equal to "norm" * it is a normalized version which is computed * AUTHOR * Bruno Pincon <*****@*****.**> */ int it = 0, lc = 0, mM = 0, nM = 0, m1 = 0, m2 = 0, mN = 0, nN = 0; int n1 = 0, n2 = 0, mx = 0, nx = 0, mnx = 0, ms = 0, ns = 0; int M_is_scalar = 0, N_is_scalar = 0, normalized = 0, MNp1 = 0, *ipqa = NULL; double xx = 0., dnu1 = 0.; int id = 0, ierror = 0, i = 0, j = 0, nudiff = 0; SciErr sciErr; int* piAddr1 = NULL; int* piAddr2 = NULL; int* piAddr3 = NULL; int* piAddr4 = NULL; int nbInputArg = nbInputArgument(pvApiCtx); double* pdblN = NULL; double* pdblM = NULL; double* pdblX = NULL; double* pdblPQA = NULL; int* piPQA = NULL; int iType1 = 0; int iType2 = 0; int iType3 = 0; CheckInputArgument(pvApiCtx, 3, 4); CheckOutputArgument(pvApiCtx, 1, 1); /* get N */ //get variable address of the input argument sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddr1); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } sciErr = getVarType(pvApiCtx, piAddr1, &iType1); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (iType1 != sci_matrix) { Scierror(999, _("%s: Wrong type for input argument #%d: Integer or vector of integers expected.\n"), fname, 1); return 1; } sciErr = getMatrixOfDouble(pvApiCtx, piAddr1, &mN, &nN, &pdblN); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (verify_cstr(pdblN, mN * nN, &n1, &n2) == 0) { Scierror(999, _("%s: Wrong type for input argument #%d: Integer >= %d expected.\n"), fname, 1, 0); return 1; } if ( mN == 1 && nN == 1) { N_is_scalar = 1; } /* get M */ //get variable address of the input argument sciErr = getVarAddressFromPosition(pvApiCtx, 2, &piAddr2); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } sciErr = getVarType(pvApiCtx, piAddr2, &iType2); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (iType2 != sci_matrix) { Scierror(999, _("%s: Wrong type for input argument #%d: Integer or vector of integers expected.\n"), fname, 2); return 1; } sciErr = getMatrixOfDouble(pvApiCtx, piAddr2, &mM, &nM, &pdblM); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (verify_cstr(pdblM, mM * nM, &m1, &m2) == 0) { Scierror(999, _("%s: Wrong type for input argument #%d: Integer >= %d expected.\n"), fname, 2, 0); return 1; } if ( mM == 1 && nM == 1) { M_is_scalar = 1; } if ( ! M_is_scalar && ! N_is_scalar ) { Scierror(999, _("%s: Only one of arg1 and arg2 may be a vector.\n"), fname); return 1; } /* get X */ //get variable address of the input argument sciErr = getVarAddressFromPosition(pvApiCtx, 3, &piAddr3); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } sciErr = getVarType(pvApiCtx, piAddr3, &iType3); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (iType3 != sci_matrix || isVarComplex(pvApiCtx, piAddr3)) { Scierror(999, _("%s: Wrong type for input argument #%d: Real matrix expected.\n"), fname, 3); return 1; } sciErr = getMatrixOfDouble(pvApiCtx, piAddr3, &mx, &nx, &pdblX); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } mnx = mx * nx; for ( i = 0 ; i < mnx ; i++ ) { if ((fabs(pdblX[i]) <= 1.0) == 0) { Scierror(999, _("%s: Wrong value for input argument #%d: Matrix with elements in [%d,%d] expected.\n"), fname, 3, -1, 1); return 1; } } if ( nbInputArg == 4 ) { //get variable address int iRet = 0; char* lschar = NULL; sciErr = getVarAddressFromPosition(pvApiCtx, 4, &piAddr4); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } // Retrieve a single string at position 4 iRet = getAllocatedSingleString(pvApiCtx, piAddr4, &lschar); if (iRet) { return iRet; } if ( strcmp(lschar, "norm") == 0) { normalized = 1; } else { normalized = 0; } freeAllocatedSingleString(lschar); } else { normalized = 0; } MNp1 = Max (n2 - n1, m2 - m1) + 1; allocMatrixOfDouble(pvApiCtx, nbInputArg + 1, MNp1, mnx, &pdblPQA); piPQA = (int*)MALLOC(MNp1 * mnx * sizeof(int)); if ( normalized ) { id = 4; } else { id = 3; } nudiff = n2 - n1; dnu1 = (double) n1; for ( i = 0 ; i < mnx ; i++ ) { xx = fabs(pdblX[i]); /* manage the case where xx = 1 with n scalar*/ if (N_is_scalar && xx == 1) { if (m1 == 0) { pdblPQA[i * MNp1] = 1; } else { pdblPQA[i * MNp1] = 0; } if (normalized) { pdblPQA[i * MNp1] = pdblPQA[i * MNp1] * sqrt(dnu1 + 0.5); } piPQA[i * MNp1] = 0; for (j = 1; j < MNp1; j++) { pdblPQA[i * MNp1 + j] = 0; piPQA[i * MNp1 + j] = 0; } } else { /* dxleg computes only for x in [0,1] */ C2F(dxlegf) (&dnu1, &nudiff, &m1, &m2, &xx, &id, pdblPQA + i * MNp1, piPQA + i * MNp1, &ierror); if ( ierror != 0 ) { if ( ierror == 207 ) /* @TODO what is 207 ? */ { Scierror(999, _("%s: overflow or underflow of an extended range number\n"), fname); } else { Scierror(999, _("%s: error number %d\n"), fname, ierror); } return 0; } } } /* dxlegf returns the result under a form (pqa,ipqa) (to * compute internaly with an extended exponent range) * When the "exponent" part (ipqa) is 0 then the number is exactly * given by pqa else it leads to an overflow or an underflow. */ for ( i = 0 ; i < mnx * MNp1 ; i++ ) { if ( piPQA[i] < 0 ) { pdblPQA[i] = 0.0; } if ( piPQA[i] > 0 ) { pdblPQA[i] = pdblPQA[i] * return_an_inf(); /* pqa[i] * Inf to have the sign */ } } FREE(piPQA); /* complete the result by odd/even symmetry for negative x */ for ( i = 0 ; i < mnx ; i++ ) { if ( pdblX[i] < 0.0 ) { if ( (n1 + m1) % 2 == 1 ) { for ( j = 0 ; j < MNp1 ; j += 2 ) { pdblPQA[i * MNp1 + j] = -pdblPQA[i * MNp1 + j]; } } else { for ( j = 1 ; j < MNp1 ; j += 2 ) { pdblPQA[i * MNp1 + j] = -pdblPQA[i * MNp1 + j]; } } } } AssignOutputVariable(pvApiCtx, 1) = nbInputArg + 1; ReturnArguments(pvApiCtx); return 0; }
static int badWrapTest( CSSM_CSP_HANDLE cspHand, CSSM_KEY_PTR unwrappedKey, CSSM_KEYBLOB_FORMAT wrapForm, CSSM_BOOL quiet, const char *keyAlgStr, const char *testStr) { CSSM_CC_HANDLE ccHand; CSSM_RETURN crtn; CSSM_ACCESS_CREDENTIALS creds; CSSM_KEY wrappedKey; // should not get created CSSM_KEY wrappingKey; int irtn; /* first generate a DES wrapping key */ if(genSymKey(cspHand, &wrappingKey, CSSM_ALGID_DES, "DES", CSP_DES_KEY_SIZE_DEFAULT, CSSM_KEYATTR_RETURN_REF, CSSM_KEYUSE_ANY, CSSM_OK, quiet, CSSM_FALSE, "not a test case")) { return 1; } memset(&wrappedKey, 0, sizeof(CSSM_KEY)); memset(&creds, 0, sizeof(CSSM_ACCESS_CREDENTIALS)); /* symmetric wrapping context */ crtn = CSSM_CSP_CreateSymmetricContext(cspHand, CSSM_ALGID_DES, CSSM_ALGMODE_CBCPadIV8, &creds, // passPhrase, &wrappingKey, NULL, // IV CSSM_PADDING_PKCS5, 0, // Params &ccHand); if(crtn) { printError("cspWrapKey/CreateContext", crtn); return testError(quiet); } /* do it, demand error */ crtn = CSSM_WrapKey(ccHand, &creds, unwrappedKey, NULL, // DescriptiveData &wrappedKey); if(crtn != CSSMERR_CSP_INVALID_KEYATTR_MASK) { printf("***Testing %s for alg %s:\n", testStr, keyAlgStr); printf(" CSSM_WrapKey: expect CSSMERR_CSP_INVALID_KEYATTR_MASK, got %s\n", cssmErrToStr(crtn)); irtn = testError(quiet); } else { irtn = 0; } CSSM_DeleteContext(ccHand); cspFreeKey(cspHand, &wrappingKey); return irtn; }
static bool import_sparse(int* pvCtx, int _iDatasetId, int _iItemPos, int *_piAddress, char *_pstVarname) { int iRet = 0; int iRows = 0; int iCols = 0; int iComplex = 0; double *pdblReal = NULL; double *pdblImg = NULL; int iNbItem = 0; int *piNbItemRow = NULL; int *piColPos = NULL; SciErr sciErr; iRet = getSparseDimension(_iDatasetId, &iRows, &iCols, &iNbItem); if (iRet) { return false; } iComplex = isComplexData(_iDatasetId); if (iComplex) { piNbItemRow = (int *)MALLOC(iRows * sizeof(int)); piColPos = (int *)MALLOC(iNbItem * sizeof(int)); pdblReal = (double *)MALLOC(iNbItem * sizeof(double)); pdblImg = (double *)MALLOC(iNbItem * sizeof(double)); iRet = readSparseComplexMatrix(_iDatasetId, iRows, iCols, iNbItem, piNbItemRow, piColPos, pdblReal, pdblImg); } else { piNbItemRow = (int *)MALLOC(iRows * sizeof(int)); piColPos = (int *)MALLOC(iNbItem * sizeof(int)); pdblReal = (double *)MALLOC(iNbItem * sizeof(double)); iRet = readSparseMatrix(_iDatasetId, iRows, iCols, iNbItem, piNbItemRow, piColPos, pdblReal); } if (iRet) { FREE(piNbItemRow); FREE(piColPos); FREE(pdblReal); if (iComplex) { FREE(pdblImg); } return false; } if (_piAddress == NULL) { if (iComplex) { sciErr = createNamedComplexSparseMatrix(pvCtx, _pstVarname, iRows, iCols, iNbItem, piNbItemRow, piColPos, pdblReal, pdblImg); } else { sciErr = createNamedSparseMatrix(pvCtx, _pstVarname, iRows, iCols, iNbItem, piNbItemRow, piColPos, pdblReal); } } else //if not null this variable is in a list { if (iComplex) { sciErr = createComplexSparseMatrixInNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, iRows, iCols, iNbItem, piNbItemRow, piColPos, pdblReal, pdblImg); } else { sciErr = createSparseMatrixInNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, iRows, iCols, iNbItem, piNbItemRow, piColPos, pdblReal); } } FREE(piNbItemRow); FREE(piColPos); FREE(pdblReal); if (iComplex) { FREE(pdblImg); } if (sciErr.iErr) { printError(&sciErr, 0); return false; } return true; }
int main(int argc, char **argv) { int arg; char *argp; unsigned oloop; unsigned iloop; CSSM_DATA ptext = {0, NULL}; CSSM_CSP_HANDLE cspHand; int i; int rtn = 0; uint32 keySizeInBits = 0; CSSM_KEY pubKey; CSSM_KEY privKey; CSSM_DATA sig = {0, NULL}; CSSM_DATA digest = {0, NULL}; CSSM_RETURN crtn; const char *digestStr; /* * User-spec'd params */ CSSM_BOOL keySizeSpec = CSSM_FALSE; unsigned oloops = OLOOPS_DEF; unsigned iloops = ILOOPS_DEF; CSSM_BOOL verbose = CSSM_FALSE; CSSM_BOOL quiet = CSSM_FALSE; unsigned pauseInterval = 0; CSSM_BOOL bareCsp = CSSM_TRUE; CSSM_ALGORITHMS rawSigAlg = CSSM_ALGID_RSA; for(arg=1; arg<argc; arg++) { argp = argv[arg]; switch(argp[0]) { case 'a': switch(argp[2]) { case 'r': rawSigAlg = CSSM_ALGID_RSA; break; case 'd': rawSigAlg = CSSM_ALGID_DSA; break; default: usage(argv); } break; case 'l': oloops = atoi(&argp[2]); break; case 'i': iloops = atoi(&argp[2]); break; case 'k': keySizeInBits = atoi(&argp[2]); keySizeSpec = CSSM_TRUE; break; case 'v': verbose = CSSM_TRUE; break; case 'D': bareCsp = CSSM_FALSE; break; case 'q': quiet = CSSM_TRUE; break; case 'p': pauseInterval = atoi(&argp[2]);; break; case 'h': default: usage(argv); } } ptext.Data = (uint8 *)CSSM_MALLOC(MAX_TEXT_SIZE); if(ptext.Data == NULL) { printf("Insufficient heap space\n"); exit(1); } /* ptext length set in inner test loop */ printf("Starting rawRsaSig; args: "); for(i=1; i<argc; i++) { printf("%s ", argv[i]); } printf("\n"); cspHand = cspDlDbStartup(bareCsp, NULL); if(cspHand == 0) { exit(1); } if(pauseInterval) { fpurge(stdin); printf("Top of test; hit CR to proceed: "); getchar(); } for(oloop=0; ; oloop++) { /* key size? */ if(!keySizeSpec) { /* random key size */ keySizeInBits = randKeySizeBits(rawSigAlg, OT_Sign); } if(!quiet) { if(verbose || ((oloop % LOOP_NOTIFY) == 0)) { printf("...oloop %d keySize %u\n", oloop, (unsigned)keySizeInBits); } } /* generate a key pair */ crtn = cspGenKeyPair(cspHand, rawSigAlg, "foo", 3, keySizeInBits, &pubKey, CSSM_TRUE, // all keys ref for speed CSSM_KEYUSE_VERIFY, CSSM_KEYBLOB_RAW_FORMAT_NONE, &privKey, CSSM_TRUE, CSSM_KEYUSE_SIGN, CSSM_KEYBLOB_RAW_FORMAT_NONE, CSSM_FALSE); // genSeed not used if(crtn) { return testError(quiet); } for(iloop=0; iloop<iloops; iloop++) { CSSM_ALGORITHMS sigAlg; CSSM_ALGORITHMS digestAlg; CSSM_CC_HANDLE sigHand; /* alternate digest algs for RSA */ if(rawSigAlg == CSSM_ALGID_RSA) { if(iloop & 1) { sigAlg = CSSM_ALGID_SHA1WithRSA; digestAlg = CSSM_ALGID_SHA1; digestStr = "SHA1"; } else { sigAlg = CSSM_ALGID_MD5WithRSA; digestAlg = CSSM_ALGID_MD5; digestStr = "MD5 "; } } else { sigAlg = CSSM_ALGID_SHA1WithDSA; digestAlg = CSSM_ALGID_SHA1; digestStr = "SHA1"; } /* new plaintext each inner loop */ simpleGenData(&ptext, 1, MAX_TEXT_SIZE); if(!quiet) { if(verbose || ((iloop % LOOP_NOTIFY) == 0)) { printf(" ...iloop %d digest %s text size %lu\n", iloop, digestStr, ptext.Length); } } /*** phase 1 ***/ /* digest+sign */ crtn = cspStagedSign(cspHand, sigAlg, &privKey, &ptext, DO_MULTI_UPDATE, // multiUpdates &sig); if(crtn && testError(quiet)) { goto abort; } /* digest */ crtn = cspStagedDigest(cspHand, digestAlg, CSSM_FALSE, // mallocDigest DO_MULTI_UPDATE, // multiUpdates &ptext, &digest); if(crtn && testError(quiet)) { goto abort; } /* raw RSA/DSA verify */ crtn = CSSM_CSP_CreateSignatureContext(cspHand, rawSigAlg, NULL, // passPhrase &pubKey, &sigHand); if(crtn) { printError("CSSM_CSP_CreateSignatureContext (1)", crtn); return crtn; } crtn = CSSM_VerifyData(sigHand, &digest, 1, digestAlg, &sig); if(crtn) { printError("CSSM_VerifyData(raw RSA)", crtn); if(testError(quiet)) { goto abort; } } /* free resources - reuse the digest for raw sign */ appFreeCssmData(&sig, CSSM_FALSE); CSSM_DeleteContext(sigHand); /*** phase 2 ***/ /* raw RSA/DSA sign */ crtn = CSSM_CSP_CreateSignatureContext(cspHand, rawSigAlg, NULL, // passPhrase &privKey, &sigHand); if(crtn) { printError("CSSM_CSP_CreateSignatureContext (1)", crtn); return crtn; } crtn = CSSM_SignData(sigHand, &digest, 1, digestAlg, &sig); if(crtn) { printError("CSSM_SignData(raw RSA)", crtn); if(testError(quiet)) { goto abort; } } /* all-in-one verify */ crtn = cspStagedSigVerify(cspHand, sigAlg, &pubKey, &ptext, &sig, DO_MULTI_UPDATE, // multiUpdates CSSM_OK); if(crtn && testError(quiet)) { goto abort; } /* clean up */ appFreeCssmData(&sig, CSSM_FALSE); appFreeCssmData(&digest, CSSM_FALSE); CSSM_DeleteContext(sigHand); } /* end of inner loop */ /* free keys */ cspFreeKey(cspHand, &pubKey); cspFreeKey(cspHand, &privKey); if(oloops && (oloop == oloops)) { break; } if(pauseInterval && ((oloop % pauseInterval) == 0)) { fpurge(stdin); printf("hit CR to proceed: "); getchar(); } } abort: cspShutdown(cspHand, bareCsp); if(pauseInterval) { fpurge(stdin); printf("ModuleDetach/Unload complete; hit CR to exit: "); getchar(); } if((rtn == 0) && !quiet) { printf("%s test complete\n", argv[0]); } CSSM_FREE(ptext.Data); return rtn; }
int _tmain(int argc, _TCHAR* argv[]) { try { require( argc == 3, USAGE ); require( fileExists( argv[1] ), "File not found" ); require( fileExists( argv[2] ), "File not found" ); TCOMIXMLDOMDocument3 xml = Msxml2_tlb::CoDOMDocument60::Create(); TCOMIXMLDOMDocument3 xsl = Msxml2_tlb::CoDOMDocument60::Create(); xsl->resolveExternals = VARIANT_TRUE; load( xml, argv[1] ); load( xsl, argv[2] ); BSTR result = NULL; Msxml2_tlb::IXMLDOMNodePtr pXSLDOM = xsl->documentElement; HRESULT hr = xml->transformNode( pXSLDOM, &result ); if (FAILED(hr)) { WideString errMsg = L"Failure code obtained from transformNode. "; // Try to get extended error info... IErrorInfo* errorInfo = NULL; if ( SUCCEEDED( GetErrorInfo( 0, &errorInfo ) ) ) { boost::shared_ptr<void> releaseOnExit( errorInfo, release ); BSTR reason = NULL; if ( SUCCEEDED( errorInfo->GetDescription( &reason ) ) ) { boost::shared_ptr<void> freeStringOnExit( reason, freeString ); if ( reason ) { errMsg += WideString(reason); } } } throw Exception( UnicodeString( errMsg ) ); } boost::shared_ptr<void> freeStringOnExit( result, freeString ); WideString ws(result); std::wcout << (wchar_t*)ws; return 0; } catch( Exception& e ) { printError( e.Message ); } catch( const std::exception& e ) { printError( e.what() ); } catch( ... ) { printError( "Unspecified exception" ); } return 1; }
/*--------------------------------------------------------------------------*/ int sci_mputl(char *fname, unsigned long fname_len) { SciErr sciErr; int *piAddressVarOne = NULL; int *piAddressVarTwo = NULL; char **pStVarOne = NULL; int *lenStVarOne = NULL; int mOne = 0, nOne = 0; int mnOne = 0; char *filename = NULL; int fileDescriptor = -1; BOOL bCloseFile = FALSE; int i = 0; int mputlErr = MPUTL_ERROR; if (Rhs != 2) { Scierror(999, _("%s: Wrong number of input arguments: %d expected.\n"), fname, 2); return 0; } if (Lhs != 1) { Scierror(999, _("%s: Wrong number of output arguments: %d expected.\n"), fname, 1); return 0; } sciErr = getVarAddressFromPosition(pvApiCtx, 2, &piAddressVarTwo); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 2); return 0; } if ( isDoubleType(pvApiCtx, piAddressVarTwo) ) { double dValue = 0.; if (!isScalar(pvApiCtx, piAddressVarTwo)) { Scierror(999, _("%s: Wrong size for input argument #%d: Integer expected.\n"), fname, 2); return 0; } if ( getScalarDouble(pvApiCtx, piAddressVarTwo, &dValue) == 0) { fileDescriptor = (int)dValue; } else { Scierror(999, _("%s: Memory allocation error.\n"), fname); return 0; } } else if ( isStringType(pvApiCtx, piAddressVarTwo) ) { if (!isScalar(pvApiCtx, piAddressVarTwo)) { Scierror(999, _("%s: Wrong size for input argument #%d: String expected.\n"), fname, 2); return 0; } if (getAllocatedSingleString(pvApiCtx, piAddressVarTwo, &filename) == 0) { #define WRITE_ONLY_TEXT_MODE "wt" int f_swap = 0; double res = 0.0; int ierr = 0; char *expandedFileName = expandPathVariable(filename); C2F(mopen)(&fileDescriptor, expandedFileName, WRITE_ONLY_TEXT_MODE, &f_swap, &res, &ierr); if (expandedFileName) { FREE(expandedFileName); expandedFileName = NULL; } switch (ierr) { case MOPEN_NO_ERROR: break; case MOPEN_NO_MORE_LOGICAL_UNIT: { freeAllocatedSingleString(filename); Scierror(66, _("%s: Too many files opened!\n"), fname); return 0; } break; case MOPEN_CAN_NOT_OPEN_FILE: { Scierror(999, _("%s: Cannot open file %s.\n"), fname, filename); freeAllocatedSingleString(filename); return 0; } break; case MOPEN_NO_MORE_MEMORY: { freeAllocatedSingleString(filename); Scierror(999, _("%s: No more memory.\n"), fname); return 0; } break; case MOPEN_INVALID_FILENAME: { if (filename) { Scierror(999, _("%s: invalid filename %s.\n"), fname, filename); } else { freeAllocatedSingleString(filename); Scierror(999, _("%s: invalid filename.\n"), fname); } return 0; } break; case MOPEN_INVALID_STATUS: default: { freeAllocatedSingleString(filename); Scierror(999, _("%s: invalid status.\n"), fname); return 0; } break; } bCloseFile = TRUE; freeAllocatedSingleString(filename); } else { Scierror(999, _("%s: Memory allocation error.\n"), fname); return 0; } } else { Scierror(999, _("%s: Wrong type for input argument #%d: a String or Integer expected.\n"), fname, 2); } sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddressVarOne); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); return 0; } if (!isStringType(pvApiCtx, piAddressVarOne)) { Scierror(999, _("%s: Wrong type for input argument #%d: String expected.\n"), fname, 1); return 0; } sciErr = getMatrixOfString(pvApiCtx, piAddressVarOne, &mOne, &nOne, NULL, NULL); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } if ( !((mOne == 1) || (nOne == 1)) ) { Scierror(999, _("%s: Wrong size for input argument #%d: A 1-by-n or m-by-1 array expected.\n"), fname, 1); return 0; } mnOne = mOne * nOne; lenStVarOne = (int*)MALLOC(sizeof(int) * mnOne); if (lenStVarOne == NULL) { Scierror(999, _("%s: No more memory.\n"), fname); return 0; } sciErr = getMatrixOfString(pvApiCtx, piAddressVarOne, &mOne, &nOne, lenStVarOne, NULL); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); return 0; } pStVarOne = (char**) MALLOC(sizeof(char*) * mnOne); if (pStVarOne == NULL) { FREE(lenStVarOne); lenStVarOne = NULL; Scierror(999, _("%s: No more memory.\n"), fname); return 0; } for (i = 0; i < mnOne; i++) { pStVarOne[i] = (char*)MALLOC(sizeof(char) * (lenStVarOne[i] + 1)); if (pStVarOne[i] == NULL) { freeArrayOfString(pStVarOne, i); if (lenStVarOne) { FREE(lenStVarOne); lenStVarOne = NULL; } Scierror(999, _("%s: No more memory.\n"), fname); return 0; } } sciErr = getMatrixOfString(pvApiCtx, piAddressVarOne, &mOne, &nOne, lenStVarOne, pStVarOne); if (lenStVarOne) { FREE(lenStVarOne); lenStVarOne = NULL; } if (sciErr.iErr) { freeArrayOfString(pStVarOne, mnOne); printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); return 0; } mputlErr = mputl(fileDescriptor, pStVarOne, mnOne); freeArrayOfString(pStVarOne, mnOne); if (bCloseFile) { double dErrClose = 0.; C2F(mclose)(&fileDescriptor, &dErrClose); } switch (mputlErr) { case MPUTL_NO_ERROR: createScalarBoolean(pvApiCtx, Rhs + 1, TRUE); LhsVar(1) = Rhs + 1; PutLhsVar(); break; case MPUTL_INVALID_FILE_DESCRIPTOR: // commented for compatiblity // Scierror(999, _("%s: invalid file descriptor.\n"), fname); // break; case MPUTL_ERROR: case MPUTL_NO_WRITE_RIGHT: default: createScalarBoolean(pvApiCtx, Rhs + 1, FALSE); LhsVar(1) = Rhs + 1; PutLhsVar(); break; } return 0; }
/*--------------------------------------------------------------------------*/ int sci_scinotes(char * fname, void* pvApiCtx) { SciErr sciErr; CheckRhs(0, 3); CheckLhs(0, 1); if (Rhs == 0) { try { callSciNotesW(NULL, 0); } catch (GiwsException::JniCallMethodException exception) { Scierror(999, "%s: %s\n", fname, exception.getJavaDescription().c_str()); } catch (GiwsException::JniException exception) { Scierror(999, "%s: %s\n", fname, exception.whatStr().c_str()); } } else { int m1 = 0, n1 = 0; int *piAddressVarOne = NULL; wchar_t **pStVarOne = NULL; int *lenStVarOne = NULL; int i = 0; int iType1 = 0; char *functionName = NULL; sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddressVarOne); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); return 0; } sciErr = getVarType(pvApiCtx, piAddressVarOne, &iType1); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); return 0; } if (iType1 != sci_strings) { Scierror(999, _("%s: Wrong type for argument #%d: string expected.\n"), fname, 1); return 0; } /* get dimensions */ sciErr = getMatrixOfWideString(pvApiCtx, piAddressVarOne, &m1, &n1, lenStVarOne, NULL); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); return 0; } lenStVarOne = (int *)MALLOC(sizeof(int) * (m1 * n1)); if (lenStVarOne == NULL) { Scierror(999, _("%s: No more memory.\n"), fname); return 0; } /* get lengths */ sciErr = getMatrixOfWideString(pvApiCtx, piAddressVarOne, &m1, &n1, lenStVarOne, pStVarOne); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); FREE(lenStVarOne); return 0; } pStVarOne = (wchar_t **) MALLOC(sizeof(wchar_t *) * (m1 * n1)); if (pStVarOne == NULL) { Scierror(999, _("%s: No more memory.\n"), fname); FREE(lenStVarOne); return 0; } for (i = 0; i < m1 * n1; i++) { pStVarOne[i] = (wchar_t *) MALLOC(sizeof(wchar_t) * (lenStVarOne[i] + 1)); if (pStVarOne[i] == NULL) { Scierror(999, _("%s: No more memory.\n"), fname); for (; i >= 0; i--) { FREE(pStVarOne[i]); } FREE(pStVarOne); FREE(lenStVarOne); return 0; } } /* get strings */ sciErr = getMatrixOfWideString(pvApiCtx, piAddressVarOne, &m1, &n1, lenStVarOne, pStVarOne); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } if (Rhs >= 2) //get line numbers { int *piAddressVarTwo = NULL; int m2 = 0, n2 = 0; double *pdblVarTwo = NULL; int iType2 = 0; sciErr = getVarAddressFromPosition(pvApiCtx, 2, &piAddressVarTwo); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 2); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } sciErr = getVarType(pvApiCtx, piAddressVarTwo, &iType2); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 2); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } if (iType2 != sci_matrix && iType2 != sci_strings) { Scierror(999, _("%s: Wrong type for argument #%d: Real matrix or \'readonly\' expected.\n"), fname, 2); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } if (iType2 == sci_strings) { /* get dimensions */ wchar_t **pStVarTwo = NULL; int *lenStVarTwo = NULL; sciErr = getMatrixOfWideString(pvApiCtx, piAddressVarTwo, &m2, &n2, lenStVarTwo, NULL); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 2); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } lenStVarTwo = (int *)MALLOC(sizeof(int) * m2 * n2); if (lenStVarTwo == NULL) { Scierror(999, _("%s: No more memory.\n"), fname); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } /* get lengths */ sciErr = getMatrixOfWideString(pvApiCtx, piAddressVarTwo, &m2, &n2, lenStVarTwo, pStVarTwo); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 2); FREE(lenStVarTwo); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } pStVarTwo = (wchar_t **) MALLOC(sizeof(wchar_t *) * m2 * n2); if (pStVarTwo == NULL) { Scierror(999, _("%s: No more memory.\n"), fname); FREE(lenStVarTwo); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } for (int i = 0; i < m2 * n2; i++) { pStVarTwo[i] = (wchar_t *) MALLOC(sizeof(wchar_t) * (lenStVarTwo[i] + 1)); if (pStVarTwo[i] == NULL) { Scierror(999, _("%s: No more memory.\n"), fname); freeArrayOfWideString(pStVarTwo, i); FREE(lenStVarTwo); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } } /* get strings */ sciErr = getMatrixOfWideString(pvApiCtx, piAddressVarTwo, &m2, &n2, lenStVarTwo, pStVarTwo); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 2); FREE(pStVarTwo); FREE(lenStVarTwo); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } try { callSciNotesWWithOption(pStVarOne, pStVarTwo, m2 * n2, m1 * n1); } catch (GiwsException::JniCallMethodException exception) { Scierror(999, "%s: %s\n", fname, exception.getJavaDescription().c_str()); freeArrayOfWideString(pStVarTwo, m2 * n2); FREE(lenStVarTwo); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } catch (GiwsException::JniException exception) { Scierror(999, "%s: %s\n", fname, exception.whatStr().c_str()); freeArrayOfWideString(pStVarTwo, m2 * n2); FREE(lenStVarTwo); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } freeArrayOfWideString(pStVarTwo, m2 * n2); FREE(lenStVarTwo); } else { if (isVarComplex(pvApiCtx, piAddressVarTwo) == 1) { Scierror(999, _("%s: Wrong type for argument #%d: Real matrix expected.\n"), fname, 2); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } sciErr = getMatrixOfDouble(pvApiCtx, piAddressVarTwo, &m2, &n2, &pdblVarTwo); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 2); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } if (m2 * n2 != m1 * n1) { Scierror(999, _("%s: Wrong size for input arguments #%d and #%d: Same dimensions expected.\n"), fname, 1, 2); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } if (Rhs == 3) { int *piAddressVarThree = NULL; sciErr = getVarAddressFromPosition(pvApiCtx, 3, &piAddressVarThree); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 3); return 0; } if (!isStringType(pvApiCtx, piAddressVarThree)) { Scierror(999, _("%s: Wrong type for argument #%d: string expected.\n"), fname, 3); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } int ret = getAllocatedSingleString(pvApiCtx, piAddressVarThree, &functionName); if (ret) { Scierror(999, _("%s: Wrong type for argument #%d: string expected.\n"), fname, 3); freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); return 0; } } try { callSciNotesWWithLineNumberAndFunction(pStVarOne, pdblVarTwo, functionName, m1 * n1); } catch (GiwsException::JniCallMethodException exception) { Scierror(999, "%s: %s\n", fname, exception.getJavaDescription().c_str()); } catch (GiwsException::JniException exception) { Scierror(999, "%s: %s\n", fname, exception.whatStr().c_str()); } } } else { try { callSciNotesW(pStVarOne, m1 * n1); } catch (GiwsException::JniCallMethodException exception) { Scierror(999, "%s: %s\n", fname, exception.getJavaDescription().c_str()); } catch (GiwsException::JniException exception) { Scierror(999, "%s: %s\n", fname, exception.whatStr().c_str()); } } freeArrayOfWideString(pStVarOne, m1 * n1); FREE(lenStVarOne); if (functionName) { freeAllocatedSingleString(functionName); } } LhsVar(1) = 0; PutLhsVar(); return 0; }
/*--------------------------------------------------------------------------*/ int sci_plot3d(char * fname, void *pvApiCtx) { SciErr sciErr; static double ebox_def [6] = { 0, 1, 0, 1, 0, 1}; double *ebox = ebox_def; static int iflag_def[3] = {2, 2, 4}; int *iflag = iflag_def; double alpha_def = 35.0 , theta_def = 45.0; double *alpha = &alpha_def, *theta = &theta_def; int m1 = 0, n1 = 0, m2 = 0, n2 = 0, m3 = 0, n3 = 0; int m3n = 0, n3n = 0, m3l = 0; int izcol = 0, isfac = 0; double *zcol = NULL; int mustFree = 0; static rhs_opts opts[] = { { -1, "alpha", -1, 0, 0, NULL}, { -1, "ebox", -1, 0, 0, NULL}, { -1, "flag", -1, 0, 0, NULL}, { -1, "leg", -1, 0, 0, NULL}, { -1, "theta", -1, 0, 0, NULL}, { -1, NULL, -1, 0, 0, NULL} }; char * legend = NULL; int* piAddr1 = NULL; int* piAddr2 = NULL; int* piAddr3 = NULL; int* piAddr31 = NULL; int* piAddr32 = NULL; double* l1 = NULL; double* l2 = NULL; double* l3 = NULL; double* l3n = NULL; /* ** This overload the function to call demo script ** the demo script is called %_<fname> */ if (nbInputArgument(pvApiCtx) <= 0) { sci_demo(fname, pvApiCtx); return 0; } if (nbInputArgument(pvApiCtx) == 2) { Scierror(77, _("%s: Wrong number of input argument(s).\n"), fname); return -1; } CheckInputArgument(pvApiCtx, 1, 8); if (getOptionals(pvApiCtx, fname, opts) == 0) { ReturnArguments(pvApiCtx); return 0; } if (nbInputArgument(pvApiCtx) != 1 && FirstOpt(pvApiCtx) < 4) { Scierror(999, _("%s: Misplaced optional argument: #%d must be at position %d.\n"), fname, 1, 4); return -1; } //get variable address sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddr1); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } // Retrieve a matrix of double at position 1. sciErr = getMatrixOfDouble(pvApiCtx, piAddr1, &m1, &n1, &l1); if (sciErr.iErr) { Scierror(202, _("%s: Wrong type for argument #%d: A real expected.\n"), fname, 1); printError(&sciErr, 0); return 1; } if (nbInputArgument(pvApiCtx) == 1) { int i; if (m1 * n1 == 0) { AssignOutputVariable(pvApiCtx, 1) = 0; ReturnArguments(pvApiCtx); return 0; } if (m1 == 1 || n1 == 1) { Scierror(999, _("%s: Wrong size for input argument #%d.\n"), fname, 1); return 1; } l3 = l1; m3 = m1; n3 = n1; m1 = 1; n1 = m3; m2 = 1; n2 = n3; l1 = (double *)MALLOC(sizeof(double) * n1); for (i = 0; i < n1; ++i) { l1[i] = i + 1; } l2 = (double *)MALLOC(sizeof(double) * n2); for (i = 0; i < n2; ++i) { l2[i] = i + 1; } mustFree = 1; } if (nbInputArgument(pvApiCtx) >= 3) { //get variable address sciErr = getVarAddressFromPosition(pvApiCtx, 2, &piAddr2); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } // Retrieve a matrix of double at position 2. sciErr = getMatrixOfDouble(pvApiCtx, piAddr2, &m2, &n2, &l2); if (sciErr.iErr) { Scierror(202, _("%s: Wrong type for argument #%d: A real expected.\n"), fname, 2); printError(&sciErr, 0); return 1; } if (m1 * n1 == 0) { AssignOutputVariable(pvApiCtx, 1) = 0; ReturnArguments(pvApiCtx); return 0; } /* third argument can be a matrix z or a list list(z,zcol) */ sciErr = getVarAddressFromPosition(pvApiCtx, 3, &piAddr3); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } switch (getInputArgumentType(pvApiCtx, 3)) { case sci_matrix : //get variable address sciErr = getVarAddressFromPosition(pvApiCtx, 3, &piAddr3); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } // Retrieve a matrix of double at position 3. sciErr = getMatrixOfDouble(pvApiCtx, piAddr3, &m3, &n3, &l3); if (sciErr.iErr) { Scierror(202, _("%s: Wrong type for argument #%d: A real expected.\n"), fname, 3); printError(&sciErr, 0); return 1; } izcol = 0; break; case sci_list : izcol = 1; /* z = list(z,colors) */ sciErr = getListItemNumber(pvApiCtx, piAddr3, &m3l); if (sciErr.iErr) { Scierror(202, _("%s: Wrong type for argument #%d: A real expected.\n"), fname, 3); printError(&sciErr, 0); return 1; } if (m3l != 2) { Scierror(999, _("%s: Wrong size for input argument #%d: List of size %d expected.\n"), fname, 2, m3l, 2); return 1; } sciErr = getListItemAddress(pvApiCtx, piAddr3, 1, &piAddr31); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } sciErr = getMatrixOfDouble(pvApiCtx, piAddr31, &m3, &n3, &l3); /* z */ if (sciErr.iErr) { Scierror(202, _("%s: Wrong type for argument #%d: A real expected.\n"), fname, 3); printError(&sciErr, 0); return 1; } sciErr = getListItemAddress(pvApiCtx, piAddr3, 2, &piAddr32); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } sciErr = getMatrixOfDouble(pvApiCtx, piAddr32, &m3n, &n3n, &l3n); /* z */ if (sciErr.iErr) { Scierror(202, _("%s: Wrong type for argument #%d: A real expected.\n"), fname, 3); printError(&sciErr, 0); return 1; } zcol = (l3n); if (m3n * n3n != n3 && m3n * n3n != m3 * n3) { Scierror(999, _("%s: Wrong size for input argument #%d: %d or %d expected.\n"), fname, 3, n3, m3 * n3); return 1; } /* * Added by E Segre 4/5/2000. In the case where zcol is a * matrix of the same size as z, we set izcol to 2. This * value is later transmitted to the C2F(fac3dg) routine, * which has been modified to do the interpolated shading * (see the file SCI/modules/graphics/src/c/Plo3d.c */ if (m3n * n3n == m3 * n3) { izcol = 2 ; } break; default : OverLoad(3); return 0; } } if (m1 * n1 == m3 * n3 && m1 * n1 == m2 * n2 && m1 * n1 != 1) { if (! (m1 == m2 && m2 == m3 && n1 == n2 && n2 == n3)) { Scierror(999, _("%s: Wrong value for input arguments #%d, #%d and #%d: Incompatible length.\n"), fname, 1, 2, 3); return 1; } } else { if (m2 * n2 != n3) { Scierror(999, _("%s: Wrong value for input arguments #%d and #%d: Incompatible length.\n"), fname, 2, 3); return 1; } if (m1 * n1 != m3) { Scierror(999, _("%s: Wrong value for input arguments #%d and #%d: Incompatible length.\n"), fname, 1, 3); return 1; } if (m1 * n1 <= 1 || m2 * n2 <= 1) { Scierror(999, _("%s: Wrong size for input arguments #%d and #%d: %s expected.\n"), fname, 2, 3, ">= 2"); return 1; } } if (m1 * n1 == 0 || m2 * n2 == 0 || m3 * n3 == 0) { AssignOutputVariable(pvApiCtx, 1) = 0; ReturnArguments(pvApiCtx); return 0; } iflag_def[1] = 8; GetOptionalDoubleArg(pvApiCtx, fname, 4, "theta", &theta, 1, opts); GetOptionalDoubleArg(pvApiCtx, fname, 5, "alpha", &alpha, 1, opts); GetLabels(pvApiCtx, fname, 6, opts, &legend); GetOptionalIntArg(pvApiCtx, fname, 7, "flag", &iflag, 3, opts); GetOptionalDoubleArg(pvApiCtx, fname, 8, "ebox", &ebox, 6, opts); getOrCreateDefaultSubwin(); /******************** 24/05/2002 ********************/ if (m1 * n1 == m3 * n3 && m1 * n1 == m2 * n2 && m1 * n1 != 1) /* NG beg */ { isfac = 1; } else { isfac = 0; } Objplot3d (fname, &isfac, &izcol, (l1), (l2), (l3), zcol, &m3, &n3, theta, alpha, legend, iflag, ebox, &m1, &n1, &m2, &n2, &m3, &n3, &m3n, &n3n); /*Adding F.Leray 12.03.04 and 19.03.04*/ if (mustFree) { FREE(l1); FREE(l2); } AssignOutputVariable(pvApiCtx, 1) = 0; ReturnArguments(pvApiCtx); return 0; }
int main() { bool test = false, simulateBathy = false; if (test) { runTests(); return 0; } acousticParams.insert({ "debug", "0" }); acousticParams.insert({ "cellSize", "5" }); acousticParams.insert({ "fishmodel", "0" }); acousticParams.insert({ "suppressionRangeFactor", "1"}), acousticParams.insert({ "suppressionMethod", "suppression.quick"}), acousticParams.insert({ "userSensors", "100,100,0,0,100,0,0,200" }); acousticParams.insert({ "numOptimalSensors", "10" }); acousticParams.insert({ "numProjectedSensors", "2" }); acousticParams.insert({ "bias", "2" }); acousticParams.insert({ "ousdx", ".1" }); acousticParams.insert({ "ousdy", ".1" }); acousticParams.insert({ "oucor", "0" }); acousticParams.insert({ "mux", ".5" }); acousticParams.insert({ "muy", ".5" }); acousticParams.insert({ "fishmodel", "1" }); acousticParams.insert({ "minDepth", "15" }); acousticParams.insert({ "maxDepth", "30" }); acousticParams.insert({ "meanRelativePosition", "1" }); acousticParams.insert({ "relativePositionSD", "1" }); // acousticParams.insert({"inputFile", "himbsyn.bathy.v19.grd"}); acousticParams.insert({"inputFile", "himbsyn.bathytopo.1km.v19.grd"}); // acousticParams.insert({ "inputFile", "pal_5m.asc" }); acousticParams.insert({ "inputFileType", "netcdf" }); acousticParams.insert({ "seriesName", "z" }); acousticParams.insert({ "timestamp", "-1" }); acousticParams.insert({ "logScaleGraphColoring", "1" }); acousticParams.insert({ "contourDepths", "0,-20,-40,-80" }); double suppressionRangeFactor = std::stod(acousticParams["suppressionRangeFactor"]), ousdx = std::stod(acousticParams["ousdx"]), ousdy = std::stod(acousticParams["ousdy"]), oucor = std::stod(acousticParams["oucor"]), mux = std::stod(acousticParams["mux"]), muy = std::stod(acousticParams["muy"]), fishmodel = std::stod(acousticParams["fishmodel"]), networkSparsity = 0, absRecoveryRate = 0, uniqueRecoveryRate = 0, goodnessGridComputationTime = 0, totalComputationTime = 0; int startRow = 450, startCol = 340, // 450,340,201,201 (1km)netcdf rowDist = 1001, // 100 0 800 1500 (5m)netcdf colDist = 1001, // 300 200 501 501 (palmyra) asc height = 1000, width = 1000, bias = 2, sensorDetectionRange = 4, sensorDetectionDiameter = 2 * sensorDetectionRange + 1, sensorPeakDetectionProbability = 1, SDofSensorDetectionRange = 1, i = 0, row = 0, col = 0, cellSize = std::stoi(acousticParams["cellSize"]), numOptimalSensors = std::stoi(acousticParams["numOptimalSensors"]), numProjectedSensors = std::stoi(acousticParams["numProjectedSensors"]), numSensorsToPlace = numOptimalSensors + numProjectedSensors, suppressionDiameter = (2 * ceil(sensorDetectionRange * suppressionRangeFactor)) + 1; // Set the global border size border = sensorDetectionRange; omp_set_num_threads(numThreads); Eigen::setNbThreads(numThreads); clock_t begin, end, vizBegin, vizEnd; // TODO(Greg) Data validation // Parse User Sensor Placements std::cout << "\nReading userSensor List...\n"; std::vector<std::string> userSensors; parseCDString(&userSensors, acousticParams["userSensors"], ','); Eigen::MatrixXd userSensorList; userSensorList.resize(userSensors.size()/2, 4); for (i = 0; i < userSensorList.rows(); i ++) { row = std::stoi(userSensors[2 * i]); col = std::stoi(userSensors[2 * i + 1]); if (row < 0 || col < 0 || row >= rowDist || col >= colDist) { printError("A user-defined sensor is out of bounds.", 1, acousticParams["timestamp"]); } // Translate user points to our internal grid userSensorList(i, 0) = row; userSensorList(i, 1) = col; } begin = clock(); // Compute contour depth meta data (used for graphical output) std::vector<std::string> contourLevels; parseCDString(&contourLevels, acousticParams["contourDepths"], ','); // Note the number of contours we need to graph acousticParams.insert({ "numContourDepths", std::to_string(contourLevels.size()) }); // TODO(Greg) Sort is broken, throws segfaults. Possibly b/c file doesn't // exist (tried with pal5m.asc). fix plx. // sort(&contourLevels, &contourLevels + numContourDepths); // File path variables std::string outputDataFilePath = "data/", outputDataFileType = ".dat", bathymetryTitle = "Topography", habitatTitle = "Habitat", goodnessTitle = "Goodness", coverageTitle = "Acoustic Coverage", bathymetryFilePath = outputDataFilePath + bathymetryTitle + outputDataFileType, habitatFilePath = outputDataFilePath + habitatTitle + outputDataFileType, goodnessFilePath = outputDataFilePath + goodnessTitle + outputDataFileType, coverageFilePath = outputDataFilePath + coverageTitle + outputDataFileType; Grid bGrid(rowDist + 2 * border, colDist + 2 * border, "Behavior"); Grid gGrid(rowDist + 2 * border, colDist + 2 * border, "Goodness"); Grid tGrid(rowDist + 2 * border, colDist + 2 * border, "Topography"); Grid cGrid(rowDist + 2 * border, colDist + 2 * border, "Coverage"); Eigen::MatrixXd suppressionReference; Eigen::MatrixXd distanceGradient; Eigen::MatrixXd detectionGradient; distanceGradient.resize(sensorDetectionDiameter, sensorDetectionDiameter); distanceGradient.setConstant(0); detectionGradient.resize(sensorDetectionDiameter, sensorDetectionDiameter); detectionGradient.setConstant(0); // Create a gradient of distances to avoid redundant computation makeDistGradient(&distanceGradient, sensorDetectionRange); // Create a gradient of probability of detection (due to sensorRange) to // avoid redundant computation makeDetectionGradient(&detectionGradient, & distanceGradient, sensorPeakDetectionProbability, SDofSensorDetectionRange); // Fetch or simulate topography std::cout << "Getting topography..."; if (simulateBathy) { // Simulate topography simulatetopographyGrid(&tGrid, rowDist, colDist); } else { // Fetch actual topography getBathy(&tGrid, acousticParams["inputFile"], acousticParams["inputFileType"], size_t(startRow), size_t(startCol), size_t(rowDist), size_t(colDist), acousticParams["seriesName"], acousticParams["timestamp"]); } std::cout << bGrid.data; // Fill in Behavior Grid std::cout << "\nGetting Behavior..."; populateBehaviorGrid(&tGrid, &bGrid, bias, cellSize, ousdx, ousdy, oucor, mux, muy, fishmodel); // Initalize the Coverage Grid cGrid.data.block(border, border, rowDist, colDist).setConstant(1); // Mr. Gaeta, START THE CLOCK! vizBegin = clock(); std::cout << "\nGetting Goodness...\nBias: " << bias << "\n"; // Calculate good sensor locations calculateGoodnessGrid(&tGrid, &bGrid, &gGrid, &suppressionReference, &detectionGradient, &distanceGradient, bias, sensorDetectionRange, border, border, rowDist, colDist); vizEnd = clock(); goodnessGridComputationTime = static_cast<double>(end - begin) / CLOCKS_PER_SEC; std::cout << "Copying goodness grid...\n"; Grid UGGrid(&gGrid, "Unsuppressed Goodness"); // Find optimal placements std::cout << "\nPlacing Sensors...\n"; Eigen::MatrixXd bestSensors; bestSensors.resize(numSensorsToPlace, 4); //============================ gGrid.name = "x1"; Graph x1Graph = Graph(&gGrid); x1Graph.writeMat(); // Grab the top n sensor r,c locations and recovery rates. selectTopSensorLocations(&tGrid, &bGrid, &gGrid, &UGGrid, &bestSensors, &userSensorList, &suppressionReference, &detectionGradient, &distanceGradient, numSensorsToPlace, sensorDetectionRange, bias, suppressionRangeFactor, suppressionDiameter, sensorPeakDetectionProbability, SDofSensorDetectionRange, acousticParams["timestamp"]); gGrid.name = "x2"; Graph x2Graph = Graph(&gGrid); x2Graph.writeMat(); std::cout << bestSensors << "\n"; std::cout << "Computing Statistics...\n"; getStats(&UGGrid, &gGrid, &bestSensors, sensorDetectionRange, &networkSparsity, &absRecoveryRate, &uniqueRecoveryRate, &cGrid); gGrid.name = "x3"; Graph x3Graph = Graph(&gGrid); x3Graph.writeMat(); gGrid.name = "Goodness"; // Generate graphs std::cout<< "\nWriting Graphs..."; Graph gGraph = Graph(&UGGrid); Graph tGraph = Graph(&tGrid); Graph bGraph = Graph(&bGrid); Graph cGraph = Graph(&cGrid); try { // Print the matrix & data files for Topography Grid tGraph.writeMat(); tGraph.writeDat(); // Print the contour file used by all graphs. // (Do this just once as it takes a loooong time). tGraph.printContourFile(&contourLevels); // Graph the Topography Grid with contour lines. bool plotSensors = true; tGraph.printContourGraph(width, height, &contourLevels, plotSensors, &userSensorList, &bestSensors, numProjectedSensors, false); // Print the matrix & data files for Bathymetry Grid bGraph.writeMat(); bGraph.writeDat(); // Graph Behavior Grid with contour lines. bGraph.printContourGraph(width, height, &contourLevels, plotSensors, &userSensorList, &bestSensors, numProjectedSensors, false); // Print the matrix & data files for Goodness Grid gGraph.writeMat(); gGraph.writeDat(); // Graph Goodness Grid with contour lines. gGraph.printContourGraph(width, height, &contourLevels, plotSensors, &userSensorList, &bestSensors, numProjectedSensors, false); // Print the matrix & data files for Goodness Grid cGraph.writeMat(); cGraph.writeDat(); // Graph Goodness Grid with contour lines. cGraph.printContourGraph(width, height, &contourLevels, plotSensors, &userSensorList, &bestSensors, numProjectedSensors, false); } catch (int e) { std::cout << "Error:" << e << "\n"; return 0; } end = clock(); goodnessGridComputationTime = static_cast<double>(vizEnd - vizBegin) / CLOCKS_PER_SEC; std::cout << "\nVisibility calculation took " << goodnessGridComputationTime << " s"; totalComputationTime = static_cast<double>(end - begin) / CLOCKS_PER_SEC; std::cout << "\nEntire Run took " << totalComputationTime << " s"; return 0; }
int server::listenAndserve() { char * sfdstr = getenv("sfd"); char * epollfdstr = getenv("epollfd"); //return 0; if(sfdstr){ sfd = atoi(sfdstr); } if(epollfdstr) { //epollfd = atoi(epollfdstr); } if(sfd == 0) { sfd = socket(AF_INET,SOCK_STREAM,0); int flag = fcntl(sfd,F_GETFL,0); int result = fcntl(sfd,F_SETFL,flag | O_NONBLOCK); if(sfd < 0) { printf("create socket error\n"); exit(-1); //closeProc(); } struct sockaddr_in addr; bzero(&addr,sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(10001); printf("port is %d\n",addr.sin_port); int on; on = 1; setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&on, sizeof(on)); int bid = bind(sfd,(struct sockaddr*)&addr,sizeof(struct sockaddr)); if(bid < 0) { printf("bind err\n"); printError(errno,__LINE__); exit(-1); //closeProc(); } int lister = listen(sfd,10); if(lister < 0){ printError(errno,__LINE__); exit(-1); //closeProc(); }else { printf("listen sucess\n"); } } if(epollfd == 0) { epollfd = epoll_create1(0); printf("epofd = %d\n",epollfd); } { Connection * sfdConnect = new Connection(sfd,NULL); int add = EventProcess(epollfd,sfd,EPOLL_CTL_ADD,EPOLLET|EPOLLIN|EPOLLOUT,sfdConnect); if(add < 0) { printError(errno,__LINE__); exit(-1); //closeProc(); } } printf("------------------\n"); logger->Loginfo("sfd = %d sfd = %d",sfd,epollfd); { int x = pipe(loopSwitch); if(x < 0) { printf("create pipe err\n"); } //loopSwitch = open("./loopSwitch",O_CREAT|O_RDWR,0644); Connection * sfdConnect = new Connection(loopSwitch[0],NULL); int add = EventProcess(epollfd,loopSwitch[0],EPOLL_CTL_ADD,EPOLLET|EPOLLIN|EPOLLOUT,sfdConnect); // if(add < 0) { // printf("add looperr errno %d\n",errno); // } if(add < 0) { printError(errno,__LINE__); exit(-1); //closeProc(); } } int subfd = 0; struct sockaddr_in remoteaddr; socklen_t len; struct epoll_event *eventArry = (struct epoll_event*)malloc(sizeof(struct epoll_event) * MAXEVENTS); int num = 0,index = 0; while(true) { bzero(eventArry,sizeof(struct epoll_event) * MAXEVENTS); struct sigaction act; int sig = SIGSEGV; sigemptyset(&act.sa_mask); sigaddset(&act.sa_mask,SIGUSR1); sigaddset(&act.sa_mask,SIGUSR2); num = epoll_pwait(epollfd,eventArry,MAXEVENTS,-1,NULL); //printf("wait success num = %d err %d pid = %d\n",num,errno,getpid()); int xx = errno; if(num == -1) { switch(xx) { case EBADF:{ break; } case EFAULT:{ break; } case EINTR:{ break; } case EINVAL:{ break; } } continue; } // EBADF epfd is not a valid file descriptor. // // EFAULT The memory area pointed to by events is not accessible with write permis‐ // sions. // // EINTR The call was interrupted by a signal handler before either (1) any of the // requested events occurred or (2) the timeout expired; see signal(7). // // EINVAL epfd is not an epoll file descriptor, or maxevents is less than or equal to // zero. for(index = 0;index < num; index++) { Connection * context = (Connection*)eventArry[index].data.ptr; int aFd = context->fd; int subfd = -1; if(aFd == sfd) { if(accepton) { while((subfd = accept(sfd,(struct sockaddr*)&remoteaddr,&len)) > 0){ Connection * connection = new Connection(subfd,&remoteaddr); //printf("172 addr %x\n",connection); EventProcess(epollfd,subfd,EPOLL_CTL_ADD,EPOLLET|EPOLLIN ,connection); //handleConnect(connection); connection->readHandler = &readHandler; } } }else if( aFd == loopSwitch[0] ||aFd == loopSwitch[1]){ printf("pipe closed\n"); return 0; } else { Connection * connection = (Connection*)eventArry[index].data.ptr; //printf("179 addr %x\n",connection); if(eventArry[index].events & EPOLLIN) { if(connection->readHandler != NULL){ int x = connection->readHandler(connection); if(x == 0) { EventProcess(epollfd,aFd,EPOLL_CTL_DEL,0,NULL); connection->Close(); delete(connection); } } } } } // subfd = accept(sfd,(struct sockaddr*)&remoteaddr,&len); //printf("remoate port %d\n",remoteaddr.sin_port); //close(subfd); } }
/*--------------------------------------------------------------------------*/ int sci_gsort(char *fname, unsigned long fname_len) { char iord[2]; char typex[10]; SciIntMat Im; int Type = 0; char **S = NULL; int m1 = 0, n1 = 0, l1 = 0; int m2 = 0, n2 = 0, l2 = 0; int m3 = 0, n3 = 0, l3 = 0; int ind_m1 = 0, ind_n1 = 0; int *indices = NULL; int iflag = 0; int i; iord[0] = DECREASE_COMMAND; iord[1] = '\0'; typex[0] = GLOBAL_SORT; typex[1] = '\0'; Rhs = Max(0, Rhs); CheckRhs(1, 3); CheckLhs(1, 2); if (Rhs >= 1) { Type = VarType(1); switch (Type) { case sci_strings: GetRhsVar(1, MATRIX_OF_STRING_DATATYPE, &m1, &n1, &S); break; case sci_matrix: { #define COMPLEX 1 int *header = NULL; int Cmplx = 0; header = (int *)GetData(1); Cmplx = header[3]; if (Cmplx == COMPLEX) { return gsort_complex(fname, typex, iord); } else { GetRhsVar(1, MATRIX_OF_DOUBLE_DATATYPE, &m1, &n1, &l1); if ((m1 * n1) == 0) /* [] returns [] */ { int m = 0, n = 0, l = 0; CreateVar(Rhs + 1, MATRIX_OF_DOUBLE_DATATYPE, &m, &n, &l); LhsVar(1) = Rhs + 1; if (Lhs == 2) { CreateVar(Rhs + 2, MATRIX_OF_DOUBLE_DATATYPE, &m, &n, &l); LhsVar(2) = Rhs + 2; } PutLhsVar(); return 0; } } } break; case sci_ints: GetRhsVar(1, MATRIX_OF_VARIABLE_SIZE_INTEGER_DATATYPE, &m1, &n1, &Im); break; case sci_sparse: default: OverLoad(1); return 0; break; } } if (Rhs == 3) { int* piAddr = NULL; char* pstData = NULL; SciErr sciErr = getVarAddressFromPosition(pvApiCtx, 3, &piAddr); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (getAllocatedSingleString(pvApiCtx, piAddr, &pstData)) { return 1; } if (strcmp(pstData, "i") && strcmp(pstData, "d")) { if (getWarningMode()) { sciprint(_("WARNING: %s\n"), _("This usage of the third argument of gsort is obsolete.")); sciprint(_("WARNING: %s\n"), _("It will no more be available in Scilab 6.")); sciprint(_("WARNING: %s\n"), _("Please use 'd' or 'i' instead.")); } } iord[0] = pstData[0]; freeAllocatedSingleString(pstData); } if (Rhs >= 2) { int* piAddr = NULL; char* pstData = NULL; SciErr sciErr = getVarAddressFromPosition(pvApiCtx, 2, &piAddr); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (getAllocatedSingleString(pvApiCtx, piAddr, &pstData)) { return 1; } if ((pstData[0] != ROW_SORT) && (pstData[0] != COLUMN_SORT) && (pstData[0] != GLOBAL_SORT) && (pstData[0] != LIST_SORT)) { Scierror(999, _("%s: Wrong value for input argument #%d: '%s', '%s', '%s', '%s' or '%s' expected.\n"), fname, 2, "r", "c", "g", "lr", "lc"); return 1; } if (strcmp(pstData, "c") && strcmp(pstData, "r") && strcmp(pstData, "g") && strcmp(pstData, "lc") && strcmp(pstData, "lr")) { if (getWarningMode()) { sciprint(_("WARNING: %s\n"), _("This usage of the second argument of gsort is obsolete.")); sciprint(_("WARNING: %s\n"), _("It will no more be available in Scilab 6.")); sciprint(_("WARNING: %s\n"), _("Please use 'r', 'c', 'g', 'lr' or 'lc' instead.")); } } strcpy(typex, pstData); freeAllocatedSingleString(pstData); } if (typex[0] == LIST_SORT) { if (typex[1] == ROW_SORT) { ind_m1 = m1; ind_n1 = 1; if (ind_m1 != 0) { indices = (int *)MALLOC(sizeof(int) * (ind_m1)); /* Only return in row */ } } else if (typex[1] == COLUMN_SORT) { ind_m1 = 1; ind_n1 = n1; if (ind_n1 != 0) { indices = (int *)MALLOC(sizeof(int) * (ind_n1)); /*Only return in col */ } } else { Scierror(999, _("%s: Wrong value for input argument #%d.\n"), fname, 2); return 0; } } else { ind_m1 = m1; ind_n1 = n1; if (ind_m1 * ind_n1 != 0) { indices = (int *)MALLOC(sizeof(int) * (ind_m1 * ind_n1)); /* return a matrix */ } } if (Lhs == 2) { iflag = 1; } else { iflag = 0; } switch (Type) { case sci_matrix: { if (m1 * n1 != 0) { int lr; double *matrix = stk(l1); double *tmp_matrix = NULL; /* next CreateVar and corresponding copy not needed if arg1 is not passed by reference */ if (!CreateVarNoCheck(Rhs + 1, MATRIX_OF_DOUBLE_DATATYPE, &m1, &n1, &lr)) { if (indices) { FREE(indices); indices = NULL; } return 0; } tmp_matrix = stk(lr); for (i = 0; i < m1 * n1; i++) { tmp_matrix[i] = matrix[i]; } C2F(gsortd) (tmp_matrix, indices, &iflag, &m1, &n1, typex, iord); LhsVar(1) = Rhs + 1; if (Lhs == 2) { if (!CreateVarFromPtrNoCheck(Rhs + 2, MATRIX_OF_INTEGER_DATATYPE, &ind_m1, &ind_n1, &indices)) { if (indices) { FREE(indices); indices = NULL; } return 0; } LhsVar(2) = Rhs + 2; } if (indices) { FREE(indices); indices = NULL; } PutLhsVar(); } } break; case sci_ints: { int lr; lr = Im.it; /* next CreateVar and corresponding copy not needed if arg1 is not passed by reference */ if (!CreateVarNoCheck(Rhs + 1, MATRIX_OF_VARIABLE_SIZE_INTEGER_DATATYPE, &m1, &n1, &lr)) { if (indices) { FREE(indices); indices = NULL; } return 0; } switch (Im.it) /* Type defined in stack-c.h */ { case I_CHAR: { char *matrix = Im.D; char *tmp_matrix = (char *)istk(lr); for (i = 0; i < m1 * n1; i++) { tmp_matrix[i] = matrix[i]; } C2F(gsortchar) (tmp_matrix, indices, &iflag, &m1, &n1, typex, iord); } break; case I_INT32: { int *matrix = Im.D; int *tmp_matrix = istk(lr); for (i = 0; i < m1 * n1; i++) { tmp_matrix[i] = matrix[i]; } C2F(gsortint) (tmp_matrix, indices, &iflag, &m1, &n1, typex, iord); } break; case I_UCHAR: { unsigned char *matrix = Im.D; unsigned char *tmp_matrix = (unsigned char *)istk(lr); for (i = 0; i < m1 * n1; i++) { tmp_matrix[i] = matrix[i]; } C2F(gsortuchar) (tmp_matrix, indices, &iflag, &m1, &n1, typex, iord); } break; case I_INT16: { short *matrix = Im.D; short *tmp_matrix = (short *)istk(lr); for (i = 0; i < m1 * n1; i++) { tmp_matrix[i] = matrix[i]; } C2F(gsortshort) (tmp_matrix, indices, &iflag, &m1, &n1, typex, iord); } break; case I_UINT16: { unsigned short *matrix = Im.D; unsigned short *tmp_matrix = (short *)istk(lr); for (i = 0; i < m1 * n1; i++) { tmp_matrix[i] = matrix[i]; } C2F(gsortushort) (tmp_matrix, indices, &iflag, &m1, &n1, typex, iord); } break; case I_UINT32: { unsigned int *matrix = Im.D; unsigned int *tmp_matrix = (unsigned int *)istk(lr); for (i = 0; i < m1 * n1; i++) { tmp_matrix[i] = matrix[i]; } C2F(gsortuint) (tmp_matrix, indices, &iflag, &m1, &n1, typex, iord); } break; default: if (indices) { FREE(indices); indices = NULL; } Scierror(999, _("%s: Wrong type for input argument #%d: Unknown type.\n"), fname, 1); return 0; } LhsVar(1) = Rhs + 1; if (Lhs == 2) { if (!CreateVarFromPtrNoCheck(Rhs + 2, MATRIX_OF_INTEGER_DATATYPE, &ind_m1, &ind_n1, &indices)) { if (indices) { FREE(indices); indices = NULL; } return 0; } LhsVar(2) = Rhs + 2; } if (indices) { FREE(indices); indices = NULL; } PutLhsVar(); } break; case sci_strings: { C2F(gsorts) (S, indices, &iflag, &m1, &n1, typex, iord); if (!CreateVarFromPtrNoCheck(Rhs + 1, MATRIX_OF_STRING_DATATYPE, &m1, &n1, S)) { if (indices) { FREE(indices); indices = NULL; } return 0; } LhsVar(1) = Rhs + 1; if (Lhs == 2) { if (!CreateVarFromPtrNoCheck(Rhs + 2, MATRIX_OF_INTEGER_DATATYPE, &ind_m1, &ind_n1, &indices)) { if (indices) { FREE(indices); indices = NULL; } return 0; } LhsVar(2) = Rhs + 2; } if (indices) { FREE(indices); indices = NULL; } freeArrayOfString(S, m1 * n1); PutLhsVar(); } break; default: if (indices) { FREE(indices); indices = NULL; } Scierror(999, _("%s: Wrong type for input argument #%d.\n"), fname, 1); return 0; break; } return 0; }
int sci_hdf5_load_v2(char *fn, int* pvApiCtx) { SciErr sciErr; int* piAddr = NULL; char* pstFilename = NULL; char* pstExpandedFilename = NULL; bool bImport = true; const int nbIn = nbInputArgument(pvApiCtx); int iSelectedVar = nbIn - 1; CheckInputArgumentAtLeast(pvApiCtx , 1); CheckOutputArgument(pvApiCtx, 1, 1); sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddr); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (getAllocatedSingleString(pvApiCtx, piAddr, &pstFilename)) { if (pstFilename) { freeAllocatedSingleString(pstFilename); } Scierror(999, _("%s: Wrong size for input argument #%d: A string expected.\n"), fname.data(), 2); return 1; } //open hdf5 file pstExpandedFilename = expandPathVariable(pstFilename); int iFile = openHDF5File(pstExpandedFilename, 0); if (iFile < 0) { Scierror(999, _("%s: Unable to open file: %s\n"), fname.data(), pstFilename); FREE(pstExpandedFilename); FREE(pstFilename); return 1; } FREE(pstExpandedFilename); FREE(pstFilename); //manage version information int iVersion = getSODFormatAttribute(iFile); if (iVersion != SOD_FILE_VERSION) { if (iVersion > SOD_FILE_VERSION) { //can't read file with version newer that me ! Scierror(999, _("%s: Wrong SOD file format version. Max Expected: %d Found: %d\n"), fname.data(), SOD_FILE_VERSION, iVersion); return 1; } else { //call older import functions and exit or ... EXIT ! if (iVersion == 1 || iVersion == -1) { return sci_hdf5_load_v1(fn, pvApiCtx); } } } std::vector<wchar_t*> varList; if (iSelectedVar) { //selected variable char* pstVarName = NULL; for (int i = 0 ; i < iSelectedVar ; i++) { sciErr = getVarAddressFromPosition(pvApiCtx, i + 2, &piAddr); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (getAllocatedSingleString(pvApiCtx, piAddr, &pstVarName)) { if (pstVarName) { freeAllocatedSingleString(pstVarName); } Scierror(999, _("%s: Wrong size for input argument #%d: A string expected.\n"), fname.data(), i + 1); return 1; } if (import_variable(pvApiCtx, iFile, pstVarName) == false) { FREE(pstVarName); bImport = false; break; } varList.push_back(to_wide_string(pstVarName)); FREE(pstVarName); pstVarName = NULL; } } else { //all variables int iNbItem = 0; iNbItem = getVariableNames(iFile, NULL); if (iNbItem != 0) { char **pstVarNameList = (char **)MALLOC(sizeof(char *) * iNbItem); iNbItem = getVariableNames(iFile, pstVarNameList); //import all data for (int i = 0; i < iNbItem; i++) { if (import_variable(pvApiCtx, iFile, pstVarNameList[i]) == false) { bImport = false; break; } varList.push_back(to_wide_string(pstVarNameList[i])); } freeArrayOfString(pstVarNameList, iNbItem); } } //close the file closeHDF5File(iFile); if (bImport == true && varList.size() != 0) { createMatrixOfWideString(pvApiCtx, nbIn + 1, 1, static_cast<int>(varList.size()), varList.data()); } else { createEmptyMatrix(pvApiCtx, nbIn + 1); } for (auto & i : varList) { FREE(i); } AssignOutputVariable(pvApiCtx, 1) = nbIn + 1; ReturnArguments(pvApiCtx); // printf("End gateway !!!\n"); return 0; }
int sci_umf_lusolve(char* fname, unsigned long l) { SciErr sciErr; int mb = 0; int nb = 0; int it_flag = 0; int i = 0; int j = 0; int NoTranspose = 0; int NoRaffinement = 0; SciSparse AA; CcsSparse A; /* umfpack stuff */ double Info[UMFPACK_INFO]; // double *Info = (double *) NULL; double Control[UMFPACK_CONTROL]; void* Numeric = NULL; int lnz = 0, unz = 0, n = 0, n_col = 0, nz_udiag = 0, umf_flag = 0; int* Wi = NULL; int mW = 0; double *W = NULL; int iComplex = 0; int* piAddr1 = NULL; int* piAddr2 = NULL; int* piAddr3 = NULL; int* piAddr4 = NULL; double* pdblBR = NULL; double* pdblBI = NULL; double* pdblXR = NULL; double* pdblXI = NULL; int mA = 0; // rows int nA = 0; // cols int iNbItem = 0; int* piNbItemRow = NULL; int* piColPos = NULL; double* pdblSpReal = NULL; double* pdblSpImg = NULL; /* Check numbers of input/output arguments */ CheckInputArgument(pvApiCtx, 2, 4); CheckOutputArgument(pvApiCtx, 1, 1); /* First get arg #1 : the pointer to the LU factors */ sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddr1); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } sciErr = getPointer(pvApiCtx, piAddr1, &Numeric); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } /* Check if this pointer is a valid ref to a umfpack LU numeric object */ if ( ! IsAdrInList(Numeric, ListNumeric, &it_flag) ) { Scierror(999, _("%s: Wrong value for input argument #%d: Must be a valid reference to (umf) LU factors.\n"), fname, 1); return 1; } /* get some parameters of the factorization (for some checking) */ if ( it_flag == 0 ) { umfpack_di_get_lunz(&lnz, &unz, &n, &n_col, &nz_udiag, Numeric); } else { iComplex = 1; umfpack_zi_get_lunz(&lnz, &unz, &n, &n_col, &nz_udiag, Numeric); } if ( n != n_col ) { Scierror(999, _("%s: An error occurred: %s.\n"), fname, _("This is not a factorization of a square matrix")); return 1; } if ( nz_udiag < n ) { Scierror(999, _("%s: An error occurred: %s.\n"), fname, _("This is a factorization of a singular matrix")); return 1; } /* Get now arg #2 : the vector b */ sciErr = getVarAddressFromPosition(pvApiCtx, 2, &piAddr2); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (isVarComplex(pvApiCtx, piAddr2)) { iComplex = 1; sciErr = getComplexMatrixOfDouble(pvApiCtx, piAddr2, &mb, &nb, &pdblBR, &pdblBI); } else { sciErr = getMatrixOfDouble(pvApiCtx, piAddr2, &mb, &nb, &pdblBR); } if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (mb != n || nb < 1) /* test if the right hand side is compatible */ { Scierror(999, _("%s: Wrong size for input argument #%d.\n"), fname, 2); return 1; } /* allocate memory for the solution x */ if (iComplex) { sciErr = allocComplexMatrixOfDouble(pvApiCtx, nbInputArgument(pvApiCtx) + 1, mb, nb, &pdblXR, &pdblXI); } else { sciErr = allocMatrixOfDouble(pvApiCtx, nbInputArgument(pvApiCtx) + 1, mb, nb, &pdblXR); } if (sciErr.iErr) { printError(&sciErr, 0); return 1; } /* selection between the different options : * -- solving Ax=b or A'x=b (Note: we could add A.'x=b) * -- with or without raffinement */ if (nbInputArgument(pvApiCtx) == 2) { NoTranspose = 1; NoRaffinement = 1; } else /* 3 or 4 input arguments but the third must be a string */ { char* pStr = NULL; sciErr = getVarAddressFromPosition(pvApiCtx, 3, &piAddr3); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } getAllocatedSingleString(pvApiCtx, piAddr3, &pStr); if (strcmp(pStr, "Ax=b") == 0) { NoTranspose = 1; } else if ( strcmp(pStr, "A'x=b") == 0 ) { NoTranspose = 0; } else { Scierror(999, _("%s: Wrong input argument #%d: '%s' or '%s' expected.\n"), fname, 3, "Ax=b", "A'x=b"); return 1; } if (nbInputArgument(pvApiCtx) == 4) { sciErr = getVarAddressFromPosition(pvApiCtx, 4, &piAddr4); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } if (isVarComplex(pvApiCtx, piAddr4)) { AA.it = 1; sciErr = getComplexSparseMatrix(pvApiCtx, piAddr4, &mA, &nA, &iNbItem, &piNbItemRow, &piColPos, &pdblSpReal, &pdblSpImg); } else { AA.it = 0; sciErr = getSparseMatrix(pvApiCtx, piAddr4, &mA, &nA, &iNbItem, &piNbItemRow, &piColPos, &pdblSpReal); } if (sciErr.iErr) { printError(&sciErr, 0); return 1; } // fill struct sparse AA.m = mA; AA.n = nA; AA.nel = iNbItem; AA.mnel = piNbItemRow; AA.icol = piColPos; AA.R = pdblSpReal; AA.I = pdblSpImg; /* some check... but we can't be sure that the matrix corresponds to the LU factors */ if ( mA != nA || mA != n || AA.it != it_flag ) { Scierror(999, _("%s: Wrong size for input argument #%d: %s.\n"), fname, 4, _("Matrix is not compatible with the given LU factors")); return 1; } NoRaffinement = 0; } else { NoRaffinement = 1; /* only 3 input var => no raffinement */ } } /* allocate memory for umfpack_di_wsolve usage or umfpack_zi_wsolve usage*/ Wi = (int*)MALLOC(n * sizeof(int)); if (it_flag == 1) { if (NoRaffinement) { mW = 4 * n; } else { mW = 10 * n; } } else { if (NoRaffinement) { mW = n; } else { mW = 5 * n; } } W = (double*)MALLOC(mW * sizeof(double)); if (NoRaffinement == 0) { SciSparseToCcsSparse(&AA, &A); } else { A.p = NULL; A.irow = NULL; A.R = NULL; A.I = NULL; } /* get the pointer for b */ if (it_flag == 1 && pdblBI == NULL) { int iSize = mb * nb * sizeof(double); pdblBI = (double*)MALLOC(iSize); memset(pdblBI, 0x00, iSize); } /* init Control */ if (it_flag == 0) { umfpack_di_defaults(Control); } else { umfpack_zi_defaults(Control); } if (NoRaffinement) { Control[UMFPACK_IRSTEP] = 0; } if (NoTranspose) { umf_flag = UMFPACK_A; } else { umf_flag = UMFPACK_At; } if (it_flag == 0) { for (j = 0; j < nb ; j++) { umfpack_di_wsolve(umf_flag, A.p, A.irow, A.R, &pdblXR[j * mb], &pdblBR[j * mb], Numeric, Control, Info, Wi, W); } if (iComplex == 1) { for (j = 0; j < nb ; j++) { umfpack_di_wsolve(umf_flag, A.p, A.irow, A.R, &pdblXI[j * mb], &pdblBI[j * mb], Numeric, Control, Info, Wi, W); } } } else { for (j = 0; j < nb ; j++) { umfpack_zi_wsolve(umf_flag, A.p, A.irow, A.R, A.I, &pdblXR[j * mb], &pdblXI[j * mb], &pdblBR[j * mb], &pdblBI[j * mb], Numeric, Control, Info, Wi, W); } } if (isVarComplex(pvApiCtx, piAddr2) == 0) { FREE(pdblBI); } freeCcsSparse(A); FREE(W); FREE(Wi); AssignOutputVariable(pvApiCtx, 1) = nbInputArgument(pvApiCtx) + 1; ReturnArguments(pvApiCtx); return 0; }
static bool import_poly(int* pvCtx, int _iDatasetId, int _iItemPos, int *_piAddress, char *_pstVarname) { int iRet = 0; int iComplex = 0; char pstVarName[64] = { 0 }; double **pdblReal = NULL; double **pdblImg = NULL; int *piNbCoef = NULL; int iDims = 0; int* piDims = NULL; int iSize = 0; SciErr sciErr; iRet = getDatasetInfo(_iDatasetId, &iComplex, &iDims, NULL); if (iRet < 0) { return false; } piDims = (int*)MALLOC(sizeof(int) * iDims); iSize = getDatasetInfo(_iDatasetId, &iComplex, &iDims, piDims); if (iComplex) { piNbCoef = (int *)MALLOC(iSize * sizeof(int)); pdblReal = (double **)MALLOC(iSize * sizeof(double *)); pdblImg = (double **)MALLOC(iSize * sizeof(double *)); iRet = readPolyComplexMatrix(_iDatasetId, pstVarName, iDims, piDims, piNbCoef, pdblReal, pdblImg); } else { piNbCoef = (int *)MALLOC(iSize * sizeof(int)); pdblReal = (double **)MALLOC(iSize * sizeof(double *)); iRet = readPolyMatrix(_iDatasetId, pstVarName, iDims, piDims, piNbCoef, pdblReal); } if (iRet) { FREE(piDims); FREE(piNbCoef); for (int i = 0; i < iSize; i++) { FREE(pdblReal[i]); } FREE(pdblReal); if (iComplex) { for (int i = 0; i < iSize; i++) { FREE(pdblImg[i]); } FREE(pdblImg); } return false; } if (_piAddress == NULL) { if (iComplex) { sciErr = createNamedComplexMatrixOfPoly(pvCtx, _pstVarname, pstVarName, piDims[0], piDims[1], piNbCoef, pdblReal, pdblImg); } else { sciErr = createNamedMatrixOfPoly(pvCtx, _pstVarname, pstVarName, piDims[0], piDims[1], piNbCoef, pdblReal); } } else //if not null this variable is in a list { if (iComplex) { sciErr = createComplexMatrixOfPolyInNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, pstVarName, piDims[0], piDims[1], piNbCoef, pdblReal, pdblImg); } else { sciErr = createMatrixOfPolyInNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, pstVarName, piDims[0], piDims[1], piNbCoef, pdblReal); } } FREE(piDims); FREE(piNbCoef); for (int i = 0; i < iSize; i++) { FREE(pdblReal[i]); } FREE(pdblReal); if (iComplex) { for (int i = 0; i < iSize; i++) { FREE(pdblImg[i]); } FREE(pdblImg); } if (sciErr.iErr) { printError(&sciErr, 0); return false; } return true; }
int main(int argc, char* argv[]){ if (argc < 3) { std::cout << "********* Please enter valid login & api key *********" << std::endl; std::cout << ">> bin/contacts_example username C7XDKZOQZo6HvhJPtO0MBcWl3qwtp2" << std::endl; return 1; } std::cout << "********* Textmagic::ListsController example *********" << std::endl; Textmagic::Rest::RequestData vars; Textmagic::Client tm(argv[1], argv[2]); // //******************* contactLists example *********************** std::cout << "********* ListsController.contactLists() *********" << std::endl; vars["limit"] = "5"; Textmagic::Resources<Textmagic::ContactModel> contacts = tm.Lists().contactsByList("106985"); if (tm.Lists().isError) { std::cout << tm.Lists().lastError.code << " * " << tm.Lists().lastError.message << " * " << std::endl; } else { std::cout << contacts.page << " * " << contacts.limit << " * " << contacts.pageCount << " * " << contacts.resources[0].phone << " * " << contacts.resources[0].firstName << " * " << std::endl; } // //******************* get example *********************** std::cout << "********* ListsController.get() *********" << std::endl; Textmagic::ListModel glist = tm.Lists().get("106985"); if (! tm.Lists().isError) { std::cout << "get list by id " << " * " << glist.id << " * " << glist.name << " * " << std::endl; } else { printError(tm); return 1; } // ******************* create example *********************** std::cout << "********* ListsController.create() *********" << std::endl; Textmagic::ListModel list; list.name = "!CPP_TEST_LIST"; list.description = "..."; list.membersCount = 0; list.shared = false; int result = tm.Lists().create(list); if (! tm.Lists().isError) { std::cout << "create list " << " * " << result << " * " << list.id << " * " << std::endl; } else { printError(tm); return 1; } //******************* assign / unassign example *********************** std::cout << "********* ListsController.assign/unassign() *********" << std::endl; std::vector<std::string> listContacts; listContacts.push_back("930065"); result = tm.Lists().assign(list, listContacts); std::cout << "Assign result" << " * " << list.id << " * " << Textmagic::Utils::vectorJoin(listContacts, " ") << " * " << result << " * " << std::endl; if (tm.Lists().isError) { printError(tm); return 1; } // result = tm.Lists().unassign(list, listContacts); // std::cout // << "Unassign result" << " * " // << result << " * " // << std::endl; // // if (tm.Lists().isError) { // printError(tm); // return 1; // } result = tm.Lists().remove(list.id); std::cout << "Remove result" << " * " << result << " * " << std::endl; if (tm.Lists().isError) { printError(tm); return 1; } return 0; };
void printUsage() { printError("Usage http-client <url>"); }
/* ==================================================================== */ int sci_edf_set_patientname(char *fname) { SciErr sciErr; int m1 = 0, n1 = 0; int *piAddressVarOne = NULL; int* piLenVarOne = NULL; double *pdVarOne = NULL; int iType1 = 0; int m2 = 0, n2 = 0; int *piAddressVarTwo = NULL; int* piLenVarTwo = NULL; char **stringData = NULL; int iType2 = 0; int m_out = 0, n_out = 0; double *dOut = NULL; int i; int handle; /* --> result = csum(3,8) /* check that we have only 2 parameters input */ /* check that we have only 1 parameters output */ CheckInputArgument(pvApiCtx,2,2) ; CheckOutputArgument(pvApiCtx,1,1) ; /* get Address of inputs */ sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddressVarOne); if(sciErr.iErr) { printError(&sciErr, 0); return 0; } sciErr = getVarAddressFromPosition(pvApiCtx, 2, &piAddressVarTwo); if(sciErr.iErr) { printError(&sciErr, 0); return 0; } /* check input type */ sciErr = getVarType(pvApiCtx, piAddressVarOne, &iType1); if(sciErr.iErr) { printError(&sciErr, 0); return 0; } if ( iType1 != sci_matrix ) { Scierror(999,"%s: Wrong type for input argument #%d: A integer expected.\n",fname,1); return 0; } sciErr = getVarType(pvApiCtx, piAddressVarTwo, &iType2); if(sciErr.iErr) { printError(&sciErr, 0); return 0; } if ( iType2 != sci_strings ) { Scierror(999,"%s: Wrong type for input argument #%d: A string expected.\n",fname,2); return 0; } sciErr = getMatrixOfDouble(pvApiCtx, piAddressVarOne,&m1,&n1,&pdVarOne); if(sciErr.iErr) { printError(&sciErr, 0); return 0; } /* get string */ sciErr = getMatrixOfString(pvApiCtx, piAddressVarTwo,&m2, &n2, NULL, NULL); if(sciErr.iErr) { printError(&sciErr, 0); return 0; } piLenVarTwo = (int*)malloc(sizeof(int) * m2 * n2); sciErr = getMatrixOfString(pvApiCtx, piAddressVarTwo, &m2, &n2, piLenVarTwo, NULL); if(sciErr.iErr) { printError(&sciErr, 0); return 0; } stringData = (char**)malloc(sizeof(char*) * m2 * n2); for(i = 0 ; i < n2 * m2 ; i++) { stringData[i] = (char*)malloc(sizeof(char) * (piLenVarTwo[i] + 1));//+ 1 for null termination } sciErr = getMatrixOfString(pvApiCtx, piAddressVarTwo, &m2, &n2, piLenVarTwo, stringData); if(sciErr.iErr) { printError(&sciErr, 0); return 0; } /* check size */ if ( (m1 != 1) || (n1 != 1) ) { Scierror(999,"%s: Wrong size for input argument #%d: A scalar expected.\n",fname,1); return 0; } if ( (m2 !=1) || (n2 !=1) ) { Scierror(999,"%s: Wrong size for input argument #%d: A single stringr expected.\n",fname,2); return 0; } /* call c function csum */ // csum(&pdVarOne[0],&pdVarTwo[0],&dOut); if ( edf_set_patientname(pdVarOne[0], stringData[0]) <0) { Scierror(999,"Could not write string\n"); return 0; } m_out = 1; n_out = 1; dOut = (double*)malloc(sizeof(double) * m_out*n_out); // CreateVar(1, MATRIX_OF_DOUBLE_DATATYPE, &m_out, &n_out, &dout); dOut[0]=0; /* create result on stack */ createMatrixOfDouble(pvApiCtx, nbInputArgument(pvApiCtx) + 1, m_out, n_out, dOut); free(dOut); AssignOutputVariable(pvApiCtx,1) = nbInputArgument(pvApiCtx) + 1; /* This function put on scilab stack, the lhs variable which are at the position lhs(i) on calling stack */ /* You need to add PutLhsVar here because WITHOUT_ADD_PUTLHSVAR was defined and equal to %t */ /* without this, you do not need to add PutLhsVar here */ ReturnArguments(pvApiCtx); return 0; }
/*--------------------------------------------------------------------------*/ int sci_messagebox(char *fname, unsigned long fname_len) { SciErr sciErr; int* piAddrmessageAdr = NULL; int* piAddrtitleAdr = NULL; int* piAddriconAdr = NULL; int* piAddrbuttonsTextAdr = NULL; int* piAddrmodalOptionAdr = NULL; double* buttonNumberAdr = NULL; int messageBoxID = 0; /* Used to read input arguments */ int nbRow = 0, nbCol = 0; int nbRowButtons = 0, nbColButtons = 0; int nbRowMessage = 0, nbColMessage = 0; char **buttonsTextAdr = 0; char **messageAdr = 0; char **titleAdr = 0; char **modalOptionAdr = 0; char **iconAdr = 0; /* Used to write output argument */ int buttonNumber = 0; CheckInputArgument(pvApiCtx, 1, 5); CheckOutputArgument(pvApiCtx, 0, 1); /* Message to be displayed */ if ((checkInputArgumentType(pvApiCtx, 1, sci_strings))) { sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddrmessageAdr); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } // Retrieve a matrix of string at position 1. if (getAllocatedMatrixOfString(pvApiCtx, piAddrmessageAdr, &nbRowMessage, &nbColMessage, &messageAdr)) { Scierror(202, _("%s: Wrong type for argument #%d: String matrix expected.\n"), fname, 1); return 1; } } else { Scierror(999, _("%s: Wrong type for input argument #%d: A string expected.\n"), fname, 1); return FALSE; } /* Title to be displayed */ if (nbInputArgument(pvApiCtx) >= 2) { if (checkInputArgumentType(pvApiCtx, 2, sci_strings)) { sciErr = getVarAddressFromPosition(pvApiCtx, 2, &piAddrtitleAdr); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } // Retrieve a matrix of string at position 2. if (getAllocatedMatrixOfString(pvApiCtx, piAddrtitleAdr, &nbRow, &nbCol, &titleAdr)) { Scierror(202, _("%s: Wrong type for argument #%d: String matrix expected.\n"), fname, 2); return 1; } if (nbRow*nbCol != 1) { Scierror(999, _("%s: Wrong size for input argument #%d: A string expected.\n"), fname, 2); return FALSE; } /* The title argument can be used to give the modal option */ if (isModalOption(titleAdr[0])) { modalOptionAdr = titleAdr; titleAdr = NULL; } } else { Scierror(999, _("%s: Wrong type for input argument #%d: A string expected.\n"), fname, 2); return FALSE; } } /* Icon to be displayed */ if (nbInputArgument(pvApiCtx) >= 3) { if ((checkInputArgumentType(pvApiCtx, 3, sci_strings))) { sciErr = getVarAddressFromPosition(pvApiCtx, 3, &piAddriconAdr); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } // Retrieve a matrix of string at position 3. if (getAllocatedMatrixOfString(pvApiCtx, piAddriconAdr, &nbRow, &nbCol, &iconAdr)) { Scierror(202, _("%s: Wrong type for argument #%d: String matrix expected.\n"), fname, 3); return 1; } if (nbRow*nbCol == 1) { /* The icon argument can be used to give the modal option or the buttons names */ if (isModalOption(iconAdr[0])) { modalOptionAdr = (char **)iconAdr; iconAdr = NULL; } else if (!isIconName(iconAdr[0])) { buttonsTextAdr = (char **)iconAdr; nbRowButtons = nbRow; nbColButtons = nbCol; iconAdr = NULL; } } else /* More than one string --> buttons names */ { buttonsTextAdr = (char **)iconAdr; nbRowButtons = nbRow; nbColButtons = nbCol; iconAdr = NULL; } } else { Scierror(999, _("%s: Wrong type for input argument #%d: A string or a string vector expected.\n"), fname, 3); return FALSE; } } /* Buttons names */ if (nbInputArgument(pvApiCtx) >= 4) { if ((checkInputArgumentType(pvApiCtx, 4, sci_strings))) { sciErr = getVarAddressFromPosition(pvApiCtx, 4, &piAddrbuttonsTextAdr); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } // Retrieve a matrix of string at position 4. if (getAllocatedMatrixOfString(pvApiCtx, piAddrbuttonsTextAdr, &nbRowButtons, &nbColButtons, &buttonsTextAdr)) { Scierror(202, _("%s: Wrong type for argument #%d: String matrix expected.\n"), fname, 4); return 1; } if (nbRow*nbCol == 1) { /* The buttons names argument can be used to give the modal option */ if (isModalOption(buttonsTextAdr[0])) { modalOptionAdr = buttonsTextAdr; buttonsTextAdr = NULL; } } } else { Scierror(999, _("%s: Wrong type for input argument #%d: A string or a string vector expected.\n"), fname, 3); return FALSE; } } /* Modal option */ if (nbInputArgument(pvApiCtx) == 5) { if ((checkInputArgumentType(pvApiCtx, 5, sci_strings))) { sciErr = getVarAddressFromPosition(pvApiCtx, 5, &piAddrmodalOptionAdr); if (sciErr.iErr) { printError(&sciErr, 0); return 1; } // Retrieve a matrix of string at position 5. if (getAllocatedMatrixOfString(pvApiCtx, piAddrmodalOptionAdr, &nbRow, &nbCol, &modalOptionAdr)) { Scierror(202, _("%s: Wrong type for argument #%d: String matrix expected.\n"), fname, 5); return 1; } if (nbRow*nbCol != 1) { Scierror(999, _("%s: Wrong size for input argument #%d: A string expected.\n"), fname, 5); return FALSE; } } else { Scierror(999, _("%s: Wrong type for input argument #%d: A string expected.\n"), fname, 5); return FALSE; } } /* Create the Java Object */ messageBoxID = createMessageBox(); /* Message */ setMessageBoxMultiLineMessage(messageBoxID, messageAdr, nbColMessage * nbRowMessage); freeAllocatedMatrixOfString(nbRowMessage, nbColMessage, messageAdr); /* Title */ if (titleAdr != NULL) { setMessageBoxTitle(messageBoxID, titleAdr[0]); freeAllocatedMatrixOfString(nbRow, nbCol, titleAdr); } else { setMessageBoxTitle(messageBoxID, _("Scilab Message")); } /* Icon */ if (iconAdr != NULL) { setMessageBoxIcon(messageBoxID, iconAdr[0]); freeAllocatedMatrixOfString(nbRow, nbCol, iconAdr); } /* Buttons */ if (buttonsTextAdr != NULL) { setMessageBoxButtonsLabels(messageBoxID, buttonsTextAdr, nbColButtons * nbRowButtons); freeAllocatedMatrixOfString(nbRowButtons, nbColButtons, buttonsTextAdr); } /* Modal ? */ if (modalOptionAdr != NULL) { setMessageBoxModal(messageBoxID, !stricmp(modalOptionAdr[0], "modal")); freeAllocatedMatrixOfString(nbRow, nbCol, modalOptionAdr); } else { setMessageBoxModal(messageBoxID, FALSE); } /* Display it and wait for a user input */ messageBoxDisplayAndWait(messageBoxID); /* Return the index of the button selected */ if (nbOutputArgument(pvApiCtx) == 1) { /* Read the user answer */ buttonNumber = getMessageBoxSelectedButton(messageBoxID); nbRow = 1; nbCol = 1; sciErr = allocMatrixOfDouble(pvApiCtx, nbInputArgument(pvApiCtx) + 1, nbRow, nbCol, &buttonNumberAdr); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Memory allocation error.\n"), fname); return 1; } buttonNumberAdr[0] = buttonNumber; AssignOutputVariable(pvApiCtx, 1) = nbInputArgument(pvApiCtx) + 1; } else { AssignOutputVariable(pvApiCtx, 1) = 0; } ReturnArguments(pvApiCtx); return TRUE; }
void *MakeCurrentScreenThread(void *arg) { MakeCurrentScreenThreadArgs *t; int i; int ret = 0; GLXContext *ctxs; struct window_info *wi; int screen, offset; int firstScreen, numScreens; char *vendor; struct { GLint req; GLboolean saw; void *ret; } makeCurrentTestResultsParams; t = (MakeCurrentScreenThreadArgs *)arg; wi = t->wi; ctxs = t->ctxs; numScreens = t->numScreens; firstScreen = t->firstScreen; for (i = 0; i < t->iterations; i++) { for (offset = 0; offset < numScreens; offset++) { screen = (firstScreen + offset) % numScreens; FAILIF(!glXMakeContextCurrent(wi[screen].dpy, wi[screen].win, wi[screen].win, ctxs[screen]), "Failed to make current!\n"); // Make a call to glMakeCurrentTestResults() to get the vendor // string. makeCurrentTestResultsParams.req = GL_MC_VENDOR_STRING; makeCurrentTestResultsParams.saw = GL_FALSE; makeCurrentTestResultsParams.ret = NULL; pMakeCurrentTestResults(makeCurrentTestResultsParams.req, &makeCurrentTestResultsParams.saw, &makeCurrentTestResultsParams.ret); FAILIF(!makeCurrentTestResultsParams.saw, "Failed to dispatch!\n"); FAILIF(!makeCurrentTestResultsParams.ret, "No vendor string!\n"); vendor = (char *)makeCurrentTestResultsParams.ret; DBG_PRINTF(0, "Screen %d has vendor \"%s\"\n", screen, vendor); if (strcmp(vendor, t->vendorNames[screen])) { printError("Vendor string mismatch on screen %d: " "expected \"%s\", got \"%s\"\n", screen, t->vendorNames[screen], vendor); ret = 1; } free(vendor); if (!(i % 2)) { // Test losing current as well FAILIF(!glXMakeContextCurrent(wi[screen].dpy, None, None, NULL), "Failed to lose current!\n"); } // TODO pthread_barrier_wait(nextScreenBarrier); } } cleanup: return (void *)((uintptr_t)ret); }
/* * Common, flexible, error-tolerant key pair generator. */ static int genKeyPair( CSSM_CSP_HANDLE cspHand, uint32 algorithm, const char *keyAlgStr, uint32 keySizeInBits, CSSM_KEY_PTR pubKey, CSSM_KEYATTR_FLAGS pubKeyAttr, CSSM_KEYUSE pubKeyUsage, CSSM_KEY_PTR privKey, CSSM_KEYATTR_FLAGS privKeyAttr, CSSM_KEYUSE privKeyUsage, CSSM_RETURN expectRtn, CSSM_BOOL quiet, CSSM_BOOL freeKeys, // true: free the keys on exit const char *testStr) { CSSM_RETURN crtn; CSSM_CC_HANDLE ccHand; CSSM_DATA keyLabelData = {4, (uint8 *)"foo"}; int irtn; memset(pubKey, 0, sizeof(CSSM_KEY)); memset(privKey, 0, sizeof(CSSM_KEY)); crtn = CSSM_CSP_CreateKeyGenContext(cspHand, algorithm, keySizeInBits, NULL, // Seed NULL, // Salt NULL, // StartDate NULL, // EndDate NULL, // Params &ccHand); if(crtn) { printError("CSSM_CSP_CreateKeyGenContext", crtn); return testError(quiet); } /* post-context-create algorithm-specific stuff */ switch(algorithm) { case CSSM_ALGID_RSA: break; case CSSM_ALGID_DSA: /* * extra step - generate params - this just adds some * info to the context */ { CSSM_DATA dummy = {0, NULL}; crtn = CSSM_GenerateAlgorithmParams(ccHand, keySizeInBits, &dummy); if(crtn) { printError("CSSM_GenerateAlgorithmParams", crtn); return testError(quiet); } appFreeCssmData(&dummy, CSSM_FALSE); } break; default: break; } crtn = CSSM_GenerateKeyPair(ccHand, pubKeyUsage, pubKeyAttr, &keyLabelData, pubKey, privKeyUsage, privKeyAttr, &keyLabelData, // same labels NULL, // CredAndAclEntry privKey); if(crtn != expectRtn) { printf("***Testing %s for alg %s:\n", testStr, keyAlgStr); printf(" CSSM_GenerateKeyPair: expect %s\n", cssmErrToStr(expectRtn)); printf(" CSSM_GenerateKeyPair: got %s\n", cssmErrToStr(crtn)); irtn = testError(quiet); } else { irtn = 0; } CSSM_DeleteContext(ccHand); if(freeKeys && (crtn == CSSM_OK)) { cspFreeKey(cspHand, pubKey); cspFreeKey(cspHand, privKey); } return irtn; }
static bool import_list(int* pvCtx, int _iDatasetId, int _iVarType, int _iItemPos, int *_piAddress, char *_pstVarname) { int iRet = 0; int i = 0; int iItems = 0; int *piListAddr = NULL; hobj_ref_t *piItemRef = NULL; SciErr sciErr; iRet = getListDims(_iDatasetId, &iItems); if (iRet) { return false; } if (iItems == 0) { //special case for empty list } else { iRet = getListItemReferences(_iDatasetId, &piItemRef); if (iRet) { return false; } } if (_piAddress == 0) { switch (_iVarType) { case sci_list: sciErr = createNamedList(pvCtx, _pstVarname, iItems, &piListAddr); break; case sci_tlist: sciErr = createNamedTList(pvCtx, _pstVarname, iItems, &piListAddr); break; case sci_mlist: sciErr = createNamedMList(pvCtx, _pstVarname, iItems, &piListAddr); break; default: return false; } } else //if not null this variable is in a list { switch (_iVarType) { case sci_list: sciErr = createListInNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, iItems, &piListAddr); break; case sci_tlist: sciErr = createTListInNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, iItems, &piListAddr); break; case sci_mlist: sciErr = createMListInNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, iItems, &piListAddr); break; default: return false; } } if (sciErr.iErr) { printError(&sciErr, 0); return false; } for (i = 0; i < iItems; i++) { int iItemDataset = 0; iRet = getListItemDataset(_iDatasetId, piItemRef, i, &iItemDataset); if (iRet || iItemDataset == 0) { return false; } bool bRet = import_data(pvCtx, iItemDataset, i + 1, piListAddr, _pstVarname); if (bRet == false) { return false; } } iRet = deleteListItemReferences(_iDatasetId, piItemRef); if (iRet) { return false; } return true; }
/*--------------------------------------------------------------------------*/ int sci_chdir(char *fname, unsigned long fname_len) { SciErr sciErr; int *piAddressVarOne = NULL; wchar_t *pStVarOne = NULL; int iType1 = 0; int lenStVarOne = 0; int m1 = 0, n1 = 0; wchar_t *expandedPath = NULL; Rhs = Max(0, Rhs); CheckRhs(0, 1); CheckLhs(1, 1); if (Rhs == 0) { pStVarOne = (wchar_t*)MALLOC(sizeof(wchar_t) * ((int)wcslen(L"home") + 1)); if (pStVarOne) { wcscpy(pStVarOne, L"home"); } } else { sciErr = getVarAddressFromPosition(pvApiCtx, 1, &piAddressVarOne); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); return 0; } sciErr = getVarType(pvApiCtx, piAddressVarOne, &iType1); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); return 0; } if (iType1 != sci_strings ) { Scierror(999, _("%s: Wrong type for input argument #%d: A string expected.\n"), fname, 1); return 0; } // get value of lenStVarOne sciErr = getMatrixOfWideString(pvApiCtx, piAddressVarOne, &m1, &n1, &lenStVarOne, NULL); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); return 0; } if ( (m1 != n1) && (n1 != 1) ) { Scierror(999, _("%s: Wrong size for input argument #%d: A string expected.\n"), fname, 1); return 0; } pStVarOne = (wchar_t*)MALLOC(sizeof(wchar_t) * (lenStVarOne + 1)); if (pStVarOne == NULL) { Scierror(999, _("%s: Memory allocation error.\n"), fname); return 0; } sciErr = getMatrixOfWideString(pvApiCtx, piAddressVarOne, &m1, &n1, &lenStVarOne, &pStVarOne); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read input argument #%d.\n"), fname, 1); return 0; } } expandedPath = expandPathVariableW(pStVarOne); if (pStVarOne) { FREE(pStVarOne); pStVarOne = NULL; } if (expandedPath) { /* get value of PWD scilab variable (compatiblity scilab 4.x) */ if (wcscmp(expandedPath, L"PWD") == 0) { sciErr = getNamedVarType(pvApiCtx, "PWD", &iType1); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read named argument %s.\n"), fname, "PWD"); return 0; } if (iType1 == sci_strings) { wchar_t *VARVALUE = NULL; int VARVALUElen = 0; int m = 0, n = 0; sciErr = readNamedMatrixOfWideString(pvApiCtx, "PWD", &m, &n, &VARVALUElen, &VARVALUE); if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Can not read named argument %s.\n"), fname, "PWD"); return 0; } if ( (m == 1) && (n == 1) ) { VARVALUE = (wchar_t*)MALLOC(sizeof(wchar_t) * (VARVALUElen + 1)); if (VARVALUE) { readNamedMatrixOfWideString(pvApiCtx, "PWD", &m, &n, &VARVALUElen, &VARVALUE); FREE(expandedPath); expandedPath = VARVALUE; } } } } if (strcmp(fname, "chdir") == 0) /* chdir output boolean */ { BOOL *bOutput = (BOOL*)MALLOC(sizeof(BOOL)); int ierr = scichdirW(expandedPath); if (ierr) { bOutput[0] = FALSE; } else { bOutput[0] = TRUE; } sciErr = createMatrixOfBoolean(pvApiCtx, Rhs + 1, 1, 1, bOutput); if (sciErr.iErr) { printError(&sciErr, 0); FREE(bOutput); Scierror(999, _("%s: Memory allocation error.\n"), fname); return 0; } LhsVar(1) = Rhs + 1; if (bOutput) { FREE(bOutput); bOutput = NULL; } PutLhsVar(); } else /* cd output string current path */ { if ( isdirW(expandedPath) || (wcscmp(expandedPath, L"/") == 0) || (wcscmp(expandedPath, L"\\") == 0) ) { int ierr = scichdirW(expandedPath); wchar_t *currentDir = scigetcwdW(&ierr); if ( (ierr == 0) && currentDir) { sciErr = createMatrixOfWideString(pvApiCtx, Rhs + 1, 1, 1, ¤tDir); } else { sciErr = createMatrixOfDouble(pvApiCtx, Rhs + 1, 0, 0, NULL); } if (sciErr.iErr) { printError(&sciErr, 0); Scierror(999, _("%s: Memory allocation error.\n"), fname); return 0; } LhsVar(1) = Rhs + 1; if (currentDir) { FREE(currentDir); currentDir = NULL; } PutLhsVar(); } else { char *path = wide_string_to_UTF8(expandedPath); if (path) { Scierror(998, _("%s: Cannot go to directory %s\n"), fname, path); FREE(path); path = NULL; } else { Scierror(998, _("%s: Cannot go to directory.\n"), fname); } } } FREE(expandedPath); expandedPath = NULL; } else { Scierror(999, _("%s: Memory allocation error.\n"), fname); } return 0; }
static bool import_double(int* pvCtx, int _iDatasetId, int _iItemPos, int *_piAddress, char *_pstVarname) { SciErr sciErr; int iRet = 0; double *pdblReal = NULL; double *pdblImg = NULL; int iDims = 0; int* piDims = NULL; int iComplex = 0; int iSize = 0; iRet = getDatasetInfo(_iDatasetId, &iComplex, &iDims, NULL); if (iRet < 0) { return false; } if (iDims) { if (iDims > 2) { //hypermatrix return false; } piDims = (int*)MALLOC(sizeof(int) * iDims); iSize = getDatasetInfo(_iDatasetId, &iComplex, &iDims, piDims); if (iSize > 0) { pdblReal = (double *)MALLOC(iSize * sizeof(double)); if (iComplex) { pdblImg = (double *)MALLOC(iSize * sizeof(double)); iRet = readDoubleComplexMatrix(_iDatasetId, pdblReal, pdblImg); } else { iRet = readDoubleMatrix(_iDatasetId, pdblReal); } //to be sure ti have 2 dims if (iDims == 1) { FREE(piDims); piDims = (int*)MALLOC(sizeof(int) * 2); piDims[0] = 1; piDims[1] = iSize; } } } if (iDims == 0 || iSize == 0) //empty matrix { if (piDims) { FREE(piDims); } /*bug 7224 : to close dataset */ iRet = readEmptyMatrix(_iDatasetId); if (iRet) { return false; } // Hack to sure that piDims will not be null at line 372. iDims = 2; piDims = (int*)MALLOC(sizeof(int) * iDims); memset(piDims, 0, sizeof(int) * iDims); pdblReal = (double*)MALLOC(sizeof(double) * 1); pdblReal[0] = 0; iComplex = 0; } if (_piAddress == NULL) { if (iComplex) { sciErr = createNamedComplexMatrixOfDouble(pvCtx, _pstVarname, piDims[0], piDims[1], pdblReal, pdblImg); } else { sciErr = createNamedMatrixOfDouble(pvCtx, _pstVarname, piDims[0], piDims[1], pdblReal); } } else //if not null this variable is in a list { if (iComplex) { sciErr = createComplexMatrixOfDoubleInNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, piDims[0], piDims[1], pdblReal, pdblImg); } else { sciErr = createMatrixOfDoubleInNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, piDims[0], piDims[1], pdblReal); } } FREE(piDims); FREE(pdblReal); if (iComplex) { FREE(pdblImg); } if (sciErr.iErr) { printError(&sciErr, 0); return false; } return true; }
int sci_matfile_varreadnext(char *fname, unsigned long fname_len) { mat_t *matfile = NULL; matvar_t *matvar = NULL; int fileIndex = 0; int returnedClass = 0, var_type; int * fd_addr = NULL; double tmp_dbl; SciErr sciErr; CheckRhs(1, 1); CheckLhs(1, 3); /* Input argument is the index of the file to read */ sciErr = getVarAddressFromPosition(pvApiCtx, 1, &fd_addr); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } sciErr = getVarType(pvApiCtx, fd_addr, &var_type); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } if (var_type == sci_matrix) { getScalarDouble(pvApiCtx, fd_addr, &tmp_dbl); if (!isScalar(pvApiCtx, fd_addr)) { Scierror(999, _("%s: Wrong size for first input argument: Single double expected.\n"), fname); return FALSE; } fileIndex = (int)tmp_dbl; } else { Scierror(999, _("%s: Wrong type for first input argument: Double expected.\n"), fname); return FALSE; } /* Gets the corresponding matfile */ matfile_manager(MATFILEMANAGER_GETFILE, &fileIndex, &matfile); if (matfile == NULL) { Scierror(999, _("%s: Invalid file identifier.\n"), fname); return FALSE; } matvar = Mat_VarReadNext(matfile); if ((matvar == NULL) || (matvar->name == NULL)) { /* Return empty name */ createSingleString(pvApiCtx, Rhs + 1, "\0"); LhsVar(1) = Rhs + 1; if (Lhs >= 2) { /* Return empty value */ createEmptyMatrix(pvApiCtx, Rhs + 2); LhsVar(2) = Rhs + 2; } if (Lhs == 3) { /* Return error flag instead of variable class */ createScalarDouble(pvApiCtx, Rhs + 3, NO_MORE_VARIABLES); LhsVar(3) = Rhs + 3; } PutLhsVar(); return TRUE; } /* To be sure isComplex is 0 or 1 */ matvar->isComplex = matvar->isComplex != 0; /* Return the variable name */ createSingleString(pvApiCtx, Rhs + 1, matvar->name); LhsVar(1) = Rhs + 1; returnedClass = matvar->class_type; if (Lhs >= 2) { /* Return the values */ if (!CreateMatlabVariable(pvApiCtx, Rhs + 2, matvar, NULL, -1)) /* Could not Create Variable */ { sciprint("Do not know how to read a variable of class %d.\n", matvar->class_type); returnedClass = UNKNOWN_VARIABLE_TYPE; } LhsVar(2) = Rhs + 2; } if (Lhs == 3) { /* Create class return value */ createScalarDouble(pvApiCtx, Rhs + 3, returnedClass); LhsVar(3) = Rhs + 3; } Mat_VarFree(matvar); PutLhsVar(); return TRUE; }
static bool import_integer(int* pvCtx, int _iDatasetId, int _iItemPos, int *_piAddress, char *_pstVarname) { int iRet = 0; int iDims = 0; int* piDims = NULL; int iComplex = 0; int iSize = 0; int iPrec = 0; SciErr sciErr; iRet = getDatasetInfo(_iDatasetId, &iComplex, &iDims, NULL); if (iRet < 0) { return false; } piDims = (int*)MALLOC(sizeof(int) * iDims); iSize = getDatasetInfo(_iDatasetId, &iComplex, &iDims, piDims); iRet = getDatasetPrecision(_iDatasetId, &iPrec); if (iRet) { FREE(piDims); return false; } switch (iPrec) { case SCI_INT8: { char *pcData = NULL; pcData = (char *)MALLOC(sizeof(char) * iSize); iRet = readInteger8Matrix(_iDatasetId, pcData); if (iRet) { FREE(piDims); return false; } if (_piAddress == NULL) { sciErr = createNamedMatrixOfInteger8(pvCtx, _pstVarname, piDims[0], piDims[1], pcData); } else { sciErr = createMatrixOfInteger8InNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, piDims[0], piDims[1], pcData); } FREE(pcData); } break; case SCI_UINT8: { unsigned char *pucData = NULL; pucData = (unsigned char *)MALLOC(sizeof(unsigned char) * iSize); iRet = readUnsignedInteger8Matrix(_iDatasetId, pucData); if (iRet) { FREE(piDims); return false; } if (_piAddress == NULL) { sciErr = createNamedMatrixOfUnsignedInteger8(pvCtx, _pstVarname, piDims[0], piDims[1], pucData); } else { sciErr = createMatrixOfUnsignedInteger8InNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, piDims[0], piDims[1], pucData); } FREE(pucData); } break; case SCI_INT16: { short *psData = NULL; psData = (short *)MALLOC(sizeof(short) * iSize); iRet = readInteger16Matrix(_iDatasetId, psData); if (iRet) { FREE(piDims); return false; } if (_piAddress == NULL) { sciErr = createNamedMatrixOfInteger16(pvCtx, _pstVarname, piDims[0], piDims[1], psData); } else { sciErr = createMatrixOfInteger16InNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, piDims[0], piDims[1], psData); } FREE(psData); } break; case SCI_UINT16: { unsigned short *pusData = NULL; pusData = (unsigned short *)MALLOC(sizeof(unsigned short) * iSize); iRet = readUnsignedInteger16Matrix(_iDatasetId, pusData); if (iRet) { FREE(piDims); return false; } if (_piAddress == NULL) { sciErr = createNamedMatrixOfUnsignedInteger16(pvCtx, _pstVarname, piDims[0], piDims[1], pusData); } else { sciErr = createMatrixOfUnsignedInteger16InNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, piDims[0], piDims[1], pusData); } FREE(pusData); } break; case SCI_INT32: { int *piData = NULL; piData = (int *)MALLOC(sizeof(int) * iSize); iRet = readInteger32Matrix(_iDatasetId, piData); if (iRet) { FREE(piDims); return false; } if (_piAddress == NULL) { sciErr = createNamedMatrixOfInteger32(pvCtx, _pstVarname, piDims[0], piDims[1], piData); } else { sciErr = createMatrixOfInteger32InNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, piDims[0], piDims[1], piData); } FREE(piData); } break; case SCI_UINT32: { unsigned int *puiData = NULL; puiData = (unsigned int *)MALLOC(sizeof(unsigned int) * iSize); iRet = readUnsignedInteger32Matrix(_iDatasetId, puiData); if (iRet) { FREE(piDims); return false; } if (_piAddress == NULL) { sciErr = createNamedMatrixOfUnsignedInteger32(pvCtx, _pstVarname, piDims[0], piDims[1], puiData); } else { sciErr = createMatrixOfUnsignedInteger32InNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, piDims[0], piDims[1], puiData); } FREE(puiData); } break; case SCI_INT64: { #ifdef __SCILAB_INT64__ long long *pllData = NULL; pllData = (long long *)MALLOC(sizeof(long long) * iSize); iRet = readInteger64Matrix(_iDatasetId, pllData); if (iRet) { FREE(piDims); return false; } if (_piAddress == NULL) { sciErr = createNamedMatrixOfInteger64(pvCtx, _pstVarname, piDims[0], piDims[1], pllData); } else { sciErr = createMatrixOfInteger64InNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, piDims[0], piDims[1], pllData); } FREE(pllData); #else FREE(piDims); return false; #endif } break; case SCI_UINT64: { #ifdef __SCILAB_INT64__ unsigned long long *pullData = NULL; pullData = (unsigned long long *)MALLOC(sizeof(unsigned long long) * iSize); iRet = readUnsignedInteger64Matrix(_iDatasetId, pullData); if (iRet) { FREE(piDims); return false; } if (_piAddress == NULL) { sciErr = createNamedMatrixOfUnsignedInteger64(pvCtx, _pstVarname, piDims[0], piDims[1], pullData); } else { sciErr = createMatrixOfUnsignedInteger64InNamedList(pvCtx, _pstVarname, _piAddress, _iItemPos, piDims[0], piDims[1], pullData); } FREE(pullData); #else FREE(piDims); return false; #endif } break; default: return false; } FREE(piDims); if (sciErr.iErr) { printError(&sciErr, 0); return false; } return true; }
/* * symmetric key generator with startDate/endDate */ static int genSymKey( CSSM_CSP_HANDLE cspHand, CSSM_KEY_PTR symKey, uint32 alg, const char *keyAlgStr, uint32 keySizeInBits, CSSM_KEYATTR_FLAGS keyAttr, CSSM_KEYUSE keyUsage, CSSM_BOOL quiet, bool setStartDate, int startDeltaDays, bool setEndDate, int endDeltaDays, CSSM_DL_DB_HANDLE *dlDbHand = NULL) // optional { CSSM_RETURN crtn; CSSM_CC_HANDLE ccHand; CSSM_DATE startDate; CSSM_DATE endDate; if(setStartDate) { setDate(startDate, startDeltaDays); } if(setEndDate) { setDate(endDate, endDeltaDays); } memset(symKey, 0, sizeof(CSSM_KEY)); crtn = CSSM_CSP_CreateKeyGenContext(cspHand, alg, keySizeInBits, // keySizeInBits NULL, // Seed NULL, // Salt setStartDate ? &startDate : NULL, setEndDate ? &endDate : NULL, NULL, // Params &ccHand); if(crtn) { printError("CSSM_CSP_CreateKeyGenContext", crtn); return testError(quiet); } if(dlDbHand) { /* add in DL/DB to context */ crtn = cspAddDlDbToContext(ccHand, dlDbHand->DLHandle, dlDbHand->DBHandle); if(crtn) { return testError(quiet); } } crtn = CSSM_GenerateKey(ccHand, keyUsage, keyAttr, &keyLabelData, NULL, // ACL symKey); if(crtn) { printError("CSSM_GenerateKey", crtn); return testError(quiet); } CSSM_DeleteContext(ccHand); CSSM_KEYHEADER &hdr = symKey->KeyHeader; CSSM_DATE *cdp = NULL; if(setStartDate) { cdp = &startDate; } if(compareDates(cdp, &hdr.StartDate, keyAlgStr, quiet)) { return 1; } if(setEndDate) { cdp = &endDate; } else { cdp = NULL; } if(compareDates(cdp, &hdr.EndDate, keyAlgStr, quiet)) { return 1; } return 0; }
int main(int argc, char **argv) { int rc = 0; /* Defaults */ inInAddr.sin_addr.s_addr = INADDR_ANY; inInAddr.sin_port = htons(DEFAULT_PORT); inInAddr.sin_family = AF_INET; inSocket = socket(PF_INET, SOCK_DGRAM, 0); if (0 > inSocket) { printf("socket() call failed.\n"); printError(inSocket, "socket"); rc = -1; goto socket_failed; } /* Process cmdline opts. */ char *shortOpts = "hi:e:p:"; int getoptRet; while(-1 != (getoptRet = getopt(argc, argv, shortOpts))) { switch(getoptRet) { case 'i': inInAddr.sin_addr.s_addr = inet_addr(optarg); break; case 'e': { struct ifreq fetchIfInfo; memset(&fetchIfInfo, 0, sizeof(struct ifreq)); memcpy(fetchIfInfo.ifr_name, optarg, IFNAMSIZ - 1); /* Fetch the IP address to listen to based on interface name. */ ioctl(inSocket, SIOCGIFADDR, &fetchIfInfo); struct sockaddr_in * const sockInfo = (struct sockaddr_in * const) &fetchIfInfo.ifr_addr; inInAddr.sin_addr.s_addr = sockInfo->sin_addr.s_addr; } break; case 'p': inInAddr.sin_port = htons(atoi(optarg)); break; case 'h': case '?': default: Usage(argv[0]); goto normal_exit; break; } } printf("Listening to: %s:%d\n", inet_ntoa(inInAddr.sin_addr), ntohs(inInAddr.sin_port)); int timestampOn = 1; rc = setsockopt(inSocket, SOL_SOCKET, SO_TIMESTAMP, (int *) ×tampOn, sizeof(timestampOn)); if (0 > rc) { printf("setsockopt(SO_TIMESTAMP) failed.\n"); printError(rc, "setsockopt"); goto setsockopt_failed; } rc = bind(inSocket, (struct sockaddr *) &inInAddr, sizeof(struct sockaddr_in)); if (0 > rc) { printf("UDP bind() failed.\n"); printError(rc, "bind"); goto bind_failed; } struct msghdr msg; struct iovec iov; char pktbuf[2048]; char ctrl[CMSG_SPACE(sizeof(struct timeval))]; struct cmsghdr *cmsg = (struct cmsghdr *) &ctrl; msg.msg_control = (char *) ctrl; msg.msg_controllen = sizeof(ctrl); msg.msg_name = &inInAddr; msg.msg_namelen = sizeof(inInAddr); msg.msg_iov = &iov; msg.msg_iovlen = 1; iov.iov_base = pktbuf; iov.iov_len = sizeof(pktbuf); struct timeval time_kernel, time_user; int timediff; printf("Starting main loop.\n"); for(keepRunning = true; keepRunning;) { rc = recvmsg(inSocket, &msg, 0); gettimeofday(&time_user, NULL); if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_TIMESTAMP && cmsg->cmsg_len == CMSG_LEN(sizeof(time_kernel))) { memcpy(&time_kernel, CMSG_DATA(cmsg), sizeof(time_kernel)); } printf("\n"); printf("time_kernel : %d.%06d\n", (int) time_kernel.tv_sec, (int) time_kernel.tv_usec); printf("time_user : %d.%06d\n", (int) time_user.tv_sec, (int) time_user.tv_usec); timediff = (time_user.tv_sec - time_kernel.tv_sec) * 1000000 + (time_user.tv_usec - time_kernel.tv_usec); totalUsec += timediff; ++totalPackets; rollingAverage += timediff; rollingAverage -= latencies[inDEX]; latencies[inDEX] = timediff; inDEX = (inDEX + 1) % NUM_LATENCIES; printf("Current time diff is %d \n",timediff); printf("Total Average : %d/%d = %.2f us\n", totalUsec, totalPackets, (float) totalUsec / totalPackets); printf("Rolling Average (%d samples) : %.2f us\n", NUM_LATENCIES, (float) rollingAverage / NUM_LATENCIES); } bind_failed: setsockopt_failed: close(inSocket); socket_failed: normal_exit: return rc; }