Beispiel #1
0
Point CImg_display::getMouseClick(){
    boost::mutex::scoped_lock l(img_mutex);
    mouse.wait(img_mutex);
    return Point(clickedx,clickedy);
}
Beispiel #2
0
double BFGS (
    Vector & x,         // i: Startwert
    // o: Loesung, falls IFAIL = 0
    const MinFunction & fun,
    const OptiParameters & par,
    double eps
)


{
    int n = x.Size();
    long it;
    char a1crit, a3acrit;


    Vector d(n), g(n), p(n), temp(n), bs(n), xneu(n), y(n), s(n), x0(n);
    DenseMatrix l(n);
    DenseMatrix hesse(n);

    double /* normg, */ alphahat, hd, fold;
    double a1, a2;
    const double mu1 = 0.1, sigma = 0.1, xi1 = 1, xi2 = 10;
    const double tau = 0.1, tau1 = 0.1, tau2 = 0.6;

    Vector typx(x.Size());      // i: typische Groessenordnung der Komponenten
    double f, f0;
    double typf;               // i: typische Groessenordnung der Loesung
    double fmin = -1e5;           // i: untere Schranke fuer Funktionswert
    //  double eps = 1e-8;            // i: Abbruchschranke fuer relativen Gradienten
    double tauf = 0.1;            // i: Abbruchschranke fuer die relative Aenderung der
    //    Funktionswerte
    int ifail;                    // o:  0 .. Erfolg
    //    -1 .. Unterschreitung von fmin
    //     1 .. kein Erfolg bei Liniensuche
    //     2 .. Überschreitung von itmax

    typx = par.typx;
    typf = par.typf;


    l = 0;
    for (int i = 1; i <= n; i++)
        l.Elem(i, i) = 1;

    f = fun.FuncGrad (x, g);
    f0 = f;
    x0 = x;

    it = 0;
    do
    {
        // Restart

        if (it % (5 * n) == 0)
        {

            for (int i = 1; i <= n; i++)
                d(i-1) = typf/ sqr (typx(i-1));   // 1;
            for (int i = 2; i <= n; i++)
                for (int j = 1; j < i; j++)
                    l.Elem(i, j) = 0;

            /*
            hesse = 0;
            for (i = 1; i <= n; i++)
              hesse.Elem(i, i) = typf / sqr (typx.Get(i));

            fun.ApproximateHesse (x, hesse);

            Cholesky (hesse, l, d);
            */
        }

        it++;
        if (it > par.maxit_bfgs)
        {
            ifail = 2;
            break;
        }


        // Solve with factorized B

        SolveLDLt (l, d, g, p);

//      (*testout) << "l " << l << endl
// 		 << "d " << d << endl
// 		 << "g " << g << endl
// 		 << "p " << p << endl;


        p *= -1;
        y = g;

        fold = f;

        // line search

        alphahat = 1;
        lines (x, xneu, p, f, g, fun, par, alphahat, fmin,
               mu1, sigma, xi1, xi2, tau, tau1, tau2, ifail);

        if(ifail == 1)
            (*testout) << "no success with linesearch" << endl;

        /*
        // if (it > par.maxit_bfgs/2)
        {
          (*testout) << "x = " << x << endl;
          (*testout) << "xneu = " << xneu << endl;
          (*testout) << "f = " << f << endl;
          (*testout) << "g = " << g << endl;
        }
             */

        //      (*testout) << "it = " << it << " f = " << f << endl;
        //      if (ifail != 0) break;

        s.Set2 (1, xneu, -1, x);
        y *= -1;
        y.Add (1,g); // y += g;

        x = xneu;

        // BFGS Update

        MultLDLt (l, d, s, bs);

        a1 = y * s;
        a2 = s * bs;

        if (a1 > 0 && a2 > 0)
        {
            if (LDLtUpdate (l, d, 1 / a1, y) != 0)
            {
                cerr << "BFGS update error1" << endl;
                (*testout) << "BFGS update error1" << endl;
                (*testout) << "l " << endl << l << endl
                           << "d " << d << endl;
                ifail = 1;
                break;
            }

            if (LDLtUpdate (l, d, -1 / a2, bs) != 0)
            {
                cerr << "BFGS update error2" << endl;
                (*testout) << "BFGS update error2" << endl;
                (*testout) << "l " << endl << l << endl
                           << "d " << d << endl;
                ifail = 1;
                break;
            }
        }

        // Calculate stop conditions

        hd = eps * max2 (typf, fabs (f));
        a1crit = 1;
        for (int i = 1; i <= n; i++)
            if ( fabs (g(i-1)) * max2 (typx(i-1), fabs (x(i-1))) > hd)
                a1crit = 0;


        a3acrit = (fold - f <= tauf * max2 (typf, fabs (f)));

        //    testout << "g = " << g << endl;
        //    testout << "a1crit, a3crit = " << int(a1crit) << ", " << int(a3acrit) << endl;

        /*
        // Output for tests

        normg = sqrt (g * g);

        testout << "it =" << setw (5) << it
        << " f =" << setw (12) << setprecision (5) << f
        << " |g| =" << setw (12) << setprecision (5) << normg;

        testout << " x = (" << setw (12) << setprecision (5) << x.Elem(1);
        for (i = 2; i <= n; i++)
        testout << "," << setw (12) << setprecision (5) << x.Elem(i);
        testout << ")" << endl;
        */

        //(*testout) << "it = " << it << " f = " << f << " x = " << x << endl
        //	 << " g = " << g << " p = " << p << endl << endl;

        //      (*testout) << "|g| = " << g.L2Norm() << endl;

        if (g.L2Norm() < fun.GradStopping (x)) break;

    }
    while (!a1crit || !a3acrit);

    /*
    (*testout) << "it = " << it << " g = " << g << " f = " << f
         << " fail = " << ifail << endl;
    */
    if (f0 < f || (ifail == 1))
    {
        (*testout) << "fail, f = " << f << " f0 = " << f0 << endl;
        f = f0;
        x = x0;
    }

    //  (*testout) << "x = " << x << ", x0 = " << x0 << endl;
    return f;
}
SampleRate getOutputSampleRate() {
  Lock l(outputRate()->lock_);
  return outputRate()->sampleRate_;
}
Beispiel #4
0
void JetPlayer::setEventCallback(jetevent_callback eventCallback)
{
    Mutex::Autolock l(mMutex);
    mEventCallback = eventCallback;
}
Beispiel #5
0
    void connection_handler::handle_messages()
    {
        detail::handling_messages hm(handling_messages_);       // reset on exit

        bool bootstrapping = hpx::is_starting();
        bool has_work = true;
        std::size_t k = 0;

        hpx::util::high_resolution_timer t;
        std::list<std::pair<int, MPI_Request> > close_requests;

        // We let the message handling loop spin for another 2 seconds to avoid the
        // costs involved with posting it to asio
        while(bootstrapping || (!stopped_ && has_work) || (!has_work && t.elapsed() < 2.0))
        {
            // break the loop if someone requested to pause the parcelport
            if(!enable_parcel_handling_) break;

            // handle all send requests
            {
                hpx::lcos::local::spinlock::scoped_lock l(senders_mtx_);
                for(
                    senders_type::iterator it = senders_.begin();
                    !stopped_ && enable_parcel_handling_ && it != senders_.end();
                    /**/)
                {
                    if((*it)->done())
                    {
                        it = senders_.erase(it);
                    }
                    else
                    {
                        ++it;
                    }
                }
                has_work = !senders_.empty();
            }

            // Send the pending close requests
            {
                hpx::lcos::local::spinlock::scoped_lock l(close_mtx_);
                typedef std::pair<int, int> pair_type;

                BOOST_FOREACH(pair_type p, pending_close_requests_)
                {
                    header close_request = header::close(p.first, p.second);
                    close_requests.push_back(std::make_pair(p.first, MPI_Request()));
                    MPI_Isend(
                        close_request.data(),         // Data pointer
                        close_request.data_size_,     // Size
                        close_request.type(),         // MPI Datatype
                        close_request.rank(),         // Destination
                        0,                            // Tag
                        communicator_,                // Communicator
                        &close_requests.back().second
                    );
                }
                pending_close_requests_.clear();
            }

            // add new receive requests
            std::pair<bool, header> next(acceptor_.next_header());
            if(next.first)
            {
                boost::shared_ptr<receiver> rcv;
                receivers_rank_map_type::iterator jt = receivers_map_.find(next.second.rank());
                if(jt != receivers_map_.end())
                {
                    receivers_tag_map_type::iterator kt = jt->second.find(next.second.tag());
                    if(kt != jt->second.end())
                    {
                        if(next.second.close_request())
                        {
                            hpx::lcos::local::spinlock::scoped_lock l(tag_mtx_);
                            free_tags_.push_back(kt->second->tag());
                            jt->second.erase(kt);
                            if(jt->second.empty())
                            {
                                receivers_map_.erase(jt);
                            }
                        }
                        else
                        {
                            rcv = kt->second;
                        }
                    }
                }
                if(!next.second.close_request())
                {
                    next.second.assert_valid();
                    if(!rcv)
                    {
                        rcv = boost::make_shared<receiver>(communicator_, get_next_tag());
                    }
                    rcv->async_read(next.second, *this);
                    receivers_.push_back(rcv);
                }
            }

            // handle all receive requests
            for(
                receivers_type::iterator it = receivers_.begin();
                !stopped_ && enable_parcel_handling_ && it != receivers_.end();
                /**/)
            {
                if((*it)->done(*this))
                {
                    HPX_ASSERT(
                        !receivers_map_[(*it)->rank()][(*it)->sender_tag()]
                     || receivers_map_[(*it)->rank()][(*it)->sender_tag()].get() == it->get()
                    );
                    receivers_map_[(*it)->rank()][(*it)->sender_tag()] = *it;
                    it = receivers_.erase(it);
                }
                else
                {
                    ++it;
                }
            }

            if(!has_work) has_work = !receivers_.empty();

            // handle completed close requests
            for(
                std::list<std::pair<int, MPI_Request> >::iterator it = close_requests.begin();
                !stopped_ && enable_parcel_handling_ && it != close_requests.end();
            )
            {
                int completed = 0;
                MPI_Status status;
                int ret = 0;
                ret = MPI_Test(&it->second, &completed, &status);
                HPX_ASSERT(ret == MPI_SUCCESS);
                if(completed && status.MPI_ERROR != MPI_ERR_PENDING)
                {
                    hpx::lcos::local::spinlock::scoped_lock l(tag_mtx_);
                    free_tags_.push_back(it->first);
                    it = close_requests.erase(it);
                }
                else
                {
                    ++it;
                }
            }
            if(!has_work)
                has_work = !close_requests.empty();

            if (bootstrapping)
                bootstrapping = hpx::is_starting();

            if(has_work)
            {
                t.restart();
                k = 0;
            }
            else
            {
                if(enable_parcel_handling_)
                {
                    hpx::lcos::local::spinlock::yield(k);
                    ++k;
                }
            }
        }
Beispiel #6
0
bool CLogerManager::PushLog(LoggerId id, int level, const char * log)
{
	if (id < 0 || id >= LOG4Z_LOGGER_MAX)
	{
		return false;
	}
	if (!m_bRuning || !m_loggers[id]._enable)
	{
		return false;
	}
	if (level < m_loggers[id]._level)
	{
		return false;
	}

	LogData * pLog = new LogData;
	pLog->_id =id;
	pLog->_level = level;

	{
#ifdef WIN32
		FILETIME ft;
		GetSystemTimeAsFileTime(&ft);
		unsigned long long now = ft.dwHighDateTime;
		now <<= 32;
		now |= ft.dwLowDateTime;
		now /=10;
		now -=11644473600000000Ui64;
		now /=1000;
		pLog->_time = now/1000;
		pLog->_precise = (unsigned int)(now%1000);
#else
		struct timeval tm;
		gettimeofday(&tm, NULL);
		pLog->_time = tm.tv_sec;
		pLog->_precise = tm.tv_usec/1000;
#endif
	}

	if (m_loggers[pLog->_id]._display && LOG4Z_ALL_SYNCHRONOUS_DISPLAY)
	{
		tm tt;
		if (!TimeToTm(pLog->_time, &tt))
		{
			memset(&tt, 0, sizeof(tt));
		}
		std::string text;
		sprintf(pLog->_content, "%d-%02d-%02d %02d:%02d:%02d.%03d %s ", 
			tt.tm_year+1900, tt.tm_mon+1, tt.tm_mday, tt.tm_hour, tt.tm_min, tt.tm_sec, pLog->_precise,
			LOG_STRING[pLog->_level]);
		text = pLog->_content;
		text += log;
		text += " \r\n";
		ShowColorText(text.c_str(), pLog->_level);
	}

	int len = (int) strlen(log);
	if (len >= LOG4Z_LOG_BUF_SIZE)
	{
		memcpy(pLog->_content, log, LOG4Z_LOG_BUF_SIZE);
		pLog->_content[LOG4Z_LOG_BUF_SIZE-1] = '\0';
	}
	else
	{
		memcpy(pLog->_content, log, len+1);
	}
	CAutoLock l(m_lock);
	m_logs.push_back(pLog);
	m_ullStatusTotalPushLog ++;
	return true;
}
Beispiel #7
0
    bool empty()
    {
        std::unique_lock<std::mutex> l(_m);

        return _q.empty();
    }
Beispiel #8
0
void ConnectionPool::close() {
    closed = true;
    sys::ScopedLock<sys::Mutex> l(lock);
    clear();
}
Beispiel #9
0
 void process_data(Function func)
 {
     std::lock_guard<std::mutex> l(m);
     func(data);
 }
Beispiel #10
0
void ConnectionPool::clear() {
    sys::ScopedLock<sys::Mutex> l(lock);
    clear(idle);
    clear(busy);
}
Beispiel #11
0
void ConnectionPool::clear(const InetSocketAddress& key) {
    sys::ScopedLock<sys::Mutex> l(lock);
    TransportQueuePtr idleQ = idle[key];
    clear(key, idleQ);
    idle.erase(key);
}
Beispiel #12
0
bool Threaded::running(){
    boost::mutex::scoped_lock l(startup_mutex);
    return _running;
}
Beispiel #13
0
Point CImg_display::getMouseCoords(int& button){
    boost::mutex::scoped_lock l(img_mutex);
    button = this->button;
    return Point(mx,my);
}
Beispiel #14
0
Point CImg_display::getLastClick(){
    boost::mutex::scoped_lock l(img_mutex);
    return Point(clickedx,clickedy);
}
bool StringAnimationManager::customInterpolation(double time,std::string* ret) const {
    
    QMutexLocker l(&_imp->keyframesMutex);
    assert(_imp->customInterpolation);
    ///if there's a single keyframe, return it
    
    if (_imp->keyframes.empty()) {
        return false;
    }
    
    if (_imp->keyframes.size() == 1) {
        *ret = _imp->keyframes.begin()->value;
        return true;
    }
    
    /// get the keyframes surrounding the time
    Keyframes::const_iterator upper = _imp->keyframes.end();
    Keyframes::const_iterator lower = _imp->keyframes.end();
    for (Keyframes::const_iterator it = _imp->keyframes.begin(); it!=_imp->keyframes.end(); ++it) {
        if (it->time > time) {
            upper = it;
            break;
        } else if(it->time == time) {
            ///if there's a keyframe exactly at this time, return its value
            *ret = it->value;
            return true;
        }
    }
    
    if (upper == _imp->keyframes.end()) {
        ///if the time is greater than the time of all keyframes return the last
        
        --upper;
        *ret = upper->value;
        return true;
    } else if(upper == _imp->keyframes.begin()) {
        ///if the time is lesser than the time of all keyframes, return the first
        * ret = upper->value;
    } else {
        ///general case, we're in-between 2 keyframes
        lower = upper;
        --lower;
    }
    
    OFX::Host::Property::PropSpec inArgsSpec[] = {
        { kOfxPropName,    OFX::Host::Property::eString, 1, true, "" },
        { kOfxPropTime,    OFX::Host::Property::eDouble, 1, true, "" },
        { kOfxParamPropCustomValue,    OFX::Host::Property::eString, 2, true, ""},
        { kOfxParamPropInterpolationTime,    OFX::Host::Property::eDouble, 2, true, "" },
        { kOfxParamPropInterpolationAmount,    OFX::Host::Property::eDouble, 1, true, "" },
        OFX::Host::Property::propSpecEnd
    };
    OFX::Host::Property::Set inArgs(inArgsSpec);
    inArgs.setStringProperty(kOfxPropName, _imp->knob->getName());
    inArgs.setDoubleProperty(kOfxPropTime, time);
    
    inArgs.setStringProperty(kOfxParamPropCustomValue, lower->value,0);
    inArgs.setStringProperty(kOfxParamPropCustomValue, upper->value,1);
    inArgs.setDoubleProperty(kOfxParamPropInterpolationTime, lower->time,0);
    inArgs.setDoubleProperty(kOfxParamPropInterpolationTime, upper->time,1);
    inArgs.setDoubleProperty(kOfxParamPropInterpolationAmount, (time - lower->time) / (double)(upper->time - lower->time));
    
    
    
    OFX::Host::Property::PropSpec outArgsSpec[] = {
        { kOfxParamPropCustomValue,    OFX::Host::Property::eString, 1, false, ""},
        OFX::Host::Property::propSpecEnd
    };
    OFX::Host::Property::Set outArgs(outArgsSpec);
    
    l.unlock();
    _imp->customInterpolation(_imp->ofxParamHandle,inArgs.getHandle(),outArgs.getHandle());
    
    *ret = outArgs.getStringProperty(kOfxParamPropCustomValue,0).c_str();
    return true;
}
Beispiel #16
0
            mt19937( const seed_type s = 0 )
            {
                std::lock_guard<std::mutex> l( mtx );

                init( s );
            }
Beispiel #17
0
void MQTT::SendDeviceInfo(const int m_HwdID, const unsigned long long DeviceRowIdx, const std::string &DeviceName, const unsigned char *pRXCommand)
{
	boost::lock_guard<boost::mutex> l(m_mqtt_mutex);
	if (!m_IsConnected)
		return;
	std::vector<std::vector<std::string> > result;
	result = m_sql.safe_query("SELECT DeviceID, Unit, Name, [Type], SubType, nValue, sValue, SwitchType, SignalLevel, BatteryLevel FROM DeviceStatus WHERE (HardwareID==%d) AND (ID==%llu)", m_HwdID, DeviceRowIdx);
	if (result.size() > 0)
	{
		std::vector<std::string> sd = result[0];
		std::string did = sd[0];
		int dunit = atoi(sd[1].c_str());
		std::string name = sd[2];
		int dType = atoi(sd[3].c_str());
		int dSubType = atoi(sd[4].c_str());
		int nvalue = atoi(sd[5].c_str());
		std::string svalue = sd[6];
		_eSwitchType switchType = (_eSwitchType)atoi(sd[7].c_str());
		int RSSI = atoi(sd[8].c_str());
		int BatteryLevel = atoi(sd[9].c_str());

		Json::Value root;

		root["idx"] = DeviceRowIdx;
		root["id"] = did;
		root["unit"] = dunit;
		root["name"] = name;
		root["dtype"] = RFX_Type_Desc(dType,1);
		root["stype"] = RFX_Type_SubType_Desc(dType, dSubType);

		if (IsLightOrSwitch(dType, dSubType) == true) {
			root["switchType"] = Switch_Type_Desc(switchType);
		}

		root["RSSI"] = RSSI;
		root["Battery"] = BatteryLevel;
		root["nvalue"] = nvalue;

		//give all svalues separate
		std::vector<std::string> strarray;
		StringSplit(svalue, ";", strarray);

		std::vector<std::string>::const_iterator itt;
		int sIndex = 1;
		for (itt = strarray.begin(); itt != strarray.end(); ++itt)
		{
			std::stringstream szQuery("");
			szQuery << "svalue" << sIndex;
			root[szQuery.str()] = *itt;
			sIndex++;
		}
		std::string message =  root.toStyledString();
		if (m_publish_topics & PT_out)
		{
			SendMessage(TOPIC_OUT, message);
		}

		if (m_publish_topics & PT_floor_room) {
			result = m_sql.safe_query("SELECT F.Name, P.Name, M.DeviceRowID FROM Plans as P, Floorplans as F, DeviceToPlansMap as M WHERE P.FloorplanID=F.ID and M.PlanID=P.ID and M.DeviceRowID=='%llu'", DeviceRowIdx);
			for(size_t i=0 ; i<result.size(); i++)
			{
				std::vector<std::string> sd = result[i];
				std::string floor = sd[0];
				std::string room =  sd[1];
				std::stringstream topic("");
				topic << TOPIC_OUT << "/" << floor << "/" + room;

				SendMessage(topic.str() , message);
			}
		}
	}
}
Beispiel #18
0
 void pin(K key, V val) {
   Mutex::Locker l(lock);
   pinned.emplace(std::move(key), std::move(val));
 }
int
main()
{
	int N(5);
	int M(3);	// 2以上
	const int x[] = {1, 2, 4, 8, 9};

	int w;
	Node* l(0);
	Node* c;
	Node* p(0);
	Node* n;

	std::priority_queue<VN, std::vector<VN>, std::greater<VN> > heap;
	std::unordered_set<Node*> used;

	for (int i(1); i < N; ++i) {
		w = x[i] - x[i-1];
		c = new Node(w, p);
		if (!l) l = c;
		if (p) p->n_ = c;
		p = c;
		heap.push(VN(w, c));
	}

	int u(0);

	while (M + u <= heap.size()) {
		VN vn = heap.top();
		heap.pop();
		c = vn.second;
		if (0 < used.count(c)) {
			--u;
			continue;
		}
		if (c->n_ && (!c->p_ || c->n_->v_ <= c->p_->v_)) {
			n = c->n_;
			heap.push(VN(vn.first + n->v_, c));
			c->n_ = n->n_;
			if (n->n_) n->n_->p_ = c;
			used.insert(n);
			delete n;
			++u;
		}
		else {
			assert(c->p_);
			p = c->p_;
			heap.push(VN(vn.first + p->v_, c));
			c->p_ = p->p_;
			if (!p->p_) l = c;
			else p->p_->n_ = c;
			used.insert(p);
			delete p;
			++u;
		}
	}

	while ('-') {
		VN vn = heap.top();
		if (0 == used.count(vn.second)) break;
		heap.pop();
	}

	std::printf("%d\n", heap.top().first);

	c = l;
	while(c) {
		n = c->n_;
		delete c;
		c = n;
	}

	return 0;
}
Beispiel #20
0
 void set_size(size_t new_size) {
   Mutex::Locker l(lock);
   max_size = new_size;
   trim_cache();
 }
void TebConfig::reconfigure(TebLocalPlannerReconfigureConfig& cfg)
{ 
  boost::mutex::scoped_lock l(config_mutex_);
  
  // Trajectory
  trajectory.teb_autosize = cfg.teb_autosize;
  trajectory.dt_ref = cfg.dt_ref;
  trajectory.dt_hysteresis = cfg.dt_hysteresis;
  trajectory.global_plan_overwrite_orientation = cfg.global_plan_overwrite_orientation;
  trajectory.force_reinit_new_goal_dist = cfg.force_reinit_new_goal_dist;
  
  // Robot     
  robot.max_vel_x = cfg.max_vel_x;
  robot.max_vel_x_backwards = cfg.max_vel_x_backwards;
  robot.max_vel_theta = cfg.max_vel_theta;
  robot.acc_lim_x = cfg.acc_lim_x;
  robot.acc_lim_theta = cfg.acc_lim_theta;
  
  // GoalTolerance
  goal_tolerance.xy_goal_tolerance = cfg.xy_goal_tolerance;
  goal_tolerance.yaw_goal_tolerance = cfg.yaw_goal_tolerance;
  goal_tolerance.free_goal_vel = cfg.free_goal_vel;
  
  // Obstacles
  obstacles.min_obstacle_dist = cfg.min_obstacle_dist;
  obstacles.costmap_emergency_stop_dist = cfg.costmap_emergency_stop_dist;
  obstacles.include_costmap_obstacles = cfg.include_costmap_obstacles;
  obstacles.costmap_obstacles_front_only = cfg.costmap_obstacles_front_only;
  obstacles.obstacle_poses_affected = cfg.obstacle_poses_affected;
  obstacles.line_obstacle_poses_affected = cfg.line_obstacle_poses_affected;
  obstacles.polygon_obstacle_poses_affected = cfg.polygon_obstacle_poses_affected;

  
  // Optimization
  optim.no_inner_iterations = cfg.no_inner_iterations;
  optim.no_outer_iterations = cfg.no_outer_iterations;
  optim.optimization_activate = cfg.optimization_activate;
  optim.optimization_verbose = cfg.optimization_verbose;
  optim.penalty_scale = cfg.penalty_scale;
  optim.penalty_epsilon = cfg.penalty_epsilon;
  optim.weight_max_vel_x = cfg.weight_max_vel_x;
  optim.weight_max_vel_theta = cfg.weight_max_vel_theta;
  optim.weight_acc_lim_x = cfg.weight_acc_lim_x;
  optim.weight_acc_lim_theta = cfg.weight_acc_lim_theta;
  optim.weight_kinematics_nh = cfg.weight_kinematics_nh;
  optim.weight_kinematics_forward_drive = cfg.weight_kinematics_forward_drive;
  optim.weight_optimaltime = cfg.weight_optimaltime;
  optim.weight_point_obstacle = cfg.weight_point_obstacle;
  optim.weight_line_obstacle = cfg.weight_line_obstacle;
  optim.weight_poly_obstacle = cfg.weight_poly_obstacle;
  optim.weight_dynamic_obstacle = cfg.weight_dynamic_obstacle;
  optim.alternative_time_cost = cfg.alternative_time_cost;
  
  // Homotopy Class Planner
  hcp.enable_multithreading = cfg.enable_multithreading;
  hcp.simple_exploration = cfg.simple_exploration;
  hcp.max_number_classes = cfg.max_number_classes; 
  
  hcp.obstacle_keypoint_offset = cfg.obstacle_keypoint_offset;
  hcp.obstacle_heading_threshold = cfg.obstacle_heading_threshold;
  hcp.roadmap_graph_no_samples = cfg.roadmap_graph_no_samples;
  hcp.roadmap_graph_area_width = cfg.roadmap_graph_area_width;
  hcp.h_signature_prescaler = cfg.h_signature_prescaler;
  hcp.h_signature_threshold = cfg.h_signature_threshold;
  hcp.visualize_hc_graph = cfg.visualize_hc_graph;
}
Beispiel #22
0
 void add(K key, V value) {
   Mutex::Locker l(lock);
   _add(std::move(key), std::move(value));
 }
Beispiel #23
0
//-------------------------------------------------------------------------------------------------
int JetPlayer::render() {
    EAS_RESULT result = EAS_FAILURE;
    EAS_I32 count;
    int temp;
    bool audioStarted = false;

    LOGV("JetPlayer::render(): entering");

    // allocate render buffer
    mAudioBuffer =
        new EAS_PCM[pLibConfig->mixBufferSize * pLibConfig->numChannels * MIX_NUM_BUFFERS];
    if (!mAudioBuffer) {
        LOGE("JetPlayer::render(): mAudioBuffer allocate failed");
        goto threadExit;
    }

    // signal main thread that we started
    {
        Mutex::Autolock l(mMutex);
        mTid = myTid();
        LOGV("JetPlayer::render(): render thread(%d) signal", mTid);
        mCondition.signal();
    }

    while (1) {

        mMutex.lock(); // [[[[[[[[ LOCK ---------------------------------------

        if (mEasData == NULL) {
            mMutex.unlock();
            LOGV("JetPlayer::render(): NULL EAS data, exiting render.");
            goto threadExit;
        }

        // nothing to render, wait for client thread to wake us up
        while (!mRender)
        {
            LOGV("JetPlayer::render(): signal wait");
            if (audioStarted) {
                mAudioTrack->pause();
                // we have to restart the playback once we start rendering again
                audioStarted = false;
            }
            mCondition.wait(mMutex);
            LOGV("JetPlayer::render(): signal rx'd");
        }

        // render midi data into the input buffer
        int num_output = 0;
        EAS_PCM* p = mAudioBuffer;
        for (int i = 0; i < MIX_NUM_BUFFERS; i++) {
            result = EAS_Render(mEasData, p, pLibConfig->mixBufferSize, &count);
            if (result != EAS_SUCCESS) {
                LOGE("JetPlayer::render(): EAS_Render returned error %ld", result);
            }
            p += count * pLibConfig->numChannels;
            num_output += count * pLibConfig->numChannels * sizeof(EAS_PCM);

            // send events that were generated (if any) to the event callback
            fireEventsFromJetQueue();
        }

        // update playback state
        //LOGV("JetPlayer::render(): updating state");
        JET_Status(mEasData, &mJetStatus);
        fireUpdateOnStatusChange();
        mPaused = mJetStatus.paused;

        mMutex.unlock(); // UNLOCK ]]]]]]]] -----------------------------------

        // check audio output track
        if (mAudioTrack == NULL) {
            LOGE("JetPlayer::render(): output AudioTrack was not created");
            goto threadExit;
        }

        // Write data to the audio hardware
        //LOGV("JetPlayer::render(): writing to audio output");
        if ((temp = mAudioTrack->write(mAudioBuffer, num_output)) < 0) {
            LOGE("JetPlayer::render(): Error in writing:%d",temp);
            return temp;
        }

        // start audio output if necessary
        if (!audioStarted) {
            LOGV("JetPlayer::render(): starting audio playback");
            mAudioTrack->start();
            audioStarted = true;
        }

    }//while (1)

threadExit:
    if (mAudioTrack) {
        mAudioTrack->stop();
        mAudioTrack->flush();
    }
    if (mAudioBuffer) {
        delete [] mAudioBuffer;
        mAudioBuffer = NULL;
    }
    mMutex.lock();
    mTid = -1;
    mCondition.signal();
    mMutex.unlock();
    return result;
}
Beispiel #24
0
bool CDomoticzHardwareBase::Stop()
{
	boost::lock_guard<boost::mutex> l(readQueueMutex);
	return StopHardware();
}
void SharedStoreStats::onStore(const StringData *key, const SharedVariant *var,
                               int64_t ttl, bool prime) {
  char normalizedKey[MAX_KEY_LEN + 1];

  SharedValueProfile *svpInd;

  svpInd = new SharedValueProfile(key->data());
  svpInd->calcInd(key, var);
  svpInd->ttl = ttl > 0 && ttl < 48*3600 ? ttl : 48*3600;

  if (RuntimeOption::EnableAPCSizeGroup) {
    // Here so that it is out of critical section
    normalizeKey(key->data(), normalizedKey, MAX_KEY_LEN);
    normalizedKey[MAX_KEY_LEN] = '\0';
  }

  ReadLock l(s_rwlock);

  if (RuntimeOption::EnableAPCSizeGroup) {
    SharedValueProfile *group;
    StatsMap::const_accessor cacc;
    StatsMap::accessor acc;
    if (s_statsMap.find(cacc, normalizedKey)) {
      group = cacc->second;
    } else {
      cacc.release();
      group = new SharedValueProfile(normalizedKey);
      if (s_statsMap.insert(acc, group->key)) {
        group->isGroup = true;
        group->keyCount = 0;
        acc->second = group;
      } else {
        // already there
        delete group;
        group = acc->second;
      }
    }
    group->addToGroup(svpInd);
    if (ttl == 0) {
      group->sizeNoTTL += svpInd->totalSize;
    }
  }

  if (RuntimeOption::EnableAPCSizeDetail) {
    StatsMap::accessor acc;
    if (s_detailMap.insert(acc, svpInd->key)) {
      acc->second = svpInd;
      if (prime) {
        svpInd->isPrime = true;
      }
    } else {
      SharedValueProfile *existing = acc->second;
      // update size but keep other stats
      existing->totalSize = svpInd->totalSize;
      existing->keySize = svpInd->keySize;
      existing->var = svpInd->var;
      delete svpInd;
      svpInd = existing;
    }
    svpInd->isValid = true;
    svpInd->storeCount++;
    svpInd->lastStoreTime = time(nullptr);
  } else {
    delete svpInd;
  }
}
void StringAnimationManager::clearKeyFrames() {
    QMutexLocker l(&_imp->keyframesMutex);
    _imp->keyframes.clear();
}
static fingerprint_notify_t fingerprint_get_notify(struct fingerprint_device *dev)
{
    fpc1020_device_t *fpc1020_dev = (fpc1020_device_t *) dev;
    android::Mutex::Autolock l(fpc1020_dev->notify_lock);
    return dev->notify;
}
void StringAnimationManager::clone(const StringAnimationManager& other) {
    QMutexLocker l(&_imp->keyframesMutex);
    QMutexLocker l2(&other._imp->keyframesMutex);
    _imp->keyframes = other._imp->keyframes;
}
void ClientConnection::ReadZlibRect(rfbFramebufferUpdateRectHeader *pfburh,int XOR) {

	UINT numpixels = pfburh->r.w * pfburh->r.h;
    // this assumes at least one byte per pixel. Naughty.
	UINT numRawBytes = numpixels * m_minPixelBytes;
	UINT numCompBytes;
	int inflateResult;

	rfbZlibHeader hdr;

	// Read in the rfbZlibHeader
	ReadExact((char *)&hdr, sz_rfbZlibHeader);

	numCompBytes = Swap32IfLE(hdr.nBytes);

	// Read in the compressed data
    CheckBufferSize(numCompBytes);
	ReadExact(m_netbuf, numCompBytes);

	// Verify enough buffer space for screen update.
	CheckZlibBufferSize(numRawBytes);

	m_decompStream.next_in = (unsigned char *)m_netbuf;
	m_decompStream.avail_in = numCompBytes;
	m_decompStream.next_out = m_zlibbuf;
	m_decompStream.avail_out = numRawBytes;
	m_decompStream.data_type = Z_BINARY;
		
	// Insure the inflator is initialized
	if ( m_decompStreamInited == false ) {
		m_decompStream.total_in = 0;
		m_decompStream.total_out = 0;
		m_decompStream.zalloc = Z_NULL;
		m_decompStream.zfree = Z_NULL;
		m_decompStream.opaque = Z_NULL;

		inflateResult = inflateInit( &m_decompStream );
		if ( inflateResult != Z_OK ) {
			vnclog.Print(0, _T("zlib inflateInit error: %d\n"), inflateResult);
			return;
		}
		m_decompStreamInited = true;
	}

	// Decompress screen data
	inflateResult = inflate( &m_decompStream, Z_SYNC_FLUSH );
	if ( inflateResult < 0 ) {
		vnclog.Print(0, _T("zlib inflate error: %d\n"), inflateResult);
		return;
	}
	SETUP_COLOR_SHORTCUTS;
	if (XOR==3)
	{
		mybool *maskbuffer=(mybool *)m_zlibbuf;
		BYTE *color=m_zlibbuf+(((pfburh->r.w*pfburh->r.h)+7)/8);
		BYTE *color2=m_zlibbuf+(((pfburh->r.w*pfburh->r.h)+7)/8)+m_myFormat.bitsPerPixel/8;
		// No other threads can use bitmap DC
		omni_mutex_lock l(m_bitmapdcMutex);						  

		// This big switch is untidy but fast
		switch (m_myFormat.bitsPerPixel) {
		case 8:
			SETXORMONOPIXELS(maskbuffer,color2, color,8, pfburh->r.x, pfburh->r.y, pfburh->r.w, pfburh->r.h)
				break;
		case 16:
			SETXORMONOPIXELS(maskbuffer,color2, color,16, pfburh->r.x, pfburh->r.y, pfburh->r.w, pfburh->r.h)
				break;
		case 24:
		case 32:
			SETXORMONOPIXELS(maskbuffer,color2, color,32, pfburh->r.x, pfburh->r.y, pfburh->r.w, pfburh->r.h)            
				break;
		default:
			vnclog.Print(0, _T("Invalid number of bits per pixel: %d\n"), m_myFormat.bitsPerPixel);
			return;
		}
	}
Beispiel #30
0
void CImg_display::close(){
    boost::mutex::scoped_lock l(img_mutex);
    requestClose = true;
}