void DataReaderListenerImpl::on_data_available( ::DDS::DataReader_ptr reader ) { ::Xyz::FooDataReader_var foo_dr = ::Xyz::FooDataReader::_narrow(reader); if (CORBA::is_nil (foo_dr.in ())) { ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) ::Xyz::FooDataReader::_narrow failed.\n"))); } const int num_ops_per_thread = 100; ::Xyz::FooSeq foo(num_ops_per_thread) ; ::DDS::SampleInfoSeq si(num_ops_per_thread) ; DDS::ReturnCode_t status ; status = foo_dr->read(foo, si, num_ops_per_thread, ::DDS::NOT_READ_SAMPLE_STATE, ::DDS::ANY_VIEW_STATE, ::DDS::ANY_INSTANCE_STATE); if (status == ::DDS::RETCODE_OK) { for (CORBA::ULong i = 0 ; i < si.length() ; i++) { last_si_ = si[i] ; } } else { ACE_OS::fprintf (stderr, "read - Error: %d\n", status) ; } }
/** * Overwrite a byte array with a specified byte. This is frequently done * to a plaintext byte array so the sensitive data is not lying around * exposed in memory. * @param bytes The byte array to be overwritten. * @param size The size of the byte array. * @param x The byte array {@code bytes} is overwritten with this byte. */ void CryptoHelper::overwrite(byte bytes[], size_t size, byte x) { ASSERT(bytes); ASSERT(size); if(!bytes || !size) return; try { // Will throw if ptr wraps. T* and size_t causing trouble on Linux SafeInt<size_t> si((size_t)bytes); si += size; g_dummy = (void*)(size_t)si; } catch(const SafeIntException&) { throw IllegalArgumentException("Source or destination array pointer wrap"); } for(size_t i = 0; i < size; i++) bytes[i] = x; // Tame the otpimizer g_dummy = bytes; }
int main() { ChrString Str_; ULongInt si(61515012); Str_ = si.ToString(); assert(!strcmp(Str_.c_str(), "61515012")); ULongInt si2(61515012); ULongInt si3(41057012); Str_ = si3.ToString(); assert(!strcmp(Str_.c_str(), "41057012")); assert(!(si < si3)); assert(si > si3); assert(si == si2); assert(!(si == si3)); assert(si != si3); ofstream fout("testing.bin"); Write(fout, si); fout.close(); ifstream fin("testing.bin"); Read(fin, si3); fin.close(); assert(si3 == ULongInt(61515012)); si2 = "abc"; assert(si2.IsNullObject()); assert(si2.DataConversionError()); UInteger uintv("56800012"); si2.Assign(uintv); assert(si2 == ULongInt(56800012)); UShortInt usintv("65534"); si2.Assign(usintv); assert(si2 == ULongInt(65534)); cout <<"Enter a number: "; cin >>si; cout <<si <<endl; // Testing bounds checking ULongInt chk1 = ULONG_MAX; chk1 += 5; assert(chk1.Overflow()); chk1.ClearError(); chk1 = 1; --chk1; assert(!chk1.Underflow()); --chk1; assert(chk1.Underflow()); chk1.ClearError(); chk1 = 65536; chk1 *= chk1; assert(chk1.Overflow()); chk1 = 65536; chk1 >>= 2; assert(Ulong(chk1) == 16384); chk1 <<= 4; assert(Ulong(chk1) == 262144); chk1 |= ULongInt(0x0F); assert(Ulong(chk1) == 262159); chk1 = ULongInt(chk1) / ULongInt(0); assert(chk1.DivideByZero()); assert(chk1.Overflow()); assert(!chk1.NoError()); chk1.ClearError(); try { chk1.ThrowError(); } catch (const SciEngErr& ErrObj_) { cerr <<ErrObj_.message(); } // Testing series comparison class on user defined type ULongInt* List_[25]; int i; for (i = 0; i < 10; ++i) List_[i] = new ULongInt(i+1); List_[10] = NULL; ULongInt ZeroChar(0); assert(SeriesCompare<ULongInt>::SumOfUnsignedSeriesCmp(ULongInt(11), List_, ZeroChar, CHAR_MAX).Result() < 0); assert(SeriesCompare<ULongInt>::SumOfUnsignedSeriesCmp(ULongInt(55), List_, ZeroChar, CHAR_MAX).Result() == 0); assert(SeriesCompare<ULongInt>::SumOfUnsignedSeriesCmp(ULongInt(77), List_, ZeroChar, CHAR_MAX).Result() > 0); assert(SeriesCompare<ULongInt>::SumOfUnsignedSeriesCmp(ULongInt(1), List_, ZeroChar, CHAR_MAX, TRUE).Result() < 0); delete List_[5]; List_[5] = NULL; SeriesCompare<ULongInt> Pobj_ = SeriesCompare<ULongInt>::ProductOfUnsignedSeriesCmp(ULongInt(120), List_, ZeroChar, CHAR_MAX); assert(Pobj_.Result() == 0); Pobj_ = SeriesCompare<ULongInt>::ProductOfUnsignedSeriesCmp(ULongInt(121), List_, ZeroChar, CHAR_MAX); assert(Pobj_.Result() > 0); Pobj_ = SeriesCompare<ULongInt>::ProductOfUnsignedSeriesCmp(ULongInt(119), List_, ZeroChar, CHAR_MAX); assert(Pobj_.Result() < 0); for (i = 0; i < 10; ++i) delete List_[i]; cout <<endl <<"SUCCESS Testing ULongInt" <<endl; return 0; }
inline PROCESS_INFORMATION win32_start(const Executable &exe, const Arguments &args, const environment &env, stream_info &infoin, stream_info &infoout, stream_info &infoerr, const win32_setup &setup) { file_handle chin, chout, cherr; BOOST_ASSERT(setup.startupinfo->cb >= sizeof(STARTUPINFOA)); BOOST_ASSERT(!(setup.startupinfo->dwFlags & STARTF_USESTDHANDLES)); boost::scoped_ptr<STARTUPINFOA> si(new STARTUPINFOA); ::CopyMemory(si.get(), setup.startupinfo, sizeof(*setup.startupinfo)); si->dwFlags |= STARTF_USESTDHANDLES; switch (infoin.type_) { case stream_info::close: { break; } case stream_info::inherit: { chin = file_handle::win32_std(STD_INPUT_HANDLE, true); break; } case stream_info::use_file: { HANDLE h = ::CreateFileA(infoin.file_.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (h == INVALID_HANDLE_VALUE) boost::throw_exception(boost::system::system_error(boost::system::error_code(::GetLastError(), boost::system::get_system_category()), "boost::process::detail::win32_start: CreateFile failed")); chin = file_handle(h); break; } case stream_info::use_handle: { chin = infoin.handle_; chin.win32_set_inheritable(true); break; } case stream_info::use_pipe: { infoin.pipe_->rend().win32_set_inheritable(true); chin = infoin.pipe_->rend(); break; } default: { BOOST_ASSERT(false); break; } } si->hStdInput = chin.valid() ? chin.get() : INVALID_HANDLE_VALUE; switch (infoout.type_) { case stream_info::close: { break; } case stream_info::inherit: { chout = file_handle::win32_std(STD_OUTPUT_HANDLE, true); break; } case stream_info::use_file: { HANDLE h = ::CreateFileA(infoout.file_.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (h == INVALID_HANDLE_VALUE) boost::throw_exception(boost::system::system_error(boost::system::error_code(::GetLastError(), boost::system::get_system_category()), "boost::process::detail::win32_start: CreateFile failed")); chout = file_handle(h); break; } case stream_info::use_handle: { chout = infoout.handle_; chout.win32_set_inheritable(true); break; } case stream_info::use_pipe: { infoout.pipe_->wend().win32_set_inheritable(true); chout = infoout.pipe_->wend(); break; } default: { BOOST_ASSERT(false); break; } } si->hStdOutput = chout.valid() ? chout.get() : INVALID_HANDLE_VALUE; switch (infoerr.type_) { case stream_info::close: { break; } case stream_info::inherit: { cherr = file_handle::win32_std(STD_ERROR_HANDLE, true); break; } case stream_info::redirect: { BOOST_ASSERT(infoerr.desc_to_ == 1); BOOST_ASSERT(chout.valid()); cherr = file_handle::win32_dup(chout.get(), true); break; } case stream_info::use_file: { HANDLE h = ::CreateFileA(infoerr.file_.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (h == INVALID_HANDLE_VALUE) boost::throw_exception(boost::system::system_error(boost::system::error_code(::GetLastError(), boost::system::get_system_category()), "boost::process::detail::win32_start: CreateFile failed")); cherr = file_handle(h); break; } case stream_info::use_handle: { cherr = infoerr.handle_; cherr.win32_set_inheritable(true); break; } case stream_info::use_pipe: { infoerr.pipe_->wend().win32_set_inheritable(true); cherr = infoerr.pipe_->wend(); break; } default: { BOOST_ASSERT(false); break; } } si->hStdError = cherr.valid() ? cherr.get() : INVALID_HANDLE_VALUE; PROCESS_INFORMATION pi; ::ZeroMemory(&pi, sizeof(pi)); boost::shared_array<char> cmdline; boost::scoped_array<char> executable; // exe could be "", in which case call CreateProcess with NULL first argument if (exe.size()) { executable.reset(new char[exe.size() + 1]); #if defined(__CYGWIN__) || defined(_SCL_SECURE_NO_DEPRECATE) ::strcpy(executable.get(), exe.c_str()); #else ::strcpy_s(executable.get(), exe.size() + 1, exe.c_str()); #endif cmdline = collection_to_win32_cmdline(args); } else if (args.size() == 1) { // No exe and just a single argument. Dont escape anything - pass it through unchanged. std::string const &c = args.front(); cmdline.reset(new char[c.size() + 1]); #if defined(__CYGWIN__) || defined(_SCL_SECURE_NO_DEPRECATE) ::strcpy(cmdline.get(), c.c_str()); #else ::strcpy_s(cmdline.get(), c.size() + 1, c.c_str()); #endif } else { cmdline = collection_to_win32_cmdline(args); } boost::scoped_array<char> workdir(new char[setup.work_directory.size() + 1]); #if defined(__CYGWIN__) || defined(_SCL_SECURE_NO_DEPRECATE) ::strcpy(workdir.get(), setup.work_directory.c_str()); #else ::strcpy_s(workdir.get(), setup.work_directory.size() + 1, setup.work_directory.c_str()); #endif boost::shared_array<char> envstrs = environment_to_win32_strings(env); if (!::CreateProcessA(executable.get(), cmdline.get(), NULL, NULL, TRUE, 0, envstrs.get(), workdir.get(), si.get(), &pi)) boost::throw_exception(boost::system::system_error(boost::system::error_code(::GetLastError(), boost::system::get_system_category()), "boost::process::detail::win32_start: CreateProcess failed")); return pi; }
void plan(void) { // construct the state space we are planning in ob::StateSpacePtr space(new ob::SE2StateSpace()); // set the bounds for the R^2 part of SE(2) ob::RealVectorBounds bounds(2); bounds.setLow(0); bounds.setHigh(2); space->as<ob::SE2StateSpace>()->setBounds(bounds); // create triangulation that ignores obstacle and respects propositions MyDecomposition* ptd = new MyDecomposition(bounds); // helper method that adds an obstacle, as well as three propositions p0,p1,p2 addObstaclesAndPropositions(ptd); ptd->setup(); oc::PropositionalDecompositionPtr pd(ptd); // create a control space oc::ControlSpacePtr cspace(new oc::RealVectorControlSpace(space, 2)); // set the bounds for the control space ob::RealVectorBounds cbounds(2); cbounds.setLow(-.5); cbounds.setHigh(.5); cspace->as<oc::RealVectorControlSpace>()->setBounds(cbounds); oc::SpaceInformationPtr si(new oc::SpaceInformation(space, cspace)); si->setStateValidityChecker(std::bind(&isStateValid, si.get(), ptd, std::placeholders::_1)); si->setStatePropagator(std::bind(&propagate, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); si->setPropagationStepSize(0.025); //LTL co-safety sequencing formula: visit p2,p0 in that order std::vector<unsigned int> sequence(2); sequence[0] = 2; sequence[1] = 0; oc::AutomatonPtr cosafety = oc::Automaton::SequenceAutomaton(3, sequence); //LTL safety avoidance formula: never visit p1 std::vector<unsigned int> toAvoid(1); toAvoid[0] = 1; oc::AutomatonPtr safety = oc::Automaton::AvoidanceAutomaton(3, toAvoid); //construct product graph (propDecomp x A_{cosafety} x A_{safety}) oc::ProductGraphPtr product(new oc::ProductGraph(pd, cosafety, safety)); // LTLSpaceInformation creates a hybrid space of robot state space x product graph. // It takes the validity checker from SpaceInformation and expands it to one that also // rejects any hybrid state containing rejecting automaton states. // It takes the state propagator from SpaceInformation and expands it to one that // follows continuous propagation with setting the next decomposition region // and automaton states accordingly. // // The robot state space, given by SpaceInformation, is referred to as the "lower space". oc::LTLSpaceInformationPtr ltlsi(new oc::LTLSpaceInformation(si, product)); // LTLProblemDefinition creates a goal in hybrid space, corresponding to any // state in which both automata are accepting oc::LTLProblemDefinitionPtr pdef(new oc::LTLProblemDefinition(ltlsi)); // create a start state ob::ScopedState<ob::SE2StateSpace> start(space); start->setX(0.2); start->setY(0.2); start->setYaw(0.0); // addLowerStartState accepts a state in lower space, expands it to its // corresponding hybrid state (decomposition region containing the state, and // starting states in both automata), and adds that as an official start state. pdef->addLowerStartState(start.get()); //LTL planner (input: LTL space information, product automaton) oc::LTLPlanner* ltlPlanner = new oc::LTLPlanner(ltlsi, product); ltlPlanner->setProblemDefinition(pdef); // attempt to solve the problem within thirty seconds of planning time // considering the above cosafety/safety automata, a solution path is any // path that visits p2 followed by p0 while avoiding obstacles and avoiding p1. ob::PlannerStatus solved = ltlPlanner->as<ob::Planner>()->solve(30.0); if (solved) { std::cout << "Found solution:" << std::endl; // The path returned by LTLProblemDefinition is through hybrid space. // getLowerSolutionPath() projects it down into the original robot state space // that we handed to LTLSpaceInformation. pdef->getLowerSolutionPath()->print(std::cout); } else std::cout << "No solution found" << std::endl; delete ltlPlanner; }
ScoreItem* ScoreBrowser::genScoreItem(const QFileInfo& fi, ScoreListWidget* l) { ScoreInfo si(fi); QPixmap pm(l->iconSize() * qApp->devicePixelRatio()); if (!QPixmapCache::find(fi.filePath(), &pm)) { //load and scale pixmap QPixmap pixmap = mscore->extractThumbnail(fi.filePath()); if (pixmap.isNull()) pixmap = icons[int(Icons::file_ICON)]->pixmap(QSize(50,60)); pixmap = pixmap.scaled(pm.width() - 2, pm.height() - 2, Qt::KeepAspectRatio, Qt::SmoothTransformation); // draw pixmap and add border pm.fill(Qt::transparent); QPainter painter( &pm ); painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::TextAntialiasing); painter.drawPixmap(0, 0, pixmap); painter.setPen(QPen(QColor(0, 0, 0, 128), 1)); painter.setBrush(Qt::white); if (fi.baseName() == "00-Blank" || fi.baseName() == "Create_New_Score") { qreal round = 8.0 * qApp->devicePixelRatio(); painter.drawRoundedRect(QRectF(0, 0, pm.width() - 1 , pm.height() - 1), round, round); } else painter.drawRect(0, 0, pm.width() - 1, pm.height() - 1); if (fi.baseName() != "00-Blank") painter.drawPixmap(1, 1, pixmap); painter.end(); QPixmapCache::insert(fi.filePath(), pm); } si.setPixmap(pm); ScoreItem* item = new ScoreItem(si); item->setTextAlignment(Qt::AlignHCenter | Qt::AlignBottom); QFont f = item->font(); f.setPointSize(f.pointSize() - 2.0); f.setBold(_boldTitle); if (fi.baseName() == "00-Blank") { item->setText(tr("Choose Instruments")); f.setBold(true); } else if (fi.baseName() == "Create_New_Score") { item->setText(tr("Create New Score")); f.setBold(true); } else if (fi.baseName() == "Getting_Started") { item->setText(tr("Getting Started")); f.setBold(true); } else { QString s(si.completeBaseName()); if (!s.isEmpty() && s[0].isNumber() && _stripNumbers) s = s.mid(3); s = s.replace('_', ' '); item->setText(s); } item->setFont(f); item->setTextAlignment(Qt::AlignHCenter | Qt::AlignTop); item->setIcon(QIcon(pm)); item->setSizeHint(l->cellSize()); return item; }
Z H1(ts){A z;Z C *t[]={"int","float","char","null","box","sym","func", "unknown"}; W(gs(Et))*z->p=MS(si(t[QA(a)?(Et<a->t?6:Et>a->t?a->t:!a->n?3: Et==a->t?(QA(a=(A)*a->p)&&a->t<Xt?4:QS(a)?5:6):6): QP(a)?6:QX(a)?6:7]));R(I)z;}
void threadMain() { while (!boost::this_thread::interruption_requested()) { syscalls::sleep(60 * 60); begin_touch: boost::this_thread::disable_interruption di; boost::this_thread::disable_syscall_interruption dsi; // Fork a process which touches everything in the server instance dir. pid_t pid = syscalls::fork(); if (pid == 0) { // Child int prio, ret, e; closeAllFileDescriptors(2); // Make process nicer. do { prio = getpriority(PRIO_PROCESS, getpid()); } while (prio == -1 && errno == EINTR); if (prio != -1) { prio++; if (prio > 20) { prio = 20; } do { ret = setpriority(PRIO_PROCESS, getpid(), prio); } while (ret == -1 && errno == EINTR); } else { perror("getpriority"); } do { ret = chdir(wo->instanceDir->getPath().c_str()); } while (ret == -1 && errno == EINTR); if (ret == -1) { e = errno; fprintf(stderr, "chdir(\"%s\") failed: %s (%d)\n", wo->instanceDir->getPath().c_str(), strerror(e), e); fflush(stderr); _exit(1); } restoreOomScore(agentsOptions); execlp("/bin/sh", "/bin/sh", "-c", "find . | xargs touch", (char *) 0); e = errno; fprintf(stderr, "Cannot execute 'find . | xargs touch': %s (%d)\n", strerror(e), e); fflush(stderr); _exit(1); } else if (pid == -1) { // Error P_WARN("Could not touch the server instance directory because " "fork() failed. Retrying in 2 minutes..."); boost::this_thread::restore_interruption si(di); boost::this_thread::restore_syscall_interruption rsi(dsi); syscalls::sleep(60 * 2); goto begin_touch; } else { syscalls::waitpid(pid, NULL, 0); } } }
/* void setView (in nsISupports aParentKey, in nsISupports aPageKey, in sbIMediaListView aView); */ NS_IMETHODIMP sbMediaListViewMap::SetView(nsISupports *aParentKey, nsISupports *aPageKey, sbIMediaListView *aView) { TRACE(("sbMediaListViewMap[0x%x] - SetView", this)); NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); NS_ENSURE_ARG_POINTER( aParentKey ); NS_ENSURE_ARG_POINTER( aPageKey ); NS_ENSURE_ARG_POINTER( aView ); nsresult rv; PRBool success; sbViewMapInner *innerMap = nsnull; // If our inner map does not yet exist, create and stash it if ( ! mViewMap.Get( aParentKey, &innerMap ) ) { innerMap = new sbViewMapInner; NS_ENSURE_TRUE(innerMap, NS_ERROR_OUT_OF_MEMORY); success = innerMap->Init(); NS_ENSURE_TRUE(success, NS_ERROR_OUT_OF_MEMORY); success = mViewMap.Put( aParentKey, innerMap ); // Takes over memory management for innerMap NS_ENSURE_TRUE(success, NS_ERROR_FAILURE); } nsCOMPtr<sbIMediaList> list; nsString listGuid; rv = aView->GetMediaList(getter_AddRefs(list)); NS_ENSURE_SUCCESS(rv, rv); rv = list->GetGuid(listGuid); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<sbILibrary> library; nsString libraryGuid; rv = list->GetLibrary(getter_AddRefs(library)); NS_ENSURE_SUCCESS(rv, rv); rv = library->GetGuid(libraryGuid); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<sbIMediaListViewState> state; rv = aView->GetState(getter_AddRefs(state)); NS_ENSURE_SUCCESS(rv, rv); #ifdef DEBUG { nsString buff; state->ToString(buff); TRACE(("sbMediaListViewMap[0x%x] - Saving view %s %s %s", this, NS_LossyConvertUTF16toASCII(libraryGuid).get(), NS_LossyConvertUTF16toASCII(libraryGuid).get(), NS_LossyConvertUTF16toASCII(buff).get())); } #endif nsAutoPtr<sbViewStateInfo> si( new sbViewStateInfo(libraryGuid, listGuid, state)); NS_ENSURE_TRUE(si, NS_ERROR_OUT_OF_MEMORY); // Put the view into the inner map success = innerMap->Put( aPageKey, si ); NS_ENSURE_TRUE(success, NS_ERROR_FAILURE); si.forget(); return NS_OK; }
static GrowableArray<EmptyVtableSlot*>* find_empty_vtable_slots( InstanceKlass* klass, GrowableArray<Method*>* mirandas, TRAPS) { assert(klass != NULL, "Must be valid class"); GrowableArray<EmptyVtableSlot*>* slots = new GrowableArray<EmptyVtableSlot*>(); // All miranda methods are obvious candidates for (int i = 0; i < mirandas->length(); ++i) { Method* m = mirandas->at(i); if (!already_in_vtable_slots(slots, m)) { slots->append(new EmptyVtableSlot(m)); } } // Also any overpasses in our superclasses, that we haven't implemented. // (can't use the vtable because it is not guaranteed to be initialized yet) InstanceKlass* super = klass->java_super(); while (super != NULL) { for (int i = 0; i < super->methods()->length(); ++i) { Method* m = super->methods()->at(i); if (m->is_overpass() || m->is_static()) { // m is a method that would have been a miranda if not for the // default method processing that occurred on behalf of our superclass, // so it's a method we want to re-examine in this new context. That is, // unless we have a real implementation of it in the current class. Method* impl = klass->lookup_method(m->name(), m->signature()); if (impl == NULL || impl->is_overpass() || impl->is_static()) { if (!already_in_vtable_slots(slots, m)) { slots->append(new EmptyVtableSlot(m)); } } } } // also any default methods in our superclasses if (super->default_methods() != NULL) { for (int i = 0; i < super->default_methods()->length(); ++i) { Method* m = super->default_methods()->at(i); // m is a method that would have been a miranda if not for the // default method processing that occurred on behalf of our superclass, // so it's a method we want to re-examine in this new context. That is, // unless we have a real implementation of it in the current class. Method* impl = klass->lookup_method(m->name(), m->signature()); if (impl == NULL || impl->is_overpass() || impl->is_static()) { if (!already_in_vtable_slots(slots, m)) { slots->append(new EmptyVtableSlot(m)); } } } } super = super->java_super(); } #ifndef PRODUCT if (TraceDefaultMethods) { tty->print_cr("Slots that need filling:"); streamIndentor si(tty); for (int i = 0; i < slots->length(); ++i) { tty->indent(); slots->at(i)->print_on(tty); tty->cr(); } } #endif // ndef PRODUCT return slots; }
void print_exception(outputStream* str, int indent) { assert(throws_exception(), "Should be called otherwise"); assert(_exception_name != NULL, "exception_name should be set"); streamIndentor si(str, indent * 2); str->indent().print_cr("%s: %s", _exception_name->as_C_string(), _exception_message->as_C_string()); }
bool visit() { InstanceKlass* cls = current_class(); streamIndentor si(tty, current_depth() * 2); tty->indent().print_cr("%s", cls->name()->as_C_string()); return true; }
/*! solve */ int32_t gmres ( const CPPL::dgsmatrix& A, const CPPL::dcovector& b, CPPL::dcovector& x, const double& eps ) { /////////////////////////////////////////////// //////////////// preconditioner /////////////// /////////////////////////////////////////////// CPPL::dgbmatrix Minv(x.l, x.l, 0, 0); //////// no precondition //////// Minv.identity(); /////////////////////////////////////////////// ///////////////// mid values ////////////////// /////////////////////////////////////////////// long m(10);//restart number CPPL::dcovector r(b-A*x); CPPL::dcovector s(m+1), co(m+1), si(m+1), w; std::vector<CPPL::dcovector> v(m+1); CPPL::dgematrix H(m+1,m); //H.zero(); //co.zero(); //si.zero(); //s.zero(); //////// norm //////// double norm_r, norm_r_min(DBL_MAX); const double norm_r_ini(fabs(damax(r))); std::cerr << "[NOTE]@gmres: norm_r_ini=" << norm_r_ini << ", eps=" << eps<< std::endl; if( norm_r_ini<DBL_MIN ){ std::cerr << "[NOTE]@gmres: already converged. v(^^)" << std::endl; return 0; } /////////////////////////////////////////////// //////////////////// loop ///////////////////// /////////////////////////////////////////////// int itc(1); //int itmax(int(2.1*x.l)); int itmax(int(1.1*x.l)); //int itmax(int(0.6*x.l)); do{ std::cerr << "** itc=" << itc << " ********************************************" << std::endl; //////// 0 //////// v[0] =r/nrm2(r); s.zero(); s(0) =nrm2(r); for(long i=0; i<m; i++){ //std::cerr << "++++ i=" << i << " ++++" << std::endl; w =A*v[i]; w =Minv*w; for(long k=0; k<i+1; k++){ H(k,i) =w%v[k]; w -=H(k,i)*v[k]; } H(i+1,i) =nrm2(w); v[i+1] =w/H(i+1,i); //// J,s //// for(long k=0; k<i; k++){ rotate(H(k,i), H(k+1,i), co(k), si(k)); } make_rotator( H(i,i), H(i+1,i), co(i), si(i) ); //std::cerr << "co = " << t(co) << std::endl; std::cerr << "si = " << t(si) << std::endl; rotate( H(i,i), H(i+1,i), co(i), si(i) );//necessary //std::cerr << "H =\n" << H << std::endl; rotate( s(i), s(i+1), co(i), si(i) ); //std::cerr << "s = " << t(s) << std::endl; } //for(long i=0; i<m+1; i++){ for(long j=i+1; j<m+1; j++){ std::cerr << "vv = " << v[i]%v[j] << std::endl; } }// v check //std::cerr << "H =\n" << H << std::endl; //std::cerr << "s =" << t(s) << std::endl; //for(long i=0; i<m+1; i++){ std::cerr << "v["<<i<<"] =" << t(v[i]) << std::flush; } //////// y //////// CPPL::dcovector y(s); for(long i=m-1; i>=0; i--){ y(i) /= H(i,i); for(long j=i-1; j>=0; j--){ y(j) -= H(j,i) * y(i); } } //std::cerr << "H*y = " << t(H*y) << std::endl; //std::cerr << "s = " << t(s) << std::endl; //std::cerr << "y = " << t(s) << std::endl; //////// update //////// for(long i=0; i<m; i++){ x += v[i] * y(i); } //std::cerr << "x = " << t(x) << std::endl; //////// residual //////// r =b-A*x; r =Minv*r; //std::cerr << "r = " << t(r) << std::endl; //////// convergence check //////// norm_r =fabs(damax(r)); std::cerr << "norm_r = " << norm_r << std::endl; if( isnan(norm_r) ){ break; }//failed if( !std::isnormal(norm_r) ){ break; }//failed if( !std::isfinite(norm_r) ){ break; }//failed if( norm_r>1e3*norm_r_ini ){ break; }//failed (getting so worse) if( norm_r<=eps ){//r satistied std::cerr << "[NOTE]@gmres: converged. v(^^) itc=" << itc << "/" << itmax << ", norm=" << norm_r << std::endl; return 0; } }while(++itc<itmax); //////// failed //////// std::cerr << "[NOTE]@gmres: itc=" << itc << ", norm=" << norm_r << ", r_satisfied=" << (norm_r<=eps) << std::endl; std::cerr << "[NOTE]@gmres: failed to converge. orz" << std::endl; return 1; }
void FalhttpdClient::serve() { m_log->log( LOGLEVEL_DEBUG, "Serving client "+ m_sRemote ); // get the header String sHeader; StreamBuffer si( new SocketInputStream( m_nSocket ) ); uint32 chr; while ( ! sHeader.endsWith("\r\n") && si.get(chr) ) { // do nothing sHeader.append( chr ); } if ( ! sHeader.endsWith("\r\n") ) { m_log->log( LOGLEVEL_WARN, "Client "+ m_sRemote + " has sent an invalid header." ); return; } // remove trailing \r\n sHeader.remove( sHeader.length()-2, 2 ); // parse the header; must be in format GET/POST/HEAD 'uri' HTTP/1.x uint32 p1, p2; p1 = sHeader.find( " " ); p2 = sHeader.rfind( " " ); if ( p1 == p2 ) { sHeader.trim(); m_log->log( LOGLEVEL_WARN, "Client "+ m_sRemote + " has sent an invalid header: " + sHeader ); return; } String sRequest = sHeader.subString( 0, p1 ); String sUri = sHeader.subString( p1+1, p2 ); String sProto = sHeader.subString( p2+1 ); // a bit of formal control int type = sRequest == "GET" ? 1 : ( sRequest == "POST" ? 2 : ( sRequest == "HEAD" ? 3 : 0 ) ); if ( type == 0 ) { m_log->log( LOGLEVEL_WARN, "Client "+ m_sRemote + " has sent an invalid type: " + sHeader ); replyError( 400, "Invalid requests type" ); return; } URI uri( sUri ); if( ! uri.isValid() ) { m_log->log( LOGLEVEL_WARN, "Client "+ m_sRemote + " has sent an invalid URI: " + sHeader ); replyError( 400, "Invalid invalid uri" ); return; } if( sProto != "HTTP/1.0" && sProto != "HTTP/1.1" ) { m_log->log( LOGLEVEL_WARN, "Client "+ m_sRemote + " has sent an invalid Protocol: " + sHeader ); replyError( 505 ); return; } // ok, we got a valid header -- proceed in serving the request. serveRequest( sRequest, sUri, sProto, &si ); }
ReturnCode CN_AC::decode(NetworkBuffer& tsdu) { SPDU::control(tsdu); if (sli() == 0) return OK; ReturnCode rc = OK; while (tsdu.hasRemaining()) { /* switch (code) { case PI_UDATA: if (!bool(pmask & PMASK_UDATA) || li() > 512) spkt.spdu_errno = SC_PROTOCOL; break; case PI_XDATA: if (!bool(pmask & PMASK_XDATA) || li() <= 512) spkt.spdu_errno = SC_PROTOCOL; break; default: if (bool(code < pi_table.length) && bool(pi_table[code]) && !bool(pmask & pi_table[code])) spkt.spdu_errno = SC_PROTOCOL; break; } if (code < pi_table.length && bool(pi_table[code])&& !bool(pi_table[code] & PMASK_PGI)) { if (li() > 0) { if (bool(pi_table[code] & PMASK_VARLEN)) { if (li() > pi_length[code]) { spkt.spdu_errno = SC_PROTOCOL; // break; } } else if (li() != pi_length[code]) { spkt.spdu_errno = SC_PROTOCOL; // break; } } } */ tsdu.markit(); byte code = tsdu.get() & 0xFF; switch (code) { case PGI::PGI_CN_ID: { CN_ID pi(*this, tsdu); addMask(SMASK_CN_REF); } break; case PGI::PGI_CN_ITEMS: { CN_ITEMS pgi(*this, tsdu); addMask(SMASK_CN_REF); } break; case PI::PI_CALLED_SS: { CALLED_SS pi(tsdu); int length = 0; const byte* data = pi.getValue(length); cn_reference.udata(length, data); addMask(SMASK_CN_REF); } break; case PI::PI_CALLING_SS: { // case PI_AR_CALLED: // case PI_AR_CALLING: CALLING_SS pi(tsdu); int length = 0; const byte* data = pi.getValue(length); cn_reference.udata(length, data); addMask(SMASK_CN_REF); } break; case PI::PI_COMMON_REF: { // case PI_AR_COMMON: COMMON_REF pi(tsdu); int length = 0; const byte* data = pi.getValue(length); cn_reference.cdata(length, data); addMask(SMASK_CN_REF); } break; case PI::PI_ADD_INFO: { // case PI_AR_ADDT: ADD_INFO pi(tsdu); int length = 0; const byte* data = pi.getValue(length); cn_reference.adata(length, data); addMask(SMASK_CN_REF); } break; case PI::PI_VERSION: { VERSION pi(tsdu); cn_version = pi.getValue(); addMask(SMASK_CN_VRSN); } break; case PI::PI_USER_REQ: { USER_REQ pi(tsdu); cn_require = pi.getValue(); addMask(SMASK_CN_REQ); } break; case PI::PI_ISN: { ISN pi(tsdu); cn_isn = pi.getValue(); addMask(SMASK_CN_ISN); } break; case PI::PI_TOKEN: { if (si() != SPDU_AC) { //FIXME throw exception } TOKEN pi(tsdu); ac_token = pi.getValue(); addMask(SMASK_AC_TOKEN); } break; case PI::PI_TOISN: {/* not supported yet */ } break; case PI::PI_SSAP_CALLING: { SSAP_CALLING pi(tsdu); int length = 0; const byte* data = pi.getValue(length); cn_callinglen = pi.pli(); //FIXME check cn_callinglen == length memcpy(cn_calling, data, min(cn_callinglen, sizeof(cn_calling))); addMask(SMASK_CN_CALLING); } break; case PI::PI_SSAP_CALLED: { SSAP_CALLED pi(tsdu); int length = 0; const byte* data = pi.getValue(length); cn_calledlen = pi.pli(); //FIXME check cn_callinglen == length memcpy(cn_called, data, min(cn_calledlen, sizeof(cn_calling))); addMask(SMASK_CN_CALLED); } break; case PI::PI_UDATA: { UDATA pi(tsdu); addMask(SMASK_UDATA_PGI); if (pi.pli() > 0) { // if (si() == SPDU_AB && !spkt.hasMask(SMASK_SPDU_AB)) { // throw SSAPException(SC_PROTOCOL); // } else if (pi.pli() > MAX_CONNECT_DATA_SIZE) { throw Exception(AbortCode::SC_PROTOCOL); } int length = 0; const byte* data = pi.getValue(length); setData(length, data); } } break; case PI::PI_XDATA: { XDATA pi(tsdu); addMask(SMASK_UDATA_PGI); if (pi.pli() > 0) { // if (si() == SPDU_AB && !spkt.hasMask(SMASK_SPDU_AB)) { // throw SSAPException(SC_PROTOCOL); // } else if (pi.pli() > MAX_CONNECT_DATA_SIZE) { throw Exception(AbortCode::SC_PROTOCOL); } int length = 0; const byte* data = pi.getValue(length); setData(length, data); } } break; default: tsdu.reset(); goto EXIT; } } EXIT: return rc; }
Word lodS() { address = si(); setSI(si() + stringIncrement()); return read(address); }
A EnumTables::enumSymbols(const char *str_) { A r=aplus_nl; if (MSSymbol(str_) == MSSymbol("disclaimer")) { r=gv(Et,6); r->p[0]=MS(si((char *)stringEnumHashTable()->lookup(MSP::Text))); r->p[1]=MS(si((char *)stringEnumHashTable()->lookup(MSP::Box))); r->p[2]=MS(si((char *)stringEnumHashTable()->lookup(MSP::Rule))); r->p[3]=MS(si((char *)stringEnumHashTable()->lookup(MSP::Toprule))); r->p[4]=MS(si((char *)stringEnumHashTable()->lookup(MSP::Append))); r->p[5]=MS(si((char *)stringEnumHashTable()->lookup(MSP::NoDisclaimer))); } else if (MSSymbol(str_) == MSSymbol("orientation")) { r=gv(Et,2); r->p[0]=MS(si((char *)stringEnumHashTable()->lookup(MSP::Portrait))); r->p[1]=MS(si((char *)stringEnumHashTable()->lookup(MSP::Landscape))); } else if (MSSymbol(str_) == MSSymbol("pageSize")) { r=gv(Et,6); r->p[0]=MS(si((char *)pageSizeEnumHashTable()->lookup(MSP::Letter))); r->p[1]=MS(si((char *)pageSizeEnumHashTable()->lookup(MSP::Legal))); r->p[2]=MS(si((char *)pageSizeEnumHashTable()->lookup(MSP::A4))); r->p[3]=MS(si((char *)pageSizeEnumHashTable()->lookup(MSP::B5))); r->p[4]=MS(si((char *)pageSizeEnumHashTable()->lookup(MSP::A))); r->p[5]=MS(si((char *)pageSizeEnumHashTable()->lookup(MSP::B))); } else if (MSSymbol(str_) == MSSymbol("printMode")) { r=gv(Et,4); r->p[0]=MS(si((char *)stringEnumHashTable()->lookup(MSP::Mono))); r->p[1]=MS(si((char *)stringEnumHashTable()->lookup(MSP::Color))); r->p[2]=MS(si((char *)stringEnumHashTable()->lookup(MSP::Colorfg))); r->p[3]=MS(si((char *)stringEnumHashTable()->lookup(MSP::Reverse))); } else if (MSSymbol(str_) == MSSymbol("printTray")) { r=gv(Et,2); r->p[0]=MS(si((char *)stringEnumHashTable()->lookup(MSTop))); r->p[1]=MS(si((char *)stringEnumHashTable()->lookup(MSBottom))); } else if (MSSymbol(str_) == MSSymbol("outputMode")) { r=gv(Et,3); r->p[0]=MS(si((char *)stringEnumHashTable()->lookup(MSP::PS))); r->p[1]=MS(si((char *)stringEnumHashTable()->lookup(MSP::EPS))); r->p[2]=MS(si((char *)stringEnumHashTable()->lookup(MSP::PPM))); } else if (MSSymbol(str_) == MSSymbol("reportStyle")) { r=gv(Et,4); r->p[0]=MS(si((char *)reportStyleEnumHashTable()->lookup(MSP::ColMajor))); r->p[1]=MS(si((char *)reportStyleEnumHashTable()->lookup(MSP::RowMajor))); r->p[2]=MS(si((char *)reportStyleEnumHashTable()->lookup(MSP::Aligned))); r->p[3]=MS(si((char *)reportStyleEnumHashTable()->lookup(MSP::NoHeadings))); } else if (MSSymbol(str_) == MSSymbol("printTextStyle")) { r=gv(Et,16); r->p[0] =MS(si((char *)styleEnumHashTable()->lookup(MSP::Underline ))); r->p[1] =MS(si((char *)styleEnumHashTable()->lookup(MSP::DUnderline))); r->p[2] =MS(si((char *)styleEnumHashTable()->lookup(MSP::Superscript))); r->p[3] =MS(si((char *)styleEnumHashTable()->lookup(MSP::Subscript ))); r->p[4] =MS(si((char *)styleEnumHashTable()->lookup(MSP::Outline ))); r->p[5] =MS(si((char *)styleEnumHashTable()->lookup(MSP::Smallcap ))); r->p[6] =MS(si((char *)styleEnumHashTable()->lookup(MSP::Strikethru))); r->p[7] =MS(si((char *)styleEnumHashTable()->lookup(MSP::BoxL ))); r->p[8] =MS(si((char *)styleEnumHashTable()->lookup(MSP::BoxR ))); r->p[9] =MS(si((char *)styleEnumHashTable()->lookup(MSP::BoxT ))); r->p[10] =MS(si((char *)styleEnumHashTable()->lookup(MSP::BoxB ))); r->p[11]=MS(si((char *)styleEnumHashTable()->lookup(MSP::Cell ))); r->p[12]=MS(si((char *)styleEnumHashTable()->lookup(MSP::Stipple ))); r->p[13]=MS(si((char *)styleEnumHashTable()->lookup(MSP::CharOnly ))); r->p[14]=MS(si((char *)styleEnumHashTable()->lookup(MSP::PosAbove ))); r->p[15]=MS(si((char *)styleEnumHashTable()->lookup(MSP::PosBelow ))); } else if (MSSymbol(str_) == MSSymbol("compmode")) { r=gv(Et,6); r->p[0] =MS(si((char *)reportCompModeEnumHashTable()->lookup((unsigned long) AplusReportAlgorithm::Sum ))); r->p[1] =MS(si((char *)reportCompModeEnumHashTable()->lookup((unsigned long) AplusReportAlgorithm::Max ))); r->p[2] =MS(si((char *)reportCompModeEnumHashTable()->lookup((unsigned long) AplusReportAlgorithm::Min ))); r->p[3] =MS(si((char *)reportCompModeEnumHashTable()->lookup((unsigned long) AplusReportAlgorithm::Avg ))); r->p[4] =MS(si((char *)reportCompModeEnumHashTable()->lookup((unsigned long) AplusReportAlgorithm::StdDev ))); r->p[5] =MS(si((char *)reportCompModeEnumHashTable()->lookup((unsigned long) AplusReportAlgorithm::Variance))); } return r; }
int check_sub_file(void* /*pv*/, SubmitHash * sub, _submit_file_role role, const char * pathname, int flags) { if (role == SFR_LOG) { if ( !DumpClassAdToFile && !DashDryRun ) { // check that the log is a valid path if ( !DisableFileChecks ) { FILE* test = safe_fopen_wrapper_follow(pathname, "a+", 0664); if (!test) { fprintf(stderr, "\nERROR: Invalid log file: \"%s\" (%s)\n", pathname, strerror(errno)); return 1; } else { fclose(test); } } // Check that the log file isn't on NFS bool nfs_is_error = param_boolean("LOG_ON_NFS_IS_ERROR", false); bool nfs = false; if ( nfs_is_error ) { if ( fs_detect_nfs( pathname, &nfs ) != 0 ) { fprintf(stderr, "\nWARNING: Can't determine whether log file %s is on NFS\n", pathname ); } else if ( nfs ) { fprintf(stderr, "\nERROR: Log file %s is on NFS.\nThis could cause" " log file corruption. Condor has been configured to" " prohibit log files on NFS.\n", pathname ); return 1; } } } return 0; } else if (role == SFR_EXECUTABLE || role == SFR_PSEUDO_EXECUTABLE) { const char * ename = pathname; bool transfer_it = (flags & 1) != 0; LastExecutable = ename; SpoolLastExecutable = false; // ensure the executables exist and spool them only if no // $$(arch).$$(opsys) are specified (note that if we are simply // dumping the class-ad to a file, we won't actually transfer // or do anything [nothing that follows will affect the ad]) if ( transfer_it && !DumpClassAdToFile && !strstr(ename,"$$") ) { StatInfo si(ename); if ( SINoFile == si.Error () ) { fprintf ( stderr, "\nERROR: Executable file %s does not exist\n", ename ); return 1; // abort } if (!si.Error() && (si.GetFileSize() == 0)) { fprintf( stderr, "\nERROR: Executable file %s has zero length\n", ename ); return 1; // abort } if (role == SFR_EXECUTABLE) { bool param_exists; SpoolLastExecutable = sub->submit_param_bool( SUBMIT_KEY_CopyToSpool, "CopyToSpool", false, ¶m_exists ); if ( ! param_exists) { if ( submit_hash.getUniverse() == CONDOR_UNIVERSE_STANDARD ) { // Standard universe jobs can't restore from a checkpoint // if the executable changes. Therefore, it is deemed // too risky to have copy_to_spool=false by default // for standard universe. SpoolLastExecutable = true; } else { // In so many cases, copy_to_spool=true would just add // needless overhead. Therefore, (as of 6.9.3), the // default is false. SpoolLastExecutable = false; } } } } return 0; } // Queue files for testing access if not already queued int junk; if( flags & O_WRONLY ) { if ( CheckFilesWrite.lookup(pathname,junk) < 0 ) { // this file not found in our list; add it CheckFilesWrite.insert(pathname,junk); } } else { if ( CheckFilesRead.lookup(pathname,junk) < 0 ) { // this file not found in our list; add it CheckFilesRead.insert(pathname,junk); } } return 0; // of the check is ok, nonzero to abort }
void Format::DecFig(ostream& os, double value, int ndec, bool force_decimal) const { int i; double v = value; bool variant1 = (variant_val == Format::VAR1); // sign bool neg; if (v < 0) { v = -v; neg = true; } else neg = false; // round and break into integer and decimal bits // iv will contain the integer part // v will contain the rounded decimal part, multiplied up to make an integer double p = pow(10.0,ndec); // 10 ** ndec double iv; // integer part v = modf(v, &iv); // decimal parts v = floor(v * p + 0.5); // rounded decimal part if (v >= p) { iv += 1.0; v -= p; } // decimal part over 1 // check for underflow if ( iv == 0 && value != 0.0 && underflow_policy_val == Format::E && !force_decimal && (!variant1 || v < 0.1) ) { Scientific(os, value, ndec+1); return; } // space available for integer part int li = max_width_val - ndec; // max space for integer part int lj = min_width_val - ndec; // min space for integer part // space for sign if (neg || positive_val != Format::NX) { li--; lj--; } // are we going to show the decimal point bool dp = (ndec > 0); if (dp) { li--; lj--; } // space for decimal point // try again with reduced number of decimals if (variant1) { if (li < 0) { DecFig(os, value, ndec+li, force_decimal); return; } } else { if (li < 1) { DecFig(os, value, ndec+li-1, force_decimal); return; } } String si(li, ' '); int nchar = 0; for (i = li-1; i >= 0; i--) { if (iv < 0.5) break; nchar++; // chars in integer part double x; x = modf(iv/10, &iv); si[i] = (char)('0' + (int)floor(x * 10 + 0.5)); } if (iv > 0.5) // won't fit { if (overflow_policy_val == Format::HASH) ErrorOut(os); else Scientific(os, value, max_width_val-4);// maybe do precision better return; } if (nchar == 0 && !variant1) { nchar = 1; si[li-1] = '0'; } // integer part is zero int spaces = lj - nchar; // number of spaces if (spaces < 0) spaces = 0; int s1, s2; // leading and following sp if (alignment_val == Format::LEFT) { s1 = 0; s2 = spaces; } else if (alignment_val == Format::RIGHT) { s1 = spaces; s2 = 0; } else { s1 = spaces / 2; s2 = spaces - s1; } // in VAR1 variant, if there are no decimals but there is room for // the decimal point, put it in. if (ndec == 0 && variant1 && s1 > 0) { dp = true; --s1; } // leading spaces for (i = 0; i < s1; i++) os << ' '; // sign if (neg) os << '-'; else if (positive_val == Format::SPACE) os << ' '; else if (positive_val == Format::PLUS) os << '+'; // integer part for (i = 0; i < nchar; i++) os << si[li - nchar + i]; // decimal part if (dp) { os << '.'; String sv(ndec, '0'); for (i = ndec-1; i >= 0; i--) { double x; x = modf(v/10, &v); sv[i] = (char)('0' + (int)floor(x * 10 + 0.5)); } for (i = 0; i < ndec; i++) os << sv[i]; } // trailing blanks for (i = 0; i < s2; i++) os << ' '; }
int eWidget::eventHandler(const eWidgetEvent &evt) { switch (evt.type) { case eWidgetEvent::childChangedHelpText: /* emit */ focusChanged(focus); // faked focusChanged Signal to the Statusbar break; case eWidgetEvent::evtAction: if (evt.action == shortcut && isVisible()) (shortcutFocusWidget?shortcutFocusWidget:this)-> event(eWidgetEvent(eWidgetEvent::evtShortcut)); else if (evt.action == &i_focusActions->up) focusNext(focusDirPrev); else if (evt.action == &i_focusActions->down) focusNext(focusDirNext); else if (evt.action == &i_focusActions->left) focusNext(focusDirPrev); else if (evt.action == &i_focusActions->right) focusNext(focusDirNext); else if (evt.action == &i_cursorActions->help) { int wasvisible=state&stateShow; if (wasvisible) hide(); /* emit */ showHelp( &actionHelpList, helpID ); if (wasvisible) show(); } else return 0; return 1; case eWidgetEvent::evtKey: { eActionPrioritySet prio; findAction(prio, *evt.key, this); if (focus && (focus != this)) focus->findAction(prio, *evt.key, focus); for (actionMapList::iterator i = globalActions.begin(); i != globalActions.end(); ++i) { const std::set<eString> &styles=eActionMapList::getInstance()->getCurrentStyles(); for (std::set<eString>::const_iterator si(styles.begin()); si != styles.end(); ++si) (*i)->findAction(prio, *evt.key, 0, *si); } for (eActionPrioritySet::iterator i(prio.begin()); i != prio.end(); ++i) { if (i->first) { if (((eWidget*)i->first)->event(eWidgetEvent(eWidgetEvent::evtAction, i->second))) break; } else { (const_cast<eAction*>(i->second))->handler(); // only useful for global actions break; } } if (focus) { /* Action not found, try to use old Keyhandle */ int c = evt.key->producer->getKeyCompatibleCode(*evt.key); if (c != -1) { if (evt.key->flags & eRCKey::flagBreak) focus->keyUp(c); else focus->keyDown(c); } } return 1; break; } case eWidgetEvent::gotFocus: gotFocus(); break; case eWidgetEvent::lostFocus: lostFocus(); break; case eWidgetEvent::changedSize: case eWidgetEvent::changedFont: case eWidgetEvent::changedPosition: case eWidgetEvent::changedPixmap: invalidate(); break; case eWidgetEvent::evtShortcut: setFocus(this); break; case eWidgetEvent::wantClose: /* if (in_loop==0) eFatal("attempt to close non-execing widget");*/ if (in_loop==1) // nur wenn das ne echte loop ist { in_loop=-1; eApp->exit_loop(); } result=evt.parameter; break; default: break; } return 0; }
void qapp::read_cprops(void) // read app defaults { QString fname,cline,name,par; int flags; int apnum = 1; fname = get_cfile("appdefaults"); if(fname.isNull()) return; QFile istr(fname); if(! istr.open(IO_ReadOnly)) { perror("cannot open appdefaults"); return; } cprops.clear(); apclients.clear(); while(! istr.atEnd()) { istr.readLine(cline, 1024); QTextIStream si(&cline); si >> name; par = si.readLine(); if(par.find("ToolBar") != -1) { apclients.insert(name, apnum++); continue; } flags = 0; int i; int paf[] = { WindowListSkip,Sticky,SmallFrame,NoResize,NoTile,NoKey,NoScreen }; char *pas[] = { "WindowListSkip","Sticky","SmallFrame","NoResize","NoTile","NoKey","NoScreen" }; for(i=0; i < 7; i++) { if(par.find(pas[i]) != -1) flags |= paf[i]; } if(flags) cprops.insert(name, flags); } istr.close(); // check for clients to update xwindow *client; for(client = clients.first(); client != NULL; client = clients.next()) client->set_pflags(); tb_ap->remove(); // update clients on toolbar }
void see(){ FILE *ptr; int test = 0,rate; int choice; float SI; float inst; float time; int quit; ptr = fopen ("bank.dat","r"); printf("enter account no. :"); scanf("%d",&check.acc_no); while (fscanf(ptr,"%d %s %s %s %d/%d/%d %d %s %ld %s %f %d/%d/%d",&add.acc_no, add.fname ,add.mname,add.lname,&add.dob.month, &add.dob.day,&add.dob.year,&add.age,add.city,&add.phone,add.acc_type,&add.amount,&add.deposit.month,&add.deposit.day, &add.deposit.year )!=EOF) if(add.acc_no == check.acc_no) { test = 1; printf("\nAccount NO. :%d\n",add.acc_no); printf("\n FNAME :%s\n",add.fname); printf("\nMNAME :%s\n",add.mname); printf("\nLname :%s\n",add.lname); printf("dob:month/day/year :%d/%d/%d\n",add.dob.month, add.dob.day, add.dob.year); printf("AGE :%d\n",add.age); printf("CITY :%s\n",add.city); printf("MOBILE :%ld\n",add.phone); printf("account type :%s\n",add.acc_type); printf("amount :%f\n",add.amount); printf("month/day/year :%d/%d/%d\n\n\n",add.deposit.month, add.deposit.day, add.deposit.year); if(strcmp(add.acc_type, "Fixed1") == 0) { time = 1.0; rate = 10; inst = si(time, add.amount, rate); printf("Interest : $%.2f as on %d/%d/%d\n", inst, add.deposit.day, add.deposit.month, add.deposit.year+1); } else if(strcmp(add.acc_type, "Fixed2") == 0) { time = 2.0; rate = 11; inst = si(time, add.amount, rate); printf("Interest : $%.2f as on %d/%d/%d\n", inst, add.deposit.day, add.deposit.month, add.deposit.year+2); } else if(strcmp(add.acc_type, "Fixed3") == 0) { time = 3.0; rate = 13; inst = si(time, add.amount, rate); printf("Interest : $%.2f as on %d/%d/%d\n", inst, add.deposit.day, add.deposit.month, add.deposit.year+3); } else if(strcmp(add.acc_type,"saving")==0) { time = (1.0/12.0); rate = 10; inst = si(time, add.amount, rate); printf("Interest : $%.2f as on %d of every month\n", inst, add.deposit.day); } else if (strcmp(add.acc_type,"current")==0) printf("no interest"); } fclose(ptr); if (test != 1) { printf("enter 1 to main menu and 2 for exit"); scanf("%d",&quit); } if (quit == 1) menu(); else close(); }
ExecStatus ElementUnion<SView,RView>::propagate(Space& home, const ModEventDelta&) { Region r(home); int n = iv.size(); bool loopVar; do { loopVar = false; // Cache the upper bound iterator, as we have to // modify the upper bound while iterating LubRanges<RView> x1ub(x1); Iter::Ranges::Cache<LubRanges<RView> > x1ubc(r,x1ub); Iter::Ranges::ToValues<Iter::Ranges::Cache<LubRanges<RView> > > vx1ub(x1ubc); GlbRanges<RView> x1lb(x1); Iter::Ranges::Cache<GlbRanges<RView> > x1lbc(r,x1lb); Iter::Ranges::ToValues<Iter::Ranges::Cache<GlbRanges<RView> > > vx1(x1lbc); // In the first iteration, compute in before[i] the union // of all the upper bounds of the x_i. At the same time, // exclude inconsistent x_i from x1 and remove them from // the list, cancel their dependencies. GLBndSet sofarBefore(home); LUBndSet selectedInter(home, IntSet (Limits::min, Limits::max)); GLBndSet* before = static_cast<GLBndSet*>(r.ralloc(sizeof(GLBndSet)*n)); int j = 0; int i = 0; unsigned int maxCard = 0; unsigned int minCard = Limits::card; while ( vx1ub() ) { // Remove vars at indices not in the upper bound if (iv[i].idx < vx1ub.val()) { iv[i].view.cancel(home,*this, PC_SET_ANY); ++i; continue; } assert(iv[i].idx == vx1ub.val()); iv[j] = iv[i]; SView candidate = iv[j].view; int candidateInd = iv[j].idx; // inter = glb(candidate) & complement(lub(x0)) GlbRanges<SView> candlb(candidate); LubRanges<SView> x0ub(x0); Iter::Ranges::Diff<GlbRanges<SView>, LubRanges<SView> > diff(candlb, x0ub); bool selectSingleInconsistent = false; if (x1.cardMax() <= 1) { GlbRanges<SView> x0lb(x0); LubRanges<SView> candub(candidate); Iter::Ranges::Diff<GlbRanges<SView>, LubRanges<SView> > diff2(x0lb, candub); selectSingleInconsistent = diff2() || candidate.cardMax() < x0.cardMin(); } // exclude inconsistent x_i // an x_i is inconsistent if // * at most one x_i can be selected and there are // elements in x_0 that can't be in x_i // (selectSingleInconsistent) // * its min cardinality is greater than maxCard of x0 // * inter is not empty (there are elements in x_i // that can't be in x_0) if (selectSingleInconsistent || candidate.cardMin() > x0.cardMax() || diff()) { ModEvent me = (x1.exclude(home,candidateInd)); loopVar |= me_modified(me); GECODE_ME_CHECK(me); iv[j].view.cancel(home,*this, PC_SET_ANY); ++i; ++vx1ub; continue; } else { // if x_i is consistent, check whether we know // that its index is in x1 if (vx1() && vx1.val()==candidateInd) { // x0 >= candidate, candidate <= x0 GlbRanges<SView> candlb(candidate); ModEvent me = x0.includeI(home,candlb); loopVar |= me_modified(me); GECODE_ME_CHECK(me); LubRanges<SView> x0ub(x0); me = candidate.intersectI(home,x0ub); loopVar |= me_modified(me); GECODE_ME_CHECK(me); ++vx1; } new (&before[j]) GLBndSet(home); before[j].update(home,sofarBefore); LubRanges<SView> cub(candidate); sofarBefore.includeI(home,cub); GlbRanges<SView> clb(candidate); selectedInter.intersectI(home,clb); maxCard = std::max(maxCard, candidate.cardMax()); minCard = std::min(minCard, candidate.cardMin()); } ++vx1ub; ++i; ++j; } // cancel the variables with index greater than // max of lub(x1) for (int k=i; k<n; k++) { iv[k].view.cancel(home,*this, PC_SET_ANY); } n = j; iv.size(n); if (x1.cardMax()==0) { // Selector is empty, hence the result must be empty { GECODE_ME_CHECK(x0.cardMax(home,0)); } for (int i=n; i--;) before[i].dispose(home); return home.ES_SUBSUMED(*this); } if (x1.cardMin() > 0) { // Selector is not empty, hence the intersection of the // possibly selected lower bounds is contained in x0 BndSetRanges si(selectedInter); ModEvent me = x0.includeI(home, si); loopVar |= me_modified(me); GECODE_ME_CHECK(me); me = x0.cardMin(home, minCard); loopVar |= me_modified(me); GECODE_ME_CHECK(me); } selectedInter.dispose(home); if (x1.cardMax() <= 1) { ModEvent me = x0.cardMax(home, maxCard); loopVar |= me_modified(me); GECODE_ME_CHECK(me); } { // x0 <= sofarBefore BndSetRanges sfB(sofarBefore); ModEvent me = x0.intersectI(home,sfB); loopVar |= me_modified(me); GECODE_ME_CHECK(me); } sofarBefore.dispose(home); GLBndSet sofarAfter(home); // In the second iteration, this time backwards, compute // sofarAfter as the union of all lub(x_j) with j>i for (int i=n; i--;) { // TODO: check for size of universe here? // if (sofarAfter.size() == 0) break; // extra = inter(before[i], sofarAfter) - lub(x0) BndSetRanges b(before[i]); BndSetRanges s(sofarAfter); GlbRanges<SView> x0lb(x0); Iter::Ranges::Union<BndSetRanges, BndSetRanges> inter(b,s); Iter::Ranges::Diff<GlbRanges<SView>, Iter::Ranges::Union<BndSetRanges,BndSetRanges> > diff(x0lb, inter); if (diff()) { ModEvent me = (x1.include(home,iv[i].idx)); loopVar |= me_modified(me); GECODE_ME_CHECK(me); // candidate != extra me = iv[i].view.includeI(home,diff); loopVar |= me_modified(me); GECODE_ME_CHECK(me); } LubRanges<SView> iviub(iv[i].view); sofarAfter.includeI(home,iviub); before[i].dispose(home); } sofarAfter.dispose(home); } while (loopVar); // Test whether we determined x1 without determining x0 if (x1.assigned() && !x0.assigned()) { int ubsize = static_cast<int>(x1.lubSize()); if (ubsize > 2) { assert(ubsize==n); ViewArray<SView> is(home,ubsize); for (int i=n; i--;) is[i]=iv[i].view; GECODE_REWRITE(*this,(RelOp::UnionN<SView, SView> ::post(home(*this),is,x0))); } else if (ubsize == 2) { assert(n==2); SView a = iv[0].view; SView b = iv[1].view; GECODE_REWRITE(*this,(RelOp::Union<SView, SView, SView> ::post(home(*this),a,b,x0))); } else if (ubsize == 1) { assert(n==1); GECODE_REWRITE(*this,(Rel::Eq<SView,SView>::post(home(*this),x0,iv[0].view))); } else { GECODE_ME_CHECK(x0.cardMax(home, 0)); return home.ES_SUBSUMED(*this); } } bool allAssigned = true; for (int i=iv.size(); i--;) { if (!iv[i].view.assigned()) { allAssigned = false; break; } } if (x0.assigned() && x1.assigned() && allAssigned) { return home.ES_SUBSUMED(*this); } return ES_FIX; }
ScreenNameEntry::ScreenNameEntry( CString sClassName ) : Screen( sClassName ) { LOG->Trace( "ScreenNameEntry::ScreenNameEntry()" ); // update cache g_fCharsZoomSmall = CHARS_ZOOM_SMALL; g_fCharsZoomLarge = CHARS_ZOOM_LARGE; g_fCharsSpacingY = CHARS_SPACING_Y; g_ScrollingCharsColor = SCROLLING_CHARS_COLOR; g_SelectedCharsColor = SELECTED_CHARS_COLOR; g_fReceptorArrowsY = GRAY_ARROWS_Y; g_iNumCharsToDrawBehind = NUM_CHARS_TO_DRAW_BEHIND; g_iNumCharsToDrawTotal = NUM_CHARS_TO_DRAW_TOTAL; g_fFakeBeatsPerSec = FAKE_BEATS_PER_SEC; // DEBUGGING STUFF // GAMESTATE->m_CurGame = GAME_DANCE; // GAMESTATE->m_CurStyle = STYLE_DANCE_SINGLE; // GAMESTATE->m_PlayMode = PLAY_MODE_REGULAR; // GAMESTATE->m_bSideIsJoined[PLAYER_1] = true; // GAMESTATE->m_MasterPlayerNumber = PLAYER_1; // GAMESTATE->m_RankingCategory[PLAYER_1] = RANKING_A; // GAMESTATE->m_iRankingIndex[PLAYER_1] = 0; /* Save options. We'll reset them to display letters, and we must put them * back when we're done. */ GAMESTATE->StoreSelectedOptions(); // reset Player and Song Options { FOREACH_PlayerNumber( p ) GAMESTATE->m_pPlayerState[p]->m_PlayerOptions = PlayerOptions(); GAMESTATE->m_SongOptions = SongOptions(); } vector<GameState::RankingFeat> aFeats[NUM_PLAYERS]; // Find out if players deserve to enter their name FOREACH_PlayerNumber( p ) { GAMESTATE->GetRankingFeats( p, aFeats[p] ); m_bStillEnteringName[p] = aFeats[p].size()>0; } if( !AnyStillEntering() ) { /* Nobody made a high score. */ HandleScreenMessage( SM_GoToNextScreen ); return; } bool IsOnRanking = ( (GAMESTATE->m_PlayMode == PLAY_MODE_NONSTOP || GAMESTATE->m_PlayMode == PLAY_MODE_ONI) && !(GAMESTATE->m_pCurCourse->IsRanking()) ); if( PREFSMAN->m_GetRankingName == PrefsManager::RANKING_OFF || (PREFSMAN->m_GetRankingName == PrefsManager::RANKING_LIST && !IsOnRanking) ) { // don't collect score due to ranking setting HandleScreenMessage( SM_GoToNextScreen ); return; } GAMESTATE->m_bPastHereWeGo = true; // enable the gray arrows FOREACH_PlayerNumber( p ) { // load last used ranking name if any Profile* pProfile = PROFILEMAN->GetProfile(p); if( pProfile && !pProfile->m_sLastUsedHighScoreName.empty() ) m_sSelectedName[p] = pProfile->m_sLastUsedHighScoreName; // resize string to MAX_RANKING_NAME_LENGTH m_sSelectedName[p] = ssprintf( "%*.*s", MAX_RANKING_NAME_LENGTH, MAX_RANKING_NAME_LENGTH, m_sSelectedName[p].c_str() ); ASSERT( (int) m_sSelectedName[p].length() == MAX_RANKING_NAME_LENGTH ); // don't load player if they aren't going to enter their name if( !m_bStillEnteringName[p] ) continue; // skip // remove modifiers that may have been on the last song GAMESTATE->m_pPlayerState[p]->m_PlayerOptions = PlayerOptions(); ASSERT( GAMESTATE->IsHumanPlayer(p) ); // they better be enabled if they made a high score! float fPlayerX = PLAYER_X(p,GAMESTATE->GetCurrentStyle()->m_StyleType); { LockNoteSkin l( GAMESTATE->m_pPlayerState[p]->m_PlayerOptions.m_sNoteSkin ); m_ReceptorArrowRow[p].Load( GAMESTATE->m_pPlayerState[p], 0 ); m_ReceptorArrowRow[p].SetX( fPlayerX ); m_ReceptorArrowRow[p].SetY( SCREEN_TOP + 100 ); this->AddChild( &m_ReceptorArrowRow[p] ); } const Style* pStyle = GAMESTATE->GetCurrentStyle(); m_ColToStringIndex[p].insert(m_ColToStringIndex[p].begin(), pStyle->m_iColsPerPlayer, -1); int CurrentStringIndex = 0; for( int t=0; t<pStyle->m_iColsPerPlayer; t++ ) { if(CurrentStringIndex == MAX_RANKING_NAME_LENGTH) continue; /* We have enough columns. */ /* Find out if this column is associated with the START menu button. */ StyleInput si(p, t); GameInput gi=GAMESTATE->GetCurrentStyle()->StyleInputToGameInput(si); MenuInput m=GAMESTATE->GetCurrentGame()->GameInputToMenuInput(gi); if(m.button == MENU_BUTTON_START) continue; m_ColToStringIndex[p][t] = CurrentStringIndex++; float ColX = fPlayerX + pStyle->m_ColumnInfo[p][t].fXOffset; m_textSelectedChars[p][t].LoadFromFont( THEME->GetPathF("ScreenNameEntry","letters") ); m_textSelectedChars[p][t].SetX( ColX ); m_textSelectedChars[p][t].SetY( GRAY_ARROWS_Y ); m_textSelectedChars[p][t].SetDiffuse( g_SelectedCharsColor ); m_textSelectedChars[p][t].SetZoom( CHARS_ZOOM_LARGE ); if( t < (int)m_sSelectedName[p].length() ) m_textSelectedChars[p][t].SetText( m_sSelectedName[p].substr(t,1) ); this->AddChild( &m_textSelectedChars[p][t] ); // draw these manually m_textScrollingChars[p][t].LoadFromFont( THEME->GetPathF("ScreenNameEntry","letters") ); m_textScrollingChars[p][t].SetX( ColX ); m_textScrollingChars[p][t].SetY( GRAY_ARROWS_Y ); m_textScrollingChars[p][t].SetDiffuse( g_ScrollingCharsColor ); //this->AddChild( &m_textScrollingChars[p][t] ); // draw these manually } m_textCategory[p].LoadFromFont( THEME->GetPathF("ScreenNameEntry","category") ); m_textCategory[p].SetX( fPlayerX ); m_textCategory[p].SetY( CATEGORY_Y ); m_textCategory[p].SetZoom( CATEGORY_ZOOM ); CString joined; for( unsigned j = 0; j < aFeats[p].size(); ++j ) { if( j ) joined += "\n"; joined += aFeats[p][j].Feat; } m_textCategory[p].SetText( joined ); this->AddChild( &m_textCategory[p] ); } if( !PREFSMAN->m_bMenuTimer ) m_Timer.Disable(); else m_Timer.SetSeconds(TIMER_SECONDS); m_Timer.SetXY( TIMER_X, TIMER_Y ); this->AddChild( &m_Timer ); m_In.Load( THEME->GetPathB("ScreenNameEntry","in") ); m_In.StartTransitioning(); // this->AddChild( &m_In ); // draw and update this manually too m_Out.Load( THEME->GetPathB("ScreenNameEntry","out") ); // this->AddChild( &m_Out ); // draw and update this manually too m_soundStep.Load( THEME->GetPathS("ScreenNameEntry","step") ); SOUND->PlayMusic( THEME->GetPathS("ScreenNameEntry","music") ); m_fFakeBeat = 0; }
void plan(double runTime, optimalPlanner plannerType, planningObjective objectiveType, std::string outputFile) { // Construct the robot state space in which we're planning. We're // planning in [0,1]x[0,1], a subset of R^2. ob::StateSpacePtr space(new ob::RealVectorStateSpace(2)); // Set the bounds of space to be in [0,1]. space->as<ob::RealVectorStateSpace>()->setBounds(0.0, 1.0); // Construct a space information instance for this state space ob::SpaceInformationPtr si(new ob::SpaceInformation(space)); // Set the object used to check which states in the space are valid si->setStateValidityChecker(ob::StateValidityCheckerPtr(new ValidityChecker(si))); si->setup(); // Set our robot's starting state to be the bottom-left corner of // the environment, or (0,0). ob::ScopedState<> start(space); start->as<ob::RealVectorStateSpace::StateType>()->values[0] = 0.0; start->as<ob::RealVectorStateSpace::StateType>()->values[1] = 0.0; // Set our robot's goal state to be the top-right corner of the // environment, or (1,1). ob::ScopedState<> goal(space); goal->as<ob::RealVectorStateSpace::StateType>()->values[0] = 1.0; goal->as<ob::RealVectorStateSpace::StateType>()->values[1] = 1.0; // Create a problem instance ob::ProblemDefinitionPtr pdef(new ob::ProblemDefinition(si)); // Set the start and goal states pdef->setStartAndGoalStates(start, goal); // Create the optimization objective specified by our command-line argument. // This helper function is simply a switch statement. pdef->setOptimizationObjective(allocateObjective(si, objectiveType)); // Construct the optimal planner specified by our command line argument. // This helper function is simply a switch statement. ob::PlannerPtr optimizingPlanner = allocatePlanner(si, plannerType); // Set the problem instance for our planner to solve optimizingPlanner->setProblemDefinition(pdef); optimizingPlanner->setup(); // attempt to solve the planning problem in the given runtime ob::PlannerStatus solved = optimizingPlanner->solve(runTime); if (solved) { // Output the length of the path found std::cout << optimizingPlanner->getName() << " found a solution of length " << pdef->getSolutionPath()->length() << " with an optimization objective value of " << pdef->getSolutionPath()->cost(pdef->getOptimizationObjective()) << std::endl; // If a filename was specified, output the path as a matrix to // that file for visualization if (!outputFile.empty()) { std::ofstream outFile(outputFile.c_str()); std::static_pointer_cast<og::PathGeometric>(pdef->getSolutionPath())-> printAsMatrix(outFile); outFile.close(); } } else std::cout << "No solution found." << std::endl; }
void Reader::read (const SampleInfoMap& si_map, ::DDS::SampleStateMask ss, ::DDS::ViewStateMask vs, ::DDS::InstanceStateMask is) { ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) Reader::read \n"))); const int factor = 20; const int timeout_sec = 10 ; ACE_Time_Value small_time(0,1000000/factor); int timeout_loops = timeout_sec * factor; try { ::DDS::DataReaderSeq_var readers = new ::DDS::DataReaderSeq(10); bool found(false) ; while (timeout_loops-- > 0) // Danger! fix later { sub_->get_datareaders ( readers.inout (), ss, vs, is ); if (readers->length () > 0) { found = true ; break ; } ACE_OS::sleep (small_time); } if (!found) { ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) ERROR: timeout waiting for data.\n"))); throw TestException() ; } else { ACE_DEBUG ((LM_DEBUG, ACE_TEXT("(%P|%t) get_datareaders returned %d reader(s)\n"), readers->length ())); } ::Xyz::FooSeq foo(max_samples_per_instance_) ; ::DDS::SampleInfoSeq si(max_samples_per_instance_) ; for (CORBA::ULong i = 0 ; i < readers->length() ; i++) { ::Xyz::FooDataReader_var foo_dr = ::Xyz::FooDataReader::_narrow(readers[i]); if (CORBA::is_nil (foo_dr.in ())) { ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) ::Xyz::FooDataReader::_narrow failed.\n"))); throw TestException() ; } ::Xyz::FooDataReaderImpl* dr_servant = dynamic_cast<Xyz::FooDataReaderImpl*> (foo_dr.in ()); DDS::ReturnCode_t status ; status = dr_servant->read(foo, si, max_samples_per_instance_, ss, vs, is) ; if (status == ::DDS::RETCODE_OK) { for (CORBA::ULong i = 0 ; i < si.length() ; i++) { // skip the dispose notification sample. if (si[i].valid_data == 0) { ACE_OS::printf ("got SampleInfo[%d] dispose sample\n", i); continue; } ACE_OS::printf ("foo[%d] - %c : x = %f y = %f, key = %d\n", i, foo[i].c, foo[i].x, foo[i].y, foo[i].key); PrintSampleInfo(si[i]) ; SampleInfoMap::const_iterator it = si_map.find(foo[i].c); if (it == si_map.end()) { ACE_OS::printf ("read - Error: %c not returned\n", foo[i].c) ; throw TestException() ; } else { if (si[i] != it->second) { ACE_OS::printf ("read - Error: %c SampleInfo != expected\n", foo[i].c) ; throw TestException() ; } } } } else if (status == ::DDS::RETCODE_NO_DATA) { ACE_OS::printf ("read returned ::DDS::RETCODE_NO_DATA\n") ; throw TestException() ; } else { ACE_OS::printf ("read - Error: %d\n", status) ; throw TestException() ; } } } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught in read:"); throw TestException() ; } }
void AipcAttributes::init(void) { ipcWarn(0,"%t AipcAttributes::init\n"); _flagAttrs=_readPriority=_writePriority=_readBufsize=_writeBufsize= _listener=0; _clientData=(A)0; retry(MSTrue); if(0==SetableAttrs) SetableAttrs=gvi(Et,10,MS(si("noDelay")), MS(si("readPause")),MS(si("writePause")), MS(si("readPriority")),MS(si("writePriority")), MS(si("readBufsize")),MS(si("writeBufsize")), MS(si("retry")),MS(si("clientData")),MS(si("debug"))); if(0==NonsetableAttrs) NonsetableAttrs=gvi(Et,5,MS(si("fd")),MS(si("port")), MS(si("writeStatus")),MS(si("readStatus")), MS(si("listener"))); }
forceinline ModEvent ComplementView<View>::intersect(Space& home, int i, int j) { Iter::Ranges::Singleton si(i,j); RangesCompl<Iter::Ranges::Singleton> csi(si); return me_negateset((x.includeI(home, csi))); }
void init_issues(py::module &m) { py::module m2 = m.def_submodule("issues"); #if !defined(_MSC_VER) // Visual Studio 2015 currently cannot compile this test // (see the comment in type_caster_base::make_copy_constructor) // #70 compilation issue if operator new is not public class NonConstructible { private: void *operator new(size_t bytes) throw(); }; py::class_<NonConstructible>(m, "Foo"); m2.def("getstmt", []() -> NonConstructible * { return nullptr; }, py::return_value_policy::reference); #endif // #137: const char* isn't handled properly m2.def("print_cchar", [](const char *string) { std::cout << string << std::endl; }); // #150: char bindings broken m2.def("print_char", [](char c) { std::cout << c << std::endl; }); // #159: virtual function dispatch has problems with similar-named functions struct Base { virtual void dispatch(void) const { /* for some reason MSVC2015 can't compile this if the function is pure virtual */ }; }; struct DispatchIssue : Base { virtual void dispatch(void) const { PYBIND11_OVERLOAD_PURE(void, Base, dispatch, /* no arguments */); } }; py::class_<Base, std::unique_ptr<Base>, DispatchIssue>(m2, "DispatchIssue") .def(py::init<>()) .def("dispatch", &Base::dispatch); m2.def("dispatch_issue_go", [](const Base * b) { b->dispatch(); }); struct Placeholder { int i; Placeholder(int i) : i(i) { } }; py::class_<Placeholder>(m2, "Placeholder") .def(py::init<int>()) .def("__repr__", [](const Placeholder &p) { return "Placeholder[" + std::to_string(p.i) + "]"; }); // #171: Can't return reference wrappers (or STL datastructures containing them) m2.def("return_vec_of_reference_wrapper", [](std::reference_wrapper<Placeholder> p4){ Placeholder *p1 = new Placeholder{1}; Placeholder *p2 = new Placeholder{2}; Placeholder *p3 = new Placeholder{3}; std::vector<std::reference_wrapper<Placeholder>> v; v.push_back(std::ref(*p1)); v.push_back(std::ref(*p2)); v.push_back(std::ref(*p3)); v.push_back(p4); return v; }); // #181: iterator passthrough did not compile m2.def("iterator_passthrough", [](py::iterator s) -> py::iterator { return py::make_iterator(std::begin(s), std::end(s)); }); // #187: issue involving std::shared_ptr<> return value policy & garbage collection struct ElementBase { virtual void foo() { } /* Force creation of virtual table */ }; struct ElementA : ElementBase { ElementA(int v) : v(v) { } int value() { return v; } int v; }; struct ElementList { void add(std::shared_ptr<ElementBase> e) { l.push_back(e); } std::vector<std::shared_ptr<ElementBase>> l; }; py::class_<ElementBase, std::shared_ptr<ElementBase>> (m2, "ElementBase"); py::class_<ElementA, std::shared_ptr<ElementA>>(m2, "ElementA", py::base<ElementBase>()) .def(py::init<int>()) .def("value", &ElementA::value); py::class_<ElementList, std::shared_ptr<ElementList>>(m2, "ElementList") .def(py::init<>()) .def("add", &ElementList::add) .def("get", [](ElementList &el){ py::list list; for (auto &e : el.l) list.append(py::cast(e)); return list; }); // (no id): should not be able to pass 'None' to a reference argument m2.def("print_element", [](ElementA &el) { std::cout << el.value() << std::endl; }); // (no id): don't cast doubles to ints m2.def("expect_float", [](float f) { return f; }); m2.def("expect_int", [](int i) { return i; }); // (no id): don't invoke Python dispatch code when instantiating C++ // classes that were not extended on the Python side struct A { virtual ~A() {} virtual void f() { std::cout << "A.f()" << std::endl; } }; struct PyA : A { PyA() { std::cout << "PyA.PyA()" << std::endl; } void f() override { std::cout << "PyA.f()" << std::endl; PYBIND11_OVERLOAD(void, A, f); } }; auto call_f = [](A *a) { a->f(); }; pybind11::class_<A, std::unique_ptr<A>, PyA>(m2, "A") .def(py::init<>()) .def("f", &A::f); m2.def("call_f", call_f); try { py::class_<Placeholder>(m2, "Placeholder"); throw std::logic_error("Expected an exception!"); } catch (std::runtime_error &) { /* All good */ } // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid class StrIssue { public: StrIssue(int i) : val{i} {} StrIssue() : StrIssue(-1) {} int value() const { return val; } private: int val; }; py::class_<StrIssue> si(m2, "StrIssue"); si .def(py::init<int>()) .def(py::init<>()) .def("__str__", [](const StrIssue &si) { std::cout << "StrIssue.__str__ called" << std::endl; return "StrIssue[" + std::to_string(si.value()) + "]"; }) ; }
void check_recovery_file( const char *execute_dir ) { MyString recovery_file; FILE *recovery_fp = NULL; ClassAd *recovery_ad = NULL; if ( execute_dir == NULL ) { return; } recovery_file.formatstr( "%s.recover", execute_dir ); StatInfo si( recovery_file.Value() ); if ( si.Error() ) { if ( si.Error() != SINoFile ) { if (unlink(recovery_file.Value()) < 0) { dprintf( D_FULLDEBUG, "check_recovery_file: Failed to remove file '%s'\n", recovery_file.Value() ); } } return; } // TODO: check file ownership? recovery_fp = safe_fopen_wrapper_follow( recovery_file.Value(), "r" ); if ( recovery_fp == NULL ) { if (unlink(recovery_file.Value()) < 0) { dprintf( D_FULLDEBUG, "check_recovery_file: Failed to remove file '%s'\n", recovery_file.Value() ); } return; } int eof = 0; int error = 0; int empty = 0; recovery_ad = new ClassAd( recovery_fp, "***", eof, error, empty ); if ( error || empty ) { fclose( recovery_fp ); if (unlink(recovery_file.Value()) < 0) { dprintf( D_FULLDEBUG, "check_recovery_file: Failed to remove file '%s'\n", recovery_file.Value() ); } return; } int universe = 0; recovery_ad->LookupInteger( ATTR_JOB_UNIVERSE, universe ); if ( universe == CONDOR_UNIVERSE_VM ) { MyString vm_id; recovery_ad->LookupString( "JobVMId", vm_id ); if ( !vm_id.IsEmpty() ) { resmgr->m_vmuniverse_mgr.killVM( vm_id.Value() ); } } delete recovery_ad; fclose( recovery_fp ); if (unlink(recovery_file.Value()) < 0) { dprintf( D_FULLDEBUG, "check_recovery_file: Failed to remove file '%s'\n", recovery_file.Value() ); } }