void AppleUSBUHCI::UIMRootHubStatusChange(void) { UInt8 bitmap, bit; unsigned int i, index, move; IOUSBHubPortStatus portStatus; USBLog(7, "AppleUSBUHCI[%p]::UIMRootHubStatusChange (_controllerAvailable: %d)", this, _controllerAvailable); if (_controllerAvailable && !_wakingFromHibernation) { // For UHCI, we first need to see if we have a pending resume RHCheckStatus(); // Assume a byte can hold all port bits. assert(kUHCI_NUM_PORTS < 8); /* * Encode the status change bitmap. The format of the bitmap: * bit0 = hub status changed * bit1 = port 1 status changed * bit2 = port 2 status changed * ... * See USB 1.0 spec section 11.8.3 for more info. */ bitmap = 0; bit = 0x2; for (i=1; i <= kUHCI_NUM_PORTS; i++) { GetRootHubPortStatus(&portStatus, i); if (portStatus.changeFlags != 0) { UInt64 elapsedTime; uint64_t currentTime; USBLog(5, "AppleUSBUHCI[%p]::UIMRootHubStatusChange Port %d hub flags:", this, i); RHDumpHubPortStatus(&portStatus); bitmap |= bit; // If this port has seen a recovery attempt (see below) already, check to see what the current time is and if it's > than 2 seconds since the port recovery, then 'forget" about it currentTime = mach_absolute_time(); SUB_ABSOLUTETIME(¤tTime, &_portRecoveryTime[i-1] ); absolutetime_to_nanoseconds(*(AbsoluteTime *)¤tTime, &elapsedTime); elapsedTime /= 1000000000; // Convert to seconds from nanoseconds if ( _previousPortRecoveryAttempted[i-1] && (elapsedTime >= kUHCITimeoutForPortRecovery) ) { USBLog(2, "AppleUSBUHCI[%p]::UIMRootHubStatusChange Forgetting about our portRecovery state since the last change occurred %qd seconds ago", this, elapsedTime); _previousPortRecoveryAttempted[i-1] = false; } // If this port has a PED (port enable change) AND the current status is PortPower and Port Connection (which indicates that a condition // on the bus caused the controller to disable the port) then we need to see if we should attempt to re-enable the port w/out calling the // hub driver. We will do this ONLY if the previous root hub status change for this port did NOT attempt this recovery -- we only try once if ( !_previousPortRecoveryAttempted[i-1] ) { USBLog(7, "AppleUSBUHCI[%p]::UIMRootHubStatusChange Port %d had a change: 0x%x", this, i, portStatus.changeFlags); if ( !(portStatus.statusFlags & kHubPortEnabled) // if we are not presently enabled && (portStatus.changeFlags & kHubPortEnabled) // and we were previously enabled && (portStatus.statusFlags & kHubPortConnection) // and we are presently connected && !(portStatus.changeFlags & kHubPortConnection) // and the connection has not recently changed (i.e. quick disconnect-connect) && (portStatus.statusFlags & kHubPortPower) ) // and the power is on { // Indicate that we are attempting a recovery _previousPortRecoveryAttempted[i-1] = true; currentTime = mach_absolute_time(); _portRecoveryTime[i-1] = *(AbsoluteTime*)¤tTime; USBLog(1, "AppleUSBUHCI[%p]::UIMRootHubStatusChange Port %d attempting to enable a disabled port to work around a fickle UHCI controller", this, i); USBTrace( kUSBTUHCI, kTPUHCIRootHubStatusChange, (uintptr_t)this, portStatus.statusFlags, portStatus.changeFlags, i ); RHEnablePort(i, true); // Clear the bitmap bitmap &= ~bit; } } else { // If this is just the notification that the port has been enabled, then don't reset our previousPortRecoveryAttempt if ( (portStatus.changeFlags & kHubPortEnabled) and (portStatus.statusFlags & kHubPortConnection) and (portStatus.statusFlags & kHubPortPower) and (portStatus.statusFlags & kHubPortEnabled) ) { USBLog(2, "AppleUSBUHCI[%p]::UIMRootHubStatusChange Port %d had a change but it's just the port enabled notification", this, i); } else { USBLog(2, "AppleUSBUHCI[%p]::UIMRootHubStatusChange Port %d had a change but last time we attempted a recovery, so not attempting again", this, i); _previousPortRecoveryAttempted[i-1] = false; } } } bit <<= 1; // Don't clear status bits until explicitly told to. } if (bitmap) { USBLog(5, "AppleUSBUHCI[%p]::UIMRootHubStatusChange RH status bitmap = %x", this, bitmap); } _rootHubStatusChangedBitmap = bitmap; } // Bitmap is only one byte, so it doesn't need swapping. }
bool korting::inDate(const std::string &startdate, const std::string &enddate){ int start[3]; int end[3]; start[0] = fromStringtoDate(startdate)[0]; start[1] = fromStringtoDate(startdate)[1]; start[2] = fromStringtoDate(startdate)[2]; end[0] = fromStringtoDate(enddate)[0]; end[1] = fromStringtoDate(enddate)[1]; end[2] = fromStringtoDate(enddate)[2]; if(((end[2] >= startDate[2]) and (startDate[2] >= start[2])) or ((end[2] >= endDate[2]) and (endDate[2] >= start[2])) or ((end[2] >= endDate[2]) and (startDate[2] >= start[2])) or ((endDate[2] >= end[2]) and (start[2] >= startDate[2]))){ if(((end[1] >= startDate[1]) and (startDate[1] >= start[1])) or ((end[1] >= endDate[1]) and (endDate[1] >= start[1])) or ((end[1] >= endDate[1]) and (startDate[1] >= start[1])) or ((endDate[1] >= end[1]) and (start[1] >= startDate[1]))){ if(((end[0] >= startDate[0]) and (startDate[0] >= start[0])) or ((end[0] >= endDate[0]) and (endDate[0] >= start[0])) or ((end[0] >= endDate[0]) and (startDate[0] >= start[0])) or ((endDate[0] >= end[0]) and (start[0] >= startDate[0]))){ return true; } } } return false; }
int Interpret(int, char* []) { MockDb db = {}; MockDb::_serializer_context_t printer = {}; const auto f = test::TabFoo{}; const auto t = test::TabBar{}; select(t.alpha.as(t.beta)); serialize(insert_into(t).columns(t.beta, t.gamma), printer).str(); { auto i = insert_into(t).columns(t.gamma, t.beta); i.values.add(t.gamma = true, t.beta = "cheesecake"); serialize(i, printer).str(); i.values.add(t.gamma = false, t.beta = sqlpp::tvin("coffee")); i.values.add(t.gamma = false, t.beta = sqlpp::tvin(std::string())); serialize(i, printer).str(); i.values.add(t.gamma = sqlpp::default_value, t.beta = sqlpp::null); serialize(i, printer).str(); } serialize(t.alpha = sqlpp::null, printer).str(); serialize(t.alpha = sqlpp::default_value, printer).str(); serialize(t.alpha, printer).str(); serialize(-t.alpha, printer).str(); serialize(+t.alpha, printer).str(); serialize(-(t.alpha + 7), printer).str(); serialize(t.alpha = 0, printer).str(); serialize(t.alpha = sqlpp::tvin(0), printer).str(); serialize(t.alpha == 0, printer).str(); serialize(t.alpha == sqlpp::tvin(0), printer).str(); serialize(t.alpha != 0, printer).str(); serialize(t.gamma != sqlpp::tvin(false), printer).str(); serialize(t.alpha == 7, printer).str(); serialize(t.delta = sqlpp::tvin(0), printer).str(); serialize(t.beta + "kaesekuchen", printer).str(); serialize(sqlpp::select(), printer).str(); serialize(sqlpp::select().flags(sqlpp::distinct), printer).str(); serialize(select(t.alpha, t.beta).flags(sqlpp::distinct), printer).str(); serialize(select(t.alpha, t.beta), printer).str(); serialize(select(t.alpha, t.beta).from(t), printer).str(); serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3), printer).str(); serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3).group_by(t.gamma), printer).str(); serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3).group_by(t.gamma).having(t.beta.like("%kuchen")), printer).str(); serialize(select(t.alpha, t.beta) .from(t) .where(t.alpha == 3) .group_by(t.gamma) .having(t.beta.like("%kuchen")) .order_by(t.beta.asc()), printer).str(); serialize(select(t.alpha, t.beta) .from(t) .where(t.alpha == 3) .group_by(t.gamma) .having(t.beta.like("%kuchen")) .order_by(t.beta.asc()) .limit(17) .offset(3), printer).str(); serialize(parameter(sqlpp::bigint(), t.alpha), printer).str(); serialize(parameter(t.alpha), printer).str(); serialize(t.alpha == parameter(t.alpha), printer).str(); serialize(t.alpha == parameter(t.alpha) and (t.beta + "gimmick").like(parameter(t.beta)), printer).str(); serialize(insert_into(t), printer).str(); serialize(insert_into(f).default_values(), printer).str(); serialize(insert_into(t).set(t.gamma = true), printer).str(); // serialize(insert_into(t).set(t.gamma = sqlpp::tvin(false)), printer).str(); cannot test this since gamma cannot be // null and a static assert is thrown serialize(update(t), printer).str(); serialize(update(t).set(t.gamma = true), printer).str(); serialize(update(t).set(t.gamma = true).where(t.beta.in("kaesekuchen", "cheesecake")), printer).str(); serialize(update(t).set(t.gamma = true).where(t.beta.in()), printer).str(); serialize(remove_from(t), printer).str(); serialize(remove_from(t).using_(t), printer).str(); serialize(remove_from(t).where(t.alpha == sqlpp::tvin(0)), printer).str(); serialize(remove_from(t).using_(t).where(t.alpha == sqlpp::tvin(0)), printer).str(); // functions serialize(sqlpp::value(7), printer).str(); serialize(sqlpp::verbatim<sqlpp::integral>("irgendwas integrales"), printer).str(); serialize(sqlpp::value_list(std::vector<int>({1, 2, 3, 4, 5, 6, 8})), printer).str(); serialize(exists(select(t.alpha).from(t)), printer).str(); serialize(any(select(t.alpha).from(t)), printer).str(); serialize(some(select(t.alpha).from(t)), printer).str(); serialize(count(t.alpha), printer).str(); serialize(min(t.alpha), printer).str(); serialize(max(t.alpha), printer).str(); serialize(avg(t.alpha), printer).str(); serialize(sum(t.alpha), printer).str(); serialize(sqlpp::verbatim_table("whatever"), printer).str(); // alias serialize(t.as(t.alpha), printer).str(); serialize(t.as(t.alpha).beta, printer).str(); // select alias serialize(select(t.alpha).from(t).where(t.beta > "kaesekuchen").as(t.gamma), printer).str(); serialize(t.alpha.is_null(), printer).str(); // join serialize(t.inner_join(t.as(t.alpha)).on(t.beta == t.as(t.alpha).beta), printer).str(); { auto inner = t.inner_join(t.as(t.alpha)).on(t.beta == t.as(t.alpha).beta); serialize(select(t.alpha).from(inner), printer).str(); } // multi_column serialize(multi_column(t.alpha, (t.beta + "cake").as(t.gamma)).as(t.alpha), printer).str(); serialize(multi_column(all_of(t)).as(t), printer).str(); serialize(all_of(t).as(t), printer).str(); // dynamic select { auto s = dynamic_select(db).dynamic_flags().dynamic_columns().from(t); s.selected_columns.add(t.beta); s.selected_columns.add(t.gamma); serialize(s, printer).str(); } { auto s = dynamic_select(db).dynamic_flags().dynamic_columns().from(t); s.select_flags.add(sqlpp::distinct); s.selected_columns.add(t.beta); s.selected_columns.add(t.gamma); serialize(s, printer).str(); } { // Behold, dynamically constructed queries might compile but be illegal SQL auto s = dynamic_select(db).dynamic_flags(sqlpp::distinct).dynamic_columns(t.alpha); s.select_flags.add(sqlpp::all); s.selected_columns.add(without_table_check(t.beta)); s.selected_columns.add(without_table_check(t.gamma)); serialize(s, printer).str(); } // distinct aggregate serialize(count(sqlpp::distinct, t.alpha % 7), printer).str(); serialize(avg(sqlpp::distinct, t.alpha - 7), printer).str(); serialize(sum(sqlpp::distinct, t.alpha + 7), printer).str(); serialize(select(all_of(t)).from(t).unconditionally(), printer).str(); for (const auto& row : db(select(all_of(t)).from(t).unconditionally())) { serialize(row.alpha, printer); serialize(row.beta, printer); serialize(row.gamma, printer); } get_sql_name(t); get_sql_name(t.alpha); flatten(t.alpha == 7, db); auto x = boolean_expression(db, t.alpha == 7); x = sqlpp::boolean_expression<MockDb>(t.beta.like("%cheesecake")); x = x and boolean_expression(db, t.gamma); std::cerr << "----------------------------" << std::endl; printer.reset(); std::cerr << serialize(x, printer).str() << std::endl; printer.reset(); std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.in(select(f.epsilon).from(f).unconditionally())), printer).str() << std::endl; printer.reset(); std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.in()), printer).str() << std::endl; printer.reset(); std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.not_in()), printer).str() << std::endl; auto schema = db.attach("lorem"); auto s = schema_qualified_table(schema, t).as(sqlpp::alias::x); printer.reset(); std::cerr << serialize(select(all_of(s)).from(s).unconditionally(), printer).str() << std::endl; printer.reset(); std::cerr << serialize(sqlpp::case_when(true).then(t.alpha).else_(t.alpha + 1).as(t.beta), printer).str() << std::endl; return 0; }
void RecursiveFilter::getAnisotropicFilterCoefficients(const double* tau, const int& arr) { double sigma = (lengthScale*lengthScale)/2; double b[5][5]; // Extend the arrLength for the Cholesky decomp? int arrLength = arr; double* htau = new double[arrLength]; for (int i=0; i< arrLength-1; i++) { htau[i] = (tau[i+1] + tau[i])/2; std::cout << htau[i] << std::endl; } double** K1 = new double*[arrLength]; double** K2 = new double*[arrLength]; double** K3 = new double*[arrLength]; double** K4 = new double*[arrLength]; double** D = new double*[arrLength]; double** sqv = new double*[arrLength]; for (int i=0; i<arrLength;i++) { K1[i] = new double[arrLength]; K2[i] = new double[arrLength]; K3[i] = new double[arrLength]; K4[i] = new double[arrLength]; D[i] = new double[arrLength]; sqv[i] = new double[arrLength]; } double* p= new double[arrLength]; abeta = new double[arrLength]; for (int a = 1; a <5; a++) { aalpha[a] = new double[arrLength]; } double coeff[5]; // b coefficients b[1][1] = 1; b[1][2] = 1./12.; b[1][3] = 1./90.; b[1][4] = 1./560.; b[2][2] = 1.; b[2][3] = 1./6.; b[2][4] = 7./240.; b[3][3] = 1.; b[3][4] = 1./4.; b[4][4] = 1; // Compute polynomial coefficients coeff[1] = b[1][1]*sigma; coeff[2] = b[1][2]*sigma + b[2][2]*(pow(sigma,2))/factorial(2); coeff[3] = b[1][3]*sigma + b[2][3]*(pow(sigma,2))/factorial(2) + b[3][3]*(pow(sigma,3))/factorial(3); coeff[4] = b[1][4]*sigma + b[2][4]*(pow(sigma,2))/factorial(2) + b[3][4]*(pow(sigma,3))/factorial(3) + b[4][4]*(pow(sigma,4))/factorial(4); // Set up K for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { K1[i][j] = 0.; sqv[i][j] = 0.; } /*if (i > 0) K1[i][i-1] = -(sigma*(tau[i-1]+tau[i])/2)/sqrt(sigma*tau[i]*sigma*tau[i-1]); if ((i > 0) and (i<(arrLength-1))) K1[i][i] = ((sigma*(tau[i-1]+tau[i])/2) + (sigma*(tau[i+1]+tau[i])/2))/(sigma*tau[i]); if (i<(arrLength-1)) K1[i][i+1] = -(sigma*(tau[i+1]+tau[i])/2)/sqrt(sigma*tau[i]*sigma*tau[i+1]); sqv[i][i] = sqrt(tau[i]); */ if (i > 1) { K1[i][i-1] = -(sigma*(tau[i]-tau[i-1]))/sqrt(sigma*(htau[i]-htau[i-1])*sigma*(htau[i-1]-htau[i-2])); } else if (i == 1) { K1[i][i-1] = -(sigma*(tau[i]-tau[i-1]))/sqrt(sigma*(htau[i]-htau[i-1])*sigma*(htau[i-1]+htau[i-1])); } if ((i > 0) and (i<(arrLength-1))) K1[i][i] = (sigma*(tau[i]-tau[i-1]) + sigma*(tau[i+1]-tau[i]))/(sigma*(htau[i]-htau[i-1])); if (i<(arrLength-2)) { K1[i][i+1] = -(sigma*(tau[i+1]-tau[i]))/sqrt(sigma*(htau[i]-htau[i-1])*sigma*(htau[i+1]-htau[i])); } else { K1[i][i+1] = -(sigma*(tau[i]-tau[i-1]))/sqrt(sigma*(htau[i]-htau[i-1])*sigma*(htau[i]-htau[i-1])); } if (i == 0) { sqv[i][i] = sqrt(htau[i]*2); } else if (i == (arrLength-1)) { sqv[i][i] = sqrt(htau[i-1]*2); } else { sqv[i][i] = sqrt(htau[i]-htau[i-1]); } } K1[0][0] = 2.; K1[0][1] = K1[1][0]; K1[arrLength-1][arrLength-1] = 2; K1[arrLength-1][arrLength-2] = K1[arrLength-2][arrLength-1]; sqv[arrLength-1][arrLength-1] = sqv[arrLength-2][arrLength-2]; // Square it for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { K2[i][j] = 0; } } for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { for (int r=0; r< arrLength; r++) { K2[i][j] += K1[i][r]*K1[r][j]; } } } // Cube it for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { K3[i][j] = 0; } } for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { for (int r=0; r< arrLength; r++) { K3[i][j] += K1[i][r]*K2[r][j]; } } } // 4th it for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { K4[i][j] = 0; } } for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { for (int r=0; r< arrLength; r++) { K4[i][j] += K1[i][r]*K3[r][j]; } } } // 4th it for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { K4[i][j] = 0; } } for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { for (int r=0; r< arrLength; r++) { K4[i][j] += K1[i][r]*K3[r][j]; } } } // Now calculate D for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { D[i][j] = coeff[1]*K1[i][j] + coeff[2]*K2[i][j] + coeff[3]*K3[i][j] + coeff[4]*K4[i][j]; //std::cout << D[i][j] << " "; } //std::cout << std::endl; } // Get the filter coefficients for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { if (K1[i][j] != 0) std::cout << K1[i][j] << "\t"; } std::cout << std::endl; } // Cholesky decomp for (int i=0;i<arrLength;i++) { for (int j=i;j<arrLength;j++) { double sum=D[i][j]; for (int k=i-1;k>=0;k--) { sum -= D[i][k]*D[j][k]; } if (i == j) { if (sum <= 0.0) { std::cout << "cholesky failed at i,j sum\n"; break; } else { p[i] = sqrt(sum); } } else { D[j][i]=sum/p[i]; if (p[i] == 0.) { std::cout << "Problem! " << i << "\t" << j << "\n"; } } } } for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { if (D[i][j] != 0) std::cout << D[i][j] << "\t"; } std::cout << std::endl; } /* Multiply by sqv (reuse K1) for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { K1[i][j] = 0.; } } for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { for (int r=0; r< arrLength; r++) { K1[i][j] += D[i][r]*sqv[r][j]; } } } // Multiply by 1/sqv (reuse K1) for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { D[i][j] = 0.; if (i == 0) { sqv[i][i] = 1/sqrt(htau[i]*2); } else if (i == (arrLength-1)) { sqv[i][i] = 1/sqrt(htau[i-1]*2); } else { sqv[i][i] = 1/sqrt(htau[i]-htau[i-1]); } } } sqv[arrLength-1][arrLength-1] = sqv[arrLength-2][arrLength-2]; for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { for (int r=0; r< arrLength; r++) { D[i][j] += sqv[i][r]*K1[r][j]; } } } */ for (int i=0; i<arrLength; i++) { for (int j=0; j<arrLength; j++) { if (D[i][j] != 0) std::cout << D[i][j] << "\t"; } std::cout << std::endl; } abeta[0]= 1/p[0]; aalpha[1][0]=0; aalpha[2][0]=0; aalpha[3][0]=0; aalpha[4][0]=0; std::cout << "0\t" << abeta[0]<< "\t" << aalpha[1][0] << "\t" << aalpha[2][0] << "\t" << aalpha[3][0] << "\t" << aalpha[4][0] << "\t(" << abeta[0] + aalpha[1][0] + aalpha[2][0] + aalpha[3][0] + aalpha[4][0] << ")\n"; abeta[1]= 1/p[1]; aalpha[1][1]=-abeta[1]*D[1][0]; aalpha[2][1]=0; aalpha[3][1]=0; aalpha[4][1]=0; std::cout << "1\t" << abeta[1]<< "\t" << aalpha[1][1] << "\t" << aalpha[2][1] << "\t" << aalpha[3][1] << "\t" << aalpha[4][1] << "\t(" << abeta[1] + aalpha[1][1] + aalpha[2][1] + aalpha[3][1] + aalpha[4][1] << ")\n"; abeta[2]= 1/p[2]; aalpha[1][2]=-abeta[2]*D[2][1]; aalpha[2][2]=-abeta[2]*D[2][0]; aalpha[3][2]=0; aalpha[4][2]=0; std::cout << "2\t" << abeta[2]<< "\t" << aalpha[1][2] << "\t" << aalpha[2][2] << "\t" << aalpha[3][2] << "\t" << aalpha[4][2] << "\t(" << abeta[2] + aalpha[1][2] + aalpha[2][2] + aalpha[3][2] + aalpha[4][2] << ")\n"; abeta[3]= 1/p[3]; aalpha[1][3]=-abeta[2]*D[3][2]; aalpha[2][3]=-abeta[2]*D[3][1]; aalpha[3][3]=-abeta[2]*D[3][0]; aalpha[4][3]=0; std::cout << "3\t" << abeta[3]<< "\t" << aalpha[1][3] << "\t" << aalpha[2][3] << "\t" << aalpha[3][3] << "\t" << aalpha[4][3] << "\t(" << abeta[3] + aalpha[1][3] + aalpha[2][3] + aalpha[3][3] + aalpha[4][3] << ")\n"; for (int i=4;i<arrLength;i++) { abeta[i] = 1/p[i]; aalpha[1][i]=-abeta[i]*D[i][i-1]; aalpha[2][i]=-abeta[i]*D[i][i-2]; aalpha[3][i]=-abeta[i]*D[i][i-3]; aalpha[4][i]=-abeta[i]*D[i][i-4]; double sum = abeta[i] + aalpha[1][i] + aalpha[2][i] + aalpha[3][i] + aalpha[4][i]; std::cout << i<< "\t" << abeta[i]<< "\t" << aalpha[1][i] << "\t" << aalpha[2][i] << "\t" << aalpha[3][i] << "\t" << aalpha[4][i] << "\t(" << sum << ")\n"; } // Boundary conditions double L[5][5]; double U[5][5]; double LT[5][5]; double UT[5][5]; double LI[5][5]; double col[5]; double colinv[5]; for (int i=1;i<=order;i++) { for (int j=1;j<=order;j++) { L[i][j]=0.; U[i][j]=0.; } } for (int i=1;i<=order;i++) { for (int j=0;j<=order;j++) { int index = i+j; if (index <= order) { L[i+j][i] = -aalpha[i+j][arr-1]; U[i][i+j] = aalpha[order-j][arr-1]; } } L[i][i] = 1.; } // Invert L for (int j=1;j<=order;j++) { for (int i=1;i<=order;i++) { col[i] = 0.0; } col[j] = 1; colinv[0] = col[0]; for (int i=1;i<=order;i++) { colinv[i] = col[i]; for (int k=i-1;k>=1;k--) { colinv[i] -= L[i][k]*colinv[k]; } } for (int i=1;i<=order;i++) { LI[i][j] = colinv[i]; } } // Transpose L & T for (int i=1;i<=order;i++) { for (int j=1;j<=order;j++) { LT[i][j] = L[j][i]; UT[i][j] = U[j][i]; } } // Get Sn matrix double tmp[5][5]; double tmp2[5][5]; for (int i=1;i<=order;i++) { for (int j=1;j<=order;j++) { tmp[i][j] = 0.; for (int k=1;k<=order;k++) { tmp[i][j] += UT[i][k]*LI[k][j]; } } } for (int i=1;i<=order;i++) { for (int j=1;j<=order;j++) { tmp2[i][j] = 0.; for (int k=1;k<=order;k++) { tmp2[i][j] += tmp[i][k]*U[k][j]; } } } for (int i=1;i<=order;i++) { for (int j=1;j<=order;j++) { Sn[i-1][j-1] = (LT[i][j] - tmp2[i][j])/beta; } } for (int i=0; i<arrLength;i++) { delete[] K1[i]; delete[] K2[i]; delete[] K3[i]; delete[] K4[i]; delete[] D[i]; delete[] sqv[i]; } delete[] tau; delete[] K1; delete[] K2; delete[] K3; delete[] K4; delete[] D; delete[] sqv; delete[] p; }
bool EnergyWindowTest::test(Array<double> &trial_coords, double trial_energy, Array<double> & old_coords, double old_energy, double temperature, MC * mc) { return ((trial_energy >= _min_energy) and (trial_energy <= _max_energy)); }
void TranzportClient::readData() { memcpy(previousbuf, currentbuf, 8); ssize_t val; static timeT loop_start_time=0; static timeT loop_end_time=0; while ((val=read(m_descriptor,currentbuf,8)) == 8) { uint32_t new_buttons = current_buttons ^ previous_buttons; if (status == 0x1) { RG_DEBUG << "TranzportClient: device just came online"; while (not commands.empty()) { commands.pop(); } device_online = true; m_rgDocument = m_rgGUIApp->getDocument(); m_composition = &m_rgGUIApp->getDocument()->getComposition(); stateUpdate(); } if (status == 0xff) { RG_DEBUG << "TranzportClient: device just went offline"; device_online = false; return; } if (new_buttons & TrackSolo and current_buttons & TrackSolo) { if (current_buttons & Shift) { bool soloflag = m_composition->isSolo(); emit solo(not soloflag); } } if (new_buttons & Add and current_buttons & Add) { if (current_buttons & Shift) { } else { AddMarkerCommand* cmd = new AddMarkerCommand(m_composition, m_composition->getPosition(), "tranzport", ""); CommandHistory::getInstance()->addCommand(cmd); } } if (new_buttons & Prev and current_buttons & Prev) { RG_DEBUG << "TranzportClient:: received marker previous"; if (current_buttons & Shift) { } else { timeT currentTime = m_composition->getPosition(); Composition::markercontainer& mc = m_composition->getMarkers(); timeT closestPrevious = -1; for (Composition::markerconstiterator it = mc.begin(); it != mc.end(); ++it) { timeT markerTime = (*it)->getTime(); if (markerTime < currentTime and markerTime > closestPrevious) { closestPrevious = markerTime; } } if (closestPrevious >= 0) { RG_DEBUG << "Tranzport:: setting position: " << closestPrevious; emit setPosition(closestPrevious); } } } if (new_buttons & Next and current_buttons & Next) { RG_DEBUG << "TranzportClient:: received marker next"; if (current_buttons & Shift) { } else { timeT currentTime = m_composition->getPosition(); Composition::markercontainer& mc = m_composition->getMarkers(); timeT closestNext = std::numeric_limits<long>::max(); for (Composition::markerconstiterator it = mc.begin(); it != mc.end(); ++it) { timeT markerTime = (*it)->getTime(); if (markerTime > currentTime and markerTime < closestNext) { closestNext = markerTime; } } if (closestNext < std::numeric_limits<long>::max()) { RG_DEBUG << "Tranzport:: setting position: " << closestNext; emit setPosition(closestNext); } } } if (new_buttons & Undo and current_buttons & Undo) { if (current_buttons & Shift) { emit redo(); } else { emit undo(); } } if (new_buttons & Play and current_buttons & Play) { if (current_buttons & Shift) { } else { emit play(); } } if (new_buttons & Stop and current_buttons & Stop) { if (current_buttons & Shift) { } else { emit stop(); } } if (new_buttons & Record and current_buttons & Record) { if (current_buttons & Shift) { } else { emit record(); } } if (new_buttons & Loop and current_buttons & Loop) { if (current_buttons & Shift) { } else { loop_start_time = m_composition->getPosition(); loop_end_time = loop_start_time; } } if (new_buttons & Loop and (not (current_buttons & Loop))) { if (current_buttons & Shift) { } else { if (loop_start_time == loop_end_time) { m_rgDocument->setLoop(0,0); } loop_start_time = 0; loop_end_time = 0; } } if (new_buttons& Rewind and current_buttons & Rewind) { if (current_buttons&Shift) { emit rewindToBeginning(); } else { emit rewind(); } } if (new_buttons & FastForward and current_buttons & FastForward) { if (current_buttons & Shift) { emit fastForwardToEnd(); } else { emit fastForward(); } } if (new_buttons & TrackRec and current_buttons & TrackRec) { if (current_buttons & Shift) { } else { emit trackRecord(); } } if (new_buttons & TrackRight and current_buttons & TrackRight) { if (current_buttons & Shift) { } else { emit trackDown(); } } if (new_buttons & TrackLeft and current_buttons & TrackLeft) { if (current_buttons& Shift) { } else { emit trackUp(); } } if (new_buttons & TrackMute and current_buttons & TrackMute) { if (current_buttons & Shift) { } else { emit trackMute(); } } if (datawheel) { if (datawheel < 0x7F) { if (current_buttons & Loop) { loop_end_time += datawheel * m_composition->getDurationForMusicalTime(loop_end_time, 0,1,0,0); m_rgDocument->setLoop(loop_start_time, loop_end_time); } else if(current_buttons & Shift) { timeT here = m_composition->getPosition(); here += datawheel * m_composition->getDurationForMusicalTime(here,0,0,1,0); if (here <= m_composition->getEndMarker()) { emit setPosition(here); } } else { timeT here = m_composition->getPosition(); here += datawheel * m_composition->getDurationForMusicalTime(here,0,1,0,0); if (here <= m_composition->getEndMarker()) { emit setPosition(here); } } } else { #define DATAWHEEL_VALUE (1 + (0xFF - (datawheel))) if (current_buttons & Loop) { loop_end_time -= (1 + (0xFF - datawheel)) * m_rgGUIApp->getDocument()->getComposition().getDurationForMusicalTime(loop_end_time, 0,1,0,0); m_rgDocument->setLoop(loop_start_time, loop_end_time); } if (current_buttons & Shift) { timeT here = m_composition->getPosition(); here -= DATAWHEEL_VALUE * m_composition->getDurationForMusicalTime(here,0,0,1,0); if (here >= m_composition->getStartMarker()) { emit setPosition(here); } } else { timeT here = m_composition->getPosition(); here -= DATAWHEEL_VALUE * m_composition->getDurationForMusicalTime(here,0,1,0,0); if (here >= m_composition->getStartMarker()) { emit setPosition(here); } } #undef DATAWHEEL_VALUE } } memcpy(previousbuf, currentbuf, 8); } if (val == -1) { if (errno == EAGAIN) { return; } else { RG_DEBUG << "TranzportClient::readData: error " << strerror(errno); } } else { RG_DEBUG << "TranzportClient::readData: partial read of length " << val; RG_DEBUG << "TranzportClient::readData: this should not happen " << val; } }
OSErr IsFlattenedResourceFile( ConstFSSpecPtr inFile, Boolean* outIsFlat) { OSErr err; CInfoPBRec pb; if (not inFile) { // This can occur when we create a new project document (Cmd-N) *outIsFlat = false; return noErr; } pb.hFileInfo.ioNamePtr = (StringPtr)inFile->name; pb.hFileInfo.ioVRefNum = inFile->vRefNum; pb.hFileInfo.ioDirID = inFile->parID; pb.hFileInfo.ioFDirIndex = 0; err = PBGetCatInfoSync(&pb); if (err == noErr) { if (pb.hFileInfo.ioFlAttrib & kioFlAttribDirMask) { // This is a directory *outIsFlat = false; return paramErr; } else { UInt32 dfSize; UInt32 rfSize; SInt16 dfRefNum; SInt32 filePos; dfSize = pb.hFileInfo.ioFlLgLen; rfSize = pb.hFileInfo.ioFlRLgLen; if (rfSize > 0) { *outIsFlat = false; } else if (dfSize == 0) { // This file has no data or resource fork. *outIsFlat = false; } else { // Only the data fork is non-empty. // Now we need to determine if it contains resources or not. UInt32 firstFourWords[4]; SInt32 byteCount; err = FSpOpenDF(inFile, fsRdPerm, &dfRefNum); if (err) return err; err = GetFPos(dfRefNum, &filePos); byteCount = sizeof(firstFourWords); err = FSRead(dfRefNum, &byteCount, &firstFourWords); if (err == noErr) { // Test is based on resource file format as described in IM: More Mac Toolbox // <http://developer.apple.com/techpubs/mac/MoreToolbox/MoreToolbox-99.html#HEADING99-0> // // First four words of the file represent the resource header // Word1: Offset from beginning of resource fork to resource data // Word2: Offset from beginning of resource fork to resource map // Word3: Length of resource data // Word4: Length of resource map // // So... // (Word1 + Word3 + Word4) == (Word2 + Word4) == size of resource fork if ((byteCount == sizeof(firstFourWords)) and (EndianU32_BtoN(firstFourWords[0]) + EndianU32_BtoN(firstFourWords[2]) + EndianU32_BtoN(firstFourWords[3]) == dfSize) and (EndianU32_BtoN(firstFourWords[1]) + EndianU32_BtoN(firstFourWords[3]) == dfSize)) { *outIsFlat = true; } } err = SetFPos(dfRefNum, fsFromStart, filePos); err = FSClose(dfRefNum); } } } return err; }
double binsvd_pred::study(RsHash train, RsHash valid, QString train_neg_fn, QString valid_fn, QList<float> p, bool verbose) { if (verbose) printf("Start binsvd studying...\n"); if (!p.empty()) { fact_n = p[0]; alfa = p[1]; lambda = p[2]; } double min_err = 100, last_err[4] = {100,100,100,100}; int min_err_step = 1; // create and fill data structures QHash<int, QVector<int> > user_negatives = load_user_negatives(train_neg_fn, verbose); QHash<int, QVector<int> > user_positives = load_user_positives(train); create_factors(user_factors, train, fact_n, 1); create_factors(item_factors, train, fact_n, 0); int un = user_positives.count(); // by steps for (int st = 1; st <= steps; st++) { if (verbose) printf("%d step: ", st); // by users QVector<int> users = user_positives.keys().toVector(); //#pragma omp parallel for for(int ui = 0; ui < un; ++ui) { int u = users[ui]; QVector<int> u_pos = user_positives[u]; QVector<int> u_neg = user_negatives[u]; if (u_pos.count() != u_neg.count()) printf("bugs!\n"); // by negative and positive items for(int r = -1; r <= 1; r += 2) { QVector<int> items_list; if (r == -1) items_list = u_neg; else items_list = u_pos; if (u_neg.count() != u_pos.count()) printf("bugs!\n"); if (u_neg.count() != u_pos.count()) printf("bugs!\n"); QVector<int>::const_iterator it2; for(it2 = items_list.constBegin(); it2 != items_list.constEnd(); ++it2) { int i = *it2; QVector<float> i_factors; //#pragma omp critical { i_factors = item_factors[i]; } QVector<float> u_factors = user_factors[u]; float pr = dot_product(u_factors, i_factors, fact_n); float err = r - pr; // update user factors for(int fi = 0; fi < fact_n; fi++) { float user_f = u_factors.value(fi); float item_f = i_factors.value(fi); u_factors[fi] = user_f + alfa * (err * item_f - lambda * user_f); } user_factors[u] = u_factors; // update item factors for(int fi = 0; fi < fact_n; fi++) { float user_f = u_factors.value(fi); float item_f = i_factors.value(fi); i_factors[fi] = item_f + alfa * (err * user_f - lambda * item_f); } //#pragma omp critical { item_factors[i] = i_factors; } } } } double err = estimate(predict(valid, false), valid_fn, "../../binsvd_pred", false); if (err < min_err) { min_err = err; min_err_step = st; } if (verbose) printf("error %2.3f, alfa=%2.5f, e_thr=%2.5f\n", err, alfa, e_thr); last_err[3] = last_err[2]; last_err[2] = last_err[1]; last_err[1] = last_err[0]; last_err[0] = err; if (st > 30 and (last_err[0] - last_err[3] > 0.01) ) break; /*if (alfa >= 0.001 and last_err[1] - last_err[0] < e_thr and last_err[2] - last_err[1] < e_thr) { alfa *= 0.66; e_thr *= 0.66; } if (alfa <= 0.001) break;*/ } if (verbose) printf("ok (min error %2.2f on %d step)\n", min_err, min_err_step); return min_err; }
void RgbEffects::RenderTree(int Branches) { int x,y,i,i7,r,ColorIdx,Count,pixels_per_branch; int maxFrame,mod,branch,row,b,f_mod,m,frame; int number_garlands,f_mod_odd,s_odd_row,odd_even; float V,H; number_garlands=1; srand(1); // always have the same random numbers for each frame (state) wxImage::HSVValue hsv; // we will define an hsv color model. The RGB colot model would have been "wxColour color;" pixels_per_branch=(int)(0.5+BufferHt/Branches); maxFrame=(Branches+1) *BufferWi; size_t colorcnt=GetColorCount(); frame = (state/4)%maxFrame; i=0; for (y=0; y<BufferHt; y++) // For my 20x120 megatree, BufferHt=120 { for (x=0; x<BufferWi; x++) // BufferWi=20 in the above example { mod=y%pixels_per_branch; if(mod==0) mod=pixels_per_branch; V=1-(1.0*mod/pixels_per_branch)*0.70; i++; ColorIdx=rand() % colorcnt; // Select random numbers from 0 up to number of colors the user has checked. 0-5 if 6 boxes checked ColorIdx=0; palette.GetHSV(ColorIdx, hsv); // Now go and get the hsv value for this ColorIdx hsv.value = V; // we have now set the color for the background tree // $orig_rgbval=$rgb_val; branch = (int)((y-1)/pixels_per_branch); row = pixels_per_branch-mod; // now row=0 is bottom of branch, row=1 is one above bottom // mod = which pixel we are in the branch // mod=1,row=pixels_per_branch-1 top picrl in branch // mod=2, second pixel down into branch // mod=pixels_per_branch,row=0 last pixel in branch // // row = 0, the $p is in the bottom row of tree // row =1, the $p is in second row from bottom b = (int) ((state)/BufferWi)%Branches; // what branch we are on based on frame # // // b = 0, we are on bottomow row of tree during frames 1 to BufferWi // b = 1, we are on second row from bottom, frames = BufferWi+1 to 2*BufferWi // b = 2, we are on third row from bottome, frames - 2*BufferWi+1 to 3*BufferWi f_mod = (state/4)%BufferWi; // if(f_mod==0) f_mod=BufferWi; // f_mod is to BufferWi-1 on each row // f_mod == 0, left strand of this row // f_mod==BufferWi, right strand of this row // m=(x%6); if(m==0) m=6; // use $m to indicate where we are in horizontal pattern // m=1, 1sr strand // m=2, 2nd strand // m=6, last strand in 6 strand pattern r=branch%5; H = r/4.0; odd_even=b%2; s_odd_row = BufferWi-x+1; f_mod_odd = BufferWi-f_mod+1; if(branch<=b && x<=frame && // for branches below or equal to current row (((row==3 or (number_garlands==2 and row==6)) and (m==1 or m==6)) || ((row==2 or (number_garlands==2 and row==5)) and (m==2 or m==5)) || ((row==1 or (number_garlands==2 and row==4)) and (m==3 or m==4)) )) if((odd_even ==0 and x<=f_mod) || (odd_even ==1 and s_odd_row<=f_mod)) { hsv.hue = H; hsv.saturation=1.0; hsv.value=1.0; } // if(branch>b) // { // return $rgb_val; // for branches below current, dont dont balnk anything out // } // else if(branch==b) // { // if(odd_even ==0 and x>f_mod) // { // $rgb_val=$orig_rgbval;// we are even row ,counting from bottom as zero // } // if(odd_even ==1 and s_odd_row>f_mod) // { // $rgb_val=$orig_rgbval;// we are even row ,counting from bottom as zero // } // } //if($branch>$b) $rgb_val=$orig_rgbval; // erase rows above our current row. // Yes, so now decide on what color it should be // we left the Hue and Saturation alone, we are just modifiying the Brightness Value SetPixel(x,y,hsv); // Turn pixel on } } }
int SHD_SAFE_MAIN(int argc, char *argv[]){ shd::set_thread_priority_safe(); //variables to be set by po std::string args, ant, subdev, ref; size_t num_bins; double rate, freq, gain, bw, frame_rate; float ref_lvl, dyn_rng; //setup the program options po::options_description desc("Allowed options"); desc.add_options() ("help", "help message") ("args", po::value<std::string>(&args)->default_value(""), "multi shd device address args") // hardware parameters ("rate", po::value<double>(&rate), "rate of incoming samples (sps)") ("freq", po::value<double>(&freq), "RF center frequency in Hz") ("gain", po::value<double>(&gain), "gain for the RF chain") ("ant", po::value<std::string>(&ant), "daughterboard antenna selection") ("subdev", po::value<std::string>(&subdev), "daughterboard subdevice specification") ("bw", po::value<double>(&bw), "daughterboard IF filter bandwidth in Hz") // display parameters ("num-bins", po::value<size_t>(&num_bins)->default_value(512), "the number of bins in the DFT") ("frame-rate", po::value<double>(&frame_rate)->default_value(5), "frame rate of the display (fps)") ("ref-lvl", po::value<float>(&ref_lvl)->default_value(0), "reference level for the display (dB)") ("dyn-rng", po::value<float>(&dyn_rng)->default_value(60), "dynamic range for the display (dB)") ("ref", po::value<std::string>(&ref)->default_value("internal"), "waveform type (internal, external, mimo)") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); //print the help message if (vm.count("help") or not vm.count("rate")){ std::cout << boost::format("SHD RX ASCII Art DFT %s") % desc << std::endl; return ~0; } //create a smini device std::cout << std::endl; std::cout << boost::format("Creating the smini device with: %s...") % args << std::endl; shd::smini::multi_smini::sptr smini = shd::smini::multi_smini::make(args); //Lock mboard clocks smini->set_clock_source(ref); //always select the subdevice first, the channel mapping affects the other settings if (vm.count("subdev")) smini->set_rx_subdev_spec(subdev); std::cout << boost::format("Using Device: %s") % smini->get_pp_string() << std::endl; //set the sample rate if (not vm.count("rate")){ std::cerr << "Please specify the sample rate with --rate" << std::endl; return ~0; } std::cout << boost::format("Setting RX Rate: %f Msps...") % (rate/1e6) << std::endl; smini->set_rx_rate(rate); std::cout << boost::format("Actual RX Rate: %f Msps...") % (smini->get_rx_rate()/1e6) << std::endl << std::endl; //set the center frequency if (not vm.count("freq")){ std::cerr << "Please specify the center frequency with --freq" << std::endl; return ~0; } std::cout << boost::format("Setting RX Freq: %f MHz...") % (freq/1e6) << std::endl; smini->set_rx_freq(freq); std::cout << boost::format("Actual RX Freq: %f MHz...") % (smini->get_rx_freq()/1e6) << std::endl << std::endl; //set the rf gain if (vm.count("gain")){ std::cout << boost::format("Setting RX Gain: %f dB...") % gain << std::endl; smini->set_rx_gain(gain); std::cout << boost::format("Actual RX Gain: %f dB...") % smini->get_rx_gain() << std::endl << std::endl; } //set the IF filter bandwidth if (vm.count("bw")){ std::cout << boost::format("Setting RX Bandwidth: %f MHz...") % bw << std::endl; smini->set_rx_bandwidth(bw); std::cout << boost::format("Actual RX Bandwidth: %f MHz...") % smini->get_rx_bandwidth() << std::endl << std::endl; } //set the antenna if (vm.count("ant")) smini->set_rx_antenna(ant); boost::this_thread::sleep(boost::posix_time::seconds(1)); //allow for some setup time //Check Ref and LO Lock detect std::vector<std::string> sensor_names; sensor_names = smini->get_rx_sensor_names(0); if (std::find(sensor_names.begin(), sensor_names.end(), "lo_locked") != sensor_names.end()) { shd::sensor_value_t lo_locked = smini->get_rx_sensor("lo_locked",0); std::cout << boost::format("Checking RX: %s ...") % lo_locked.to_pp_string() << std::endl; SHD_ASSERT_THROW(lo_locked.to_bool()); } sensor_names = smini->get_mboard_sensor_names(0); if ((ref == "mimo") and (std::find(sensor_names.begin(), sensor_names.end(), "mimo_locked") != sensor_names.end())) { shd::sensor_value_t mimo_locked = smini->get_mboard_sensor("mimo_locked",0); std::cout << boost::format("Checking RX: %s ...") % mimo_locked.to_pp_string() << std::endl; SHD_ASSERT_THROW(mimo_locked.to_bool()); } if ((ref == "external") and (std::find(sensor_names.begin(), sensor_names.end(), "ref_locked") != sensor_names.end())) { shd::sensor_value_t ref_locked = smini->get_mboard_sensor("ref_locked",0); std::cout << boost::format("Checking RX: %s ...") % ref_locked.to_pp_string() << std::endl; SHD_ASSERT_THROW(ref_locked.to_bool()); } //create a receive streamer shd::stream_args_t stream_args("fc32"); //complex floats shd::rx_streamer::sptr rx_stream = smini->get_rx_stream(stream_args); //allocate recv buffer and metatdata shd::rx_metadata_t md; std::vector<std::complex<float> > buff(num_bins); //------------------------------------------------------------------ //-- Initialize //------------------------------------------------------------------ initscr(); //curses init smini->issue_stream_cmd(shd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS); boost::system_time next_refresh = boost::get_system_time(); //------------------------------------------------------------------ //-- Main loop //------------------------------------------------------------------ while (true){ //read a buffer's worth of samples every iteration size_t num_rx_samps = rx_stream->recv( &buff.front(), buff.size(), md ); if (num_rx_samps != buff.size()) continue; //check and update the display refresh condition if (boost::get_system_time() < next_refresh) continue; next_refresh = boost::get_system_time() + boost::posix_time::microseconds(long(1e6/frame_rate)); //calculate the dft and create the ascii art frame acsii_art_dft::log_pwr_dft_type lpdft( acsii_art_dft::log_pwr_dft(&buff.front(), num_rx_samps) ); std::string frame = acsii_art_dft::dft_to_plot( lpdft, COLS, LINES, smini->get_rx_rate(), smini->get_rx_freq(), dyn_rng, ref_lvl ); //curses screen handling: clear and print frame clear(); printw("%s", frame.c_str()); //curses key handling: no timeout, any key to exit timeout(0); int ch = getch(); if (ch != KEY_RESIZE and ch != ERR) break; } //------------------------------------------------------------------ //-- Cleanup //------------------------------------------------------------------ smini->issue_stream_cmd(shd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS); endwin(); //curses done //finished std::cout << std::endl << "Done!" << std::endl << std::endl; return 0; }
/** * @brief Read next token from input buffer. * @param input The buffer from which a token will be searched. * @param index The index from where next token will be scanned. This will be * updated in the process. * @return Return the scanned token. */ std::string get_next_token(std::string *input, unsigned int* index) { std::string token = ""; /* * token_delmiters: define a point until when whatever we have read in * buffer is a token. Note that they will not be part of any token unless * token is a comment or a string as enclosed in ''(single quotes) and "" * (double quotes). Currently token delimiters are space and comma ' ' * and ',' . * * Note: No matter what we will always advance index such that it will point * to next character in the stream ahead of */ /* * token_separators: we buffer elements from input stream until one of * them is encountered. Note that they themselves are tokens as well. */ char token_separators[] = { ',', '+', '.', '-', '*', '\\', '=', '(', ')', '<', '>', ';', ':', '!', '\0' }; int number_of_token_separators = strlen(token_separators); //find tokens for (; *index < (*input).length(); (*index)++) { /* * 1. detect strings enclosed in single quotes. Note that token obtained * in this case is inclusive of opening and closing quotes. */ if ((*input)[*index] == '\'') { token = token + (*input)[*index]; (*index)++; while (((*input)[*index] != '\'') and (*index < (*input).length())) { token = token + (*input)[*index]; (*index)++; } token = token + (*input)[*index]; (*index)++; return token; } /* * 2. detect strings enclosed in double quotes. Token is inclusive of * opening and closing double quotes. */ if ((*input)[*index] == '\"') { token = token + (*input)[*index]; (*index)++; while ((*input)[*index] != '\"' and (*index < (*input).length())) { token = token + (*input)[*index]; (*index)++; } token = token + (*input)[*index]; (*index)++; return token; } /* * 3.detect token which begin with '`' backtick character. These are * legal tokens in mysql. we will consider inclusive of opening * and end backticks */ if ((*input)[*index] == '`') { token = token + (*input)[*index]; (*index)++; while ((*input)[*index] != '`' and (*index < (*input).length())) { token = token + (*input)[*index]; (*index)++; } token = token + (*input)[*index]; (*index)++; return token; } /* * 4. find token separators. they are tokens as well. However special * about them is that the moment they are encountered we return. So * a token separator is 'alone' . */ for (int i = 0; i < number_of_token_separators; i++) { if ((*input)[*index] == token_separators[i]) { //if we already have something in token then we need to return. if (token.length() != 0) { return token; } token = token + (*input)[*index]; (*index)++; return token; } } /* * 5. default case. if none of above conditions were satisfied then * this character is a part of token. * * Also note that we will eat spaces in beginning of a token not after it. * so the moment we find a space after we have filled something in token * we will return . */ if ((*input)[*index] != ' ') { token = token + (*input)[*index]; } if ((*input)[*index + 1] == ' ' and token != "") { (*index)++; return token; } //6. Eat out spaces/delimiters. if ((*input)[*index] == ' ') { (*index)++; while (((*input)[*index] == ' ') and (*index < (*input).length())) { (*index)++; } /* * stop when we have a token. but we were eating out spaces. However * if we have not read anything then dont break. continue as we have * still to find a valid token. */ if (token != "") { return token; } else { /* * this character is not space, neither is it a separator but still * has not been stored in token. however this char could be ' or " * which require special treatment. so go up but ensure that * the pointer is not incremented. */ (*index)--; continue; } } } return token; }
bool treat_as_paired() const { return is_paired() and (not is_mapped() or not mp_is_mapped() or chr_name() == mp_chr_name()); }
bool TeamInformation::amIClosestToBall() { for (size_t i=0; i<m_received_packets.size(); i++) { if (not m_received_packets[i].empty()) { if ((m_data->CurrentTime - m_received_packets[i].back().ReceivedTime < m_TIMEOUT) and (m_packet.TimeToBall > m_received_packets[i].back().TimeToBall)) return false; } } return true; }
/*********************************************************************** * Main function **********************************************************************/ int UHD_SAFE_MAIN(int argc, char *argv[]){ uhd::set_thread_priority_safe(); //variables to be set by po std::string args, wave_type, ant, subdev, ref, otw; size_t spb; double rate, freq, gain, wave_freq, bw; float ampl; //setup the program options po::options_description desc("Allowed options"); desc.add_options() ("help", "help message") ("args", po::value<std::string>(&args)->default_value(""), "single uhd device address args") ("spb", po::value<size_t>(&spb)->default_value(0), "samples per buffer, 0 for default") ("rate", po::value<double>(&rate), "rate of outgoing samples") ("freq", po::value<double>(&freq), "RF center frequency in Hz") ("ampl", po::value<float>(&l)->default_value(float(0.3)), "amplitude of the waveform [0 to 0.7]") ("gain", po::value<double>(&gain), "gain for the RF chain") ("ant", po::value<std::string>(&ant), "daughterboard antenna selection") ("subdev", po::value<std::string>(&subdev), "daughterboard subdevice specification") ("bw", po::value<double>(&bw), "daughterboard IF filter bandwidth in Hz") ("wave-type", po::value<std::string>(&wave_type)->default_value("CONST"), "waveform type (CONST, SQUARE, RAMP, SINE)") ("wave-freq", po::value<double>(&wave_freq)->default_value(0), "waveform frequency in Hz") ("ref", po::value<std::string>(&ref)->default_value("internal"), "clock reference (internal, external, mimo)") ("otw", po::value<std::string>(&otw)->default_value("sc16"), "specify the over-the-wire sample mode") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); //print the help message if (vm.count("help")){ std::cout << boost::format("UHD TX Waveforms %s") % desc << std::endl; return ~0; } //create a usrp device std::cout << std::endl; std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl; uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args); //Lock mboard clocks usrp->set_clock_source(ref); //always select the subdevice first, the channel mapping affects the other settings if (vm.count("subdev")) usrp->set_tx_subdev_spec(subdev); std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl; //set the sample rate if (not vm.count("rate")){ std::cerr << "Please specify the sample rate with --rate" << std::endl; return ~0; } std::cout << boost::format("Setting TX Rate: %f Msps...") % (rate/1e6) << std::endl; usrp->set_tx_rate(rate); std::cout << boost::format("Actual TX Rate: %f Msps...") % (usrp->get_tx_rate()/1e6) << std::endl << std::endl; //set the center frequency if (not vm.count("freq")){ std::cerr << "Please specify the center frequency with --freq" << std::endl; return ~0; } for(size_t chan = 0; chan < usrp->get_tx_num_channels(); chan++) { std::cout << boost::format("Setting TX Freq: %f MHz...") % (freq/1e6) << std::endl; usrp->set_tx_freq(freq, chan); std::cout << boost::format("Actual TX Freq: %f MHz...") % (usrp->get_tx_freq(chan)/1e6) << std::endl << std::endl; //set the rf gain if (vm.count("gain")){ std::cout << boost::format("Setting TX Gain: %f dB...") % gain << std::endl; usrp->set_tx_gain(gain, chan); std::cout << boost::format("Actual TX Gain: %f dB...") % usrp->get_tx_gain(chan) << std::endl << std::endl; } //set the IF filter bandwidth if (vm.count("bw")){ std::cout << boost::format("Setting TX Bandwidth: %f MHz...") % bw << std::endl; usrp->set_tx_bandwidth(bw, chan); std::cout << boost::format("Actual TX Bandwidth: %f MHz...") % usrp->get_tx_bandwidth(chan) << std::endl << std::endl; } //set the antenna if (vm.count("ant")) usrp->set_tx_antenna(ant, chan); } //for the const wave, set the wave freq for small samples per period if (wave_freq == 0 and wave_type == "CONST"){ wave_freq = usrp->get_tx_rate()/2; } //error when the waveform is not possible to generate if (std::abs(wave_freq) > usrp->get_tx_rate()/2){ throw std::runtime_error("wave freq out of Nyquist zone"); } if (usrp->get_tx_rate()/std::abs(wave_freq) > wave_table_len/2){ throw std::runtime_error("wave freq too small for table"); } //pre-compute the waveform values const wave_table_class wave_table(wave_type, ampl); const size_t step = boost::math::iround(wave_freq/usrp->get_tx_rate() * wave_table_len); size_t index = 0; //create a transmit streamer //linearly map channels (index0 = channel0, index1 = channel1, ...) uhd::stream_args_t stream_args("fc32", otw); for (size_t chan = 0; chan < usrp->get_tx_num_channels(); chan++) stream_args.channels.push_back(chan); //linear mapping uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args); //allocate a buffer which we re-use for each channel if (spb == 0) spb = tx_stream->get_max_num_samps()*10; std::vector<std::complex<float> > buff(spb); std::vector<std::complex<float> *> buffs(usrp->get_tx_num_channels(), &buff.front()); //setup the metadata flags uhd::tx_metadata_t md; md.start_of_burst = true; md.end_of_burst = false; md.has_time_spec = true; md.time_spec = uhd::time_spec_t(0.1); std::cout << boost::format("Setting device timestamp to 0...") << std::endl; usrp->set_time_now(uhd::time_spec_t(0.0)); //Check Ref and LO Lock detect std::vector<std::string> sensor_names; sensor_names = usrp->get_tx_sensor_names(0); if (std::find(sensor_names.begin(), sensor_names.end(), "lo_locked") != sensor_names.end()) { uhd::sensor_value_t lo_locked = usrp->get_tx_sensor("lo_locked",0); std::cout << boost::format("Checking TX: %s ...") % lo_locked.to_pp_string() << std::endl; UHD_ASSERT_THROW(lo_locked.to_bool()); } sensor_names = usrp->get_mboard_sensor_names(0); if ((ref == "mimo") and (std::find(sensor_names.begin(), sensor_names.end(), "mimo_locked") != sensor_names.end())) { uhd::sensor_value_t mimo_locked = usrp->get_mboard_sensor("mimo_locked",0); std::cout << boost::format("Checking TX: %s ...") % mimo_locked.to_pp_string() << std::endl; UHD_ASSERT_THROW(mimo_locked.to_bool()); } if ((ref == "external") and (std::find(sensor_names.begin(), sensor_names.end(), "ref_locked") != sensor_names.end())) { uhd::sensor_value_t ref_locked = usrp->get_mboard_sensor("ref_locked",0); std::cout << boost::format("Checking TX: %s ...") % ref_locked.to_pp_string() << std::endl; UHD_ASSERT_THROW(ref_locked.to_bool()); } std::signal(SIGINT, &sig_int_handler); std::cout << "Press Ctrl + C to stop streaming..." << std::endl; //send data until the signal handler gets called while(not stop_signal_called){ //fill the buffer with the waveform for (size_t n = 0; n < buff.size(); n++){ buff[n] = wave_table(index += step); } //send the entire contents of the buffer tx_stream->send(buffs, buff.size(), md); md.start_of_burst = false; md.has_time_spec = false; } //send a mini EOB packet md.end_of_burst = true; tx_stream->send("", 0, md); //finished std::cout << std::endl << "Done!" << std::endl << std::endl; return 0; }
bool Gate::is_gate(Gate* i1, Operand t){ if ((t != Operand::AND) and (t != Operand::OR) and (t != Operand::NOT)) return false; return true; }
bool BookRecord::equals(const BookRecord& other) const { return ((equalsBasic(other)) and (editorID==other.editorID) and (unknownVMAD==other.unknownVMAD) and (memcmp(unknownOBND, other.unknownOBND, 12)==0) and (title==other.title) and (modelPath==other.modelPath) and (unknownMODT==other.unknownMODT) and (text==other.text) and (unknownCNAM==other.unknownCNAM) and (pickupSoundFormID==other.pickupSoundFormID) and (putdownSoundFormID==other.putdownSoundFormID) and (keywordArray==other.keywordArray) and (bookFlags==other.bookFlags) and (spellOrSkillID==other.spellOrSkillID) and (bookValue==other.bookValue) and (weight==other.weight) and (inventoryArtFormID==other.inventoryArtFormID)); }
//Включаем выключаем кнопку удалить void class_ref_firm::slot_enable_del() { if (ui->tableView->selectionModel()->selectedIndexes().size() < 6) { ui->pushButton_del_firm->setEnabled(ui->tableView->selectionModel()->hasSelection()); if (ui->tableView->selectionModel()->hasSelection()) { ui->lineEdit_name->setText(ui->tableView->selectionModel()->selectedIndexes().at(1).data().toString()); ui->lineEdit_inn->setText(ui->tableView->selectionModel()->selectedIndexes().at(2).data().toString()); ui->lineEdit_kpp->setText(ui->tableView->selectionModel()->selectedIndexes().at(3).data().toString()); if (ui->tableView->selectionModel()->selectedIndexes().at(4).data().toString() == "Да") { ui->checkBox_stroy->setChecked(true); } else { ui->checkBox_stroy->setChecked(false); } } else { ui->lineEdit_name->setText(""); ui->lineEdit_inn->setText(""); ui->lineEdit_kpp->setText(""); ui->checkBox_stroy->setChecked(false); } if (ui->lineEdit_name->text() != "" and ui->lineEdit_kpp->text().length() == 9 and (ui->lineEdit_inn->text().length() == 12 or ui->lineEdit_inn->text().length() == 10) and ui->tableView->selectionModel()->hasSelection()) { ui->pushButton_add_firm->setEnabled(true); } else { ui->pushButton_add_firm->setEnabled(false); } if (ui->pushButton_add_firm->isEnabled()) { ui->pushButton_add_firm->setText("Изменить"); } else { ui->pushButton_add_firm->setText("Добавить"); } } else { ui->lineEdit_name->setText(""); ui->lineEdit_inn->setText(""); ui->lineEdit_kpp->setText(""); ui->checkBox_stroy->setChecked(false); ui->pushButton_add_firm->setEnabled(false); ui->pushButton_del_firm->setEnabled(false); } }
bool BodyPartAssociation::operator==(const BodyPartAssociation& other) const { return ((Index==other.Index) and (MaleBodyPart==other.MaleBodyPart) and (FemaleBodyPart==other.FemaleBodyPart)); }
int main (int argc, char const* argv[]) { SDL_Rect rect; int g, h, frame, subframe; bool arrastrar_mouse = false; int mouseX, mouseY, newX, newY; SDL_Event evento; Mario mario; Casa casa; string nombre_archivo; fstream archivo; srand(time(NULL)); mario.Inicializar(); casa.Inicializar(); setup(); DibujarFondo(); DibujarMenu(); DibujarObstaculos(); frame = 0; estado_menu = -1; do { SDL_GetMouseState(&mouseX, &mouseY); while (SDL_PollEvent (&evento)) { switch (evento.type) { case SDL_QUIT: return 0; break; case SDL_KEYDOWN: // if (estado_menu == PLAY and not mario.usando_pila and not mario.esInicializado()) { // switch (evento.key.keysym.sym) { // case SDLK_UP: // if (mario.posY-1 >= 0 and mapa_virtual[mario.posY-1][mario.posX] == ESTADO_CAMINABLE) { // mario.MoverMario(ARRIBA, casa); // } // break; /* Cierre de tecla arriba */ // // case SDLK_DOWN: // if (mario.posY+1 < PANTALLA_ALTO and mapa_virtual[mario.posY+1][mario.posX] == ESTADO_CAMINABLE) { // mario.MoverMario(ABAJO, casa); // } // break; /* Cierre de tecla abajo */ // // case SDLK_LEFT: // if (mario.posX-1 >= 0 and mapa_virtual[mario.posY][mario.posX-1] == ESTADO_CAMINABLE) { // mario.MoverMario(IZQ, casa); // } // break; /* Cierre tecla izq */ // // case SDLK_RIGHT: // if (mario.posX+1 < PANTALLA_ANCHO and mapa_virtual[mario.posY][mario.posX+1] == ESTADO_CAMINABLE) { // mario.MoverMario(DER, casa); // } // break; /* Cierre tecla der */ // // case SDLK_BACKSPACE: // if (not mario.pila_movimientos.empty()) { // mario.usando_pila = true; // } // break; // } /* Cierre del switch selector de tecla */ // } if (estado_menu != PLAY) { switch (evento.key.keysym.sym) { case SDLK_0: DibujarFondo (); mario.Inicializar(); casa.Inicializar(); break; case SDLK_1: case SDLK_2: case SDLK_3: DibujarFondo (); DibujarMapaPrecargado(evento.key.keysym.sym - 48); mario.Inicializar(); casa.Inicializar(); break; case SDLK_g: GuardarMapa(); break; case SDLK_a: DibujarFondo (); AbrirMapa(); mario.Inicializar(); casa.Inicializar(); break; } } break; /* Cierre de SDL_Keydown */ case SDL_MOUSEBUTTONDOWN: switch(evento.button.button) { case SDL_BUTTON_WHEELUP: if (porcentaje_obstaculos < RANDOM_MAXIMO and estado_menu != PLAY) { porcentaje_obstaculos = porcentaje_obstaculos + 0.4; DibujarFondo (); DibujarObstaculos(); mario.Inicializar(); casa.Inicializar(); } break; case SDL_BUTTON_WHEELDOWN: if (porcentaje_obstaculos > RANDOM_MINIMO and estado_menu != PLAY) { porcentaje_obstaculos = porcentaje_obstaculos - 0.4; DibujarFondo (); DibujarObstaculos(); mario.Inicializar(); casa.Inicializar(); } break; case SDL_BUTTON_LEFT: if (mouseX > PANTALLA_ANCHO * IMAGENES_DIMENSION + 2) { g = mouseY / IMAGENES_DIMENSION; CambiarEstadoMenu (g); } else { switch (estado_menu) { case COLOCAR_MARIO: h = mouseY / IMAGENES_DIMENSION; g = mouseX / IMAGENES_DIMENSION; if (mapa_virtual[h][g] == ESTADO_CAMINABLE) { mario.ColocarMario(h, g, casa); } break; case COLOCAR_CASA: h = mouseY / IMAGENES_DIMENSION; g = mouseX / IMAGENES_DIMENSION; if (mapa_virtual[h][g] == ESTADO_CAMINABLE) { casa.ColocarCasa(h, g); mario.ColocarMario(h, g, casa); } break; case COLOCAR_ARBOL: h = mouseY / IMAGENES_DIMENSION; g = mouseX / IMAGENES_DIMENSION; if (mapa_virtual[h][g] == ESTADO_CAMINABLE and (mario.posX != g or mario.posY != h) and (casa.posX != g or casa.posY != h) ) { ColocarArbol(h, g); } arrastrar_mouse = true; break; case COLOCAR_ARENA: h = mouseY / IMAGENES_DIMENSION; g = mouseX / IMAGENES_DIMENSION; if (mapa_virtual[h][g] == ESTADO_ANIMADO and (mario.posX != g or mario.posY != h) and (casa.posX != g or casa.posY != h) ) { ColocarArena(h, g); } arrastrar_mouse = true; break; } } break; } break; case SDL_MOUSEMOTION: if (arrastrar_mouse and mouseX < PANTALLA_ANCHO * IMAGENES_DIMENSION) { switch (estado_menu) { case COLOCAR_ARBOL: h = mouseY / IMAGENES_DIMENSION; g = mouseX / IMAGENES_DIMENSION; if (mapa_virtual[h][g] == ESTADO_CAMINABLE and (mario.posX != g or mario.posY != h) and (casa.posX != g or casa.posY != h) ) { ColocarArbol(h, g); } break; case COLOCAR_ARENA: h = mouseY / IMAGENES_DIMENSION; g = mouseX / IMAGENES_DIMENSION; if (mapa_virtual[h][g] == ESTADO_ANIMADO and (mario.posX != g or mario.posY != h) and (casa.posX != g or casa.posY != h) ) { ColocarArena(h, g); } break; } } break; case SDL_MOUSEBUTTONUP: if (arrastrar_mouse) { arrastrar_mouse = false; } break; } } /* Movimiento con la lines de Bres. */ if ((frame % 2) == 0 and estado_menu == PLAY and not casa.esInicializado()) { LineaBres(&mario, casa, &newX, &newY); if (mapa_virtual[newY][newX] == ESTADO_CAMINABLE) { mario.MoverMario (casa, newX, newY); } else { mario.MovimientoAleatorio(&newX, &newY); mario.MoverMario (casa, newX, newY); } } /* ANIMAR las cosas */ if (estado_menu == PLAY) { /* Animar arbustos */ subframe = frame / 8; for (g = 0; g < PANTALLA_ALTO; g++) { for (h = 0; h < PANTALLA_ANCHO; h++) { if (mapa_virtual [g][h] == ESTADO_ANIMADO) { rect.x = h * IMAGENES_DIMENSION; rect.y = g * IMAGENES_DIMENSION; SDL_BlitSurface (images [IMG_SAND_1], NULL, screen, &rect); SDL_BlitSurface (images [IMG_GRASS_1 + subframe], NULL, screen, &rect); } if (mapa_virtual [g][h] == ESTADO_BANDERIN_1) { rect.x = h * IMAGENES_DIMENSION; rect.y = g * IMAGENES_DIMENSION; SDL_BlitSurface (images [IMG_COURSE_1_1 + frame/16], NULL, screen, &rect); } if (mapa_virtual [g][h] == ESTADO_BANDERIN_2) { rect.x = h * IMAGENES_DIMENSION; rect.y = g * IMAGENES_DIMENSION; SDL_BlitSurface (images [IMG_COURSE_2_1 + frame/16], NULL, screen, &rect); } if (mapa_virtual [g][h] == ESTADO_BANDERIN_3) { rect.x = h * IMAGENES_DIMENSION; rect.y = g * IMAGENES_DIMENSION; SDL_BlitSurface (images [IMG_COURSE_3_1 + frame/16], NULL, screen, &rect); } if (mapa_virtual [g][h] == ESTADO_BANDERIN_4) { rect.x = h * IMAGENES_DIMENSION; rect.y = g * IMAGENES_DIMENSION; SDL_BlitSurface (images [IMG_COURSE_4_1 + frame/16], NULL, screen, &rect); } } } /* Animar Mario */ mario.AnimarMario(((frame % 8) / 4)); } frame++; if (frame > 31) frame = 0; SDL_Flip (screen); SDL_Delay (32); } while (1); return 0; }
// //**************************************************************************** // TEST OF FULL_MERGE_FOUR //**************************************************************************** void prueba6(void) { //------------------------------- begin------------------------------------ struct xk { unsigned tail : 3 ; unsigned num :24 ; xk( unsigned N, unsigned T =0):tail(T),num(N){}; bool operator < ( xk A) const { return ( num < A.num); }; }; std::vector<xk> R[4],Rout; typedef typename std::vector<xk>::iterator iter_t ; typedef std::less<xk> Compare ; Compare Comp ; //------------------------------------------------------------------------ R[0] = {3,5,9,16,17,24,25,29}; R[1] = {1,7,10,13,18,22,26,30 }; R[2] = {2 ,6,11,15,20,21,28,32}; R[3] = {4,8,12,14,19,23,27,31} ; for ( uint32_t i =0 ; i < 4 ; ++i) { for ( uint32_t k =0 ; k < 10 ; ++k) { R[i][k].tail = i ; }; }; Rout.resize ( 32,0); bs_util::range<iter_t> RG[4]= { {R[0].begin(),R[0].end()} , {R[1].begin(),R[1].end()} , {R[2].begin(),R[2].end()} , {R[3].begin(),R[3].end()} } ; bs_util::full_merge4 (&Rout[0],RG,4,Comp); if ( Rout.size() != 32) std::cout<<"Error in the size\n"; for( uint32_t i = 0 ; i < Rout.size() ; ++i) BOOST_CHECK ( Rout[i].num == i+1) ; //------------------------------------------------------------------------ R[0] = {2,3,5,6,6,10,13,20}; R[1] = {1,2,4,5,6,10,17,19 }; R[2] = {2,3,4,7,8,11,16,18}; R[3] = {1,4,5,7,9,12,14,15} ; for ( uint32_t i =0 ; i < 4 ; ++i) { for ( uint32_t k =0 ; k < R[i].size() ; ++k) R[i][k].tail = i ; }; Rout.clear() ; Rout.resize ( 32,0); RG[0] = {R[0].begin(),R[0].end()} ; RG[1] = {R[1].begin(),R[1].end()} ; RG[2] = {R[2].begin(),R[2].end()} ; RG[3] = {R[3].begin(),R[3].end()} ; bs_util::full_merge4 (&Rout[0],RG,4,Comp); for ( uint32_t i = 1 ; i < Rout.size() ; ++i) { BOOST_CHECK ( Rout[i-1].num <= Rout[i].num and (Rout[i-1].num != Rout[i].num or Rout[i-1].tail <= Rout[i].tail )); //if ( Rout[i-1].num > Rout[i].num or // (Rout[i-1].num == Rout[i].num and Rout[i-1].tail> Rout[i].tail )) // std::cout<<"Error in the sorting \n" ; }; };
LFile* PRDocument::CreateNewUnflattenedFile( ConstFSSpecPtr inFileSpec) { // Validate pointers. ValidateThis_(); OSErr err; FSSpec unflattenedSpec; SInt16 foundVRefNum; SInt32 foundDirID; SInt16 srcRefNum; SInt16 destRefNum; err = ::FindFolder(inFileSpec->vRefNum, kTemporaryFolderType, kCreateFolder, &foundVRefNum, &foundDirID); // JWW - The volume might not be what we asked, especially if it's on OS X... // ...and on OS X, it looks like FindFolder returns an error, so don't throw if ((err != noErr) || (foundVRefNum != inFileSpec->vRefNum)) { // ...and in that case, just use the document folder instead why not? foundVRefNum = inFileSpec->vRefNum; foundDirID = inFileSpec->parID; } LStr255 tempName; UInt32 ticks = ::TickCount(); do { tempName = (SInt32) ticks++; tempName += inFileSpec->name; if (tempName.Length() > 31) { tempName[0] = 31; } err = ::FSMakeFSSpec(foundVRefNum, foundDirID, tempName, &unflattenedSpec); if ((err != noErr) and (err != fnfErr)) Throw_(err); } while (err != fnfErr); // Delete any existing unflattened file if (mUnflattenedFile) { FSSpec oldUnflattenedSpec; mUnflattenedFile->GetSpecifier(oldUnflattenedSpec); delete mUnflattenedFile; mUnflattenedFile = nil; // delete the unflattened file from disk (it's just a temporary file anyways) err = ::FSpDelete(&oldUnflattenedSpec); if (err == fLckdErr) { // Unlock it and try to delete it again err = ::FSpRstFLock(&oldUnflattenedSpec); if (err == noErr) { ::FSpDelete(&oldUnflattenedSpec); } } } // Create the new unflattened file mUnflattenedFile = new LFile(unflattenedSpec); // Create the new file and create the resource map mUnflattenedFile->CreateNewFile(Type_CreatorCode, Type_MacOSDocument, smSystemScript); destRefNum = mUnflattenedFile->OpenResourceFork(fsRdWrPerm); LFile flatFile(*inFileSpec); srcRefNum = flatFile.OpenDataFork(fsRdPerm); StPointerBlock buffer(bigCopyBuffSize, false, false); if (not buffer.IsValid()) { StPointerBlock smallBuffer(minCopyBuffSize, true, false); buffer.Adopt(smallBuffer.Release()); } err = ::CopyFork(srcRefNum, destRefNum, buffer, ::GetPtrSize(buffer)); SInt32 resForkEOF; ThrowIfOSErr_(::GetEOF(destRefNum, &resForkEOF)); // Close the resource fork (we'll leave the flat file's data fork open) mUnflattenedFile->CloseResourceFork(); // The CopyFork routine may have killed the resource map in the case // where the data fork was empty. This will recreate an empty resource map. if (resForkEOF == 0) { ::FSpDelete(&unflattenedSpec); mUnflattenedFile->CreateNewFile(Type_CreatorCode, Type_MacOSDocument, smSystemScript); } // Copy the File Manager attributes over to the new file err = ::FSpCopyFileMgrAttributes(inFileSpec, &unflattenedSpec, true); return mUnflattenedFile; }
//**************************************************************************** // TEST OF UNINITIALIZED_FULL_MERGE_FOUR //**************************************************************************** void prueba8(void) { //------------------------------- begin------------------------------------ struct xk { unsigned tail : 3 ; unsigned num :24 ; xk( unsigned N, unsigned T =0):tail(T),num(N){}; bool operator < ( xk A) const { return ( num < A.num); }; }; typedef typename std::vector<xk>::iterator iter_t ; typedef std::less<xk> Compare ; std::vector<xk> R[4]; char K[320]; xk *PAux = reinterpret_cast <xk*> ( &K[0]); Compare Comp ; //------------------------------------------------------------------------ R[0] = {3,5,9,16,17,24,25,29}; R[1] = {1,7,10,13,18,22,26,30 }; R[2] = {2 ,6,11,15,20,21,28,32}; R[3] = {4,8,12,14,19,23,27,31} ; for ( uint32_t i =0 ; i < 4 ; ++i) { for ( uint32_t k =0 ; k < 10 ; ++k) { R[i][k].tail = i ; }; }; bs_util::range<iter_t> RG[4]= { {R[0].begin(),R[0].end()} , {R[1].begin(),R[1].end()} , {R[2].begin(),R[2].end()} , {R[3].begin(),R[3].end()} } ; bs_util::uninit_full_merge4 (PAux,RG,4,Comp); for( uint32_t i = 0 ; i < 32 ; ++i) BOOST_CHECK ( PAux[i].num == i+1) ; bs_util::destroy (PAux, PAux + 32 ); //------------------------------------------------------------------------ R[0] = {2,3,5,6,6,10,13,20}; R[1] = {1,2,4,5,6,10,17,19 }; R[2] = {2,3,4,7,8,11,16,18}; R[3] = {1,4,5,7,9,12,14,15} ; for ( uint32_t i =0 ; i < 4 ; ++i) { for ( uint32_t k =0 ; k < R[i].size() ; ++k) R[i][k].tail = i ; }; RG[0] = {R[0].begin(),R[0].end()} ; RG[1] = {R[1].begin(),R[1].end()} ; RG[2] = {R[2].begin(),R[2].end()} ; RG[3] = {R[3].begin(),R[3].end()} ; bs_util::uninit_full_merge4 (PAux,RG,4,Comp); for ( uint32_t i = 1 ; i < 32 ; ++i) { //if ( PAux[i-1].num > PAux[i].num or // (PAux[i-1].num == PAux[i].num and PAux[i-1].tail> PAux[i].tail )) // std::cout<<"Error in the sorting \n" ; BOOST_CHECK ( PAux[i-1].num <= PAux[i].num and (PAux[i-1].num != PAux[i].num or PAux[i-1].tail <= PAux[i].tail )); }; bs_util::destroy (PAux, PAux + 32 ); };
void aeif_cond_alpha_multisynapse::update( Time const& origin, const long_t from, const long_t to ) { assert( to >= 0 && ( delay ) from < Scheduler::get_min_delay() ); assert( from < to ); assert( State_::V_M == 0 ); for ( long_t lag = from; lag < to; ++lag ) // proceed by stepsize B_.step_ { double t = 0.0; // internal time of the integration period if ( S_.r_ > 0 ) // decrease remaining refractory steps if non-zero --S_.r_; // numerical integration with adaptive step size control: // ------------------------------------------------------ // The numerical integration of the model equations is performed by // a Dormand-Prince method (5th order Runge-Kutta method with // adaptive stepsize control) as desribed in William H. Press et // al., “Adaptive Stepsize Control for Runge-Kutta”, Chapter 17.2 // in Numerical Recipes (3rd edition, 2007), 910-914. The solver // itself performs only a single NUMERICAL integration step, // starting from t and of size B_.IntegrationStep_ (bounded by // step); the while-loop ensures integration over the whole // SIMULATION step (0, step] of size B_.step_ if more than one // integration step is needed due to a small integration stepsize; // note that (t+IntegrationStep > step) leads to integration over // (t, step] and afterwards setting t to step, but it does not // enforce setting IntegrationStep to step-t; this is of advantage // for a consistent and efficient integration across subsequent // simulation intervals. double_t& h = B_.IntegrationStep_; // numerical integration step double_t& tend = B_.step_; // end of simulation step const double_t& MAXERR = P_.MAXERR; // maximum error const double_t& HMIN = P_.HMIN; // minimal integration step double_t err; double_t t_return = 0.0; while ( t < B_.step_ ) // while not yet reached end of simulation step { bool done = false; do { if ( tend - t < h ) // stop integration at end of simulation step h = tend - t; t_return = t + h; // update t // k1 = f(told, y) aeif_cond_alpha_multisynapse_dynamics( S_.y_, S_.k1 ); // k2 = f(told + h/5, y + h*k1 / 5) for ( size_t i = 0; i < S_.y_.size(); ++i ) S_.yin[ i ] = S_.y_[ i ] + h * S_.k1[ i ] / 5.0; aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k2 ); // k3 = f(told + 3/10*h, y + 3/40*h*k1 + 9/40*h*k2) for ( size_t i = 0; i < S_.y_.size(); ++i ) S_.yin[ i ] = S_.y_[ i ] + h * ( 3.0 / 40.0 * S_.k1[ i ] + 9.0 / 40.0 * S_.k2[ i ] ); aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k3 ); // k4 for ( size_t i = 0; i < S_.y_.size(); ++i ) S_.yin[ i ] = S_.y_[ i ] + h * ( 44.0 / 45.0 * S_.k1[ i ] - 56.0 / 15.0 * S_.k2[ i ] + 32.0 / 9.0 * S_.k3[ i ] ); aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k4 ); // k5 for ( size_t i = 0; i < S_.y_.size(); ++i ) S_.yin[ i ] = S_.y_[ i ] + h * ( 19372.0 / 6561.0 * S_.k1[ i ] - 25360.0 / 2187.0 * S_.k2[ i ] + 64448.0 / 6561.0 * S_.k3[ i ] - 212.0 / 729.0 * S_.k4[ i ] ); aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k5 ); // k6 for ( size_t i = 0; i < S_.y_.size(); ++i ) S_.yin[ i ] = S_.y_[ i ] + h * ( 9017.0 / 3168.0 * S_.k1[ i ] - 355.0 / 33.0 * S_.k2[ i ] + 46732.0 / 5247.0 * S_.k3[ i ] + 49.0 / 176.0 * S_.k4[ i ] - 5103.0 / 18656.0 * S_.k5[ i ] ); aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k6 ); // 5th order for ( size_t i = 0; i < S_.y_.size(); ++i ) S_.ynew[ i ] = S_.y_[ i ] + h * ( 35.0 / 384.0 * S_.k1[ i ] + 500.0 / 1113.0 * S_.k3[ i ] + 125.0 / 192.0 * S_.k4[ i ] - 2187.0 / 6784.0 * S_.k5[ i ] + 11.0 / 84.0 * S_.k6[ i ] ); aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k7 ); // 4th order for ( size_t i = 0; i < S_.y_.size(); ++i ) { S_.yref[ i ] = S_.y_[ i ] + h * ( 5179.0 / 57600.0 * S_.k1[ i ] + 7571.0 / 16695.0 * S_.k3[ i ] + 393.0 / 640.0 * S_.k4[ i ] - 92097.0 / 339200.0 * S_.k5[ i ] + 187.0 / 2100.0 * S_.k6[ i ] + 1.0 / 40.0 * S_.k7[ i ] ); } err = std::fabs( S_.ynew[ 0 ] - S_.yref[ 0 ] ) / MAXERR + 1.0e-200; // error estimate, // based on different orders for stepsize prediction. Small value added to prevent err==0 // The following flag 'done' is needed to ensure that we accept the result // for h<=HMIN, irrespective of the error. (See below) done = ( h <= HMIN ); // Always exit loop if h was <=HMIN already // prediction of next integration stepsize. This step may result in a stepsize below HMIN. // If this happens, we must // 1. set the stepsize to HMIN // 2. compute the result and accept it irrespective of the error, because we cannot // decrease the stepsize any further. // the 'done' flag, computed above ensure that the loop is terminated after the // result was computed. h *= 0.98 * std::pow( 1.0 / err, 1.0 / 5.0 ); h = std::max( h, HMIN ); } while ( ( err > 1.0 ) and ( not done ) ); // reject step if err > 1 for ( size_t i = 0; i < S_.y_.size(); ++i ) S_.y_[ i ] = S_.ynew[ i ]; // pass updated values t = t_return; // check for unreasonable values; we allow V_M to explode if ( S_.y_[ State_::V_M ] < -1e3 || S_.y_[ State_::W ] < -1e6 || S_.y_[ State_::W ] > 1e6 ) throw NumericalInstability( get_name() ); // spikes are handled inside the while-loop // due to spike-driven adaptation if ( S_.r_ > 0 ) // if neuron is still in refractory period S_.y_[ State_::V_M ] = P_.V_reset_; // clamp it to V_reset else if ( S_.y_[ State_::V_M ] >= P_.V_peak_ ) // V_m >= V_peak: spike { S_.y_[ State_::V_M ] = P_.V_reset_; S_.y_[ State_::W ] += P_.b; // spike-driven adaptation S_.r_ = V_.RefractoryCounts_; // initialize refractory steps with refractory period set_spiketime( Time::step( origin.get_steps() + lag + 1 ) ); SpikeEvent se; network()->send( *this, se, lag ); } } // while for ( size_t i = 0; i < P_.num_of_receptors_; ++i ) { S_.y_[ State_::DG_EXC + ( State_::NUMBER_OF_STATES_ELEMENTS_PER_RECEPTOR * i ) ] += B_.spike_exc_[ i ].get_value( lag ) * V_.g0_ex_[ i ]; // add incoming spikes S_.y_[ State_::DG_INH + ( State_::NUMBER_OF_STATES_ELEMENTS_PER_RECEPTOR * i ) ] += B_.spike_inh_[ i ].get_value( lag ) * V_.g0_in_[ i ]; } // set new input current B_.I_stim_ = B_.currents_.get_value( lag ); // log state data B_.logger_.record_data( origin.get_steps() + lag ); } // for-loop }
void GlobalProblem::ConstructSubproblemPrimal(int subproblem_index, long double budget_allocation, int opt_region) { // Figure out opt u, v. long double u = subproblems_[subproblem_index].envelope_points_[opt_region].first; long double v = subproblems_[subproblem_index].envelope_points_[opt_region].second; long double allocation_value = 0; // If optimum is u = 0, optimal allocation is greedy wrt price. if (u == 0) { int max_price_index; long double max_price = 0; for (int i = 0; i < subproblems_[subproblem_index].num_vars_; ++i) { if ((max_price < subproblems_[subproblem_index].constraints_[i].price_) and (subproblems_[subproblem_index].constraints_[i].is_active_)) { max_price_index = i; max_price = subproblems_[subproblem_index].constraints_[i].price_; } } //(*primal_sol)[subproblems_[subproblem_index].advertiser_index_->at(max_price_index)][subproblem_index] = 1; //(*solution_)[subproblems_[subproblem_index].constraints_[max_price_index].advertiser_index_][subproblem_index].first = 1; //(*primal_changes)[subproblems_[subproblem_index].constraints_[max_price_index].advertiser_index_][subproblem_index] = 1; primal_changes_[subproblem_index].first = make_pair(subproblems_[subproblem_index].constraints_[max_price_index].advertiser_index_, 1.0); primal_changes_[subproblem_index].second = make_pair(-1, 0.0); allocation_value = primal_changes_[subproblem_index].first.second * subproblems_[subproblem_index].constraints_[max_price_index].price_; primal_assignment_test_ += allocation_value; } // If optimum is v = 0, optimal allocation is greedy wrt price/weight ratio. if (v == 0) { int max_ratio_index; long double max_ratio = 0; for (int i = 0; i < subproblems_[subproblem_index].num_vars_; ++i) { if (max_ratio < (subproblems_[subproblem_index].constraints_[i].price_ / subproblems_[subproblem_index].constraints_[i].coefficient_) and (subproblems_[subproblem_index].constraints_[i].is_active_)) { max_ratio_index = i; max_ratio = (subproblems_[subproblem_index].constraints_[i].price_ / subproblems_[subproblem_index].constraints_[i].coefficient_); } } //(*primal_changes)[subproblems_[subproblem_index].constraints_[max_ratio_index].advertiser_index_][subproblem_index] = budget_allocation / subproblems_[subproblem_index].constraints_[max_ratio_index].coefficient_; //(*solution_)[subproblems_[subproblem_index].constraints_[max_ratio_index].advertiser_index_][subproblem_index].first = budget_allocation / subproblems_[subproblem_index].constraints_[max_ratio_index].coefficient_; //(*primal_sol)[subproblems_[subproblem_index].advertiser_index_->at(max_ratio_index)][subproblem_index] = budget_allocation / subproblems_[subproblem_index].constraints_[max_ratio_index].coefficient_; primal_changes_[subproblem_index].first = make_pair(subproblems_[subproblem_index].constraints_[max_ratio_index].advertiser_index_, budget_allocation / subproblems_[subproblem_index].constraints_[max_ratio_index].coefficient_); primal_changes_[subproblem_index].second = make_pair(-1, 0.0); allocation_value = primal_changes_[subproblem_index].first.second * subproblems_[subproblem_index].constraints_[max_ratio_index].price_; primal_assignment_test_ += allocation_value; } // If opt is u, v > 0, the optimum whp only has two positive allocations, which are the // solutions to a system of 2 equations. if ((u > 0) and (v > 0)) { vector<int> tight_constraint_indices; for (int i = 0; i < subproblems_[subproblem_index].num_vars_; ++i) { if (subproblems_[subproblem_index].constraints_[i].is_active_) { long double slack = subproblems_[subproblem_index].constraints_[i].price_ - (u * subproblems_[subproblem_index].constraints_[i].coefficient_ + v); if (slack < 0) { slack = (-1) * slack;} if (slack < numerical_accuracy_tolerance_) { tight_constraint_indices.push_back(i); } } } if (tight_constraint_indices.size() > 2) { cout << "ERROR, PERTURB PRICES \n"; } if (tight_constraint_indices.size() == 1) { /* (*primal_sol)[subproblems_[subproblem_index].advertiser_index_-> at(tight_constraint_indices[0])] [subproblem_index] = fmin(budget_allocation / subproblems_[subproblem_index].constraints_[tight_constraint_indices[0]].coefficient_, 1); */ //(*solution_)[subproblems_[subproblem_index].constraints_[tight_constraint_indices[0]].advertiser_index_][subproblem_index].first = fmin(budget_allocation / subproblems_[subproblem_index].constraints_[tight_constraint_indices[0]].coefficient_, 1); //(*primal_changes)[subproblems_[subproblem_index].constraints_[tight_constraint_indices[0]].advertiser_index_][subproblem_index] = fmin(budget_allocation / subproblems_[subproblem_index].constraints_[tight_constraint_indices[0]].coefficient_, 1); primal_changes_[subproblem_index].first = make_pair(subproblems_[subproblem_index].constraints_[tight_constraint_indices[0]].advertiser_index_, fmin(budget_allocation / subproblems_[subproblem_index].constraints_[tight_constraint_indices[0]].coefficient_, 1)); primal_changes_[subproblem_index].second = make_pair(-1, 0.0); allocation_value = primal_changes_[subproblem_index].first.second * subproblems_[subproblem_index].constraints_[tight_constraint_indices[0]].coefficient_; primal_assignment_test_ += allocation_value; } if (tight_constraint_indices.size() == 2) { int first_index = tight_constraint_indices[0]; int second_index = tight_constraint_indices[1]; long double x_1 = (budget_allocation - subproblems_[subproblem_index].constraints_[second_index].coefficient_) / (subproblems_[subproblem_index].constraints_[first_index].coefficient_ - subproblems_[subproblem_index].constraints_[second_index].coefficient_); /* (*primal_sol)[subproblems_[subproblem_index].advertiser_index_->at(first_index)][subproblem_index] = x_1; (*primal_sol)[subproblems_[subproblem_index].advertiser_index_->at(second_index)][subproblem_index] = 1 - x_1; */ /* (*solution_)[subproblems_[subproblem_index].constraints_[first_index].advertiser_index_][subproblem_index].first = x_1; (*solution_)[subproblems_[subproblem_index].constraints_[second_index].advertiser_index_][subproblem_index].first = 1 - x_1; */ /* (*primal_changes)[subproblems_[subproblem_index].constraints_[first_index].advertiser_index_][subproblem_index] = x_1; (*primal_changes)[subproblems_[subproblem_index].constraints_[second_index].advertiser_index_][subproblem_index] = 1 - x_1; */ primal_changes_[subproblem_index].first = make_pair(subproblems_[subproblem_index].constraints_[first_index].advertiser_index_, x_1); primal_changes_[subproblem_index].second = make_pair(subproblems_[subproblem_index].constraints_[second_index].advertiser_index_, 1 - x_1); allocation_value = x_1 * subproblems_[subproblem_index].constraints_[first_index].price_ + (1-x_1) * subproblems_[subproblem_index].constraints_[second_index].price_; primal_assignment_test_ += allocation_value; } } if (((allocation_value - (u * budget_allocation + v)) > numerical_accuracy_tolerance_) || ((allocation_value - (u * budget_allocation + v)) < -numerical_accuracy_tolerance_)) { cout << "**************Error at problem************ " << subproblem_index << " equal to " << allocation_value << " - " << (u * budget_allocation + v) << "\n"; } }
int main( int argc , char** argv ) { int L_flag=0,i,j,k,l; if ( argc > 1 and !strcmp( "-nt" , argv[1] ) ) { nthreads = atoi( argv[2] ) ; omp_set_num_threads( nthreads ) ; printf("\nNumber of threads set to %d!\n" , nthreads ) ; } else { nthreads = 1 ; omp_set_num_threads( nthreads ) ; printf("\nNumber of threads set to %d!\n" , nthreads ) ; } read_input() ; if(argc == 5 ) { Nhc = atoi(argv[4]); cout<<"new Nhc "<<Nhc<<endl; } initialize() ; write_gro( ) ; write_quaternions( ) ; // Save chi for pre-equilibration steps // double tmp_ang,chi_bkp = chiAB ; FILE *otp ,*otpL; otp = fopen( "data.dat" , "w" ) ; otpL = fopen("box_L.dat","w"); printf("Entering main loop!\n") ; fflush( stdout ) ; for ( step = 0 ; step < nsteps ; step++ ) { // if ( step < pre_equil_steps ) // chiAB = 0.0 ; // else // chiAB = chi_bkp ; forces() ; //cout<<"here"<<endl; if(sigma>0){ torque(); } // exit(1); if(step >0 || rst_para == 1) update_positions() ; else update_positions_init() ; if(sigma>0){ update_euler(); } if ( stress_freq > 0 && step % stress_freq == 0 ) { calc_stress() ; for ( j=0 ; j<Dim ; j++ ){ for ( k=0 ; k<Dim ; k++ ) { sts_buf[buff_ind][j][k]= Rg3*Ptens[j][k];//( j<Dim ? Stress_bonds[j][k]:0.0) ; sts_buf_pp[buff_ind][j][k] = Rg3*Stress_PP[j][k]; sts_buf_ng[buff_ind][j][k] = Rg3*Stress_Ng[j][k]; if( ((L_fren-L_aver) < L_flag) and (optm_L >0) and (j ==k)) aver_Ptens[j][j] += Rg3*Ptens[j][j]; /*for ( k=0 ; k<nP; k++ ){ //euler_adot[k][j] = euler_q[k][j]; sts_buf[buff_ind][j][k+Dim] = euler_q[k][j]; }*/ } } if(((L_fren-L_aver) < L_flag) and (optm_L >0)) aver_Ptens[0][1] +=1; buff_ind++ ; } if(optm_L>0 ){ if( step > pre_equil_steps ) L_flag +=1 ; if(L_flag == L_fren){ adj_L(); L_flag = 0 ; fprintf( otpL , "%d %lf %lf %lf \n" ,step ,L[0],L[1],L[2]);fflush( otpL ) ; } }//optm_L if(step % sample_freq == 0){ write_np(); } if ( step > sample_wait && step % sample_freq == 0 ) { /* fftw_fwd( rho[0] , ktmp ) ; for ( i=0 ; i<M ; i++ ) { avg_sk[0][i] += ktmp[i] * conj(ktmp[i]) ; } if ( nP > 0 ) { fftw_fwd( rho[2] , ktmp ) ; for ( i=0 ; i<M ; i++ ) { avg_sk[2][i] += ktmp[i] * conj( ktmp[i] ) ; } }*/ /* for ( i=0 ; i<M ; i++ ) { avg_rho[0][i] += rho[0][i]; avg_rho[1][i] += rho[1][i]; avg_rho[3][i] += rho[3][i]; } */ calc_Unb() ; fprintf( otp , "%d %d %lf %lf %lf %lf %lf %lf %lf\n" , step ,n_surf_bonds,Ubond , U_chi_gg, U_kappa_gg,U_chi_pg,U_kappa_pg,U_kappa_pp , Utt) ; fflush( otp ) ; num_averages += 1.0 ; } if ( step % print_freq == 0 || step == nsteps-1 ) { printf("step %d of %d Ubond: %lf\n" , step , nsteps , Ubond ) ; fflush( stdout ) ; write_gro() ; write_rst_gro(); write_quaternions(); if ( stress_freq > 0 ) write_stress() ; if ( wall_para && graft_surface ) write_surface_bonds() ; write_grid_data( "rhoda.dat" , rhoda ) ; write_grid_data( "rhodb.dat" , rhodb ) ; if ( nA > 0.0 ) write_grid_data( "rhoha.dat" , rhoha ) ; if ( nB > 0.0 ) write_grid_data( "rhohb.dat" , rhohb ) ; if( nC > 0.0 ) write_grid_data( "rhohc.dat" , rhohb ) ; if ( nP > 0.0 ) write_grid_data( "rhop.dat" , rhop ) ; if ( step > sample_wait ) { /* for ( i=0 ; i<M ; i++ ) ktmp2[i] = avg_sk[0][i] / num_averages ; write_kspace_data( "avg_sk_A.dat" , ktmp2 ) ; if ( nP > 0 ) { for ( i=0 ; i<M ; i++ ) ktmp2[i] = avg_sk[2][i] / num_averages ; write_kspace_data( "avg_sk_np.dat" , ktmp2 ) ; }*/ /* for ( i=0 ; i<M ; i++ ) tmp[i] = avg_rho[0][i]/ num_averages ; write_grid_data("avg_typeA.dat",tmp); for ( i=0 ; i<M ; i++ ) tmp[i] = avg_rho[1][i]/ num_averages ; write_grid_data("avg_typeB.dat",tmp); for ( i=0 ; i<M ; i++ ) tmp[i] = avg_rho[3][i]/ num_averages ; write_grid_data("avg_typeC.dat",tmp); */ } // calc_Unb() ; // fprintf( otp , "%d %d %lf %lf %lf %lf %lf %lf %lf\n" , step ,n_surf_bonds,Ubond , U_chi_gg, U_kappa_gg,U_chi_pg,U_kappa_pg,U_kappa_pp , Utt) ; // fflush( otp ) ; }// if step % print_Freq == 0 if ( step == frame_freq ) { char nm[20] ; if ( nA > 0.0 ) { sprintf( nm , "rhoha.frame%d.dat" , step ) ; write_grid_data( nm , rhoha ) ; } if ( nB > 0.0 ) { sprintf( nm , "rhohb.frame%d.dat" , step ) ; write_grid_data( nm , rhohb ) ; } if ( nP > 0.0 ) { sprintf( nm , "rhop.frame%d.dat" , step ) ; write_grid_data( nm , rhop ) ; } if ( nD > 0.0 ) { sprintf( nm , "rhoda.frame%d.dat" , step ) ; write_grid_data( nm , rhoda ) ; sprintf( nm , "rhodb.frame%d.dat" , step ) ; write_grid_data( nm , rhodb ) ; } frame_freq *= 2 ; } } fclose( otp ) ; return 0 ; }
/** * @brief Check if an object of this type is in a valid * state * * @return true if valid, false otherwise */ bool is_valid() const noexcept { return (buffer_ not_eq nullptr) and (not err_); }
// ************************************************************** void Initialize(Double (*_function)(Double), const Double _range_min, const Double _range_max, const int _n, const std::string _name, Double *_table = NULL) { is_initialized = true; function = _function; name = _name; n = _n; range_min = _range_min; range_max = _range_max; if (_table != NULL) { table = _table; } else { table = calloc_and_check<Double>(n, "LookUpTable"); } /* * Example: * n = 6 points * n-1 = 5 intervals * dx = (xmax - xmin) / nb_intervals = (xmax - xmin) / (n-1) * x x * x x * x * x________________________________________ * | | | | | | * xmin xmax */ dx = (range_max - range_min) / Double(n-1); inv_dx = Double(1.0) / dx; if (verbose) { Print(); std_cout << "Building lookup table table \"" << _name << "\"..." << std::flush; } Double x = 0.0; int percentage = 0; if (function != NULL) { assert(table != NULL); for (int i = 0 ; i < n ; i++) { x = Get_x_from_i(i); table[i] = function(x); percentage = int(Double(i) / Double(n) * 100.0); if (verbose and (percentage % 2) == 0) printf(" %3d %%\b\b\b\b\b\b", percentage); fflush(stdout); } } else { if (verbose) std_cout << " Nothing to do since function pointer given is NULL." << std::flush; } if (verbose) std_cout << " Done. \n" << std::flush; }
void eListboxServiceContent::paint(gPainter &painter, eWindowStyle &style, const ePoint &offset, int selected) { painter.clip(eRect(offset, m_itemsize)); int marked = 0; if (m_current_marked && selected) marked = 2; else if (cursorValid() && isMarked(*m_cursor)) { if (selected) marked = 2; else marked = 1; } else style.setStyle(painter, selected ? eWindowStyle::styleListboxSelected : eWindowStyle::styleListboxNormal); eListboxStyle *local_style = 0; /* get local listbox style, if present */ if (m_listbox) local_style = m_listbox->getLocalStyle(); if (marked == 1) // marked { style.setStyle(painter, eWindowStyle::styleListboxMarked); if (m_color_set[markedForeground]) painter.setForegroundColor(m_color[markedForeground]); if (m_color_set[markedBackground]) painter.setBackgroundColor(m_color[markedBackground]); } else if (marked == 2) // marked and selected { style.setStyle(painter, eWindowStyle::styleListboxMarkedAndSelected); if (m_color_set[markedForegroundSelected]) painter.setForegroundColor(m_color[markedForegroundSelected]); if (m_color_set[markedBackgroundSelected]) painter.setBackgroundColor(m_color[markedBackgroundSelected]); } else if (local_style) { if (selected) { /* if we have a local background color set, use that. */ if (local_style->m_background_color_selected_set) painter.setBackgroundColor(local_style->m_background_color_selected); /* same for foreground */ if (local_style->m_foreground_color_selected_set) painter.setForegroundColor(local_style->m_foreground_color_selected); } else { /* if we have a local background color set, use that. */ if (local_style->m_background_color_set) painter.setBackgroundColor(local_style->m_background_color); /* same for foreground */ if (local_style->m_foreground_color_set) painter.setForegroundColor(local_style->m_foreground_color); } } if (!local_style || !local_style->m_transparent_background) /* if we have no transparent background */ { /* blit background picture, if available (otherwise, clear only) */ if (local_style && local_style->m_background) painter.blit(local_style->m_background, offset, eRect(), 0); else painter.clear(); } else { if (local_style->m_background) painter.blit(local_style->m_background, offset, eRect(), gPainter::BT_ALPHABLEND); else if (selected && !local_style->m_selection) painter.clear(); } if (cursorValid()) { /* get service information */ ePtr<iStaticServiceInformation> service_info; m_service_center->info(*m_cursor, service_info); eServiceReference ref = *m_cursor; bool isMarker = ref.flags & eServiceReference::isMarker; bool isPlayable = !(ref.flags & eServiceReference::isDirectory || isMarker); bool isRecorded = m_record_indicator_mode && isPlayable && checkServiceIsRecorded(ref,pNavigation::RecordType(pNavigation::isRealRecording|pNavigation::isUnknownRecording)); bool isStreamed = m_record_indicator_mode && isPlayable && checkServiceIsRecorded(ref,pNavigation::isStreaming); bool isPseudoRecorded = m_record_indicator_mode && isPlayable && checkServiceIsRecorded(ref,pNavigation::isPseudoRecording); ePtr<eServiceEvent> evt; bool serviceAvail = true; bool serviceFallback = false; int isplayable_value; if (!marked && isPlayable && service_info && m_is_playable_ignore.valid()) { isplayable_value = service_info->isPlayable(*m_cursor, m_is_playable_ignore); if (isplayable_value == 0) // service unavailable { if (m_color_set[serviceNotAvail]) painter.setForegroundColor(m_color[serviceNotAvail]); else painter.setForegroundColor(gRGB(0xbbbbbb)); serviceAvail = false; } else { if (isplayable_value == 2) // fallback receiver service { if (m_color_set[serviceItemFallback]) painter.setForegroundColor(m_color[serviceItemFallback]); serviceFallback = true; } } } if (m_record_indicator_mode == 3 && isPseudoRecorded) { if (m_color_set[servicePseudoRecorded]) painter.setForegroundColor(m_color[servicePseudoRecorded]); else painter.setForegroundColor(gRGB(0x41b1ec)); } if (m_record_indicator_mode == 3 && isStreamed) { if (m_color_set[serviceStreamed]) painter.setForegroundColor(m_color[serviceStreamed]); else painter.setForegroundColor(gRGB(0xf56712)); } if (m_record_indicator_mode == 3 && isRecorded) { if (m_color_set[serviceRecorded]) painter.setForegroundColor(m_color[serviceRecorded]); else painter.setForegroundColor(gRGB(0xb40431)); } if (selected && local_style && local_style->m_selection) painter.blit(local_style->m_selection, offset, eRect(), gPainter::BT_ALPHABLEND); int xoffset=0; // used as offset when painting the folder/marker symbol or the serviceevent progress time_t now = time(0); for (int e = 0; e != celServiceTypePixmap; ++e) { if (m_element_font[e]) { int flags=gPainter::RT_VALIGN_CENTER; int yoffs = 0; eRect area = m_element_position[e]; std::string text = "<n/a>"; switch (e) { case celServiceNumber: { if (area.width() <= 0) continue; // no point in going on if we won't paint anything if( m_cursor->getChannelNum() == 0 ) continue; char buffer[15]; snprintf(buffer, sizeof(buffer), "%d", m_cursor->getChannelNum() ); text = buffer; flags|=gPainter::RT_HALIGN_RIGHT; if (isPlayable && serviceFallback && selected && m_color_set[serviceSelectedFallback]) painter.setForegroundColor(m_color[serviceSelectedFallback]); break; } case celServiceName: { if (service_info) service_info->getName(*m_cursor, text); if (!isPlayable) { area.setWidth(area.width() + m_element_position[celServiceEventProgressbar].width() + m_nonplayable_margins); if (m_element_position[celServiceEventProgressbar].left() == 0) area.setLeft(0); if (m_element_position[celServiceNumber].width() && m_element_position[celServiceEventProgressbar].left() == m_element_position[celServiceNumber].width() + m_nonplayable_margins) area.setLeft(m_element_position[celServiceNumber].width() + m_nonplayable_margins); } if (!(m_record_indicator_mode == 3 && isRecorded) && isPlayable && serviceFallback && selected && m_color_set[serviceSelectedFallback]) painter.setForegroundColor(m_color[serviceSelectedFallback]); break; } case celServiceInfo: { if ( isPlayable && service_info && !service_info->getEvent(*m_cursor, evt) ) { std::string name = evt->getEventName(); if (name.empty()) continue; text = evt->getEventName(); if (serviceAvail) { if (!selected && m_color_set[eventForeground]) painter.setForegroundColor(m_color[eventForeground]); else if (selected && m_color_set[eventForegroundSelected]) painter.setForegroundColor(m_color[eventForegroundSelected]); else painter.setForegroundColor(gRGB(0xe7b53f)); if (serviceFallback && !selected && m_color_set[eventForegroundFallback]) // fallback receiver painter.setForegroundColor(m_color[eventForegroundFallback]); else if (serviceFallback && selected && m_color_set[eventForegroundSelectedFallback]) painter.setForegroundColor(m_color[eventForegroundSelectedFallback]); } break; } continue; } case celServiceEventProgressbar: { if (area.width() > 0 && isPlayable && service_info && !service_info->getEvent(*m_cursor, evt)) { char buffer[15]; snprintf(buffer, sizeof(buffer), "%d %%", (int)(100 * (now - evt->getBeginTime()) / evt->getDuration())); text = buffer; flags|=gPainter::RT_HALIGN_RIGHT; break; } continue; } } eRect tmp = area; int xoffs = 0; ePtr<gPixmap> piconPixmap; if (e == celServiceName) { //picon stuff if (isPlayable && PyCallable_Check(m_GetPiconNameFunc)) { ePyObject pArgs = PyTuple_New(1); PyTuple_SET_ITEM(pArgs, 0, PyString_FromString(ref.toString().c_str())); ePyObject pRet = PyObject_CallObject(m_GetPiconNameFunc, pArgs); Py_DECREF(pArgs); if (pRet) { if (PyString_Check(pRet)) { std::string piconFilename = PyString_AS_STRING(pRet); if (!piconFilename.empty()) loadPNG(piconPixmap, piconFilename.c_str()); } Py_DECREF(pRet); } } xoffs = xoffset; tmp.setWidth(((!isPlayable || m_column_width == -1 || (!piconPixmap && !m_column_width)) ? tmp.width() : m_column_width) - xoffs); } eTextPara *para = new eTextPara(tmp); para->setFont(m_element_font[e]); para->renderString(text.c_str()); if (e == celServiceName) { eRect bbox = para->getBoundBox(); int servicenameWidth = ((!isPlayable || m_column_width == -1 || (!piconPixmap && !m_column_width)) ? bbox.width() : m_column_width); m_element_position[celServiceInfo].setLeft(area.left() + servicenameWidth + m_items_distances + xoffs); m_element_position[celServiceInfo].setTop(area.top()); m_element_position[celServiceInfo].setWidth(area.width() - (servicenameWidth + m_items_distances + xoffs)); m_element_position[celServiceInfo].setHeight(area.height()); if (isPlayable) { //picon stuff if (PyCallable_Check(m_GetPiconNameFunc) and (m_column_width || piconPixmap)) { eRect area = m_element_position[celServiceInfo]; /* PIcons are usually about 100:60. Make it a * bit wider in case the icons are diffently * shaped, and to add a bit of margin between * icon and text. */ const int iconWidth = (area.height() + m_service_picon_downsize * 2) * 1.67 + m_items_distances; m_element_position[celServiceInfo].setLeft(area.left() + iconWidth); m_element_position[celServiceInfo].setWidth(area.width() - iconWidth); area = m_element_position[celServiceName]; xoffs += iconWidth; if (piconPixmap) { area.moveBy(offset); painter.clip(area); painter.blitScale(piconPixmap, eRect(area.left(), area.top() - m_service_picon_downsize, iconWidth, area.height() + m_service_picon_downsize * 2), area, gPainter::BT_ALPHABLEND | gPainter::BT_KEEP_ASPECT_RATIO); painter.clippop(); } } //service type marker stuff if (m_servicetype_icon_mode) { int orbpos = m_cursor->getUnsignedData(4) >> 16; const char *filename = ref.path.c_str(); ePtr<gPixmap> &pixmap = (m_cursor->flags & eServiceReference::isGroup) ? m_pixmaps[picServiceGroup] : (strstr(filename, "://")) ? m_pixmaps[picStream] : (orbpos == 0xFFFF) ? m_pixmaps[picDVB_C] : (orbpos == 0xEEEE) ? m_pixmaps[picDVB_T] : m_pixmaps[picDVB_S]; if (pixmap) { eSize pixmap_size = pixmap->size(); eRect area = m_element_position[celServiceInfo]; m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + m_items_distances); m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - m_items_distances); int offs = 0; if (m_servicetype_icon_mode == 1) { area = m_element_position[celServiceName]; offs = xoffs; xoffs += pixmap_size.width() + m_items_distances; } else if (m_crypto_icon_mode == 1 && m_pixmaps[picCrypto]) offs = offs + m_pixmaps[picCrypto]->size().width() + m_items_distances; int correction = (area.height() - pixmap_size.height()) / 2; area.moveBy(offset); painter.clip(area); painter.blit(pixmap, ePoint(area.left() + offs, offset.y() + correction), area, gPainter::BT_ALPHABLEND); painter.clippop(); } } //crypto icon stuff if (m_crypto_icon_mode && m_pixmaps[picCrypto]) { eSize pixmap_size = m_pixmaps[picCrypto]->size(); eRect area = m_element_position[celServiceInfo]; int offs = 0; if (m_crypto_icon_mode == 1) { m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + m_items_distances); m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - m_items_distances); area = m_element_position[celServiceName]; offs = xoffs; xoffs += pixmap_size.width() + m_items_distances; } int correction = (area.height() - pixmap_size.height()) / 2; area.moveBy(offset); if (service_info->isCrypted()) { if (m_crypto_icon_mode == 2) { m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + m_items_distances); m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - m_items_distances); } painter.clip(area); painter.blit(m_pixmaps[picCrypto], ePoint(area.left() + offs, offset.y() + correction), area, gPainter::BT_ALPHABLEND); painter.clippop(); } } //record icon stuff if (isRecorded && m_record_indicator_mode < 3 && m_pixmaps[picRecord]) { eSize pixmap_size = m_pixmaps[picRecord]->size(); eRect area = m_element_position[celServiceInfo]; int offs = 0; if (m_record_indicator_mode == 1) { m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + m_items_distances); m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - m_items_distances); area = m_element_position[celServiceName]; offs = xoffs; xoffs += pixmap_size.width() + m_items_distances; } int correction = (area.height() - pixmap_size.height()) / 2; area.moveBy(offset); if (m_record_indicator_mode == 2) { m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + m_items_distances); m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - m_items_distances); } painter.clip(area); painter.blit(m_pixmaps[picRecord], ePoint(area.left() + offs, offset.y() + correction), area, gPainter::BT_ALPHABLEND); painter.clippop(); } } } if (flags & gPainter::RT_HALIGN_RIGHT) para->realign(eTextPara::dirRight); else if (flags & gPainter::RT_HALIGN_CENTER) para->realign(eTextPara::dirCenter); else if (flags & gPainter::RT_HALIGN_BLOCK) para->realign(eTextPara::dirBlock); if (flags & gPainter::RT_VALIGN_CENTER) { eRect bbox = para->getBoundBox(); yoffs = (area.height() - bbox.height()) / 2 - bbox.top(); } painter.renderPara(para, offset+ePoint(xoffs, yoffs)); } else if ((e == celFolderPixmap && m_cursor->flags & eServiceReference::isDirectory) || (e == celMarkerPixmap && m_cursor->flags & eServiceReference::isMarker && !(m_cursor->flags & eServiceReference::isNumberedMarker))) { ePtr<gPixmap> &pixmap = (e == celFolderPixmap) ? m_pixmaps[picFolder] : m_pixmaps[picMarker]; if (pixmap) { eSize pixmap_size = pixmap->size(); eRect area = m_element_position[e == celFolderPixmap ? celServiceName: celServiceNumber]; int correction = (area.height() - pixmap_size.height()) / 2; if (e == celFolderPixmap) if (m_element_position[celServiceEventProgressbar].left() == 0) area.setLeft(0); xoffset = pixmap_size.width() + m_items_distances; area.moveBy(offset); painter.clip(area); painter.blit(pixmap, ePoint(area.left(), offset.y() + correction), area, gPainter::BT_ALPHABLEND); painter.clippop(); } } }
static bool is_same_freq(const double f1, const double f2) { const double epsilon = 0.1; return ((f1 - epsilon) < f2 and (f1 + epsilon) > f2); }
bool VEventComponent::validate() { int count_uid = 0; // MUST 1 int count_dtstamp = 0; // Must 1 int count_dtstart = 0; // MUST 1 int count_dtend_duration = 0; // < 2 for( Property &prop : m_properties ) { if( not prop.validate() ) return false; if( prop.m_type == Property::PT_UID ) { count_uid++; continue; } if( prop.m_type == Property::PT_DTSTAMP ) { count_dtstamp++; continue; } if( prop.m_type == Property::PT_DTSTART ) { count_dtstart++; continue; } if( prop.m_type == Property::PT_DTEND or prop.m_type == Property::PT_DURATION ) { count_dtend_duration++; continue; } if( prop.m_type == Property::PT_RRULE ) { int count_and_until = 0; // MUST 0 or 1 for( const Parameter param : prop.m_parameters ) { if( param.m_type == Parameter::RR_COUNT or param.m_type == Parameter::RR_UNTIL ) count_and_until++; } if( count_and_until > 1 ) { qDebug() << "VEventComponent::validate(): too many COUNT or UNTIL in RRULE"; return false; } } } if( count_uid == 0 ) { Property p = Property(); QString u( "UID:DAYLIGHT-Modified-Uid" ); u = u.append( QDateTime::currentDateTime().toString( "yyyyMMddhhmmss" ) ); if( p.readProperty( u ) ) { m_properties.append( p ); count_uid++; qDebug() << " * Append UID" << u ; } } if( count_dtstamp == 0 ) { Property p = Property(); QString s( "DTSTAMP:" ); s = s.append( QDateTime::currentDateTime().toString( "yyyyMMddThhmmssZ" ) ); if( p.readProperty( s ) ) { m_properties.append( p ); count_dtstamp++; qDebug() << " * Append DTSTAMP" << s ; } } bool alarm_ok = true; for( VAlarmComponent va : m_vAlarmComponents ) alarm_ok = alarm_ok and va.validate(); if( not alarm_ok ) qDebug() << " * Alarm not ok."; bool ret = alarm_ok and ( count_uid == 1 ) and ( count_dtstamp == 1 ) and ( count_dtstart == 1 ) and ( count_dtend_duration < 2 ) ; if( not ret ) qDebug() << " Validate VEventComponent FALSE"; return ret; }