Пример #1
0
void br::GalleryToolBar::enrollmentFinished()
{
    if (files.isEmpty()) {
        if (input.get<bool>("enrollAll", false) && !tbWebcam.isChecked()) {
            QMessageBox msgBox;
            msgBox.setText("Quality test failed.");
            msgBox.setInformativeText("Enroll anyway?");
            msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
            msgBox.setDefaultButton(QMessageBox::Ok);
            int ret = msgBox.exec();

            if (ret == QMessageBox::Ok) {
                br::File file = input;
                file.set("enrollAll", QVariant(false));
                enroll(file);
            }
        }
        return;
    }

    lGallery.setText(input.baseName() + (files.size() != 1 ? " (" + QString::number(files.size()) + ")" : ""));
    tbBack.setEnabled(false);
    emit newFiles(files);
    emit newGallery(gallery);
}
Пример #2
0
void br::GalleryToolBar::mean()
{
    const QString file = QString("%1/mean/%2.png").arg(br::Globals->scratchPath(), input.baseName()+input.hash());
    br_set_property("CENTER_TRAIN_B", qPrintable(file));
    br::File trainingFile = input;
    br_train(qPrintable(trainingFile.flat()), "[algorithm=MedianFace]");
    enroll(file);
}
Пример #3
0
void EnrollDialog::btnOkClicked()
{
  if (screen == 1) {
    int rut;
    QString digit;
    char calculatedDigit;

    if (rutNumber.isEmpty()) {
      lblMsg->setText(tr("RUT Vacío"));
      return;
    }

    // if (rutNumber.length() != 10) {
    //   lblMsg->setText(tr("RUT Inválido"));
    //   return;
    // }

    QStringList splitted = rutNumber.split("-");
    if (splitted.length() != 2) {
      lblMsg->setText(tr("RUT Inválido"));
      return;
    }

    rut = splitted.at(0).trimmed().toInt();
    digit = splitted.at(1).trimmed();
    calculatedDigit = Utils::rutVerifyDigit((unsigned) rut);

    DEBUG("**************************************************************");
    DEBUG("rut: %d", rut);
    DEBUG("digit: %s", digit.toStdString().c_str());
    DEBUG("calculatedDigit: %s", QString(calculatedDigit).toStdString().c_str());
    DEBUG("**************************************************************");

    if (digit != QString(calculatedDigit)) {
      lblMsg->setText(tr("RUT Inválido"));
      return;
    }

    verificaPersona();
  } else if (screen == 2) {
    DEBUG("Comenzando el proceso de enrolamiento");
    btnOk->setVisible(false);
    btnCancel->setVisible(false);
    lblEmpresa->setText(tr("Enrolando... Espere..."));
    update();
    qApp->processEvents();

    enroll(rutNumber, imgRawB64, imgbaseJpg64, template1);
  } else {  // error
    closeDialog(tr("Error procesando..."));
  }
}
Пример #4
0
std::string RemoteEnrollmentPlugin::getKey(bool force) {
  if (enrollment_key_.length() == 0 || force) {
    VLOG(1) << "Querying server for enrollment key...";
    for (int i = 1; i <= MAX_TRIES; i++) {
      if (enroll().ok()) {
        break;
      }
      if (i == MAX_TRIES) {
        return "";
      }
      sleep(i * i);
    }
  }
  return enrollment_key_;
}
Пример #5
0
void br::GalleryToolBar::_checkWebcam()
{
    static QSharedPointer<cv::VideoCapture> videoCapture;
    if (videoCapture.isNull()) {
        videoCapture = QSharedPointer<cv::VideoCapture>(new cv::VideoCapture(0));
        cv::Mat m;
        while (!m.data) videoCapture->read(m); // First frames can be empty
    }

    if (galleryLock.tryLock()) {
        cv::Mat m;
        videoCapture->read(m);
        galleryLock.unlock();
        enroll(toQImage(m));
    }
}
Пример #6
0
    void retrieveOrEnroll(const File &file, QScopedPointer<Gallery> &gallery, FileList &galleryFiles)
    {
        if (!file.getBool("enroll") && (QStringList() << "gal" << "mem" << "template").contains(file.suffix())) {
            // Retrieve it
            gallery.reset(Gallery::make(file));
            galleryFiles = gallery->files();
        } else {
            // Was it already enrolled in memory?
            gallery.reset(Gallery::make(getMemoryGallery(file)));
            galleryFiles = gallery->files();
            if (!galleryFiles.isEmpty()) return;

            // Enroll it
            enroll(file);
            gallery.reset(Gallery::make(getMemoryGallery(file)));
            galleryFiles = gallery->files();
        }
    }
Пример #7
0
int main() 
{
	bool loop = true;
	string buffer;

	while (loop)
	{
		cout << "class> ";
		cin >> buffer;

		if(buffer.compare("quit") == 0)
			loop = false;
		else if(buffer.compare("enroll") == 0)
			enroll();
		else if(buffer.compare("drop") == 0) 
			drop();
		else if(buffer.compare("roster") == 0)
			roster();
		else 
			cout << "Error! Unrecognized command." << endl;
	}

	return 0;
}
Пример #8
0
void br::GalleryToolBar::openFile()
{
    enroll(QFileDialog::getOpenFileName(this, "Select Photo", QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first()));
}
Пример #9
0
int main(int argc, char *argv[])
{
	int r = 1, i;
	int next_option;
	enum fp_finger finger = RIGHT_INDEX;

	struct fp_dscv_dev *ddev;
	struct fp_dscv_dev **discovered_devs;
	struct fp_dev *dev;
	struct fp_print_data *data;
	
	const char * const short_options = "hf:";
	const struct option long_options[] = {
		{ "help", 0, NULL, 'h'},
		{ "enroll-finger", 1, NULL, 'f'},
		{ NULL, 0, NULL, 0}
	};
	
	do {
		next_option = getopt_long(argc, argv, short_options, long_options,
			NULL);
		switch (next_option) {
		case 'h':
			/* Printing usage */
			printf("Usage: %s options\n", argv[0]);
			printf("	-h	--help			Display this usage information.\n"
			   "	-f	--enroll-finger index	Enroll finger with index.\n\n");
			printf("	Valid indexes are:\n");
			for (i = LEFT_THUMB; i <= RIGHT_LITTLE; i++) {
				printf("	%d - %s\n", i, finger_names[i]);
			}
			exit(1);
			   
			break;
		case 'f':
			sscanf(optarg, "%d", &finger);
			if (finger < LEFT_THUMB || finger > RIGHT_LITTLE) {
				printf("%s: Invalid finger index.\n", argv[0]);
				printf("%s: Valid indexes are:\n", argv[0]);
				for (i = LEFT_THUMB; i <= RIGHT_LITTLE; i++) {
					printf("%s: %d - %s\n", argv[0], i, finger_names[i]);
				}
				exit(1);
			}
			break;
		case -1:	/* Done with options. */
			break;
		default:	/* Unexpected option */
			exit(1);
		}
	} while (next_option != -1);

	printf("This program will enroll your finger, "
		"unconditionally overwriting any selected print that was enrolled "
		"previously. If you want to continue, press enter, otherwise hit "
		"Ctrl+C\n");
	getchar();

	r = fp_init();
	if (r < 0) {
		fprintf(stderr, "Failed to initialize libfprint\n");
		exit(1);
	}

	discovered_devs = fp_discover_devs();
	if (!discovered_devs) {
		fprintf(stderr, "Could not discover devices\n");
		goto out;
	}

	ddev = discover_device(discovered_devs);
	if (!ddev) {
		fprintf(stderr, "No devices detected.\n");
		goto out;
	}

	dev = fp_dev_open(ddev);
	fp_dscv_devs_free(discovered_devs);
	if (!dev) {
		fprintf(stderr, "Could not open device.\n");
		goto out;
	}

	printf("Opened device. It's now time to enroll your finger.\n\n");
	data = enroll(dev, finger);
	if (!data)
		goto out_close;

	r = fp_print_data_save(data, finger);
	if (r < 0)
		fprintf(stderr, "Data save failed, code %d\n", r);

	fp_print_data_free(data);
out_close:
	fp_dev_close(dev);
out:
	fp_exit();
	return r;
}
Пример #10
0
int main(void)
{
	struct fp_dscv_dev *ddev;
	struct fp_dscv_dev **discovered_devs;
	struct fp_dev *dev;
	struct fp_print_data *data;
	int r = fp_init();

	if (r < 0) {
		fprintf(stderr, "Failed to initialize libfprint\n");
		exit(1);
	}
	fp_set_debug(3);

	discovered_devs = fp_discover_devs();
	if (!discovered_devs) {
		fprintf(stderr, "Could not discover devices\n");
		goto out;
	}

	ddev = discover_device(discovered_devs);
	if (!ddev) {
		fprintf(stderr, "No devices detected.\n");
		goto out;
	}

	dev = fp_dev_open(ddev);
	fp_dscv_devs_free(discovered_devs);
	if (!dev) {
		fprintf(stderr, "Could not open device.\n");
		goto out;
	}

	printf("Opened device. It's now time to enroll your finger.\n\n");
	data = enroll(dev);
	if (!data)
		goto out_close;


	printf("Normally we'd save that print to disk, and recall it at some "
		"point later when we want to authenticate the user who just "
		"enrolled. In the interests of demonstration, we'll authenticate "
		"that user immediately.\n");

	do {
		char buffer[20];

		verify(dev, data);
		printf("Verify again? [Y/n]? ");
		fgets(buffer, sizeof(buffer), stdin);
		if (buffer[0] != '\n' && buffer[0] != 'y' && buffer[0] != 'Y')
			break;
	} while (1);

	fp_print_data_free(data);
out_close:
	fp_dev_close(dev);
out:
	fp_exit();
	return r;
}
Пример #11
0
int
main (int argc, char **argv)
{
  int r = 1;
  struct fp_dscv_dev *ddev;
  struct fp_dscv_dev **discovered_devs;
  struct fp_dev *dev;
  struct fp_print_data *data;

  int finger;

  finger = atoi(argv[3]);



  printf ("This program will enroll your right index finger, "
	  "unconditionally overwriting any right-index print that was enrolled "
	  "previously. If you want to continue, press enter, otherwise hit "
	  "Ctrl+C\n");
  getchar ();

  r = fp_init ();
  if (r < 0)
    {
      fprintf (stderr, "Failed to initialize libfprint\n");
      exit (1);
    }
  fp_set_debug (3);

  discovered_devs = fp_discover_devs ();
  if (!discovered_devs)
    {
      fprintf (stderr, "Could not discover devices\n");
      goto out;
    }

  ddev = discover_device (discovered_devs);
  if (!ddev)
    {
      fprintf (stderr, "No devices detected.\n");
      goto out;
    }

  dev = fp_dev_open (ddev);
  fp_dscv_devs_free (discovered_devs);
  if (!dev)
    {
      fprintf (stderr, "Could not open device.\n");
      goto out;
    }

  printf ("Opened device. It's now time to enroll your finger.\n\n");
  data = enroll (dev);
  if (!data)
    goto out_close;

  r = fp_print_data_save (data, finger, argv[1], argv[2]);
  if (r < 0)
    fprintf (stderr, "Data save failed, code %d\n", r);

  fp_print_data_free (data);
out_close:
  fp_dev_close (dev);
out:
  fp_exit ();
  return r;
}
Пример #12
0
status_t BnFingerprintDaemon::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
        uint32_t flags) {
    switch(code) {
        case AUTHENTICATE: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const uint64_t sessionId = data.readInt64();
            const uint32_t groupId = data.readInt32();
            const int32_t ret = authenticate(sessionId, groupId);
            reply->writeNoException();
            reply->writeInt32(ret);
            return NO_ERROR;
        };
        case CANCEL_AUTHENTICATION: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const int32_t ret = stopAuthentication();
            reply->writeNoException();
            reply->writeInt32(ret);
            return NO_ERROR;
        }
        case ENROLL: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const ssize_t tokenSize = data.readInt32();
            const uint8_t* token = static_cast<const uint8_t *>(data.readInplace(tokenSize));
            const int32_t groupId = data.readInt32();
            const int32_t timeout = data.readInt32();
            const int32_t ret = enroll(token, tokenSize, groupId, timeout);
            reply->writeNoException();
            reply->writeInt32(ret);
            return NO_ERROR;
        }
        case CANCEL_ENROLLMENT: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const int32_t ret = stopEnrollment();
            reply->writeNoException();
            reply->writeInt32(ret);
            return NO_ERROR;
        }
        case PRE_ENROLL: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const uint64_t ret = preEnroll();
            reply->writeNoException();
            reply->writeInt64(ret);
            return NO_ERROR;
        }
        case POST_ENROLL: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const int32_t ret = postEnroll();
            reply->writeNoException();
            reply->writeInt32(ret);
            return NO_ERROR;
        }
        case REMOVE: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const int32_t fingerId = data.readInt32();
            const int32_t groupId = data.readInt32();
            const int32_t ret = remove(fingerId, groupId);
            reply->writeNoException();
            reply->writeInt32(ret);
            return NO_ERROR;
        }
        case ENUMERATE: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const int32_t ret = enumerate();
            reply->writeNoException();
            reply->writeInt32(ret);
            return NO_ERROR;
        }
        case GET_AUTHENTICATOR_ID: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const uint64_t ret = getAuthenticatorId();
            reply->writeNoException();
            reply->writeInt64(ret);
            return NO_ERROR;
        }
        case SET_ACTIVE_GROUP: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const int32_t group = data.readInt32();
            const ssize_t pathSize = data.readInt32();
            const uint8_t* path = static_cast<const uint8_t *>(data.readInplace(pathSize));
            const int32_t ret = setActiveGroup(group, path, pathSize);
            reply->writeNoException();
            reply->writeInt32(ret);
            return NO_ERROR;
        }
        case OPEN_HAL: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const int64_t ret = openHal();
            reply->writeNoException();
            reply->writeInt64(ret);
            return NO_ERROR;
        }
        case CLOSE_HAL: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            const int32_t ret = closeHal();
            reply->writeNoException();
            reply->writeInt32(ret);
            return NO_ERROR;
        }
        case INIT: {
            CHECK_INTERFACE(IFingerprintDaemon, data, reply);
            if (!checkPermission(HAL_FINGERPRINT_PERMISSION)) {
                return PERMISSION_DENIED;
            }
            sp<IFingerprintDaemonCallback> callback =
                    interface_cast<IFingerprintDaemonCallback>(data.readStrongBinder());
            init(callback);
            reply->writeNoException();
            return NO_ERROR;
        }
        default:
            return BBinder::onTransact(code, data, reply, flags);
    }
};
Пример #13
0
int KSGateway::run()
{
	int ret = loadLocalConfig();
	if(ret)
		return ret;
	ret = setupLogSystem();
	if(ret)
		return ret;
	ACE_DEBUG((LM_INFO,"开始启动前置机..."));
	ACE_DEBUG((LM_INFO,"应用服务器[%s:%d]func[%d]",_configuration._drtpSvrIP.c_str()
		,_configuration._drtpSvrPort,_configuration._drtpMainFunc));

	ret = setupDrtpPool();
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"初始化DRTP连接失败,返回码[%d]",ret));
		return ret;
	}
	
	ret = enroll();
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"前置机签到失败,错误码[%d]",ret));
		return ret;
	}
	ret = downloadRuntimeParams();
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"下载运行参数失败,错误码[%d]",ret));
		return ret;
	}
	
	// 加载 loop 设备
	ret = loadLoopDevice();
	if(ret)
	{
		return ret;
	}
	if("" != _configuration._devType)
	{
		// 只有当有设备时,才需要调用设置初始化
		ret = loadDeviceType();
		if(ret)
		{
			return ret;
		}
		
		ret = setupAllDevices();
		if(ret)
		{
			return ret;
		}
	}
	else
	{
		ACE_DEBUG((LM_INFO,"前置机未加载设备!"));
	}
	loadTaskExecutor();

	ret = setup_all_proactor_acceptor();

	ret = startTimeScheduler();
	if(ret)
		return ret;
	
	ACE_DEBUG((LM_INFO,"启动前置机成功..."));
	// 进入主循环
	_status = stRunning;
	int i = 0;
	while(_status == stRunning)
	{
		KSGThreadUtil::Sleep(5000);
		KSGThreadUtil::yield();
	}
	ACE_DEBUG((LM_INFO,"正在停止前置机..."));
	stop_all_proactor_acceptor();
	SchedulerGroup::Instance().TerminateAll();
	_devgrpSchd.TerminateAll();
	ACE_DEBUG((LM_INFO,"主流程运行结束"));
	exit();
	return 0;
}
Пример #14
0
void br::GalleryToolBar::enroll(const QImage &input)
{
    QString tempFileName = br::Context::scratchPath() + "/tmp/" + QDateTime::currentDateTime().toString("yyyy-MM-ddThh:mm:ss:zzz") + ".png";
    input.save(tempFileName);
    enroll(tempFileName);
}
Пример #15
0
void br::GalleryToolBar::openFolder()
{
    enroll(QFileDialog::getExistingDirectory(this, "Select Photo Directory", QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first()));
}
Пример #16
0
//student menu screen
void studentMenu(char* username) {
    //query
    char q[150] = "\0";
    
    MYSQL_RES *res_set;
    MYSQL_ROW row;
    
    strcat(q, "SELECT name FROM student where id = ");
    strcat(q, username);
    
    mysql_query(connection,q);
    res_set = mysql_store_result(connection);
    
    row = mysql_fetch_row(res_set);
    
    int z;
    int m = 0, y = 0;
    char* semester;
    get_year(&y);
    semester = get_semester(m);
    
    printf("\t\t\t---------------------------------------\n");
    printf("\t\t\t           Student Menu           \n");
    printf("\t\t\t---------------------------------------\n\n");
    printf("\t\t\tHi, %s\n", row[0]);
    
    printf("\n\t\t\t%s, %d\n", semester, y);
    memset(q, 0, sizeof(q));
    
    MYSQL_RES *res_set2;
    MYSQL_ROW row2;
    
    sprintf(q, "select u.UoSName from unitofstudy u, transcript t where u.UoSCode = t.UoSCode and t.Studid = %s and t.Semester = '%s' and t.Year = %d;", username, semester, y);
    //puts(q);
    
    mysql_query(connection,q);
    res_set2 = mysql_store_result(connection);
    int numrows = (int)mysql_num_rows(res_set2);
    
    for (int i = 0; i < numrows; i++)
    {
        row2 = mysql_fetch_row(res_set2);
        if( row2 != NULL )
        {
            printf("\t\t\t%s\n", row2[0]);

        }
    }
    
    printf("\n\t\t\t---------------------------------------\n");
    
    //free?
    if(semester != NULL) {
        //free(semester);
        semester = NULL;
    }
    
    // free resources
    mysql_free_result(res_set);
    mysql_free_result(res_set2);
    
    do
    {
        printf("\t\t\t---------------------------------------\n");
        printf("\t\t\t           Commands List           \n");
        printf("\t\t\t---------------------------------------\n");
        printf("\t\t\t    [1]Transcript               \n");
        printf("\t\t\t    [2]Enroll Class             \n");
        printf("\t\t\t    [3]Withdraw Class           \n");
        printf("\t\t\t    [4]Personal Details         \n");
        printf("\t\t\t    [5]Logout                   \n");
        printf("\t\t\t    [0]Exit                     \n");
        printf("\t\t\t---------------------------------------\n\n");
        printf("Please enter the command: ");
        scanf("%d", &z);
        //system("color 2f");
        switch(z)
        {
            case 0 :return;
            case 1 :transcript(username);break;
            case 2 :enroll(username);break;
            case 3 :withdraw(username);break;
            case 4 :personaldetail(username);break;
            case 5 :logoutStudent(username);break;
            default:printf("\n INVALID COMMAND");
        }
    }
    while( 1 );
}
Пример #17
0
    void compare(File targetGallery, File queryGallery, File output)
    {
        qDebug("Comparing %s and %s%s", qPrintable(targetGallery.flat()),
               qPrintable(queryGallery.flat()),
               output.isNull() ? "" : qPrintable(" to " + output.flat()));

        // Escape hatch for distances that need to operate directly on the gallery files
        if (distance->compare(targetGallery, queryGallery, output))
            return;

        // Are we comparing the same gallery against itself?
        bool selfCompare = targetGallery == queryGallery;

        // Should we use multiple processes to do enrollment/comparison? If not, we just do multi-threading.
        bool multiProcess = Globals->file.getBool("multiProcess", false);

        // In comparing two galleries, we will keep the smaller one in memory, and load the larger one
        // incrementally. If the gallery set is larger than the probe set, we operate in transpose mode
        // i.e. we must transpose our output, to still write the output matrix in row-major order.
        bool transposeMode = false;

        // Is the larger gallery already enrolled? If not, we will enroll those images in-line with their
        // comparison against the smaller gallery (which will be enrolled, and stored in memory).
        bool needEnrollRows = false;

        if (output.exists() && output.get<bool>("cache", false)) return;
        if (queryGallery == ".") queryGallery = targetGallery;

        // To decide which gallery is larger, we need to read both, but at this point we just want the
        // metadata, and don't need the enrolled matrices.
        FileList targetMetadata;
        FileList queryMetadata;

        // Emptyread reads a gallery, and discards any matrices present, keeping only the metadata.
        targetMetadata = FileList::fromGallery(targetGallery, true);
        queryMetadata  = FileList::fromGallery(queryGallery, true);


        // Is the target or query set larger? We will use the larger as the rows of our comparison matrix (and transpose the output if necessary)
        transposeMode = targetMetadata.size() > queryMetadata.size();

        File rowGallery = queryGallery;
        File colGallery = targetGallery;
        qint64 rowSize;

        Gallery * temp;
        if (transposeMode)
        {
            rowGallery = targetGallery;
            colGallery = queryGallery;
            temp = Gallery::make(targetGallery);
        }
        else
        {
            temp = Gallery::make(queryGallery);
        }
        rowSize = temp->totalSize();
        delete temp;

        // Is the column gallery already enrolled? We keep the enrolled column gallery in memory, and in multi-process
        // mode, every worker process retains a copy of this gallery in memory. When not in multi-process mode, we can
        // simple make sure the enrolled data is stored in a memGallery, but in multi-process mode we save the enrolled
        // data to disk (as a .gal file) so that each worker process can read it without re-doing enrollment.
        File colEnrolledGallery = colGallery;
        QString targetExtension = multiProcess ? "gal" : "mem";

        // If the column gallery is not already of the appropriate type, we need to do something
        if (colGallery.suffix() != targetExtension)
        {
            // Build the name of a gallery containing the enrolled data, of the appropriate type.
            colEnrolledGallery = colGallery.baseName() + colGallery.hash() + (multiProcess ? ".gal" : ".mem");

            // Check if we have to do real enrollment, and not just convert the gallery's type.
            if (!(QStringList() << "gal" << "template" << "mem").contains(colGallery.suffix()))
            {
                enroll(colGallery, colEnrolledGallery);
            }
            // If the gallery does have enrolled templates, but is not the right type, we do a simple
            // type conversion for it.
            else
            {
                QScopedPointer<Gallery> readColGallery(Gallery::make(colGallery));
                TemplateList templates = readColGallery->read();
                QScopedPointer<Gallery> enrolledColOutput(Gallery::make(colEnrolledGallery));
                enrolledColOutput->writeBlock(templates);
            }
        }

        // We have handled the column gallery, now decide whehter or not we have to enroll the row gallery.
        if (selfCompare)
        {
            // For self-comparisons, we just use the already enrolled column set.
            rowGallery = colEnrolledGallery;
        }
        // Otherwise, we will need to enroll the row set. Since the actual comparison is defined via a transform
        // which compares incoming templates against a gallery, we will handle enrollment of the row set by simply
        // building a transform that does enrollment (using the current algorithm), then does the comparison in one
        // step. This way, we don't have to retain the complete enrolled row gallery in memory, or on disk.
        else if(!(QStringList() << "gal" << "mem" << "template").contains(rowGallery.suffix()))
        {
            needEnrollRows = true;
        }

        // At this point, we have decided how we will structure the comparison (either in transpose mode, or not), 
        // and have the column gallery enrolled, and have decided whether or not we need to enroll the row gallery.
        // From this point, we will build a single algorithm that (optionally) does enrollment, then does comparisons
        // and output, optionally using ProcessWrapper to do the enrollment and comparison in separate processes.
        //
        // There are two main components to this algorithm. The first is the (optional) enrollment and then the
        // comparison step (built from a GalleryCompare transform), and the second is the sequential matrix output and
        // progress counting step.
        // After the base algorithm is built, the whole thing will be run in a stream, so that I/O can be handled sequentially.

        // The actual comparison step is done by a GalleryCompare transform, which has a Distance, and a gallery as data.
        // Incoming templates are compared against the templates in the gallery, and the output is the resulting score
        // vector.
        QString compareRegionDesc = "Pipe([GalleryCompare("+Globals->algorithm + "," + colEnrolledGallery.flat() + ")])";


        QScopedPointer<Transform> compareRegion;
        // If we need to enroll the row set, we add the current algorithm's enrollment transform before the
        // GalleryCompare in a pipe.
        if (needEnrollRows)
        {
            if (!multiProcess)
            {
                compareRegionDesc = compareRegionDesc;
                compareRegion.reset(Transform::make(compareRegionDesc,NULL));
                CompositeTransform * downcast = dynamic_cast<CompositeTransform *> (compareRegion.data());
                if (downcast == NULL)
                    qFatal("Pipe downcast failed in compare");

                downcast->transforms.prepend(this->transform.data());
                downcast->init();
            }
            else
            {
                compareRegionDesc = "ProcessWrapper(" + this->transformString + "+" + compareRegionDesc + ")";
                compareRegion.reset(Transform::make(compareRegionDesc, NULL));
            }
        }
        else {
            if (multiProcess)
                compareRegionDesc = "ProcessWrapper(" + compareRegionDesc + ")";
            compareRegion.reset(Transform::make(compareRegionDesc,NULL));
        }

        // At this point, compareRegion is a transform, which optionally does enrollment, then compares the row
        // set against the column set. If in multi-process mode, the enrollment and comparison are wrapped in a 
        // ProcessWrapper transform, and will be transparently run in multiple processes.
        compareRegion->init();


        // We also need to add Output and progress counting to the algorithm we are building, so we will assign them to
        // two stages of a pipe.
        QString joinDesc = "Pipe()";
        QScopedPointer<Transform> join(Transform::make(joinDesc, NULL));

        // The output transform takes the metadata memGalleries we set up previously as input, along with the
        // output specification we were passed. Gallery metadata is necessary for some Outputs to function correctly.
        QString outputString = output.flat().isEmpty() ? "Empty" : output.flat();
        QString outputRegionDesc = "Output("+ outputString +"," + targetGallery.flat() +"," + queryGallery.flat() + ","+ QString::number(transposeMode ? 1 : 0) + ")";
        // The ProgressCounter transform will simply provide a display about the number of rows completed.
        outputRegionDesc += "+ProgressCounter("+QString::number(rowSize)+")+Discard";
        QScopedPointer<Transform> outputTform(Transform::make(outputRegionDesc, NULL));

        // Assign the comparison transform we previously built, and the output transform  we just built to
        // two stages of a pipe.
        CompositeTransform * downcast = dynamic_cast<CompositeTransform *> (join.data());
        downcast->transforms.append(compareRegion.data());
        downcast->transforms.append(outputTform.data());

        // With this, we have set up a transform which (optionally) enrolls templates, compares them
        // against a gallery, and outputs them.
        join->init();

        // Now, we will give that base transform to a stream, which will incrementally read the row gallery
        // and pass the transforms it reads through the base algorithm.
        QString streamDesc = "Stream(readMode=StreamGallery)";
        QScopedPointer<Transform> streamBase(Transform::make(streamDesc, NULL));
        WrapperTransform * streamWrapper = dynamic_cast<WrapperTransform *> (streamBase.data());
        streamWrapper->transform = join.data();

        // The transform we will use is now complete.
        streamWrapper->init();

        // We set up a template containing the rowGallery we want to compare. 
        TemplateList rowGalleryTemplate;
        rowGalleryTemplate.append(Template(rowGallery));
        TemplateList outputGallery;

        // Set up progress counting variables
        Globals->currentStep = 0;
        Globals->totalSteps = rowSize;
        Globals->startTime.start();

        // Do the actual comparisons
        streamWrapper->projectUpdate(rowGalleryTemplate, outputGallery);
    }
Пример #18
0
int KSGateway::run()
{
	long sleep_time = 0;
	int ret = loadLocalConfig();
	if(ret)
		return ret;
	ret = setupLogSystem();
	if(ret)
		return ret;
	ACE_DEBUG((LM_INFO,"开始启动前置机..."));
	ACE_DEBUG((LM_NOTICE,"前置机版本[%s]",KSG_FULL_VERSION));
	ACE_DEBUG((LM_NOTICE,"编译器 : %s",KSG_BUILD_INFO));
	ACE_DEBUG((LM_NOTICE,"libraries ACE : %s , boost : %s , libcurl : %s"
		,KSG_ACE_VERSION,KSG_BOOST_VERSION,KSG_CURL_VERSION));
	ACE_DEBUG((LM_NOTICE,KSG_COPYRIGHT_STRING));
	ACE_DEBUG((LM_INFO,"应用服务器[%s:%d]func[%d]",_configuration._drtpSvrIP.c_str()
		,_configuration._drtpSvrPort,_configuration._drtpMainFunc));

	ret = setupDrtpPool();
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"初始化DRTP连接失败,返回码[%d]",ret));
		return ret;
	}
	
	ret = enroll();
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"前置机签到失败,错误码[%d]",ret));
		return ret;
	}
	ret = downloadRuntimeParams(&_configuration);
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"下载运行参数失败,错误码[%d]",ret));
		return ret;
	}
	
	ret = load_vendor_config();
	if(ret)
	{
		return ret;
	}
	// 加载 loop 设备
	/*
	ret = loadLoopDevice();
	if(ret)
	{
		return ret;
	}
	*/

	ret = setupAllDevices();
	if(ret)
	{
		return ret;
	}
	//ACE_DEBUG((LM_INFO,"前置机未加载设备!"));
	loadTaskExecutor();

	_status = stRunning;

	ret = setup_all_acceptor();

	// 2007-04-19
	// 为防止调度线程在接收任务线程之后启动,当任务队列中只有一条任务的
	// 情况下,可能造成的饥饿死锁,应先启动调度线程。但是这种处理办法并
	// 不是最好的,应该增加信号量来控制任务采集线程晚于调度线程启动.
	ret = start_scheduler_algorithm();
	if(ret)
		return ret;

	ret = startTimeScheduler();
	if(ret)
		return ret;
	
	if(_configuration._start_bcc)
	{
		if(start_bcc_svr())
			return -1;
	}

	if (_configuration._loadCardState)
	{
		if(loadCardState())
			return -1;
	}
	
	ACE_DEBUG((LM_INFO,"启动前置机成功..."));
	// 进入主循环
	update_max_blk_version();
	int i = 0;
	while(_status == stRunning)
	{
		sleep_and_test(5000);
		report_status();
		update_max_blk_version();
		/*
		sleep_time += 5000;
		if(sleep_time > 1000 * 60 * 15)
		{
			
			KSGConfig config;
			config = _configuration;
			if(downloadRuntimeParams(&config) == 0)
			{
				ACE_DEBUG((LM_DEBUG,"更新前置机参数,gwid[%d]",config._gwId));
				ACE_GUARD(ACE_Thread_Mutex,mon,_global_mutex);
				_configuration = config;
			}
			sleep_time = 0;
		}
		*/
		KSGThreadUtil::yield();
	}
	ACE_DEBUG((LM_INFO,"正在停止前置机..."));
	if(_configuration._start_bcc)
		stop_bcc_svr();
	stop_all_acceptor();
	SchedulerGroup::Instance().TerminateAll();
	SchedulerGroup::Instance().ClearAll();
	// 使用循环等待方式,控制超时
	/*
	while(_status == stRunning)
	{
		ACE_Time_Value tv(5);
		tv += ACE_OS::gettimeofday();
		ACE_DEBUG((LM_DEBUG,"等待超时,准备重试"));
	}
	*/
	_status = stStop;
	//_devgrpSchd.TerminateAll();
	stop_scheduler_algorithm();
	ACE_DEBUG((LM_INFO,"主流程运行结束"));
	exit();
	return 0;
}
Пример #19
0
 inline void enroll(param_type arg)
 {
     enroll( typeid(U), arg );
 }
Пример #20
0
 static void enroll(boost::int32_t type_id)
 {
     enroll(type_id, T::_new);
 }
Пример #21
0
int KSGateway::run()
{
	long sleep_time = 0;
	int ret = loadLocalConfig();
	if(ret)
		return ret;
	ret = setupLogSystem();
	if(ret)
		return ret;
	ACE_DEBUG((LM_INFO,"开始启动前置机..."));
	ACE_DEBUG((LM_INFO,"应用服务器[%s:%d]func[%d]",_configuration._drtpSvrIP.c_str()
		,_configuration._drtpSvrPort,_configuration._drtpMainFunc));

	ret = setupDrtpPool();
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"初始化DRTP连接失败,返回码[%d]",ret));
		return ret;
	}
	
	ret = enroll();
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"前置机签到失败,错误码[%d]",ret));
		return ret;
	}
	ret = downloadRuntimeParams(&_configuration);
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"下载运行参数失败,错误码[%d]",ret));
		return ret;
	}
	
	ret = load_vendor_config();
	if(ret)
	{
		return ret;
	}
	// 加载 loop 设备
	/*
	ret = loadLoopDevice();
	if(ret)
	{
		return ret;
	}
	*/

	ret = setupAllDevices();
	if(ret)
	{
		return ret;
	}
	//ACE_DEBUG((LM_INFO,"前置机未加载设备!"));
	loadTaskExecutor();

	_status = stRunning;

	ret = setup_all_proactor_acceptor();

	// 2007-04-19
	// 为防止调度线程在接收任务线程之后启动,当任务队列中只有一条任务的
	// 情况下,可能造成的饥饿死锁,应先启动调度线程。但是这种处理办法并
	// 不是最好的,应该增加信号量来控制任务采集线程晚于调度线程启动.
	ret = start_scheduler_algorithm();
	if(ret)
		return ret;

	ret = startTimeScheduler();
	if(ret)
		return ret;
	
	
	ACE_DEBUG((LM_INFO,"启动前置机成功..."));
	// 进入主循环
	
	int i = 0;
	while(_status == stRunning)
	{
		KSGThreadUtil::Sleep(5000);
		sleep_time += 5000;
		if(sleep_time > 1000 * 60 * 15)
		{
			report_status();
			KSGConfig config;
			config = _configuration;
			if(downloadRuntimeParams(&config) == 0)
			{
				ACE_DEBUG((LM_DEBUG,"更新前置机参数,gwid[%d]",config._gwId));
				_configuration = config;
			}
			sleep_time = 0;
		}
		KSGThreadUtil::yield();
	}
	ACE_DEBUG((LM_INFO,"正在停止前置机..."));
	stop_all_proactor_acceptor();
	SchedulerGroup::Instance().TerminateAll();
	// 使用循环等待方式,控制超时
	/*
	while(_status == stRunning)
	{
		ACE_Time_Value tv(5);
		tv += ACE_OS::gettimeofday();
		ACE_DEBUG((LM_DEBUG,"等待超时,准备重试"));
	}
	*/
	_status = stStop;
	//_devgrpSchd.TerminateAll();
	stop_scheduler_algorithm();
	ACE_DEBUG((LM_INFO,"主流程运行结束"));
	exit();
	return 0;
}