Beispiel #1
0
void MessageManager::saveUsers() {
    SimpleXML xml;

    xml.addTag("Ignored");
    xml.stepIn();

    xml.addTag("Users");
    xml.stepIn();

    //TODO: cache this information?
    {
        RLock l(Ignorecs);
        for (const auto& u : ignoredUsers) {
            xml.addTag("User");
            xml.addChildAttrib("CID", u->getCID().toBase32());
            auto ou = ClientManager::getInstance()->findOnlineUser(u->getCID(), "");
            if (ou) {
                xml.addChildAttrib("Nick", ou->getIdentity().getNick());
                xml.addChildAttrib("Hub", ou->getHubUrl());
                xml.addChildAttrib("LastSeen", GET_TIME());
            }
            else {
                auto ofu = ClientManager::getInstance()->getOfflineUser(u->getCID());
                xml.addChildAttrib("Nick", ofu ? ofu->getNick() : "");
                xml.addChildAttrib("Hub", ofu ? ofu->getUrl() : "");
                xml.addChildAttrib("LastSeen", ofu ? ofu->getLastSeen() : GET_TIME());
            }
        }
    }
    xml.stepOut();
    xml.stepOut();

    SettingsManager::saveSettingFile(xml, CONFIG_DIR, CONFIG_NAME);
}
Beispiel #2
0
Matrix4f Camera::getRotationM()
{
	Matrix4f xRot, yRot, zRot, m_identity, result;
	m_identity = getIdentity();

	/* get the rotation radians about each axis */
	const float xRads = ToRadian(xRotation);
	const float yRads = ToRadian(yRotation);
	const float zRads = ToRadian(zRotation);

	/* rotate around the x axis */
	copyMatrix(xRot, m_identity);
	xRot.m[1][1] = cosf(xRads); xRot.m[1][2] = -sinf(xRads);
	xRot.m[2][1] = sinf(xRads); xRot.m[2][2] = cosf(xRads);

	/* rotate around the y axis */
	copyMatrix(yRot, m_identity);
	yRot.m[0][0] = cosf(yRads); yRot.m[0][2] = -sinf(yRads);
	yRot.m[2][0] = sinf(yRads); yRot.m[2][2] = cosf(yRads);

	/* rotate around the z axis*/
	copyMatrix(zRot, m_identity);
	zRot.m[0][0] = cosf(zRads); zRot.m[0][1] = -sinf(zRads);
	zRot.m[1][0] = sinf(zRads); zRot.m[1][1] = cosf(zRads);

	result = (yRot * xRot * zRot);

    return result;
}
Beispiel #3
0
CALLMODEL_TEMPLATE void SORTABLE_T::setHistoryCategory(QList<Call*>& calls,HistorySortingMode mode)
{
   QHash<QString,uint> popularityCount;
   QMap<QString, QList<Call*> > byDate;
   switch (mode) {
      case HistorySortingMode::Date:
         foreach (QString cat, m_slHistoryConst) {
            byDate[cat] = QList<Call*>();
         }
         break;
      case HistorySortingMode::Popularity:
         foreach (Call* call, calls) {
            popularityCount[getIdentity(call)]++;
         }
         break;
      default:
         break;
   }
   foreach (Call* call, calls) {
      QString category;
      switch (mode) {
         case HistorySortingMode::Date:
         {
            category = timeToHistoryCategory(QDateTime::fromTime_t(call->getStartTimeStamp().toUInt()).date());
            byDate[category] <<call;
         }
            break;
         case HistorySortingMode::Name2:
            category = getIdentity(call);
            break;
         case HistorySortingMode::Popularity:
            {
               QString identity = getIdentity(call);
               category = identity+"("+QString::number(popularityCount[identity])+")";
            }
            break;
         case HistorySortingMode::Length:
            category = "TODO";
            break;
         default:
            break;
      }
      call->setProperty("section",category);
   }
Beispiel #4
0
/**
 * Apply a scale to the current affine transform
 *
 * @param scaleFactor The scale factor
 */
void Affine::Scale (double scaleFactor) {
    AMatrix scale = getIdentity();
    scale[0][0] = scaleFactor;
    scale[1][1] = scaleFactor;
    p_matrix = TNT::matmult(scale,p_matrix);

    scale[0][0] = scaleFactor;
    scale[1][1] = scaleFactor;
    p_invmat = TNT::matmult(p_invmat,scale);
}
Beispiel #5
0
string OnlineUser::getLogPath() const noexcept {
	ParamMap params;
	params["userNI"] = [this] { return getIdentity().getNick(); };
	params["hubNI"] = [this] { return getClient()->getHubName(); };
	params["myNI"] = [this] { return getClient()->getMyNick(); };
	params["userCID"] = [this] { return getUser()->getCID().toBase32(); };
	params["hubURL"] = [this] { return getClient()->getHubUrl(); };

	return LogManager::getInstance()->getPath(getUser(), params);
}
Beispiel #6
0
   std::string CInformation::toString() const
   {
      // Full informations = identity + author name + url
      std::ostringstream formatedInformations;

      formatedInformations << getIdentity();
      formatedInformations << " by " << m_author;
      formatedInformations << " (" << m_url << ")";

      return formatedInformations.str();
   }
Beispiel #7
0
/**
 * Apply a translation to the current affine transform
 *
 * @param tx translatation to add to x'
 * @param ty translation to add to y'
 */
void Affine::Translate (double tx, double ty) {
    AMatrix trans = getIdentity();

    trans[0][2] = tx;
    trans[1][2] = ty;
    p_matrix = TNT::matmult(trans,p_matrix);

    trans[0][2] = -tx;
    trans[1][2] = -ty;
    p_invmat = TNT::matmult(p_invmat,trans);
}
void LayerBaseClient::dump(String8& result, char* buffer, size_t SIZE) const
{
    LayerBase::dump(result, buffer, SIZE);

    sp<Client> client(mClientRef.promote());
    snprintf(buffer, SIZE,
            "      client=%p, identity=%u\n",
            client.get(), getIdentity());

    result.append(buffer);
}
Beispiel #9
0
/**
 * Iterates through the logwriter stack and calls write() on each of them.
 *
 */
void Logger::writeMessage() {
	
	for ( std::list<LogWriter *>::iterator it = Logger::_registeredWriters.begin(); it != Logger::_registeredWriters.end(); it++ ) {
		if( m_local_identity != NULL ) {
			( *it )->write( m_messageLevel, *m_local_identity, m_message.str() );
		}
		else {
			( *it )->write( m_messageLevel, getIdentity(), m_message.str() );
		}
	}
	
}
Beispiel #10
0
void Layer::setGeometry(
    const sp<const DisplayDevice>& hw,
        HWComposer::HWCLayerInterface& layer)
{
    LayerBaseClient::setGeometry(hw, layer);

    // enable this layer
    layer.setSkip(false);

    // we can't do alpha-fade with the hwc HAL
    const State& s(drawingState());
    if (s.alpha < 0xFF) {
        layer.setSkip(true);
    }

    if (isSecure() && !hw->isSecure()) {
        layer.setSkip(true);
    }

    /*
     * Transformations are applied in this order:
     * 1) buffer orientation/flip/mirror
     * 2) state transformation (window manager)
     * 3) layer orientation (screen orientation)
     * (NOTE: the matrices are multiplied in reverse order)
     */

    const Transform bufferOrientation(mCurrentTransform);
    const Transform tr(hw->getTransform() * s.transform * bufferOrientation);

    // this gives us only the "orientation" component of the transform
    const uint32_t finalTransform = tr.getOrientation();

    // we can only handle simple transformation
    if (finalTransform & Transform::ROT_INVALID) {
        layer.setSkip(true);
    } else {
        layer.setTransform(finalTransform);
    }
    layer.setCrop(computeBufferCrop());

    // [MTK] {{{
    hwc_color_t color;
    color.a = s.alpha;
    layer.setFillColor(color);
    layer.setTransform(finalTransform);
    layer.setIdentity(getIdentity());
    layer.setMatrix(tr);
    layer.setSecure((isSecure() || isProtected()));
    // [MTK] }}}
}
Beispiel #11
0
/**
 * Apply a translation to the current affine transform
 *
 * @param angle degrees of counterclockwise rotation
 */
void Affine::Rotate(double angle) {
    AMatrix rot = getIdentity();

    double angleRadians = angle * Isis::PI / 180.0;
    rot[0][0] = cos(angleRadians);
    rot[0][1] = -sin(angleRadians);
    rot[1][0] = sin(angleRadians);
    rot[1][1] = cos(angleRadians);
    p_matrix = TNT::matmult(rot,p_matrix);

    angleRadians = -angleRadians;
    rot[0][0] = cos(angleRadians);
    rot[0][1] = -sin(angleRadians);
    rot[1][0] = sin(angleRadians);
    rot[1][1] = cos(angleRadians);
    p_invmat = TNT::matmult(p_invmat,rot);
}
Beispiel #12
0
WLCard::
WLCard(void* ioBase, void* klBase, IOService* parent) : _ioBase(ioBase),
                                     _keyLargoBase(klBase),
        			     _interrupts(0),
                                     _isEnabled(false),
                                      _parent(parent)
{
    _powerOn();
    IODelay(200 * 1000);
    _reset();

    /*
     * Get firmware vendor and version
     */
    WLIdentity ident;
    if (getIdentity(&ident) != kIOReturnSuccess) {
        WLLogErr("WLCard::WLCard: Couldn't read card identity\n");
        return;
    }

    WLLogNotice("WLCard: Firmware vendor %d, variant %d, version %d.%d\n",
                ident.vendor, ident.variant, ident.major, ident.minor);

    WLHardwareAddress macAddr;
    if (getHardwareAddress(&macAddr) != kIOReturnSuccess) {
        WLLogErr("WLCard::WLCard: Couldn't read MAC address\n");
        return;
    }
    
    _workLoop = _parent->getWorkLoop();
    if (!_workLoop) {
        WLLogErr("WLCard::WLCard: Failed to create workloop.\n");
        return;
    }
    
    _timedSendSource = IOTimerEventSource::timerEventSource(_parent, &WLCard::_myTimeoutHandler);
    if (!_timedSendSource) {
        WLLogErr("WLCard::WLCard: Failed to create timer event source.\n");
        return;
    }

    if (_workLoop->addEventSource(_timedSendSource) != kIOReturnSuccess) {
        WLLogErr("WLCard::WLCard: Failed to register timer event source.\n");
        return;
    }
}
Beispiel #13
0
void Layer::dump(String8& result, char* buffer, size_t SIZE) const
{
    LayerBaseClient::dump(result, buffer, SIZE);

    sp<const GraphicBuffer> buf0(mActiveBuffer);
    uint32_t w0=0, h0=0, s0=0, f0=0;
    if (buf0 != 0) {
        w0 = buf0->getWidth();
        h0 = buf0->getHeight();
        s0 = buf0->getStride();
        f0 = buf0->format;
    }
    snprintf(buffer, SIZE,
            "      "
            "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
            " queued-frames=%d, mRefreshPending=%d\n",
            mFormat, w0, h0, s0,f0,
            mQueuedFrames, mRefreshPending);

    result.append(buffer);

    // [MTK] {{{
    snprintf(buffer, SIZE, "secure=%d", mSecure);
    result.append(buffer);
    // [MTK] }}}

    if (mSurfaceTexture != 0) {
        mSurfaceTexture->dump(result, "            ", buffer, SIZE);
    }

    // [MTK] {{{
    char value[PROPERTY_VALUE_MAX];
    int  layerdump;

    property_get("debug.sf.layerdump", value, "0");
    layerdump = atoi(value);

    // check if the identity to dump, or -1 for all
    if ((-1 == layerdump) || (getIdentity() == (uint32_t)layerdump)) {
        mSurfaceTexture->dumpAux();
        dumpActiveBuffer();
    }
    // [MTK] }}}
}
status_t Layer::setToken(const sp<UserClient>& userClient,
        SharedClient* sharedClient, int32_t token)
{
    sp<SharedBufferServer> lcblk = new SharedBufferServer(
            sharedClient, token, mBufferManager.getDefaultBufferCount(),
            getIdentity());

    status_t err = mUserClientRef.setToken(userClient, lcblk, token);

    LOGE_IF(err != NO_ERROR,
            "ClientRef::setToken(%p, %p, %u) failed",
            userClient.get(), lcblk.get(), token);

    if (err == NO_ERROR) {
        // we need to free the buffers associated with this surface
    }

    return err;
}
Beispiel #15
0
string ClientManager::getField(const CID& cid, const string& hint, const char* field) const {
	Lock l(cs);

	OnlinePairC p;
	auto u = findOnlineUserHint(cid, hint, p);
	if(u) {
		auto value = u->getIdentity().get(field);
		if(!value.empty()) {
			return value;
		}
	}

	for(auto i = p.first; i != p.second; ++i) {
		auto value = i->second->getIdentity().get(field);
		if(!value.empty()) {
			return value;
		}
	}

	return Util::emptyString;
}
void UserConnection::handlePM(const AdcCommand& c, bool echo) noexcept {
	auto message = c.getParam(0);

	auto cm = ClientManager::getInstance();
	auto lock = cm->lock();
	auto peer = cm->findOnlineUser(user->getCID(), hubUrl);
	auto me = cm->findOnlineUser(cm->getMe()->getCID(), hubUrl);
	// null pointers allowed here as the conn may be going on without hubs.

	if(echo) {
		std::swap(peer, me);
	}

	if(peer && peer->getIdentity().noChat())
		return;

	if(PluginManager::getInstance()->runHook(HOOK_CHAT_PM_IN, peer, message))
		return;

	string tmp;
	fire(UserConnectionListener::PrivateMessage(), this, ChatMessage(message, peer, me, peer,
		c.hasFlag("ME", 1), c.getParam("TS", 1, tmp) ? Util::toInt64(tmp) : 0));
}
Beispiel #17
0
bool AgentDetector::updateModule()
{
    LockGuard lg(m);

    bool isRefreshed = client.getDepthAndPlayers(depth,players);
    client.getRgb(rgb);

    bool tracked;

    if (handleMultiplePlayers)
        tracked=client.getJoints(joints);
    else
        tracked=client.getJoints(joint, EFAA_KINECT_CLOSEST_PLAYER);
    //cout<<"Tracking value = "<<tracked<<endl;

    if (tracked)
    {
        if (handleMultiplePlayers)
            client.getSkeletonImage(joints,skeletonImage);
        else
        {
            client.getSkeletonImage(joint,skeletonImage);
            joints.clear();
            joints.push_back(joint);
        }
    } 

    client.getPlayersImage(players,playersImage);
    client.getDepthImage(depth,depthToDisplay);

    if (depthPort.getOutputCount()>0)
    {
        depthPort.prepare()=depthToDisplay;
        depthPort.write();
    }

    if (imagePort.getOutputCount()>0)
    {
        imagePort.prepare()=rgb;
        imagePort.write();
    }

    if (playersPort.getOutputCount()>0)
    {
        playersPort.prepare()=playersImage;
        playersPort.write();
    }

    if (skeletonPort.getOutputCount()>0)
    {
        skeletonPort.prepare()=skeletonImage;
        skeletonPort.write();
    }

    if (showImages)
    {        
        cvConvertScale((IplImage*)depthToDisplay.getIplImage(),depthTmp,1.0/255);
        cvCvtColor((IplImage*)rgb.getIplImage(),rgbTmp,CV_BGR2RGB);

        string mode=showMode;
        string submode;
        while (!mode.empty())
        {
            if (showImageParser(mode,submode))
            {            
                if (submode=="rgb")
                    cvShowImage("rgb",rgbTmp);
                else if (submode=="depth")
                    cvShowImage("depth",depthTmp);
                else if (submode=="skeleton")
                    cvShowImage("skeleton",(IplImage*)skeletonImage.getIplImage());
                else if (submode=="players")
                    cvShowImage("players",(IplImage*)playersImage.getIplImage());
                else
                    yError("unrecognized show mode!");
            }
        }

        cvWaitKey(1);
    }

    //Send the players information to the OPC
    //Allow click calibration
    if (!checkCalibration())
    {
        if (AgentDetector::clicked==clicked_left)
        {
            AgentDetector::clicked=idle;

            //Get the clicked point coordinate in Kinect space
            Vector clickedPoint(3);
            cout<<"Processing a click on ("<<AgentDetector::clickX<<" "<<AgentDetector::clickY<<") --> ";
            client.get3DPoint((int)AgentDetector::clickX,(int)AgentDetector::clickY,clickedPoint);
            cout<<clickedPoint.toString(3,3)<<endl;

            Bottle bCond;
            Bottle bObject;
            Bottle bRTObject;

            bObject.addString(EFAA_OPC_ENTITY_TAG);
            bObject.addString("==");
            bObject.addString(EFAA_OPC_ENTITY_OBJECT);

            bRTObject.addString(EFAA_OPC_ENTITY_TAG);
            bRTObject.addString("==");
            bRTObject.addString(EFAA_OPC_ENTITY_RTOBJECT);

            Bottle bPresent;
            bPresent.addString(EFAA_OPC_OBJECT_PRESENT_TAG);
            bPresent.addString("==");
            bPresent.addDouble(1.0);

            bCond.addList()=bObject;
            bCond.addString("&&");
            bCond.addList()=bPresent;
            bCond.addString("||");
            bCond.addList()=bRTObject;
            bCond.addString("&&");
            bCond.addList()=bPresent;
            opc->checkout();
            opc->isVerbose=true;
            list<Entity*> presentObjects=opc->Entities(bCond);
            opc->isVerbose=false;
            
            Object *o=nullptr;
            if (presentObjects.size()==1) {
                o=dynamic_cast<Object*>(presentObjects.front());
            } else {
                for(auto& presentObject : presentObjects) {
                    if(presentObject->name() == "target") {
                        o=dynamic_cast<Object*>(presentObject);
                        break;
                    }
                }
            }
            if(o) {
                Bottle botRPH, botRPHRep;
                botRPH.addString("add");
                botRPH.addString("kinect");
                Bottle &cooKinect=botRPH.addList();
                cooKinect.addDouble(clickedPoint[0]);
                cooKinect.addDouble(clickedPoint[1]);
                cooKinect.addDouble(clickedPoint[2]);

                Bottle &cooiCub=botRPH.addList();
                cooiCub.addDouble(o->m_ego_position[0]);
                cooiCub.addDouble(o->m_ego_position[1]);
                cooiCub.addDouble(o->m_ego_position[2]);
                rfh.write(botRPH,botRPHRep);
                cout<<"Sent to RFH: "<<botRPH.toString().c_str()<<endl;
                cout<<"Got from RFH: "<<botRPHRep.toString().c_str()<<endl;

                pointsCnt++;
            } else {
                yWarning("There should be 1 and only 1 object on the table");
                yWarning("If there is more than one object, the object you want");
                yWarning("to calibrate must be called \"target\"");
            }
        }
        else if (AgentDetector::clicked==clicked_right)
        {
            AgentDetector::clicked=idle;
            if (pointsCnt>=3)
            {
                Bottle calibBottle,calibReply; 
                calibBottle.addString("cal");
                calibBottle.addString("kinect");
                rfh.write(calibBottle,calibReply);
                cout<<"Calibrated ! "<<calibReply.toString().c_str()<<endl;

                calibBottle.clear();
                calibBottle.addString("save");
                rfh.write(calibBottle,calibReply);
                cout<<"Saved to file ! "<<calibReply.toString().c_str()<<endl;
                checkCalibration();
            }
            else
                yWarning("Unable to calibrate with less than 3 points pairs collected");
        }
    }

    if (isRefreshed)
    {
//        yInfo() << " refreshed";
        //////////////////////////////////////////////////////////////////
        //Clear the previous agents
        //for(map<int, Agent*>::iterator pA=identities.begin(); pA!=identities.end() ; pA++)
        //{
        //    pA->second->m_present = 0.0;
        //}  
        //partner->m_present = 0.0;

        // check if last apparition was more than dThreshlodDisaparition ago


        if (tracked)
        {
            //Go through all skeletons
            for(deque<Player>::iterator p=joints.begin(); p!=joints.end(); p++)
            {
                //check if this skeletton is really tracked
                bool reallyTracked = false;
                for(map<string,Joint>::iterator jnt = p->skeleton.begin() ; jnt != p->skeleton.end() ; jnt++)
                {
                    if (jnt->second.x != 0 && jnt->second.y != 0 && jnt->second.z != 0)
                    {
                        reallyTracked = true; break;
                    }
                }
                if (reallyTracked)
                {
                    dSince = (clock() - dTimingLastApparition) / (double) CLOCKS_PER_SEC;
                    //yInfo() << " is REALLY tracked";
                    string playerName = partner_default_name;

                    //If the skeleton is tracked we dont identify
                    if (identities.find(p->ID) != identities.end())
                    {
                        playerName = identities[p->ID];
                    }
                    else
                    {   
                        //Check if we should learn this face
                        if (currentTrainingFace != "")
                        {
                            setIdentity(*p,currentTrainingFace);
                            currentTrainingFace = "";
                        }

                        //if (useFaceRecognition)
                        playerName = getIdentity(*p);
                    }

                    //We interact with OPC only if the calibration is done
                    if (isCalibrated)
                    {
                        //main bottle to be streamed with loc of all agent body part
                        Bottle& bAgentLoc = agentLocOutPort.prepare();
                        bAgentLoc.clear();

                        //Retrieve this player in OPC or create if does not exist
                        opc->checkout();
                        partner = opc->addOrRetrieveEntity<Agent>(partner_default_name);
                        partner->m_present = 1.0;

                        // reset the timing.
                        dTimingLastApparition = clock();
                        
                        if (identities.find(p->ID) == identities.end())
                        {
                            cout<<"Assigning name "<<playerName<<" to skeleton "<<p->ID<<endl;

                            //Agent* specificAgent = opc->addEntity<Agent>(playerName);
                            Agent* specificAgent = opc->addOrRetrieveEntity<Agent>(playerName);
                            if(specificAgent == nullptr) {
                                yError() << "SHIT specificAgent";
                            } else {
                                identities[p->ID] = specificAgent->name();
                                specificAgent->m_present = 1.0;
                                yInfo() << " specific agent is commited";
                                opc->commit(specificAgent);
                                yInfo() << " specific agent is commited done";
                            }
                        }

//                        Relation r(partner->name(),"named",playerName);
//                        opc->addRelation(r,1.0);

//                        cout<<"Commiting : "<<r.toString()<<endl;
                        yarp::os::Bottle &skeleton = outputSkeletonPort.prepare();
                        skeleton.clear();
                        //Convert the skeleton into efaaHelpers body. We loose orientation in the process...
                        for(map<string,Joint>::iterator jnt = p->skeleton.begin() ; jnt != p->skeleton.end() ; jnt++)
                        {
                            Bottle bBodyPartLoc;

                            Vector kPosition(4);
                            kPosition[0] = jnt->second.x;
                            kPosition[1] = jnt->second.y;
                            kPosition[2] = jnt->second.z;
                            kPosition[3] = 1;
                            Vector icubPos = kinect2icub * kPosition;
                            Vector irPos = icubPos.subVector(0,2);

                            if (isMounted)
                            {
                                irPos = transform2IR(irPos);
                                Bottle jntBtl;
                                jntBtl.clear();
                                jntBtl.addString(jnt->first);
                                jntBtl.addDouble(jnt->second.x);
                                jntBtl.addDouble(jnt->second.y);
                                jntBtl.addDouble(jnt->second.z);
                                skeleton.addList() = jntBtl;
                            }

                            if (jnt->first == EFAA_OPC_BODY_PART_TYPE_HEAD)
                            {
                                partner->m_ego_position = irPos;
                            }
                            partner->m_body.m_parts[jnt->first] = irPos;

                            bBodyPartLoc.addString(jnt->first);
                            bBodyPartLoc.addString(irPos.toString());

                            bAgentLoc.addList() = bBodyPartLoc;
                        }

                        agentLocOutPort.write();

                        opc->commit(partner);
//                        cout << skeleton.toString()<< endl;
                        outputSkeletonPort.write();
                        //opc->commit(agent);
                    }
//                    cout<<'1'<<endl;
                }
            }
        }
        else
        {
            if (dSince > dThresholdDisparition)
            {
                opc->checkout();
                partner = opc->addOrRetrieveEntity<Agent>(partner_default_name);
                partner->m_present = 0.0;
                opc->commit(partner);
            }
            else
            {
                //yInfo() << " clock is: " << clock() << "\t last apparition: " << dTimingLastApparition  << "\t dSince: " << dSince;
                //yInfo() << " agent dissapeared but not for too long.";
            }
        }
    }
    return true;
}
Beispiel #18
0
string ClientManager::getNick(const HintedUser& user) const {
	Lock l(cs);
	auto ou = findOnlineUserHint(user);
	return ou ? ou->getIdentity().getNick() : getOfflineNick(user.user->getCID());
}
Beispiel #19
0
bool OnlineUser::supportsCCPM() const noexcept {
	return getIdentity().supports(AdcHub::CCPM_FEATURE);
}
Beispiel #20
0
epoint* computeLL(miracl* mip, epoint** elements, big* exponents, int n, int field){
		
	big bigExp =  mirvar(mip, 0);
	big two = mirvar(mip, 2);
	big zero = mirvar(mip, 0);
	int t = 0, w, h, i, j;
	epoint*** preComp;
	epoint* result;

	//get the biggest exponent
	for (i=0; i<n; i++)
		if (mr_compare(bigExp, exponents[i]) < 0)
			bigExp = exponents[i];
	//num of bitf in the biggest exponent
	t = logb2(mip, bigExp);

	//choose w according to the value of t
	w = getLLW(t);
		
	//h = n/w
	if ((n % w) == 0){
		h = n / w;
	} else{
		h = ((int) (n / w)) + 1;
	}
		
	//printf("n is: %d\n", n);
	//printf("t is: %d\n", t);
	//printf("w is: %d\n", w);
	//printf("h is: %d\n", h);

	//creates pre computation table
	preComp = createLLPreCompTable(mip, elements, w, h, n, field);
		
	result = getIdentity(mip, field); //holds the computation result		
		
	//computes the loop of the computation
	result = computeLoop(mip, exponents, w, h, preComp, result, t-1, n, field);
	
	//third part of computation
	for (j=t-2; j>=0; j--){
		//operate y^2 differently. depends on the field type
		if (field==1)
			ecurve_mult(mip, two, result, result);
		else
			ecurve2_mult(mip, two, result, result);
		//computes the loop of the computation
		result = computeLoop(mip, exponents, w, h, preComp, result, j, n, field);
	}
		
	//free the allocated memeory
	mirkill(two);
	mirkill(zero);

	for (i=0; i<h; i++){
		for (j=0; j<pow((double)2, w); j++){
			epoint_free(preComp[i][j]);
		}
		free(preComp[i]);
	}
	free(preComp);

	return result;
}
/*
 * Bekommt ein Kommando als String und bearbeitet diesen
 * Der String 'antwort' wird returned.
 */
char* doThis(char* cmd) {
	/* Erkennung der gewuenschten Methode */

	/* Ausgabe des besten Studenten (entweder allgemein oder einer Fachrichtung */
	if (!strcasecmp(cmd, "ping")) { //Testmethode, um Kommunikation Client<->Server zu testen
		return "pong";
	}

	/*
	 * *********************  Funktion Best  ********************************
	 * Rechte: 0, Antwrotet mit besten Studenten
	 */
	if (!strncasecmp(cmd, "best", 4)) {
		if (!strcasecmp(cmd, "best()")) { //der beste alle Studenten
			if (bestGlobal(&stud) != -1) { //speichert den besten Studenten auf stud und prueft gleichzeitig den Fehlerfall
				char cache[] =
						"Bester Student ist %s %s mit Notendurchschnitt: %.2lf";
				sprintf(antwort, cache, stud.fname, stud.lname, stud.avg);
				printf("%s", antwort);
				return antwort;
			} else {
				return "Lesefehler";
			}
		}
		if (!strcasecmp(cmd, "best(itti)")) { //der beste itti Student
			if (bestPartial("itti", &stud) != -1) {
				char cache[] =
						"Bester ITTI.-Student ist %s %s mit Notendurchschnitt: %.2lf";
				sprintf(antwort, cache, stud.fname, stud.lname, stud.avg);
				printf("%s", antwort);
				return antwort;
			} else {
				return "Lesefehler";
			}
		}
		if (!strcasecmp(cmd, "best(info)")) { //der beste info Student
			if (bestPartial("info", &stud) != -1) {
				char cache[] =
						"Bester INF.-Student ist %s %s mit Notendurchschnitt: %.2lf";
				sprintf(antwort, cache, stud.fname, stud.lname, stud.avg);
				printf("%s", antwort);
				return antwort;
			} else {
				return "Lesefehler";
			}
		}
		if (!strcasecmp(cmd, "best(mathe)")) { //der beste mathe Student
			if (bestPartial("mathe", &stud) != -1) {
				char cache[] =
						"Bester Math.-Student ist %s %s mit Notendurchschnitt: %.2lf";
				sprintf(antwort, cache, stud.fname, stud.lname, stud.avg);
				printf("%s", antwort);
				return antwort;
			} else {
				return "Lesefehler";
			}
		}

		return "Dieser Studiengang ist nicht bekannt.";
	}

	/*
	 *  ***********************  Funktion CREATE  ************************
	 *  Nur Admin : 111, Fuegt einen Eintrag der DB hinzu
	 */
	if (!strncasecmp(cmd, "create(", 7)) {

		if (getStatus() != 111) { //prueft, ob Admin eingeloggt ist
			return "create() ist nur Admins erlaubt.";
		}

		char vorname[64];
		char nachname[64];
		char matrikel_string[10];
		long matrikel;
		char bday[9];
		double noten[MAXLVs] = { 0 };
		char fach[32];

		int i = 6;
// Vorname parsen
		int versatz = ++i;
		while (cmd[i] != ',') {
			if (!isALetter(cmd[i])) {
				return "Namen bestehen nur aus Buchstaben.";
			}
			vorname[i - versatz] = cmd[i];
			i++;
			if (i > 50) {
				return "1. Parameter zu lang!";
			}
		}
		vorname[i - versatz] = '\0';

// Nachname parsen
		versatz = ++i;
		while (cmd[i] != ',') {
			if (!isALetter(cmd[i])) {
				return "Namen bestehen nur aus Buchstaben.";
			}
			nachname[i - versatz] = cmd[i];
			i++;
			if (i > 100) {
				return "2. Parameter zu lang!";
			}
		}
		nachname[i - versatz] = '\0';

// Matrikel parsen
		versatz = ++i;
		while (cmd[i] != ',') {
			matrikel_string[i - versatz] = cmd[i];
			if ((i - versatz > 8) && (cmd[i + 1] != ',')) {
				return "Matrikel hat 9 Stellen (1)";
			}
			if ((i - versatz < 8) && (cmd[i + 1] == ',')) {
				return "Matrikel hat 9 Stellen (2)";
			}
			if (!isANumber(cmd[i])) {
				return "Matrikelnummer besteht nur aus Zahlen.";
			}
			i++;
		}
		//matrikel_string[i - versatz] = '\0';
		matrikel = atoi(matrikel_string);
		if (matrikel < 100000000)
			return "Matrikel darf keine fuehrenden Nullen haben.";

// Geburtstag parsen
		versatz = ++i;
		while (cmd[i] != ',') {
			bday[i - versatz] = cmd[i];
			i++;
		}
		if (i - versatz != 8) {
			return "Geburtstagsangaben haben insgesamt 8 Stellen.";
		}
		int j;
		for (j = 0; j < 8; j++) { //ueberprueft richtigen Aufbau des Geburtsdatums
			if (j == 2 || j == 5) {
				if (bday[j] != '.') {
					return "Geburtsdaten haben das Format DD.MM.YY\n";
				}
			} else {
				if (!isANumber(bday[j])) {
					return "Geburtsdaten haben das Format DD.MM.YY\n";
				}
			}
		}
		char* p;
		int day, month;
		day = strtol(bday, &p, 10);
		month = strtol((p + 1), NULL, 10);

		if (day > 31 || month > 12) {
			return "Kein g�ltiges Geburtsdatum";
		}
		bday[i - versatz] = '\0';
		//long geburtstag = atoi(btag);//Geburtstag ist immer ohne f�hrende Nullen!

		versatz = ++i;
		if (cmd[i] != '[') {
			return "Noten nur in Form von [1.3,2.7,3.0,4.0] angeben (max. 10)";
		}

// Noten parsen
		versatz = ++i;
		char tempnote[4];				// Noten haben immer 3 zeichen
		int x = 0; 						// Anzahl der Noten
		while (cmd[i] != ']') {			// Bis zum Ende der Noten also ] - Noten
			if ((!isANumber(cmd[i])) || (!isANumber(cmd[i + 2]))) {
				return "Noten sind immer mit Vorkomma.Nachkomma anzugeben zB \"1.0\".";
			}
			if (i > 200)
				return "Notenliste nicht korrekt!";
			char cache[] = "%c.%c";
			sprintf(tempnote, cache, cmd[i], cmd[i + 2]);
			double checknote = atof(tempnote);
			if ((checknote < 1.0) || (checknote > 5.0))
				return "Noten muessen zwischen 1.0 und 5.0 liegen.";
			noten[x] = checknote;
			x++;
			i = i + 4;						//Sprung zu n�chsten Note
			if (cmd[i - 1] == ']') {			// Notenliste is zuende
				break;
			}
		}

//Studienfach parsen
		versatz = ++i;
		while (cmd[i] != ')' && cmd[i] != ' ') {
			fach[i - versatz] = cmd[i];
			i++;
		}
		fach[i - versatz] = '\0';

		if ((strcmp(fach, "itti")) && (strcmp(fach, "info"))
				&& (strcmp(fach, "mathe"))) {
			return "Nur \"itti\",\"info\" oder \"mathe\" als Studiengaeng maeglich.";
		}

// Doppelte Eintraege verhindern.
		if ((getStudent(matrikel, &stud))) {
			return "Dieser Eintrag existiert schon in der Datenbank";
		}

		/*
		 *		printf("Datensatz: Vorname: %s, Nachname: %s, Matrikel: %li mit %i Noten in Datenbank %s\n",
		 *				vorname, nachname, matrikel, x, fach);
		 */

// DB Operation aufrufen
		if (create(vorname, nachname, matrikel, bday, noten, fach) < 0) {
			return "Fehler beim eintragen in die Datenbank.";
		}
		return "Datensatz wurde erfolgreich in die Datenbank eingetragen.";

	}

	/*
	 *  ***********************  Funktion DELETE  ************************
	 *	Rechte: 111, entfernt einen Eintrag aus der DB
	 */
	if (!strncmp(cmd, "delete(", 7)) {

		if (getStatus() != 111) {
			return "delete() ist nur Admins erlaubt.";
		}

// Matrikel parsen
		int i = 0;
		char matrikel_string[9];
		while (cmd[i + 7] != ')') {
			if (!isANumber(cmd[i + 7])) {
				return "Matrikelnummer besteht nur aus Zahlen.";
			}
			matrikel_string[i] = cmd[i + 7];
			if ((i > 8) && (cmd[i + 7 + 1] != ')')) {
				return "Matrikel hat 9 Stellen (zu kurz)";
			}
			if ((i < 8) && (cmd[i + 7 + 1] == ')')) {
				return "Matrikel hat 9 Stellen (zu lang)";
			}
			i++;
		}
		long matrikel = atol(matrikel_string);

// DB Operation aufrufen
		if (delete(matrikel) > 0) {
			return "Eintrag wurde erfolgreich aus der DB entfernt.";
		}
		return "Eintrag konnte nicht aus der DB entfernt werden.";
	}

	/*
	 * **************************** Funktion READ  ***********************
	 * Funktioniert wie delete!
	 */
	if (!strncmp(cmd, "read(", 5)) {

		/*
		 * Studenten duerfen nur sich selbst lesen, Admins durfen alles lesen
		 * Aktueller Student : getUser(), vor der Rueckgabe vergleich.
		 */
		char user_matrikel[32];
		if (getStatus() != 111) {
			getIdentity(user_matrikel);
			if (!strcmp(user_matrikel, "000000000")) {
				return "read() ist nur Admins und Studenten erlaubt";
			}
		}

		int i = 0;
		char matrikel_string[9];
		while (cmd[i + 5] != ')') {
			if (!isANumber(cmd[i + 5])) {
				return "Matrikelnummer besteht nur aus Zahlen.";
			}
			matrikel_string[i] = cmd[i + 5];
			if ((i > 8) && (cmd[i + 5 + 1] != ')')) {
				return "Matrikel hat max. 9 Stellen";
			}
			if ((i < 8) && (cmd[i + 5 + 1] == ')')) {
				return "Matrikel besteht aus 9 Stellen";
			}
			i++;
		}
		long matrikel = atol(matrikel_string);
		/*
		 Wenn nicht Admin:
		 Usermatrikel und Studentenmatrikel pruefen
		 */
		if (getStatus() != 111) {
			getIdentity(user_matrikel);
			long user_matrikel_long = atol(user_matrikel);
			if (user_matrikel_long != matrikel) {
				return "Studenten ist der Zugriff nur auf ihre eigenen Daten gestattet.";
			}
		}
		if (getStudent(matrikel, &stud) == 1) {

			sprintf(antwort,
					"\nName: %s %s\nStudienfach: %s\nGeburtsdatum: %s\nDurchschnitt: %.2f\n",
					stud.fname, stud.lname, stud.fach, stud.bdate, stud.avg);
			char notenout[64] = "Noten:";
			int i;
			for (i = 0; i < MAXLVs; i++) {
				if (stud.marks[i] >= 1) {
					char singlenote[5];
					sprintf(singlenote, " %.1lf", stud.marks[i]);
					strcat(notenout, singlenote);
				}
			}
			strcat(antwort, notenout);
			strcat(antwort, "\n");
			return antwort;
		}
		return "Student nicht gefunden";

	}

	/*
	 *  ************************** Funktion UPDATE ***********************
	 *  Rechte 111, Veraendert die Daten eines Eintrags
	 */

	if (!strncasecmp(cmd, "update(", 7)) {
		// Rechtekontrolle
		if (getStatus() != 111) {
			return "update() ist nur Admins gestattet.";
		}
//Matrikel Parsen
		int i = 0;
		char matrikel_string[9];
		while (cmd[i + 7] != ',') {
			if (!isANumber(cmd[i + 7])) {
				return "Matrikelnummer besteht nur aus Zahlen.";
			}
			matrikel_string[i] = cmd[i + 7];
			if ((i > 8) && (cmd[i + 7 + 1] != ',')) {
				return "Matrikel hat max. 9 Stellen";
			}
			if ((i < 8) && (cmd[i + 7 + 1] == ',')) {
				return "Matrikel besteht aus 9 Stellen";
			}
			if (isALetter(cmd[i + 7])) {
				return "MAtrikel muss aus Nummern bestehen";
			}
			i++;
		}

		long matrikel = atol(matrikel_string);
		i++;
//Attribut parsen
		char attribut[32];
		int versatz = i;
		while (cmd[i + 7] != ':') {
			attribut[i - versatz] = cmd[i + 7];
			i++;
		}
		attribut[i - versatz] = '\0';
		i++;

// Attribut pr�fen
		if (strcasecmp(attribut, "vorname") && strcasecmp(attribut, "nachname")
				&& strcasecmp(attribut, "noten")
				&& strcasecmp(attribut, "datum")) {
			return "Gueltige Attribute sind: \n"
					"- Vorname\n"
					"- Nachname\n"
					"- Noten\n"
					"- Datum\n";
		}

		char value[32];
		versatz = i;
		while (cmd[i + 7] != ')') {
			if ((!strcasecmp(attribut, "vorname"))
					|| (!strcasecmp(attribut, "nachname"))) { //Wenn Vorname oder Nachname: Ueberpruefen ob nur Buchstaben
				if (!isALetter(cmd[i + 7])) {
					return "Namen bestehen nur aus Buchstaben";
				}
			}

			value[i - versatz] = cmd[i + 7];
			i++;
		}

		if (!strcasecmp(attribut, "datum")) { //Wenn Geburtstag, Ueberpruefen auf gueltiges Datum
			char* p;
			int day, month;
			day = strtol(value, &p, 10);
			month = strtol((p + 1), NULL, 10);

			if ((day > 31) || (month > 12)) {
				return "Kein gueltiges Geburtsdatum";
			}
		}
		value[i - versatz] = '\0';

// DB Operation aufrufen
		if (update(matrikel, attribut, value) > 0) {
			return "Eintrag erfolgreich modifiziert";
		}
		return "Eintrag konnte nicht modifiziert werden.";

	}

	/*
	 * ************************* Funktion RECHTE *************************
	 * rechte: 0, Gibt die Aktuellen Rechte aus
	 */
	if (!strcasecmp(cmd, "rechte")) {
		char cache[] = "Deine Rechte: %i";
		sprintf(antwort, cache, getStatus());
		return antwort;
	}

	/*
	 * ************************* Funktion LOGIN ***************************
	 * rechte: 0, ermoeglicht seine Rechte zu erhoehen
	 */
	if (!strncmp(cmd, "login(", 6)) {
		if (getStatus() > 0) {
			return "Mehrfachanmeldung nicht moeglich.";
		}
// USername parsen
		int i = 6;
		char givenName[32];
		char givenPwd[32];
		int versatz = 6;
		while (cmd[i] != ',') {
			givenName[i - versatz] = cmd[i];
			i++;
			if (i > 30) {
				return "Fehler in der Namensangabe!";
			}
		}
		givenName[i - versatz] = '\0';
		i++;

// Passwort parsen
		versatz = i;
		while (cmd[i] != ')') {
			givenPwd[i - versatz] = cmd[i];
			i++;
			if (i > 60) {
				return "Fehler in der Passwortangabe!";
			}
		}
		givenPwd[i - versatz] = '\0';

// DB Operation aufrufen
		int value = login(givenName, givenPwd);

		switch (value) {
		case 0: {
			char cache[] = "Erfolgreich angemeldet als user: %s";
			sprintf(antwort, cache, givenName);
			return antwort;
		}
		case 1:
			return "Falsches Passwort!";
		case -1:
			return "Kein Benutzerprofil gefunden.";
		}
	}

	/*
	 * ******************** Funktion LOGOUT ***********************
	 * rechte 0, Ermoeglicht ein sicheres Logout
	 */
	if (!strcasecmp(cmd, "logout")) {
		if (getStatus() == 0) {
			return "Keine abmeldung erforderlich.";
		}
		logout();
		return "Erfolgreich abgemeldet.";
	}

	return "Operation nicht bekannt. Probiere \"help\"";
}
Beispiel #22
0
void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const
{
    ATRACE_CALL();

    if (CC_UNLIKELY(mActiveBuffer == 0)) {
        // the texture has not been created yet, this Layer has
        // in fact never been drawn into. This happens frequently with
        // SurfaceView because the WindowManager can't know when the client
        // has drawn the first time.

        // If there is nothing under us, we paint the screen in black, otherwise
        // we just skip this update.

        // figure out if there is something below us
        Region under;
        const SurfaceFlinger::LayerVector& drawingLayers(
                mFlinger->mDrawingState.layersSortedByZ);
        const size_t count = drawingLayers.size();
        for (size_t i=0 ; i<count ; ++i) {
            const sp<LayerBase>& layer(drawingLayers[i]);
            if (layer.get() == static_cast<LayerBase const*>(this))
                break;
            under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
        }
        // if not everything below us is covered, we plug the holes!
        Region holes(clip.subtract(under));
        if (!holes.isEmpty()) {
            // [MTK] {{{
            // add debug log
            XLOGI("[%s] %s(i:%d): clear screen hole (l:%d, t:%d, w:%d, h:%d)",
                __func__, getName().string(), getIdentity(),
                holes.getBounds().left, holes.getBounds().top,
                holes.getBounds().width(), holes.getBounds().height());
            // [MTK] }}}
            clearWithOpenGL(hw, holes, 0, 0, 0, 1);
        }
        return;
    }

    status_t err = mSurfaceTexture->doGLFenceWait();
    if (err != OK) {
        ALOGE("onDraw: failed waiting for fence: %d", err);
        // Go ahead and draw the buffer anyway; no matter what we do the screen
        // is probably going to have something visibly wrong.
    }

    bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());

    if (!blackOutLayer) {
        // TODO: we could be more subtle with isFixedSize()
        const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();

        // Query the texture matrix given our current filtering mode.
        float textureMatrix[16];
        mSurfaceTexture->setFilteringEnabled(useFiltering);
        mSurfaceTexture->getTransformMatrix(textureMatrix);

        // Set things up for texturing.
        // [MTK] {{{
        // buffer conversion here for SF layer
        if (true == mSurfaceTexture->isAuxSlotNeedConvert()) {
            mSurfaceTexture->convertToAuxSlot(true);
        }

        if (true == mSurfaceTexture->isAuxSlotDirty()) {
            // bind to aux buffer if converted successfully
            mSurfaceTexture->bindToAuxSlot();
        } else {
            // bind to original buffer
            glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureName);
        }
        // [MTK] }}}

        GLenum filter = GL_NEAREST;
        if (useFiltering) {
            filter = GL_LINEAR;
        }
        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, filter);
        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, filter);
        glMatrixMode(GL_TEXTURE);
        glLoadMatrixf(textureMatrix);
        glMatrixMode(GL_MODELVIEW);
        glDisable(GL_TEXTURE_2D);
        glEnable(GL_TEXTURE_EXTERNAL_OES);
    } else {
        glBindTexture(GL_TEXTURE_2D, mFlinger->getProtectedTexName());
        glMatrixMode(GL_TEXTURE);
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);
        glDisable(GL_TEXTURE_EXTERNAL_OES);
        glEnable(GL_TEXTURE_2D);
    }

    drawWithOpenGL(hw, clip);

    glDisable(GL_TEXTURE_EXTERNAL_OES);
    glDisable(GL_TEXTURE_2D);
}
Beispiel #23
0
/**
 * Set the forward and inverse affine transform to the identity.
 * That is, xp = x and yp = y for all (x,y).
 */
void Affine::Identity() {
    p_matrix = getIdentity();
    p_invmat = getIdentity();
}
gMatrixSparse gMatrixSparse::getIdentity(int numRows)
{
    return getIdentity(numRows, numRows);
}
void Transform::setIdentity()
{
	*this = getIdentity();
}