コード例 #1
0
ファイル: F847126.c プロジェクト: nykma/ykt4sungard
int F847126(TRUSERID *handle,int iRequest,ST_PACK *rPack,int *pRetCode,char *szMsg)
{
	int	hi_cutid = 0;											//客户ID
	int	hi_cuttype = 0;										//客户类型
	int i=0;
	int ret = 0;
	int len = 0;
	char h_showcardid[11] = "";						//显示卡号
	char h_password[7] = "";							//卡密码
	double h_temp_Card_id = 0;						//卡号
	char seed_key[17] = "";							//种子密钥
	char card_endtime[8 + 1] = "";						//卡的有效截至日期
	char logicdate[11]="";								//业务日期
	char sysdate[11]="";
	char systime[9]="";
	char sMsg[256]="";
	char sMaxCardBalance[20]="";
	double dMaxCardBalance=0;
	int 	type=0;										//充值类型
	T_t_pif_card tCard;
	T_t_cif_customer tCustomer;
	T_t_aif_account  tAccount;
	T_t_tif_tradeserial  tradeserial;
	T_t_tif_savdtl		tSavdtl;
	T_t_pif_spefee 	tSpeFee;
	 T_t_pif_carddtl 	carddtl;
	double h_temp_Serial_no = 0;
	InAcc	IA;
	ST_CPACK aPack;
	ST_PACK *out_pack = &(aPack.pack);

	memset(&IA,0,sizeof(IA));
	memset(&tCard, 0, sizeof(tCard));
	memset(&tAccount,0,sizeof(tAccount));
	memset(&tradeserial,0,sizeof(tradeserial));
	memset(&tSpeFee,0,sizeof(tSpeFee));
	memset(&tCustomer,0,sizeof(tCustomer));
	memset(&tSavdtl,0,sizeof(tSavdtl));
	memset(&carddtl,0,sizeof(carddtl));

#ifdef DEBUG
	writelog(LOG_DEBUG,"rPack->scust_auth2[%s]",rPack->scust_auth2);
#endif
	ResetNormalCPack(&aPack,0,1);
	SetCol(handle,0);
	SetCol(handle,F_LVOL0,F_LVOL1,F_LVOL5,
				F_SCUST_NO,	F_SCUST_NO2,F_SCUST_AUTH,F_SCUST_AUTH2,
				F_SDATE0,F_SNAME,F_SNAME2,
				F_SOPEN_EMP,F_SSTATUS0,
				F_DAMT2,F_LSERIAL1,F_VSMESS,0);

	hi_cutid = rPack->lvol0;									//客户ID
	hi_cuttype = rPack->lvol3;									//客户类别
	des2src(h_showcardid,rPack->scust_no);					//显示卡号
	getsysdate(sysdate);
	getsystime(systime);
	ret=GetLogicDate(logicdate);								//业务日期
	if(ret)
	{
		*pRetCode=ret;
		goto L_RETU;
	}
	//检查客户信息,判断是否可以发行卡
	des2src(tCard.physical_no, rPack->sbank_acc);				//物理卡号
	trim(h_showcardid);
/*
	if(strlen(h_showcardid))
	{
		ret=IsExistShowCardNo(h_showcardid);
		if(ret)
		{
			*pRetCode = ret;
			goto L_RETU;
		}
	}
*/
	
	ret=IsExistShowCardNo(h_showcardid);
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}

	ret = UseShowCardNo(rPack->scust_limit,h_showcardid,CT_VIP);
	if(ret)
		return ret;
	
	ret=IsExistCardByPhyCardNo(tCard.physical_no);
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	ret=IsExistCardByCustomId(hi_cutid);
	if (ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	ret=DB_t_cif_customer_read_lock_by_cur_and_cut_id(hi_cutid, &tCustomer);
	if(ret)
	{
		writelog(LOG_ERR,"cut_id[%d]",hi_cutid);
		if(DB_NOTFOUND==ret)
			*pRetCode= E_CUSTOMER_NOT_EXIST;
		else
			*pRetCode= E_DB_CUSTOMER_R;
		goto L_RETU;
	}
	//得到收费类别
	if(tCustomer.fee_type<1)
	{
		ret=DB_t_pif_spefee_read_by_dept_code_and_cut_type(tCustomer.classdept_no, tCustomer.cut_type,&tSpeFee);
		if(ret)
		{
			if(DB_NOTFOUND==ret)
			{
				tCustomer.fee_type=tCustomer.cut_type;
			}
			else
			{
				DB_t_cif_customer_free_lock_cur();
				*pRetCode=E_DB_SPEFEE_R;
				goto L_RETU;
			}
		}
		else
		{
			tCustomer.fee_type=tSpeFee.fee_type;
		}
		//更新客户表的收费类别字段
		ret=DB_t_cif_customer_update_lock_by_cur(&tCustomer);
		if(ret)
		{
			if(DB_NOTFOUND==ret)
				*pRetCode= E_CUSTOMER_NOT_EXIST;
			else
				*pRetCode= E_DB_CUSTOMER_U;
			goto L_RETU;
		}
	}
	DB_t_cif_customer_free_lock_cur();

	tradeserial.trade_fee =rPack->damt0;

	//检查金额是否超过最大额度
	ret=GetParameter(GLOBE_MAXCARDBALANCE,sMaxCardBalance);
	if(ret)
	{
		*pRetCode=ret;
		goto L_RETU;
	}
	dMaxCardBalance=atof(sMaxCardBalance);

	if(amtcmp(tradeserial.trade_fee,dMaxCardBalance)>0)
	{
		writelog(LOG_ERR,"tradeserial.trade_fee[%lf]",tradeserial.trade_fee);
		*pRetCode=E_AMT_EXCEED_MAX;
		goto L_RETU;
	}
	//	准备数据插入卡信息表
	memcpy(seed_key,STATIC_SEED_KEY,sizeof(seed_key));			//读种子密钥
	ret=IsInvalidDateTime(rPack->sdate0,"YYYYMMDD");
	if(ret)
	{
		*pRetCode = E_INPUT_DATE;
		goto L_RETU;
	}
	if(strncmp(rPack->sdate0,sysdate,8)<=0)
	{
		*pRetCode=E_INPUT_DATE;
		goto L_RETU;
	}
	des2src(card_endtime,rPack->sdate0);
/*
	ret = GetCardValiddate(hi_cuttype,logicdate,card_endtime);				//计算卡的有效期
	if (ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
*/
	//	默认密码, 初始取身份证的后6位, 没有身份证号用666666.
	trim(rPack->sname2);
	len=strlen(rPack->sname2) ;
	if (len >= 6)
	{
		strncpy(h_password,&(rPack->sname2[len-6]),6);
		if(h_password[5]>'9'||h_password[5]<'0')
			h_password[5]='0';
	}
	else
	{
		strcpy(h_password,"666666");
	}
	ret = getNewUniqNo(KEYTYPE_CARD_ID,&h_temp_Card_id);						//获取最大卡号
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	tCard.card_id = (int)h_temp_Card_id;											//卡号
	des2src(tCard.showid,h_showcardid);										//显示卡号
	des2src(tCard.is_main,TYPE_YES);  											//是否为主卡
	des2src(tCard.state_id,CARDSTAT_REG);										//卡状态
	tCard.type_id = CT_VIP;													//卡类别
	EncodePwd(seed_key,h_password,tCard.password,0);							//卡密码
	tCard.cosumer_id = hi_cutid;													//客户标识
	tCard.account_count = ACCOUNT_COUNT_ONE;									//卡对应帐户个数
	des2src(tCard.begin_time,logicdate);											//注册时间
	des2src(tCard.end_time, card_endtime);										//截至时间

	tCard.phytype = PHYTYPE_NO_ONE;											//设备物理型号;默认为1
	//	插入卡信息
	ret = DB_t_pif_card_add(&tCard);
	if (ret)
	{
		if(DB_REPEAT==ret)
			*pRetCode = E_DB_CARD_E;
		else
			*pRetCode = E_DB_CARD_I;
		goto L_RETU;
	}

	//插入卡片操作情况表
	des2src(carddtl.accdate,sysdate);
	des2src(carddtl.acctime,systime);

	carddtl.termid=rPack->lvol6;												//上传工作站标识
	ret = getNewUniqNo(KEYTYPE_T_PIF_CARDDTL,&h_temp_Serial_no);						//获取流水号
	if(ret)
	{
		writelog(LOG_ERR,"getNewUniqNo[KEYTYPE_T_PIF_CARDDTL] ");
		return ret;
	}
	carddtl.termseqno = D2I(h_temp_Serial_no);
	des2src(carddtl.opercode,rPack->scust_limit);
	
	carddtl.cardtype=CT_VIP;
	carddtl.usetype[0]=CARDUSETYPE_USE;
	carddtl.inoutflag=INOUTFLAG_OUT;
	carddtl.transcnt=1;
	strcpy(carddtl.summary,"发行VIP 记名临时卡");
	des2src(carddtl.cardphyid,rPack->sbank_acc);
	des2src(carddtl.showcardno,h_showcardid);	
	ret=DB_t_pif_carddtl_add(&carddtl);
	if(ret)
	{
		if(DB_REPEAT==ret)
			return E_DB_CARDDTL_E;
		else
			return E_DB_CARDDTL_I;
	}
	
	//	准备数据插入帐户信息表
	ret = getNewActno(tAccount.account_id);  	    									//获得最大帐号
	if (ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	des2src(tAccount.open_date,sysdate);		   									//开户时间
	des2src(tAccount.open_time,systime);
	tAccount.current_state = ACCOUNTSTAT_REGIST;      								//当前状态
	tAccount.act_type = ACCTYPE_PERMAIN;				        						//帐号类别
	tAccount.customer_id = rPack->lvol0;				        						//客户号
	des2src(tAccount.cut_name,rPack->sname);										//客户名称
	tAccount.cut_type = hi_cuttype;													//客户类别
	des2src(tAccount.stuemp_no,rPack->scust_auth2); 								//客户学号或员工号
	tAccount.card_id = tCard.card_id;		 										//关联卡号
	tAccount.purse_id = PURSE_NO_ONE;											//关联卡钱包号
	tAccount.card_type = tCard.type_id;												//卡类别
	des2src(tAccount.subno,SUBJECT_INDIVIDUALSAVING);							//所属科目
	des2src(tAccount.isautotra,TYPE_NO); 											//是否自动转帐
	//	插入帐户信息表
	ret = DB_t_aif_account_add(&tAccount);
	if (ret)
	{
		writelog(LOG_ERR,"ret [%d]",ret);
		if(DB_REPEAT==ret)
			*pRetCode = E_DB_ACCOUNT_E;
		else
			*pRetCode = E_DB_ACCOUNT_I;
		goto L_RETU;
	}

	ret = getNewUniqNo(KEYTYPE_TRADESERIAL,&h_temp_Serial_no);  						//获得最大流水号
	if(ret)
	{
		*pRetCode = ret;
		writelog(LOG_ERR,"ret [%d]",ret);
		goto L_RETU;
	}
	// add by 汤成2005-09-05
	// 记录发行正式卡信息
	/////////////////////////////////////////////////////////////////////////
	ret = InsertToCutUpdList((int)h_temp_Card_id, CUTUPD_ADD);
	if( ret )
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	/////////////////////////////////////////////////////////////////////////
	tradeserial.serial_no = (int)h_temp_Serial_no;											//流水号
	tradeserial.other_seri_no = 0;														//上传端流水号
	tradeserial.serial_type=TXCODE_CARD_OPEN_VIP_CASH;								//交易码
	tradeserial.serial_state = SERISTAT_DEBT;												//流水状态
	des2src(tradeserial.operate_date,sysdate);											//发生日期
	des2src(tradeserial.operate_time,systime);											//发生时间
	des2src(tradeserial.collect_date,sysdate);												//采集日期
	des2src(tradeserial.collect_time,systime);												//采集时间
	des2src(tradeserial.enteract_date,logicdate);											//处理日期
	des2src(tradeserial.enteract_time,systime);											//处理时间

	tradeserial.maindevice_id = rPack->lvol6;												//上传工作站标识
	tradeserial.device_id = rPack->lvol7;													//采集设备标识
	tradeserial.card_id = tCard.card_id;													//卡号
	des2src(tradeserial.showid,tCard.showid);												//显示卡号
	tradeserial.purse_id = PURSE_NO_ONE;												//钱包号
	tradeserial.customer_id = hi_cutid;													//客户标识

	des2src(tradeserial.oper_code , rPack->scust_limit);									//操作员代码
	tradeserial.sys_id = 0;																//外部系统标识
	tradeserial.trade_count=1;															//当前卡交易次数
	type=rPack->lvol4;																//交易类型
	IA.dArrInAmt[0]=tradeserial.trade_fee;
	switch(type)
	{
		case TYPE_CASH:	//现金
			IA.iArrInFeeSwitch[1]=1;
			break;
		case TYPE_BILL:	//支票
			IA.iArrInFeeSwitch[2]=1;
			break;
		case TYPE_FUNDBOOK:	//经费本
			IA.iArrInFeeSwitch[3]=1;
			break;
		default:
			*pRetCode=E_INPUT_DEPOSIT_TYPE;
			goto L_RETU;
	}
	switch(type)
	{
		case TYPE_CASH:		//现金
			break;
 		case TYPE_BILL:		//支票
		case TYPE_FUNDBOOK:	//经费本
 			tSavdtl.amount=rPack->damt0;				//发生额
 			if(amtcmp(tSavdtl.amount,0)<=0)
				break;
			des2src(tSavdtl.bill_no,rPack->sphone);		//票据号码
			if(strlen(tSavdtl.bill_no)<1)
			{
				*pRetCode=E_INPUT_BILLNO;
				goto L_RETU;
			}
			tSavdtl.card_no=tCard.card_id;				//卡号
			des2src(tSavdtl.oper_no,rPack->scust_limit);	//操作员
			tSavdtl.seqno=tradeserial.serial_no;			//流水号
			des2src(tSavdtl.tx_date,logicdate);			//发生日期
			des2src(tSavdtl.tx_time,systime);			//发生时间
			tSavdtl.cnt=1;								//票据数量
			tSavdtl.bill_type=type;						//票据类型
			tSavdtl.tx_code=tradeserial.serial_type;		//交易码
			ret=DB_t_tif_savdtl_add(&tSavdtl);
			if(ret)
			{
				if(DB_REPEAT==ret)
					*pRetCode = E_DB_SAVDTL_E;
				else
					*pRetCode = E_DB_SAVDTL_I;
				goto L_RETU;
			}
			break;
		default:
			*pRetCode=E_TXCODE_NOT_EXIST;
			goto L_RETU;
	}
	des2src(IA.sArrInActno[0],tAccount.account_id);						//帐户
	IA.iCardNo=tCard.card_id;
	IA.iFeeType=tCustomer.fee_type;

	//调用入账子模块
	ret=process(&IA,&tradeserial);
	if(ret)
	{
		*pRetCode=ret;
		writelog(LOG_ERR,"process ret[%d]",ret);
		goto L_RETU;
	}
	sprintf(out_pack->vsmess,"流水号:%d 卡号:%d ",IA.iSerialNo,IA.iCardNo);
	for(i=1;i<=IA.iOutTxTypeCnt;i++)
	{
		switch(IA.iArrOutTxType[i])
		{
			case TXTYPE_TOLL_DEPOSIT:
			case TXTYPE_TOLL_DEPOSIT_BILL:
			case TXTYPE_TOLL_DEPOSIT_FUNDBOOK:
			case TXTYPE_DEDUCT_DEPOSIT:
			case TXTYPE_RETURN_DEPOSIT:
				tradeserial.deposit_fee=IA.dArrOutAmt[i];
				break;
			case TXTYPE_PRE_TOLL_BOARD:
			case TXTYPE_PRE_TOLL_BOARD_BILL:
			case TXTYPE_PRE_TOLL_BOARD_FUNDBOOK:
			case TXTYPE_TOLL_BOARD:
			case TXTYPE_DEDUCT_BOARD:
			case TXTYPE_RETURN_BOARD:
			case TXTYPE_RETURN_BOARD_BILL:
			case TXTYPE_RETURN_BOARD_FUNDBOOK:
				tradeserial.boardfee=IA.dArrOutAmt[i];
				break;
			case TXTYPE_TOLL_CHARGE:
			case TXTYPE_TOLL_CHARGE_BILL:
			case TXTYPE_TOLL_CHARGE_FUNDBOOK:
				tradeserial.in_fee=IA.dArrOutAmt[i];
				break;
			case TXTYPE_TOLL_CARDCOST:
			case TXTYPE_TOLL_CARDCOST_BILL:
			case TXTYPE_TOLL_CARDCOST_FUNDBOOK:
				tradeserial.cost_fee=IA.dArrOutAmt[i];
				break;
			default:
				break;
		}
		if(amtcmp(IA.dArrOutAmt[i],0)!=0)
		{
			sprintf(sMsg,"%s:%.2lf元 ",IA.sArrOutTxName[i],IA.dArrOutAmt[i]);
			strcat(out_pack->vsmess,sMsg);
		}
	}
	sprintf(sMsg,"卡当前余额:%.2lf元",tradeserial.out_balance);
	strcat(out_pack->vsmess,sMsg);
	writelog(LOG_DEBUG,out_pack->vsmess);
	// 插入交易流水表
	ret = DB_t_tif_tradeserial_add(&tradeserial);
	if (ret)
	{
		writelog(LOG_ERR,"ret[%d]",ret);
		if(DB_REPEAT==ret)
			*pRetCode = E_DB_TRADESERIAL_E;
		else
			*pRetCode = E_DB_TRADESERIAL_I;
		goto L_RETU;
	}
	if(amtcmp(tradeserial.out_balance,0)<0)
	{
		*pRetCode=E_ENTER_ACCOUNT;
		goto L_RETU;
	}
	//	返回卡号\密码\显示卡号\客户类型\图书证号\有效截至日期
	out_pack->lvol0 = (int)h_temp_Card_id;						//交易卡号
	out_pack->lvol1 = tCustomer.cut_type;						//客户类别
	out_pack->lvol5 = tCustomer.fee_type;						//收费类别
	des2src(out_pack->scust_no,h_showcardid);					//显示卡号
	des2src(out_pack->scust_no2,tCustomer.classdept_no);			//部门号
	des2src(out_pack->scust_auth,tCustomer.stuemp_no);			//学号
	des2src(out_pack->scust_auth2,tCustomer.man_id);			//身份证号
	des2src(out_pack->sname,tCustomer.cut_name);				//客户姓名
	des2src(out_pack->sname2,tCustomer.lib_cardid);				//图书证号
	des2src(out_pack->sstatus0,tCustomer.sex);					//性别
	des2src(out_pack->sopen_emp,h_password);					//卡密码
	des2src(out_pack->sdate0,card_endtime);					//有效截至日期
	out_pack->damt2=tradeserial.out_balance;					//出卡值
	out_pack->lserial1=tradeserial.serial_no;						//流水号
	PutRow(handle,out_pack,pRetCode,szMsg);
	return 0;
L_RETU:
	return -1;
}
コード例 #2
0
ファイル: filewatch.cpp プロジェクト: jgavert/Unvoid
// returns true if there was new data
bool FileWatch::update()
{
  process();
  return data.size() > 0;
}
コード例 #3
0
ファイル: inputmap.cpp プロジェクト: toughkidcst/mame
void ui_menu_input::handle()
{
	input_item_data *seqchangeditem = nullptr;
	const ui_menu_event *menu_event;
	int invalidate = false;

	/* process the menu */
	menu_event = process((pollingitem != nullptr) ? UI_MENU_PROCESS_NOKEYS : 0);

	/* if we are polling, handle as a special case */
	if (pollingitem != nullptr)
	{
		input_item_data *item = pollingitem;

		/* if UI_CANCEL is pressed, abort */
		if (ui_input_pressed(machine(), IPT_UI_CANCEL))
		{
			pollingitem = nullptr;
			record_next = false;
			toggle_none_default(item->seq, starting_seq, *item->defseq);
			seqchangeditem = item;
		}

		/* poll again; if finished, update the sequence */
		if (machine().input().seq_poll())
		{
			pollingitem = nullptr;
			record_next = true;
			item->seq = machine().input().seq_poll_final();
			seqchangeditem = item;
		}
	}

	/* otherwise, handle the events */
	else if (menu_event != nullptr && menu_event->itemref != nullptr)
	{
		input_item_data *item = (input_item_data *)menu_event->itemref;
		switch (menu_event->iptkey)
		{
			/* an item was selected: begin polling */
			case IPT_UI_SELECT:
				pollingitem = item;
				last_sortorder = item->sortorder;
				starting_seq = item->seq;
				machine().input().seq_poll_start((item->type == INPUT_TYPE_ANALOG) ? ITEM_CLASS_ABSOLUTE : ITEM_CLASS_SWITCH, record_next ? &item->seq : nullptr);
				invalidate = true;
				break;

			/* if the clear key was pressed, reset the selected item */
			case IPT_UI_CLEAR:
				toggle_none_default(item->seq, item->seq, *item->defseq);
				record_next = false;
				seqchangeditem = item;
				break;
		}

		/* if the selection changed, reset the "record next" flag */
		if (item->sortorder != last_sortorder)
			record_next = false;
		last_sortorder = item->sortorder;
	}

	/* if the sequence changed, update it */
	if (seqchangeditem != nullptr)
	{
		update_input(seqchangeditem);

		/* invalidate the menu to force an update */
		invalidate = true;
	}

	/* if the menu is invalidated, clear it now */
	if (invalidate)
	{
		pollingref = nullptr;
		if (pollingitem != nullptr)
		{
			pollingref = pollingitem->ref;
			pollingseq = pollingitem->seqtype;
		}
		reset(UI_MENU_RESET_REMEMBER_POSITION);
	}
}
コード例 #4
0
ファイル: Network.cpp プロジェクト: osushkov/vectornn
  Vector Process(const Vector &input) {
    assert(input.rows() == numInputs);

    NetworkContext ctx;
    return process(input, ctx);
  }
コード例 #5
0
void OscapScannerRemoteSsh::evaluate()
{
    if (mDryRun)
    {
        signalCompletion(mCancelRequested);
        return;
    }

    ensureConnected();

    if (mCancelRequested)
    {
        signalCompletion(true);
        return;
    }

    emit infoMessage(QObject::tr("Querying capabilities on remote machine..."));

    {
        SshSyncProcess proc(mSshConnection, this);
        proc.setCommand(SCAP_WORKBENCH_REMOTE_OSCAP_PATH);
        proc.setArguments(QStringList("--v"));
        proc.setCancelRequestSource(&mCancelRequested);
        proc.run();

        if (proc.getExitCode() != 0)
        {
            emit errorMessage(
                QObject::tr("Failed to query capabilities of oscap on local machine.\n"
                        "Diagnostic info:\n%1").arg(proc.getDiagnosticInfo())
            );

            mCancelRequested = true;
            signalCompletion(mCancelRequested);
            return;
        }

        mCapabilities.parse(proc.getStdOutContents());
    }

    if (!checkPrerequisites())
    {
        mCancelRequested = true;
        signalCompletion(mCancelRequested);
        return;
    }

    QStringList baseArgs;
    baseArgs.append("-o"); baseArgs.append(QString("ControlPath=%1").arg(mSshConnection._getMasterSocket()));
    baseArgs.append(mTarget);

    QString diagnosticInfo;

    emit infoMessage(QObject::tr("Copying input data to remote target..."));

    const QString inputFile = copyInputFileOver();
    const QString tailoringFile = mSession->hasTailoring() ?
        copyFileOver(mSession->getTailoringFilePath()) : QString();

    if (mCancelRequested)
    {
        signalCompletion(true);
        return;
    }

    const QString reportFile = createRemoteTemporaryFile();
    const QString resultFile = createRemoteTemporaryFile();
    const QString arfFile = createRemoteTemporaryFile();
    const QString workingDir = createRemoteTemporaryDirectory();

    // TODO: We could be leaking any of the temporary files at this point!
    if (mCancelRequested)
    {
        signalCompletion(true);
        return;
    }

    QStringList args;

    if (mScannerMode == SM_OFFLINE_REMEDIATION)
    {
        args = buildOfflineRemediationArgs(inputFile,
                resultFile,
                reportFile,
                arfFile);
    }
    else
    {
        args = buildEvaluationArgs(inputFile,
                tailoringFile,
                resultFile,
                reportFile,
                arfFile,
                mScannerMode == SM_SCAN_ONLINE_REMEDIATION);
    }

    const QString sshCmd = args.join(" ");

    emit infoMessage(QObject::tr("Starting the remote process..."));

    QProcess process(this);

    process.start(SCAP_WORKBENCH_LOCAL_SSH_PATH, baseArgs + QStringList(QString("cd '%1'; " SCAP_WORKBENCH_REMOTE_OSCAP_PATH " %2").arg(workingDir).arg(sshCmd)));
    process.waitForStarted();

    if (process.state() != QProcess::Running)
    {
        emit errorMessage(QObject::tr("Failed to start ssh. Perhaps the executable was not found?"));
        mCancelRequested = true;
    }

    const unsigned int pollInterval = 100;

    emit infoMessage(QObject::tr("Processing on the remote machine..."));
    while (!process.waitForFinished(pollInterval))
    {
        // read everything new
        readStdOut(process);
        watchStdErr(process);

        // pump the event queue, mainly because the user might want to cancel
        QAbstractEventDispatcher::instance(mScanThread)->processEvents(QEventLoop::AllEvents);

        if (mCancelRequested)
        {
            emit infoMessage(QObject::tr("Cancellation was requested! Terminating..."));
            // TODO: On Windows we have to kill immediately, terminate() posts WM_CLOSE
            //       but oscap doesn't have any event loop running.
            process.terminate();
            break;
        }
    }

    if (mCancelRequested)
    {
        unsigned int waited = 0;
        while (!process.waitForFinished(pollInterval))
        {
            waited += pollInterval;
            if (waited > 10000) // 10 seconds should be enough for the process to terminate
            {
                emit warningMessage(QObject::tr("The oscap process didn't terminate in time, it will be killed instead."));
                // if it didn't terminate, we have to kill it at this point
                process.kill();
                break;
            }
        }
    }
    else
    {
        // read everything left over
        readStdOut(process);
        watchStdErr(process);

        mResults = readRemoteFile(resultFile, QObject::tr("XCCDF results")).toUtf8();
        mReport = readRemoteFile(reportFile, QObject::tr("XCCDF report (HTML)")).toUtf8();
        mARF = readRemoteFile(arfFile, QObject::tr("Result DataStream (ARF)")).toUtf8();
    }

    emit infoMessage(QObject::tr("Cleaning up..."));

    // Remove all the temporary remote files
    removeRemoteFile(inputFile, QObject::tr("input file"));
    if (!tailoringFile.isEmpty())
        removeRemoteFile(tailoringFile, QObject::tr("tailoring file"));
    removeRemoteFile(resultFile, QObject::tr("XCCDF result file"));
    removeRemoteFile(reportFile, QObject::tr("XCCDF report file"));
    removeRemoteFile(arfFile, QObject::tr("Result DataStream file"));
    removeRemoteDirectory(workingDir, QObject::tr("Temporary Working Directory"));

    emit infoMessage(QObject::tr("Processing has been finished!"));
    signalCompletion(mCancelRequested);
}
コード例 #6
0
  Interpreter::CompilationResult
  MetaProcessor::readInputFromFile(llvm::StringRef filename,
                                   Value* result,
                                   size_t posOpenCurly,
                                   bool lineByLine) {

    // FIXME: This will fail for Unicode BOMs (and seems really weird)
    {
      // check that it's not binary:
      std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary);
      if (in.fail())
        return reportIOErr(filename, "open");

      char magic[1024] = {0};
      in.read(magic, sizeof(magic));
      size_t readMagic = in.gcount();
      // Binary files < 300 bytes are rare, and below newlines etc make the
      // heuristic unreliable.
      if (!in.fail() && readMagic >= 300) {
        llvm::StringRef magicStr(magic,in.gcount());
        llvm::file_magic fileType
          = llvm::identify_magic(magicStr);
        if (fileType != llvm::file_magic::unknown)
          return reportIOErr(filename, "read from binary");

        unsigned printable = 0;
        for (size_t i = 0; i < readMagic; ++i)
          if (isprint(magic[i]))
            ++printable;
        if (10 * printable <  5 * readMagic) {
          // 50% printable for ASCII files should be a safe guess.
          return reportIOErr(filename, "won't read from likely binary");
        }
      }
    }

    std::ifstream in(filename.str().c_str());
    if (in.fail())
      return reportIOErr(filename, "open");

    in.seekg(0, std::ios::end);
    if (in.fail())
      return reportIOErr(filename, "seek");

    size_t size = in.tellg();
    if (in.fail())
      return reportIOErr(filename, "tell");

    in.seekg(0);
    if (in.fail())
      return reportIOErr(filename, "rewind");

    std::string content(size, ' ');
    in.read(&content[0], size);
    if (in.fail())
      return reportIOErr(filename, "read");

    static const char whitespace[] = " \t\r\n";
    if (content.length() > 2 && content[0] == '#' && content[1] == '!') {
      // Convert shebang line to comment. That's nice because it doesn't
      // change the content size, leaving posOpenCurly untouched.
      content[0] = '/';
      content[1] = '/';
    }

    if (posOpenCurly != (size_t)-1 && !content.empty()) {
      assert(content[posOpenCurly] == '{'
             && "No curly at claimed position of opening curly!");
      // hide the curly brace:
      content[posOpenCurly] = ' ';
      // and the matching closing '}'
      size_t posCloseCurly = content.find_last_not_of(whitespace);
      if (posCloseCurly != std::string::npos) {
        if (content[posCloseCurly] == ';' && content[posCloseCurly-1] == '}') {
          content[posCloseCurly--] = ' '; // replace ';' and enter next if
        }
        if (content[posCloseCurly] == '}') {
          content[posCloseCurly] = ' '; // replace '}'
        } else {
          std::string::size_type posBlockClose = content.find_last_of('}');
          if (posBlockClose != std::string::npos) {
            content[posBlockClose] = ' '; // replace '}'
          }
          std::string::size_type posComment
            = content.find_first_not_of(whitespace, posBlockClose);
          if (posComment != std::string::npos
              && content[posComment] == '/' && content[posComment+1] == '/') {
            // More text (comments) are okay after the last '}', but
            // we can not easily find it to remove it (so we need to upgrade
            // this code to better handle the case with comments or
            // preprocessor code before and after the leading { and
            // trailing })
            while (posComment <= posCloseCurly) {
              content[posComment++] = ' '; // replace '}' and comment
            }
          } else {
            content[posCloseCurly] = '{';
            // By putting the '{' back, we keep the code as consistent as
            // the user wrote it ... but we should still warn that we not
            // goint to treat this file an unamed macro.
            cling::errs()
              << "Warning in cling::MetaProcessor: can not find the closing '}', "
              << llvm::sys::path::filename(filename)
              << " is not handled as an unamed script!\n";
          } // did not find "//"
        } // remove comments after the trailing '}'
      } // find '}'
    } // ignore outermost block

    m_CurrentlyExecutingFile = filename;
    bool topmost = !m_TopExecutingFile.data();
    if (topmost)
      m_TopExecutingFile = m_CurrentlyExecutingFile;

    content.insert(0, "#line 2 \"" + filename.str() + "\" \n");
    // We don't want to value print the results of a unnamed macro.
    if (content.back() != ';')
      content.append(";");

    Interpreter::CompilationResult ret = Interpreter::kSuccess;
    if (lineByLine) {
      int rslt = 0;
      std::string line;
      std::stringstream ss(content);
      while (std::getline(ss, line, '\n')) {
        rslt = process(line, ret, result);
        if (ret == Interpreter::kFailure)
          break;
      }
      if (rslt) {
        cling::errs() << "Error in cling::MetaProcessor: file "
                     << llvm::sys::path::filename(filename)
                     << " is incomplete (missing parenthesis or similar)!\n";
      }
    } else
      ret = m_Interp.process(content, result);

    m_CurrentlyExecutingFile = llvm::StringRef();
    if (topmost)
      m_TopExecutingFile = llvm::StringRef();
    return ret;
  }
コード例 #7
0
ファイル: F847104.cpp プロジェクト: nykma/ykt4sungard
int F847104(TRUSERID *handle,int iRequest,ST_PACK *rPack,int *pRetCode,char *szMsg)
{

	int ret =0;
	int len = 0;
	int i=0;
	int hi_cutid=0;
	char h_showcardid[11] = "";						//显示卡号
	char h_password[7] = "";							//卡密码
	double h_temp_Card_id = 0;						//卡号
	double dSerialNo=0;
	char seed_key[17] = "";							//种子密钥
	char card_endtime[8 + 1] = "";						//卡的有效截至日期
	char logicdate[11]="";								//业务日期
	char sysdate[11]="";
	char systime[9]="";
	char sEndDate[9]="";
	char sMsg[256]="";
	char sMaxCardBalance[20]="";
	char lost_date[11]="";
	double dMaxCardBalance=0;
	int lost_card_id=0;
	T_t_pif_card		tCard;
	T_t_pif_card		tOldCard;
	T_t_cif_customer 	tCustomer;
	T_t_pif_spefee 	tSpeFee;
    //	T_t_pif_cardlossinfo tCardLossInfo;
	T_t_tif_tradeserial  tradeserial;
	T_t_aif_account tAccount;
	InAcc  IA;
	ST_CPACK aPack;
	ST_PACK *out_pack = &(aPack.pack);
	ResetNormalCPack(&aPack,0,1);
	SetCol(handle,0);
	SetCol(handle,F_LVOL0,F_LVOL1,F_LVOL5,
           F_SCUST_NO,	F_SCUST_NO2,F_SCUST_AUTH,F_SCUST_AUTH2,
           F_SDATE0,F_SNAME,F_SNAME2,
           F_SOPEN_EMP,F_SSTATUS0,
           F_DAMT2,F_LSERIAL1,F_VSMESS,0);

	memset(&tCard,0,sizeof(tCard));
	memset(&tOldCard,0,sizeof(tOldCard));
	memset(&tCustomer,0,sizeof(tCustomer));
	memset(&tSpeFee,0,sizeof(tSpeFee));
    //	memset(&tCardLossInfo,0,sizeof(tCardLossInfo));
	memset(&tAccount,0,sizeof(tAccount));
	memset(&tradeserial,0,sizeof(tradeserial));
	memset(&IA,0,sizeof(IA));

	getsysdate(sysdate);
	getsystime(systime);
	ret=GetLogicDate(logicdate);										//业务日期
	if(ret)
	{
		*pRetCode=ret;
		goto L_RETU;
	}
	//检查客户信息,判断是否可以发行卡
	hi_cutid=rPack->lvol0;									//客户号
	des2src(tCard.physical_no, rPack->sbank_acc);				//物理卡号
	trim(h_showcardid);
	ret=IsExistFreezeCardByCustomId(hi_cutid);
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	ret=IsExistNoLostCardByCustomId(hi_cutid);
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	if(strlen(h_showcardid))
	{
		ret=IsExistShowCardNo(h_showcardid);
		if(ret)
		{
			*pRetCode = ret;
			goto L_RETU;
		}
	}
	ret=IsExistCardByPhyCardNo(tCard.physical_no);
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	ret=GetLostCardIdByCustomId_TypeId(hi_cutid,CT_NORMAL,&lost_card_id);
	if(ret)
	{
		writelog(LOG_ERR,"customer[%d]tCard type_id[%d]",hi_cutid,CT_NORMAL);
		*pRetCode = ret;
		goto L_RETU;
	}

    /*
      ret=DB_t_pif_cardlossinfo_read_by_card_id_and_state_id(lost_card_id, STATE_VALID, &tCardLossInfo);
      if(ret)
      {
      writelog(LOG_ERR,"lost_card_id[%d]",lost_card_id);
      if(DB_NOTFOUND==ret)
      *pRetCode =  E_CARDNO_NOT_EXIST;
      else
      *pRetCode =  E_DB_CARD_R;
      goto L_RETU;
      }
    */
	ret=get_latest_lost_date_by_card_no(lost_card_id,lost_date);
	if(ret)
	{
		writelog(LOG_ERR,"lost_card_id[%d]",lost_card_id);
		*pRetCode =ret;
		goto L_RETU;
	}
	//先检查客户的挂失的正式卡是否到了补办日期
	ret=GetLostCardValiddate(lost_date,sEndDate);
	if(ret)
	{
		*pRetCode =ret;
		goto L_RETU;
	}

	if(strncmp(sEndDate,sysdate,8)>0)
	{
		writelog(LOG_ERR,"lost_normal_card_id[%d]lost_date[%s]end_date[%s]",lost_card_id,lost_date,sEndDate);
		*pRetCode =  E_NORMALCARD_NOT_REACH_ENDDATE;
		goto L_RETU;
	}
    /*
	//更新卡挂失日期表中该卡状态为无效
	ret=UpdateCardLossInfoState(lost_card_id,STATE_VALID,STATE_INVALID);
	if(ret)
	{
    *pRetCode = ret;
    goto L_RETU;
	}
    */
	//注销原卡
	ret=DB_t_pif_card_read_lock_by_cur_and_card_id(lost_card_id,&tOldCard);
	if(ret)
	{
		writelog(LOG_ERR,"lost_card_id[%d]",lost_card_id);
		if(DB_NOTFOUND==ret)
			*pRetCode = E_CARDNO_NOT_EXIST;
		else
			*pRetCode =  E_DB_CARD_R;
		goto L_RETU;
	}
	des2src(tOldCard.state_id,CARDSTAT_LOGOUT);		//注销
	des2src(tOldCard.end_time,sysdate);				//注销日期
	ret=DB_t_pif_card_update_lock_by_cur(&tOldCard);
	if(ret)
	{
		writelog(LOG_ERR,"lost_card_id[%d]",lost_card_id);
		if(DB_NOTFOUND==ret)
			*pRetCode =   E_CARDNO_NOT_EXIST;
		else
			*pRetCode =  E_DB_CARD_R;
		goto L_RETU;
	}
	DB_t_pif_card_free_lock_by_cur();

	ret = InsertToCutUpdList(tOldCard.card_id,CUTUPD_CH_OLDCARD,tOldCard.physical_no);
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}

	ret=DB_t_cif_customer_read_lock_by_cur_and_cut_id(hi_cutid, &tCustomer);
	if(ret)
	{
		writelog(LOG_ERR,"cut_id[%d]",hi_cutid);
		if(DB_NOTFOUND==ret)
			*pRetCode= E_CUSTOMER_NOT_EXIST;
		else
			*pRetCode= E_DB_CUSTOMER_R;
		goto L_RETU;
	}
	//得到收费类别
	if(tCustomer.fee_type<1)
	{
		ret=DB_t_pif_spefee_read_by_dept_code_and_cut_type(tCustomer.classdept_no, tCustomer.cut_type,&tSpeFee);
		if(ret)
		{
			if(DB_NOTFOUND==ret)
			{
				tCustomer.fee_type=tCustomer.cut_type;
			}
			else
			{
				DB_t_cif_customer_free_lock_cur();
				*pRetCode=E_DB_SPEFEE_R;
				goto L_RETU;
			}
		}
		else
		{
			tCustomer.fee_type=tSpeFee.fee_type;
		}
		//更新客户表的收费类别字段
		ret=DB_t_cif_customer_update_lock_by_cur(&tCustomer);
		if(ret)
		{
			if(DB_NOTFOUND==ret)
				*pRetCode= E_CUSTOMER_NOT_EXIST;
			else
				*pRetCode= E_DB_CUSTOMER_U;
			goto L_RETU;
		}
	}
	DB_t_cif_customer_free_lock_cur();

	tradeserial.trade_fee =D4U5(rPack->damt0,2);
	//	准备数据插入卡信息表
	memcpy(seed_key,STATIC_SEED_KEY,16);			//读种子密钥
	if(strlen(tCustomer.can_time)==8)
	{
		ret=IsInvalidDateTime(tCustomer.can_time,"YYYYMMDD");
		if(ret)
		{
			*pRetCode=E_TB_CUSTOMER_ENDTIME;
			goto L_RETU;
		}
		if(strncmp(tCustomer.can_time,sysdate,8)<=0)
		{
			*pRetCode=E_TB_CUSTOMER_ENDTIME;
			goto L_RETU;
		}
		des2src(card_endtime,tCustomer.can_time);
	}
	else if(strlen(rPack->sdate0)==0)
	{
		*pRetCode=E_TB_CUSTOMER_NO_ENDTIME;
		goto L_RETU;
	}
	else
	{
		ret=IsInvalidDateTime(rPack->sdate0,"YYYYMMDD");
		if(ret)
		{
			*pRetCode = E_INPUT_DATE;
			goto L_RETU;
		}
		if(strncmp(rPack->sdate0,sysdate,8)<=0)
		{
			*pRetCode=E_INPUT_DATE;
			goto L_RETU;
		}
		des2src(card_endtime,rPack->sdate0);
	}

	tradeserial.trade_fee = rPack->damt0;								//金额
	tradeserial.other_seri_no = 0;										//上传端流水号
	tradeserial.serial_state = SERISTAT_DEBT;								//流水状态
	des2src(tradeserial.operate_date,sysdate);							//发生日期
	des2src(tradeserial.operate_time,systime);							//发生时间
	des2src(tradeserial.collect_date,sysdate);								//采集日期
	des2src(tradeserial.collect_time,systime);								//采集时间
	des2src(tradeserial.enteract_date,logicdate);							//处理日期
	des2src(tradeserial.enteract_time,systime);							//处理时间
	tradeserial.maindevice_id = rPack->lvol6;								//上传工作站标识
	tradeserial.device_id = rPack->lvol7;									//采集设备标识
	tradeserial.purse_id = PURSE_NO_ONE;								//钱包号
	tradeserial.customer_id = tCustomer.cut_id;							//客户标识
	tradeserial.sys_id = 0;												//外部系统标识
	des2src(tradeserial.oper_code, rPack->scust_limit);					//操作员号

	len=strlen(tCustomer.man_id) ;
	if (len >= 6)
	{
		strncpy(h_password,&(tCustomer.man_id[len-6]),6);
		if(h_password[5]>'9'||h_password[5]<'0')
			h_password[5]='0';
	}
	else
	{
		strcpy(h_password,DEFAULT_CUST_PWD);
	}
	ret = getNewUniqNo(KEYTYPE_CARD_ID,&h_temp_Card_id);						//获取最大卡号
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	tCard.card_id = D2I(h_temp_Card_id);											//卡号
	des2src(tCard.showid,h_showcardid);										//显示卡号
	des2src(tCard.is_main,TYPE_YES);  											//是否为主卡
	des2src(tCard.state_id,CARDSTAT_REG);										//卡状态
	tCard.type_id = CT_NORMAL;													//卡类别
	EncodePwd(seed_key,h_password,tCard.password,0);							//卡密码
	tCard.cosumer_id = hi_cutid;													//客户标识
	tCard.account_count = ACCOUNT_COUNT_ONE;									//卡对应帐户个数
	des2src(tCard.begin_time,sysdate);											//注册时间
	des2src(tCard.end_time, card_endtime);										//截至时间

	tCard.phytype = PHYTYPE_NO_ONE;											//设备物理型号;默认为1
	//	插入卡信息
	ret = DB_t_pif_card_add(&tCard);
	if (ret)
	{
		if(DB_REPEAT==ret)
			*pRetCode = E_DB_CARD_E;
		else
			*pRetCode = E_DB_CARD_I;
		goto L_RETU;
	}
	ret = InsertToCutUpdList(tCard.card_id,CUTUPD_CH_NEWCARD,tCard.physical_no);
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	
	//修改帐户表中对应的卡号,类型,状态
	ret=DB_t_aif_account_read_lock_by_c0_and_card_id_and_purse_id(lost_card_id,PURSE_NO_ONE,&tAccount);
	if (ret)
	{
		writelog(LOG_ERR,"normalcard_account_id[%s]",lost_card_id);
		if(DB_NOTFOUND==ret)
			*pRetCode =  E_ACTNO_NOT_EXIST;
		else
			*pRetCode =  E_DB_ACCOUNT_R;
	}
	if(tAccount.current_state!=1)
	{
		*pRetCode=E_ACTNO_LOGOUT;
		goto L_RETU;
	}
	tAccount.card_id=tCard.card_id;
	tAccount.card_balance=tAccount.cur_freebala;			//更新卡余额与库余额一致
	tAccount.consume_count=0;
	ret=DB_t_aif_account_update_lock_by_c0(&tAccount);
	if (ret)
	{
		writelog(LOG_ERR,"DB_t_aif_account_update_lock_by_cur4 ret[%d]account_id[%s]",ret,tAccount.account_id);
		if(DB_NOTFOUND==ret)
			*pRetCode =   E_ACTNO_EXIST;
		else
			*pRetCode =  E_DB_ACCOUNT_U;
	}
	DB_t_aif_account_free_lock_c0();

	ret = getNewUniqNo(KEYTYPE_TRADESERIAL,&dSerialNo);  						//获得最大流水号
	if(ret)
	{
		*pRetCode=ret;
		goto L_RETU;
	}
	tradeserial.serial_no=D2I(dSerialNo);
	tradeserial.serial_type=TXCODE_CHANGE_CARD;
	tradeserial.card_id=tCard.card_id;				//新卡号
	des2src(tradeserial.showid,tCard.showid);			//显示卡号

	strcpy(IA.sArrInActno[0],tAccount.account_id);		//账号
	IA.dArrInAmt[0]=tradeserial.trade_fee;			//交易金额
	IA.iUseCardFlag=USE_CARD_TYPE_ONLINE;		//联机交易
	IA.dInCardBala=tAccount.cur_freebala;			//入卡值
	IA.iTxCnt=1;
	IA.iCardNo=tCard.card_id;
	IA.iFeeType=tCustomer.fee_type;
	IA.iArrInFeeSwitch[0]=rPack->lvol0;
	IA.iArrInFeeSwitch[1]=rPack->lvol1;
	IA.iArrInFeeSwitch[2]=rPack->lvol2;
	IA.iArrInFeeSwitch[3]=rPack->lvol3;
	IA.iArrInFeeSwitch[4]=rPack->lvol4;
	IA.iArrInFeeSwitch[5]=rPack->lvol5;
	IA.iArrInFeeSwitch[6]=rPack->lvol6;
	IA.iArrInFeeSwitch[7]=rPack->lvol7;
	IA.iArrInFeeSwitch[8]=rPack->lvol8;
	IA.iArrInFeeSwitch[9]=rPack->lvol9;
	IA.iArrInFeeSwitch[10]=rPack->lvol10;
	ret=process(&IA,&tradeserial);
	if(ret)
	{
		writelog(LOG_ERR,"process ret[%d]",ret);
		*pRetCode=ret;
		goto L_RETU;
	}
	sprintf(out_pack->vsmess,"流水号:%d 卡号:%d ",IA.iSerialNo,IA.iCardNo);
	for(i=1;i<=IA.iOutTxTypeCnt;i++)
	{
		switch(IA.iArrOutTxType[i])
		{
        case TXTYPE_TOLL_DEPOSIT:
        case TXTYPE_DEDUCT_DEPOSIT:
        case TXTYPE_RETURN_DEPOSIT:
            tradeserial.deposit_fee=IA.dArrOutAmt[i];
            break;
        case TXTYPE_PRE_TOLL_BOARD:
        case TXTYPE_TOLL_BOARD:
        case TXTYPE_DEDUCT_BOARD:
        case TXTYPE_RETURN_BOARD:
            tradeserial.boardfee=IA.dArrOutAmt[i];
            break;
        case TXTYPE_TOLL_CHARGE:
            tradeserial.in_fee=IA.dArrOutAmt[i];
            break;
        case TXTYPE_TOLL_CARDCOST:
            tradeserial.cost_fee=IA.dArrOutAmt[i];
            break;
        default:
            break;
		}
		if(amtcmp(IA.dArrOutAmt[i],0)!=0)
		{
			sprintf(sMsg,"%s:%.2lf元 ",IA.sArrOutTxName[i],IA.dArrOutAmt[i]);
			strcat(out_pack->vsmess,sMsg);
		}
	}
	sprintf(sMsg,"卡当前余额:%.2lf元",tradeserial.out_balance);
	strcat(out_pack->vsmess,sMsg);
	writelog(LOG_DEBUG,out_pack->vsmess);
	ret = DB_t_tif_tradeserial_add(&tradeserial);
	if (ret)
	{
		writelog(LOG_ERR,"ret[%d]",ret);
		if(DB_REPEAT==ret)
			*pRetCode = E_DB_TRADESERIAL_E;
		else
			*pRetCode = E_DB_TRADESERIAL_I;
		goto L_RETU;
	}
	if(amtcmp(tradeserial.out_balance,0)<0)
	{
		*pRetCode=E_ENTER_ACCOUNT;
		goto L_RETU;
	}
	//检查金额是否超过最大额度
	ret=GetParameter(GLOBE_MAXCARDBALANCE,sMaxCardBalance);
	if(ret)
	{
		*pRetCode=ret;
		goto L_RETU;
	}
	dMaxCardBalance=atof(sMaxCardBalance);
	if(amtcmp(tradeserial.out_balance,dMaxCardBalance)>0)
	{
		writelog(LOG_ERR,"tradeserial.out_balance[%lf]",tradeserial.out_balance);
		*pRetCode=E_AMT_EXCEED_MAX;
		goto L_RETU;
	}

	//返回卡号\密码\显示卡号\客户类型\图书证号\有效截至日期
	out_pack->lvol0 = (int)h_temp_Card_id;						//交易卡号
	out_pack->lvol1 = tCustomer.cut_type;						//客户类别
	out_pack->lvol5 = tCustomer.fee_type;						//收费类别
	des2src(out_pack->scust_no,h_showcardid);					//显示卡号
	des2src(out_pack->scust_no2,tCustomer.classdept_no);			//部门号
	des2src(out_pack->scust_auth,tCustomer.stuemp_no);			//学号
	des2src(out_pack->scust_auth2,tCustomer.man_id);			//身份证号
	des2src(out_pack->sname,tCustomer.cut_name);				//客户姓名
	des2src(out_pack->sname2,tCustomer.lib_cardid);				//图书证号
	des2src(out_pack->sstatus0,tCustomer.sex);					//性别
	des2src(out_pack->sopen_emp,h_password);					//卡密码
	des2src(out_pack->sdate0,card_endtime);					//有效截至日期

	out_pack->damt2=tradeserial.out_balance;					//出卡值
	out_pack->lserial1=tradeserial.serial_no;						//流水号
	// add by 汤成 2005-8-8
	// 增加向名单表写入记录
	/*
	ret = InsertToBlkList((int)h_temp_Card_id,CHCARD_BLACKLIST);
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	*/
	PutRow(handle,out_pack,pRetCode,szMsg);
	return 0;
  L_RETU:
	return -1;
}
コード例 #8
0
ファイル: script_effector.cpp プロジェクト: OLR-xray/OLR-3.0
BOOL CScriptEffector::Process		(SPPInfo	&pp)
{
	return							(!!process(&pp));
}
コード例 #9
0
ファイル: ecs.hpp プロジェクト: respu/microecs
	void process(std::vector<Entity>& entities) {
		for(Entity& e : entities) process(e);
	}
コード例 #10
0
ファイル: lspst.c プロジェクト: mhorbul/libpst
int main(int argc, char* const* argv) {
    pst_item *item = NULL;
    pst_desc_tree *d_ptr;
    char *temp  = NULL; //temporary char pointer
    int  c;
    char *d_log = NULL;

	while ((c = getopt(argc, argv, "d:hV"))!= -1) {
		switch (c) {
			case 'd':
				d_log = optarg;
				break;
			case 'h':
				usage(argv[0]);
				exit(0);
				break;
			case 'V':
				version();
				exit(0);
				break;
			default:
				usage(argv[0]);
				exit(1);
				break;
		}
	}

    #ifdef DEBUG_ALL
        // force a log file
        if (!d_log) d_log = "lspst.log";
    #endif // defined DEBUG_ALL
    DEBUG_INIT(d_log, NULL);
    DEBUG_ENT("main");

	if (argc <= optind) {
		usage(argv[0]);
		exit(2);
	}

    // Open PST file
    if (pst_open(&pstfile, argv[optind], NULL)) DIE(("Error opening File\n"));

    // Load PST index
    if (pst_load_index(&pstfile)) DIE(("Index Error\n"));

    pst_load_extended_attributes(&pstfile);

    d_ptr = pstfile.d_head; // first record is main record
    item  = pst_parse_item(&pstfile, d_ptr, NULL);
    if (!item || !item->message_store) {
        DEBUG_RET();
        DIE(("Could not get root record\n"));
    }

    // default the file_as to the same as the main filename if it doesn't exist
    if (!item->file_as.str) {
        if (!(temp = strrchr(argv[1], '/')))
            if (!(temp = strrchr(argv[1], '\\')))
                temp = argv[1];
            else
                temp++; // get past the "\\"
        else
            temp++; // get past the "/"
        item->file_as.str = strdup(temp);
        item->file_as.is_utf8 = 1;
    }

    d_ptr = pst_getTopOfFolders(&pstfile, item);
    if (!d_ptr) DIE(("Top of folders record not found. Cannot continue\n"));

    process(item, d_ptr->child);    // do the childred of TOPF
    pst_freeItem(item);
    pst_close(&pstfile);

    DEBUG_RET();
    return 0;
}
コード例 #11
0
ファイル: lspst.c プロジェクト: mhorbul/libpst
void process(pst_item *outeritem, pst_desc_tree *d_ptr)
{
    struct file_ll ff;
    pst_item *item = NULL;
    char *result = NULL;
    size_t resultlen = 0;

    DEBUG_ENT("process");
    memset(&ff, 0, sizeof(ff));
    create_enter_dir(&ff, outeritem);

    while (d_ptr) {
        if (!d_ptr->desc) {
            DEBUG_WARN(("ERROR item's desc record is NULL\n"));
            ff.skip_count++;
        }
        else {
            DEBUG_INFO(("Desc Email ID %"PRIx64" [d_ptr->d_id = %"PRIx64"]\n", d_ptr->desc->i_id, d_ptr->d_id));

            item = pst_parse_item(&pstfile, d_ptr, NULL);
            DEBUG_INFO(("About to process item @ %p.\n", item));
            if (item) {
                if (item->message_store) {
                    // there should only be one message_store, and we have already done it
                    DIE(("A second message_store has been found. Sorry, this must be an error.\n"));
                }

                if (item->folder && d_ptr->child) {
                    // if this is a folder, we want to recurse into it
                    pst_convert_utf8(item, &item->file_as);
                    printf("Folder \"%s\"\n", item->file_as.str);
                    process(item, d_ptr->child);

                } else if (item->contact && (item->type == PST_TYPE_CONTACT)) {
                    if (!ff.type) ff.type = item->type;
                    // Process Contact item
                    if (ff.type != PST_TYPE_CONTACT) {
                        DEBUG_INFO(("I have a contact, but the folder isn't a contacts folder. Processing anyway\n"));
                    }
                    printf("Contact");
                    if (item->contact->fullname.str)
                        printf("\t%s", pst_rfc2426_escape(item->contact->fullname.str, &result, &resultlen));
                    printf("\n");

                } else if (item->email && ((item->type == PST_TYPE_NOTE) || (item->type == PST_TYPE_SCHEDULE) || (item->type == PST_TYPE_REPORT))) {
                    if (!ff.type) ff.type = item->type;
                    // Process Email item
                    if ((ff.type != PST_TYPE_NOTE) && (ff.type != PST_TYPE_SCHEDULE) && (ff.type != PST_TYPE_REPORT)) {
                        DEBUG_INFO(("I have an email, but the folder isn't an email folder. Processing anyway\n"));
                    }
                    printf("Email");
                    if (item->email->outlook_sender_name.str)
                        printf("\tFrom: %s", item->email->outlook_sender_name.str);
                    if (item->subject.str)
                        printf("\tSubject: %s", item->subject.str);
                    printf("\n");

                } else if (item->journal && (item->type == PST_TYPE_JOURNAL)) {
                    if (!ff.type) ff.type = item->type;
                    // Process Journal item
                    if (ff.type != PST_TYPE_JOURNAL) {
                        DEBUG_INFO(("I have a journal entry, but folder isn't specified as a journal type. Processing...\n"));
                    }
                    if (item->subject.str)
                        printf("Journal\t%s\n", pst_rfc2426_escape(item->subject.str, &result, &resultlen));

                } else if (item->appointment && (item->type == PST_TYPE_APPOINTMENT)) {
                    char time_buffer[30];
                    if (!ff.type) ff.type = item->type;
                    // Process Calendar Appointment item
                    DEBUG_INFO(("Processing Appointment Entry\n"));
                    if (ff.type != PST_TYPE_APPOINTMENT) {
                        DEBUG_INFO(("I have an appointment, but folder isn't specified as an appointment type. Processing...\n"));
                    }
                    printf("Appointment");
                    if (item->subject.str)
                        printf("\tSUMMARY: %s", pst_rfc2426_escape(item->subject.str, &result, &resultlen));
                    if (item->appointment->start)
                        printf("\tSTART: %s", pst_rfc2445_datetime_format(item->appointment->start, sizeof(time_buffer), time_buffer));
                    if (item->appointment->end)
                        printf("\tEND: %s", pst_rfc2445_datetime_format(item->appointment->end, sizeof(time_buffer), time_buffer));
                    printf("\tALL DAY: %s", (item->appointment->all_day==1 ? "Yes" : "No"));
                    printf("\n");

                } else {
                    ff.skip_count++;
                    DEBUG_INFO(("Unknown item type. %i. Ascii1=\"%s\"\n",
                                      item->type, item->ascii_type));
                }
                pst_freeItem(item);
            } else {
                ff.skip_count++;
                DEBUG_INFO(("A NULL item was seen\n"));
            }
        }
        d_ptr = d_ptr->next;
    }
    close_enter_dir(&ff);
    if (result) free(result);
    DEBUG_RET();
}
コード例 #12
0
ファイル: main.c プロジェクト: jasonbking/illumos-gate
int
main(int argc, char *argv[])
{
	int c, fflag;
	char *temp_arg;

	(void) setlocale(LC_ALL, "");

#ifndef TEXT_DOMAIN
#define	TEXT_DOMAIN	"SYS_TEST"
#endif
	(void) textdomain(TEXT_DOMAIN);

	fflag = 0;
	inplace = NULL;

	while ((c = getopt_long(argc, argv, "EI::ae:f:i::lnr", lopts, NULL)) !=
	    -1)
		switch (c) {
		case 'r':		/* Gnu sed compat */
		case 'E':
			rflags = REG_EXTENDED;
			break;
		case 'I':
			if (optarg != NULL)
				inplace = optarg;
			else
				inplace = "";
			ispan = 1;	/* span across input files */
			break;
		case 'a':
			aflag = 1;
			break;
		case 'e':
			eflag = 1;
			if (asprintf(&temp_arg, "%s\n", optarg) < 1)
				err(1, "asprintf");
			add_compunit(CU_STRING, temp_arg);
			break;
		case 'f':
			fflag = 1;
			add_compunit(CU_FILE, optarg);
			break;
		case 'i':
			if (optarg != NULL)
				inplace = optarg;
			else
				inplace = "";
			ispan = 0;	/* don't span across input files */
			break;
		case 'l':
			/* On SunOS, setlinebuf "returns no useful value */
			(void) setlinebuf(stdout);
			break;
		case 'n':
			nflag = 1;
			break;
		default:
		case '?':
			usage();
		}
	argc -= optind;
	argv += optind;

	/* First usage case; script is the first arg */
	if (!eflag && !fflag && *argv) {
		add_compunit(CU_STRING, *argv);
		argv++;
	}

	compile();

	/* Continue with first and start second usage */
	if (*argv)
		for (; *argv; argv++)
			add_file(*argv);
	else
		add_file(NULL);
	process();
	cfclose(prog, NULL);
	if (fclose(stdout))
		err(1, "stdout");
	return (rval);
}
コード例 #13
0
ファイル: soelim.c プロジェクト: AhmadTux/DragonFlyBSD
static int
process(const char *file)
{
	char *cp;
	int c;
	char fname[BUFSIZ];
	FILE *soee;
	int isfile;

	if (!strcmp(file, STDIN_NAME)) {
		soee = stdin;
	} else {
		soee = fopen(file, "r");
		if (soee == NULL) {
			warn("%s", file);
			return(-1);
		}
	}
	for (;;) {
		c = getc(soee);
		if (c == EOF)
			break;
		if (c != '.')
			goto simple;
		c = getc(soee);
		if (c != 's') {
			putchar('.');
			goto simple;
		}
		c = getc(soee);
		if (c != 'o') {
			printf(".s");
			goto simple;
		}
		do
			c = getc(soee);
		while (c == ' ' || c == '\t');
		cp = fname;
		isfile = 0;
		for (;;) {
			switch (c) {

			case ' ':
			case '\t':
			case '\n':
			case EOF:
				goto donename;

			default:
				*cp++ = c;
				c = getc(soee);
				isfile++;
				continue;
			}
		}
donename:
		if (cp == fname) {
			printf(".so");
			goto simple;
		}
		*cp = 0;
		if (process(fname) < 0)
			if (isfile)
				printf(".so %s\n", fname);
		continue;
simple:
		if (c == EOF)
			break;
		putchar(c);
		if (c != '\n') {
			c = getc(soee);
			goto simple;
		}
	}
	if (soee != stdin) {
		fclose(soee);
	}
	return(0);
}
コード例 #14
0
ファイル: Thread.cpp プロジェクト: tritao/ds2
void Thread::updateState(DEBUG_EVENT const &de) {
  DS2ASSERT(de.dwThreadId == _tid);

  switch (de.dwDebugEventCode) {
  case EXCEPTION_DEBUG_EVENT:
    _state = kStopped;
    _trap.event = StopInfo::kEventTrap;
    _trap.reason = StopInfo::kReasonNone;
    break;

  case LOAD_DLL_DEBUG_EVENT: {
    ErrorCode error;
    std::wstring name = L"<NONAME>";

    ProcessInfo pi;
    error = process()->getInfo(pi);
    if (error != kSuccess)
      goto noname;

    if (de.u.LoadDll.lpImageName == nullptr)
      goto noname;

    uint64_t ptr = 0;
    error = process()->readMemory(
        reinterpret_cast<uint64_t>(de.u.LoadDll.lpImageName), &ptr,
        pi.pointerSize);
    if (error != kSuccess)
      goto noname;

    if (ptr == 0)
      goto noname;

    // It seems like all strings passed by the kernel here are guaranteed to be
    // unicode.
    DS2ASSERT(de.u.LoadDll.fUnicode);

    name.clear();
    wchar_t c;
    do {
      error = process()->readMemory(ptr, &c, sizeof(c));
      if (error != kSuccess)
        break;
      name.append(1, c);

      ptr += sizeof(c);
    } while (c != '\0');

  noname:
    DS2LOG(Debug, "new DLL loaded: %s",
           Host::Platform::WideToNarrowString(name).c_str());

    if (de.u.LoadDll.hFile != NULL)
      CloseHandle(de.u.LoadDll.hFile);
  }

  case UNLOAD_DLL_DEBUG_EVENT:
  case OUTPUT_DEBUG_STRING_EVENT:
    _state = kStopped;
    _trap.event = StopInfo::kEventNone;
    _trap.reason = StopInfo::kReasonNone;
    break;

  default:
    DS2BUG("unknown debug event code: %d", de.dwDebugEventCode);
  }
}
コード例 #15
0
ファイル: i2ctalk.c プロジェクト: Xalior/minifs
int main(int argc, const char * argv[])
{
	const char * hex = "0123456789abcdef";

	self = basename((char*)argv[0]);

	for (int ai = 1; ai < argc; ai++) {
		const char * src = argv[ai];
		display_mode[ai] = NULL;

		if (!strcmp(argv[ai], "--loop")) {
			bus = 4;
			msg[0].addr = 0x55;
			msg_count = 1;

			while (1) {
				process();
				sleep(1);
			}
		}
		while (*src) {
			char c = *src++;
			switch (c) {
				case '=': {
					if (process() > 0)
						display();
					bus = 0;
					while (isdigit(*src))
						bus = (bus * 10) + (*src++ - '0');
				}	break;
				case '@': {
					if (process() > 0)
						display();

					address = 0;
					while (isxdigit(*src))
						address = (address << 4) | (int)(strchr(hex, tolower(*src++)) - hex);
				//	printf("Set address to 0x%2x\n", address);
				}	break;
				case 'w': {
					msg[msg_count].addr = address;
					msg[msg_count].flags = 0;
					msg[msg_count].len = 0;
					msg[msg_count].buf = write_ptr;
					while (isxdigit(src[0]) && isxdigit(src[1])) {
						uint8_t byte = ((strchr(hex, tolower(src[0])) - hex) << 4) |
								(int)(strchr(hex, tolower(src[1])) - hex);
						src += 2;
						*write_ptr++ = byte;
						msg[msg_count].len++;
					}
					if (msg[msg_count].len) {
					//	printf("Write %d bytes : ", msg[msg_count].len);
					//	for (int i = 0; i < msg[msg_count].len; i++)
					//		printf("%02x", msg[msg_count].buf[i]);
					//	printf("\n");
						msg_count++;
					} else {
						fprintf(stderr, "%s: Warning '%s' won't write anything\n", self, argv[ai]);
					}
				}	break;
				case 'r': {
					msg[msg_count].addr = address;
					msg[msg_count].flags = I2C_M_RD;
					msg[msg_count].len = 0;
					msg[msg_count].buf = write_ptr;
					display_mode[msg_count] = src; // keep it around for display

					int count = 0;
					while (*src) {
						switch (*src) {
							case '0' ... '9' :
								count = (count*10) + (*src++ - '0');
								break;
							case 'b':
								count = count ? count : 1;
								msg[msg_count].len += count;
								write_ptr += count;
								count = 0;
								src++;
								break;
							case 's':
								count = count ? count * 2 : 2;
								msg[msg_count].len += count;
								write_ptr += count;
								count = 0;
								src++;
								break;
							case 't':	// temperature
								count = 2;
								msg[msg_count].len += count;
								write_ptr += count;
								count = 0;
								src++;
								break;
							case 'l':
								count = count ? count * 4 : 4;
								msg[msg_count].len += count;
								write_ptr += count;
								count = 0;
								src++;
								break;
							case 'g':		// gyro from MotionPlus
								count = 6;
								msg[msg_count].len += count;
								write_ptr += count;
								count = 0;
								src++;
								break;
							case 'c':		// compass module
								count = 5;
								msg[msg_count].len += count;
								write_ptr += count;
								count = 0;
								src++;
								break;
							case 'a':		// accelerometer
								count = 6;
								msg[msg_count].len += count;
								write_ptr += count;
								count = 0;
								src++;
								break;
							case ' ':
								break;
							default:
								printf("Unknown format '%c' for reading\n", c);
								exit(1);
						}
					}
					if (msg[msg_count].len) {
					//	printf("Reading %d bytes\n", msg[msg_count].len);
						msg_count++;
					} else {
						display_mode[msg_count] = NULL;
						fprintf(stderr, "%s: Warning '%s' won't read anything\n", self, argv[ai]);
					}
				}	break;
				case ' ':
					break;
				default:
					fprintf(stderr, "%s: ERROR Unknown command character '%c'\n", self, c);
					exit(1);
			}
		}
	}
	if (process() > 0)
		display();
}
コード例 #16
0
int
main(int argc, char *argv[])
{
	unsigned char msg[MSG_SIZE];
	char pidstr[16];
	int c, log_method;
	char *logfile, *pidfile;
	 sigset_t oset, nset;
	int facility, fd;
	char *username = NULL;
	char *chrootdir = NULL;
#ifdef HAVE_GETOPT_LONG
	int opt_idx;
#endif

	pname = ((pname=strrchr(argv[0],'/')) != NULL)?pname+1:argv[0];

	srand((unsigned int)time(NULL));

	log_method = L_STDERR_SYSLOG;
	logfile = PATH_RADVD_LOG;
	conf_file = PATH_RADVD_CONF;
	facility = LOG_FACILITY;
	pidfile = PATH_RADVD_PID;

	/* parse args */
#ifdef HAVE_GETOPT_LONG
	while ((c = getopt_long(argc, argv, "d:C:l:m:p:t:u:vh", prog_opt, &opt_idx)) > 0)
#else
	while ((c = getopt(argc, argv, "d:C:l:m:p:t:u:vh")) > 0)
#endif
	{
		switch (c) {
		case 'C':
			conf_file = optarg;
			break;
		case 'd':
			set_debuglevel(atoi(optarg));
			break;
		case 'f':
			facility = atoi(optarg);
			break;
		case 'l':
			logfile = optarg;
			break;
		case 'p':
			pidfile = optarg;
			break;
		case 'm':
			if (!strcmp(optarg, "syslog"))
			{
				log_method = L_SYSLOG;
			}
			else if (!strcmp(optarg, "stderr_syslog"))
			{
				log_method = L_STDERR_SYSLOG;
			}
			else if (!strcmp(optarg, "stderr"))
			{
				log_method = L_STDERR;
			}
			else if (!strcmp(optarg, "logfile"))
			{
				log_method = L_LOGFILE;
			}
			else if (!strcmp(optarg, "none"))
			{
				log_method = L_NONE;
			}
			else
			{
				fprintf(stderr, "%s: unknown log method: %s\n", pname, optarg);
				exit(1);
			}
			break;
		case 't':
			chrootdir = strdup(optarg);
			break;
		case 'u':
			username = strdup(optarg);
			break;
		case 'v':
			version();
			break;
		case 'h':
			usage();
#ifdef HAVE_GETOPT_LONG
		case ':':
			fprintf(stderr, "%s: option %s: parameter expected\n", pname,
				prog_opt[opt_idx].name);
			exit(1);
#endif
		case '?':
			exit(1);
		}
	}

	if (chrootdir) {
		if (!username) {
			fprintf(stderr, "Chroot as root is not safe, exiting\n");
			exit(1);
		}
		
		if (chroot(chrootdir) == -1) {
			perror("chroot");
			exit (1);
		}
		
		if (chdir("/") == -1) {
			perror("chdir");
			exit (1);
		}
		/* username will be switched later */
	}
	
	if (log_open(log_method, pname, logfile, facility) < 0)
		exit(1);

	flog(LOG_INFO, "version %s started", VERSION);

	/* get a raw socket for sending and receiving ICMPv6 messages */
	sock = open_icmpv6_socket();
	if (sock < 0)
		exit(1);

	/* drop root privileges if requested. */
	if (username) {
		if (drop_root_privileges(username) < 0)
			exit(1);
	}

#if 0 //brcm: no need to check
	/* check that 'other' cannot write the file
         * for non-root, also that self/own group can't either
         */
	if (check_conffile_perm(username, conf_file) < 0) {
		if (get_debuglevel() == 0)
			exit(1);
		else
			flog(LOG_WARNING, "Insecure file permissions, but continuing anyway");
	}
	
	/* if we know how to do it, check whether forwarding is enabled */
	if (check_ip6_forwarding()) {
		if (get_debuglevel() == 0) {
			flog(LOG_ERR, "IPv6 forwarding seems to be disabled, exiting");
			exit(1);
		}
		else
			flog(LOG_WARNING, "IPv6 forwarding seems to be disabled, but continuing anyway.");
	}
#endif

	/* parse config file */
	if (readin_config(conf_file) < 0)
		exit(1);

	/* FIXME: not atomic if pidfile is on an NFS mounted volume */	
	if ((fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644)) < 0)
	{
		flog(LOG_ERR, "another radvd seems to be already running, terminating");
		exit(1);
	}
	
	/*
	 * okay, config file is read in, socket and stuff is setup, so
	 * lets fork now...
	 */
#if 0 //brcm
	if (get_debuglevel() == 0) {
		/* Detach from controlling terminal */
		if (daemon(0, 0) < 0)
			perror("daemon");

		/* close old logfiles, including stderr */
		log_close();
		
		/* reopen logfiles, but don't log to stderr unless explicitly requested */
		if (log_method == L_STDERR_SYSLOG)
			log_method = L_SYSLOG;
		if (log_open(log_method, pname, logfile, facility) < 0)
			exit(1);

	}
#endif

	/*
	 *	config signal handlers, also make sure ALRM isn't blocked and raise a warning if so
	 *      (some stupid scripts/pppd appears to do this...)
	 */
	sigemptyset(&nset);
	sigaddset(&nset, SIGALRM);
	sigprocmask(SIG_UNBLOCK, &nset, &oset);
	if (sigismember(&oset, SIGALRM))
		flog(LOG_WARNING, "SIGALRM has been unblocked. Your startup environment might be wrong.");

	signal(SIGHUP, sighup_handler);
	signal(SIGTERM, sigterm_handler);
	signal(SIGINT, sigint_handler);

	snprintf(pidstr, sizeof(pidstr), "%d\n", getpid());
	
	write(fd, pidstr, strlen(pidstr));
	
	close(fd);

	config_interface();
	kickoff_adverts();

	/* enter loop */

	for (;;)
	{
		int len, hoplimit;
		struct sockaddr_in6 rcv_addr;
		struct in6_pktinfo *pkt_info = NULL;
		
		len = recv_rs_ra(sock, msg, &rcv_addr, &pkt_info, &hoplimit);
		if (len > 0)
			process(sock, IfaceList, msg, len, 
				&rcv_addr, pkt_info, hoplimit);

		if (sigterm_received || sigint_received) {
			stop_adverts();
			break;
		}

		if (sighup_received)
		{
			reload_config();		
			sighup_received = 0;
		}
	}
	
	unlink(pidfile);
	exit(0);
}
コード例 #17
0
bool EventDispatcherEPollPrivate::processEvents(QEventLoop::ProcessEventsFlags flags)
{
    Q_Q(EventDispatcherEPoll);

    const bool exclude_notifiers = (flags & QEventLoop::ExcludeSocketNotifiers);
    const bool exclude_timers    = (flags & QEventLoop::X11ExcludeTimers);

    exclude_notifiers && disableSocketNotifiers(true);
    exclude_timers    && disableTimers(true);

    m_interrupt = false;
    Q_EMIT q->awake();

    bool result = q->hasPendingEvents();

    QCoreApplication::sendPostedEvents();

    bool can_wait =
            !m_interrupt
            && (flags & QEventLoop::WaitForMoreEvents)
            && !result
            ;

    int n_events = 0;

    if (!m_interrupt) {
        int timeout = 0;

        if (!exclude_timers && !m_zero_timers.isEmpty()) {
            QVector<ZeroTimer*> timers;
            auto it = m_zero_timers.constBegin();
            while (it != m_zero_timers.constEnd()) {
                ZeroTimer *data = it.value();
                data->ref();
                timers.push_back(data);
                ++it;
            }

            for (ZeroTimer *data : timers) {
                if (data->canProcess() && data->active) {
                    data->active = false;

                    QTimerEvent event(data->timerId);
                    QCoreApplication::sendEvent(data->object, &event);

                    result = true;
                    if (!data->active) {
                        data->active = true;
                    }
                }

                data->deref();
            }
        }

        if (can_wait && !result) {
            Q_EMIT q->aboutToBlock();
            timeout = -1;
        }

        struct epoll_event events[10024];
        do {
            n_events = epoll_wait(m_epoll_fd, events, 10024, timeout);
        } while (Q_UNLIKELY(-1 == n_events && errno == EINTR));

        for (int i = 0; i < n_events; ++i) {
            struct epoll_event &e = events[i];
            auto data = static_cast<EpollAbastractEvent*>(e.data.ptr);
            data->ref();
        }

        for (int i = 0; i < n_events; ++i) {
            struct epoll_event &e = events[i];
            auto data = static_cast<EpollAbastractEvent*>(e.data.ptr);
            if (data->canProcess()) {
                data->process(e.events);
            }

            data->deref();
        }
    }

    exclude_notifiers && disableSocketNotifiers(false);
    exclude_timers    && disableTimers(false);

    return result || n_events > 0;
}
コード例 #18
0
bool ICQListEvent::processAnswer(ICQClient *client, Buffer&, unsigned short result)
{
    if (process(client, result))
        client->process_event(this);
    return true;
}
コード例 #19
0
ファイル: tf3synth.cpp プロジェクト: DX94/Enigma-Studio-3
//-----------------------------------------------------------------------------------------
void tf3Synth::processReplacing (eF32 **inputs, eF32 **outputs, long sampleFrames)
{
	memset (outputs[0], 0, sampleFrames * sizeof (eF32));
	memset (outputs[1], 0, sampleFrames * sizeof (eF32));
	process (inputs, outputs, sampleFrames);
}
コード例 #20
0
ファイル: MODIFY.CPP プロジェクト: abishekahluwaila/read
void do_modify ( TWindow *parent )
{
   int nsigs, type ;
	char error[256], rest[256] ;
	ModifyDialog *mod ;
   Signal **signals ;

   nsigs = get_signals ( &signals ) ;
	mod = new ModifyDialog ( parent , nsigs , signals ) ;

	if (mod->Execute() == IDOK) {

      if (mod->parm_type == ID_PRED_CENTER) {
         if (mod->parm_undo)
            type = ID_PRED_UNDO_CENTER ;
         else if (mod->parm_median)
            type = ID_PRED_MEDIAN_CENTER ;
         else 
            type = ID_PRED_CENTER ;
         strcpy ( rest , mod->source_name ) ;
         }

      else if (mod->parm_type == ID_PRED_DETREND) {
         if (mod->parm_undo)
            type = ID_PRED_UNDO_DETREND ;
         else 
            type = ID_PRED_DETREND ;
         strcpy ( rest , mod->source_name ) ;
         }

      else if (mod->parm_type == ID_PRED_OFFSET) {
         if (mod->parm_undo) {
            type = ID_PRED_UNDO_OFFSET ;
            strcpy ( rest , mod->source_name ) ;
            }
         else {
            type = ID_PRED_OFFSET ;
            sprintf ( rest , "%lf %s", mod->parm_offset, mod->source_name ) ;
            }
         }

      else if (mod->parm_type == ID_PRED_SCALE) {
         if (mod->parm_undo) {
            type = ID_PRED_UNDO_SCALE ;
            strcpy ( rest , mod->source_name ) ;
            }
         else {
            type = ID_PRED_SCALE ;
            sprintf ( rest , "%lf %s", mod->parm_scale, mod->source_name ) ;
            }
         }

      else if (mod->parm_type == ID_PRED_STANDARDIZE) {
         if (mod->parm_undo)
            type = ID_PRED_UNDO_STANDARDIZE ;
         else 
            type = ID_PRED_STANDARDIZE ;
         strcpy ( rest , mod->source_name ) ;
         }

      else if (mod->parm_type == ID_PRED_DIFFERENCE) {
         if (mod->parm_undo) {
            type = ID_PRED_UNDO_DIFFERENCE ;
            strcpy ( rest , mod->source_name ) ;
            }
         else {
            type = ID_PRED_DIFFERENCE ;
            sprintf ( rest , "%d %s", mod->parm_diff, mod->source_name ) ;
            }
         }

      else if (mod->parm_type == ID_PRED_SEASONAL_DIFFERENCE) {
         if (mod->parm_undo) {
            type = ID_PRED_UNDO_SEASONAL_DIFFERENCE ;
            strcpy ( rest , mod->source_name ) ;
            }
         else {
            type = ID_PRED_SEASONAL_DIFFERENCE ;
            sprintf ( rest , "%d %s", mod->parm_seasonal, mod->source_name ) ;
            }
         }

      else if (mod->parm_type == ID_PRED_LOG) {
         type = ID_PRED_LOG ;
         strcpy ( rest , mod->source_name ) ;
         }

      else if (mod->parm_type == ID_PRED_EXP) {
         type = ID_PRED_EXP ;
         strcpy ( rest , mod->source_name ) ;
         }

      else if (mod->parm_type == ID_PRED_INTEGRATE) {
         type = ID_PRED_INTEGRATE ;
         sprintf ( rest , "%d %s", mod->parm_integrate, mod->source_name ) ;
         }

      if (mod->parm_undo  &&  strlen ( mod->per_name )) {
         strcat ( rest , " PER " ) ;
         strcat ( rest , mod->per_name ) ;
         }

      if (process ( type , rest , NULL , error , NULL ) < 0 )
         parent->MessageBox ( error , "ERROR" ) ;
      }

	delete mod ;
}
コード例 #21
0
ファイル: single_mode.cpp プロジェクト: jschlemm/ygopro
int SingleMode::SinglePlayThread(void* param) {
	const wchar_t* name = mainGame->lstSinglePlayList->getListItem(mainGame->lstSinglePlayList->getSelected());
	wchar_t fname[256];
	myswprintf(fname, L"./single/%ls", name);
	char fname2[256];
	size_t slen = BufferIO::EncodeUTF8(fname, fname2);
	mtrandom rnd;
	time_t seed = time(0);
	rnd.reset(seed);
	set_card_reader((card_reader)DataManager::CardReader);
	set_message_handler((message_handler)MessageHandler);
	pduel = create_duel(rnd.rand());
	set_player_info(pduel, 0, 8000, 5, 1);
	set_player_info(pduel, 1, 8000, 5, 1);
	mainGame->dInfo.lp[0] = 8000;
	mainGame->dInfo.lp[1] = 8000;
	myswprintf(mainGame->dInfo.strLP[0], L"%d", mainGame->dInfo.lp[0]);
	myswprintf(mainGame->dInfo.strLP[1], L"%d", mainGame->dInfo.lp[1]);
	BufferIO::CopyWStr(mainGame->ebNickName->getText(), mainGame->dInfo.hostname, 20);
	mainGame->dInfo.clientname[0] = 0;
	mainGame->dInfo.turn = 0;
	mainGame->dInfo.strTurn[0] = 0;
	if(!preload_script(pduel, fname2, slen)) {
		end_duel(pduel);
		return 0;
	}
	mainGame->gMutex.Lock();
	mainGame->HideElement(mainGame->wSinglePlay);
	mainGame->wCardImg->setVisible(true);
	mainGame->wInfos->setVisible(true);
	mainGame->btnLeaveGame->setVisible(true);
	mainGame->btnLeaveGame->setText(dataManager.GetSysString(1210));
	mainGame->stName->setText(L"");
	mainGame->stInfo->setText(L"");
	mainGame->stDataInfo->setText(L"");
	mainGame->stText->setText(L"");
	mainGame->scrCardText->setVisible(false);
	mainGame->wPhase->setVisible(true);
	mainGame->dField.panel = 0;
	mainGame->dField.hovered_card = 0;
	mainGame->dField.clicked_card = 0;
	mainGame->dField.Clear();
	mainGame->dInfo.isFirst = true;
	mainGame->dInfo.isStarted = true;
	mainGame->dInfo.isSingleMode = true;
	mainGame->device->setEventReceiver(&mainGame->dField);
	mainGame->gMutex.Unlock();
	start_duel(pduel, 0);
	char engineBuffer[0x1000];
	is_closing = false;
	is_continuing = true;
	int len = 0;
	while (is_continuing) {
		int result = process(pduel);
		len = result & 0xffff;
		/* int flag = result >> 16; */
		if (len > 0) {
			get_message(pduel, (byte*)engineBuffer);
			is_continuing = SinglePlayAnalyze(engineBuffer, len);
		}
	}
	end_duel(pduel);
	if(!is_closing) {
		mainGame->gMutex.Lock();
		mainGame->dInfo.isStarted = false;
		mainGame->dInfo.isSingleMode = false;
		mainGame->gMutex.Unlock();
		mainGame->closeDoneSignal.Reset();
		mainGame->closeSignal.Set();
		mainGame->closeDoneSignal.Wait();
		mainGame->gMutex.Lock();
		mainGame->ShowElement(mainGame->wSinglePlay);
		mainGame->device->setEventReceiver(&mainGame->menuHandler);
		mainGame->gMutex.Unlock();
	}
	return 0;
}
コード例 #22
0
ファイル: HttpServer.cpp プロジェクト: wkhq84/rhodes
bool CHttpServer::run()
{
    LOG(INFO) + "Start HTTP server";

    if (!init())
        return false;

    m_active = true;

    RHODESAPP().notifyLocalServerStarted();

    for(;;) 
    {
        RAWTRACE("Waiting for connections...");
#ifndef RHO_NO_RUBY_API
        if (rho_ruby_is_started())
            rho_ruby_start_threadidle();
#endif
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(m_listener, &readfds);

        timeval tv = {0,0};
        unsigned long nTimeout = RHODESAPP().getTimer().getNextTimeout();
        tv.tv_sec = nTimeout/1000;
        tv.tv_usec = (nTimeout - tv.tv_sec*1000)*1000;
        int ret = select(m_listener+1, &readfds, NULL, NULL, (tv.tv_sec == 0 && tv.tv_usec == 0 ? 0 : &tv) );
#ifndef RHO_NO_RUBY_API
        if (rho_ruby_is_started())
            rho_ruby_stop_threadidle();
#endif
        bool bProcessed = false;
        if (ret > 0) 
        {
            if (FD_ISSET(m_listener, &readfds))
            {
                //RAWTRACE("Before accept...");
                SOCKET conn = accept(m_listener, NULL, NULL);
                //RAWTRACE("After accept...");
                if (!m_active) {
                    RAWTRACE("Stop HTTP server");
                    return true;
                }
                if (conn == INVALID_SOCKET) {
        #if !defined(WINDOWS_PLATFORM)
                    if (RHO_NET_ERROR_CODE == EINTR)
                        continue;
        #endif
                    RAWLOG_ERROR1("Can not accept connection: %d", RHO_NET_ERROR_CODE);
                    return false;
                }

                RAWTRACE("Connection accepted, process it...");
                VALUE val;
#ifndef RHO_NO_RUBY_API                
                if (rho_ruby_is_started())
                {
                    if ( !RHOCONF().getBool("enable_gc_while_request") )                
                        val = rho_ruby_disable_gc();
                }
#endif
                m_sock = conn;
                bProcessed = process(m_sock);
#ifndef RHO_NO_RUBY_API
                if (rho_ruby_is_started())
                {
                    if ( !RHOCONF().getBool("enable_gc_while_request") )
                        rho_ruby_enable_gc(val);
                }
#endif
                RAWTRACE("Close connected socket");
                closesocket(m_sock);
                m_sock = INVALID_SOCKET;
            }
        }
        else if ( ret == 0 ) //timeout
        {
            bProcessed = RHODESAPP().getTimer().checkTimers();
        }
        else
        {
            RAWLOG_ERROR1("select error: %d", ret);
            return false;
        }
#ifndef RHO_NO_RUBY_API
        if (rho_ruby_is_started())
        {
            if ( bProcessed )
            {
                LOG(INFO) + "GC Start.";
                rb_gc();
                LOG(INFO) + "GC End.";
            }
        }
#endif
    }
}
コード例 #23
0
//main where program runs
int main(int argc, char **argv)
{
	signal(SIGPIPE, pipehandler);
	char *invalChar1;
	char *invalChar2;

	//check that there are 3 arguments
	if(argc != 3)
	{
		fprintf(stderr, "There is/are %d argument(s) (not including the file location). There should be 2 integer arguments, board size in inches and number of beetles.\n", argc - 1);
		exit(1);
	}

	long arg1;
	long arg2;
	//perform conversion
	//and check that there is no overflow
	if(((arg1 = strtol(argv[1], &invalChar1, 10)) >= INT_MAX) || ((arg2 = strtol(argv[2], &invalChar2, 10)) >= INT_MAX))
	{
		fprintf(stderr, "Overflow. The arguments: board size, %s, and the number of beetles, %s, must be valid integers less than %d\n", argv[1], argv[2], INT_MAX);
		exit(1);
	}

	//check that arguments are valid integers > 0 also checks underflow error and that there are no characters in the arguments
	if(!(arg1 > 0 && arg2 > 0) || (*invalChar1 || *invalChar2))
	{
		fprintf(stderr, "Both arguments must be valid integers greater than 0. The arguments: board size, %s, and the number of beetles, %s, are not both valid integers greater than 0.\n", argv[1], argv[2]);
		exit(1);
	}

	int boardSize = strtol(argv[1], NULL, 10);
	int numBeetles = strtol(argv[2], NULL, 10);
	double startPoint = (double) boardSize / 2;
	double locX;
	double locY;
	double prevLocX;
	double prevLocY;
	int degree;
	int dead;

	double elapsedSec = 0.0;
	double totSec = 0.0;

	//called to seed random by using time in seconds
	//makes rand() generate truly random numbers
	//kearns does not want to seed
	//srand(time(NULL));

	t.tv_sec = 1;
	t.tv_nsec = 0;
	pixelPerInch = (double) 300.0 / boardSize;


	FILE *read_from, *write_to;
	int childpid;
	char result[6];

	childpid = start_child("wish", &read_from, &write_to);
	fprintf(write_to, "source beetle.tcl\n");//initialize

	//get file descriptor numbers
	int readNum;
	int writeNum;

	if((readNum = fileno(read_from)) < 0)
	{
		fprintf(stderr, "/nError getting file number of read_from\n");
		exit(1);
	}

	if((writeNum = fileno(write_to)) < 0)
	{
		fprintf(stderr, "/nError getting file number of write_to\n");
		exit(1);
	}

	int hits;
	fd_set mask;
	struct timeval timeout;

	//set up for select statement
	timeout.tv_sec = 0;
	timeout.tv_usec = 0;

	fprintf(write_to, ".c create text 245 4 -anchor n -text \"Board Size: %d\"\n", boardSize);

	//iterate until all beetles die
	int i;
	for(i = 0; i < numBeetles; i++)
	{

		//reset variables
		locX = startPoint;
		locY = startPoint;
		pixelCordX = 250;
		pixelCordY = 250;
		elapsedSec = 0;
		dead = 0;

		//place beetle at center to start, tagged as theBeetle
		fprintf(write_to, ".c create oval 255 255 245 245 -fill blue -tags theBeetle\n");
		fprintf(write_to, ".c itemconfigure theSquare -fill white\n");

		while(dead != 1)
		{

			//set prev X and Y coordinates
			prevLocX = locX;
			prevLocY = locY;

			FD_ZERO(&mask);//these MUST be inside of loop or it will fail
			FD_SET(readNum, &mask);
			//check if tcl is sending back any data
			if((hits = select(readNum+1, &mask, (fd_set *)0, (fd_set *)0, &timeout)) < 0)
			{
				  perror("beetle:select");
				  exit(1);
			}


			if (hits > 0 && ((FD_ISSET(readNum, &mask))))
			{
				fgets(result, 5, read_from);
				//fprintf(stdout, "read b%sb\n", result);
				process(result);
			}


			//write the current beetle number
			fprintf(write_to, ".c itemconfigure beetleNumText -text \"Beetle Num: %d\"\n", i + 1);

			//get random degree
			degree = randDegree();

			locX += cos(degree / 180.0 * M_PI);
			locY += sin(degree / 180.0 * M_PI);

			elapsedSec += 1.0;// * timeRatio;

			if(nanosleep(&t, &t2) < 0)
			{
			  fprintf(stderr, "\nbeetle: nanosleep failed.\n");
			}

			//write average life text or current beetle lifetime
			if(avgLifeOn)
			{
				fprintf(write_to, ".c itemconfigure avgLifeText -text \"Average Life: %.1f\"\n", (totSec + elapsedSec) / (i + 1));
			}
			else
			{
				fprintf(write_to, ".c itemconfigure avgLifeText -text \"Current Beetle Lifetime: %.1f\"\n", elapsedSec);
			}

			//check if beetle is within an inch of the edge
			nearEdge(write_to, locX, locY, boardSize);
			//draw line
			drawLine(write_to, locX, locY, prevLocX, prevLocY);

			//check if bug died
			if(locX < 0 || locX > boardSize || locY < 0 || locY > boardSize)
			{

				if(soundOn)
				{
					fprintf(write_to, ".c itemconfigure theSquare -fill red4\n");
					fprintf(write_to, "bell\n");
				}
				sleep(1);//as specified by kearns before board cleared
				if(i != numBeetles - 1)
				{
					//delete beetle and lines from canvas
					fprintf(write_to, ".c delete lines\n");
					fprintf(write_to, ".c delete theBeetle\n");
				}
				//set bug to dead and add elapsed seconds to total seconds
				dead = 1;
				totSec += elapsedSec;
			}
			else
			{


				//bug passes out for 1*ratio second
				elapsedSec += 1.0; //* timeRatio;
				if(nanosleep(&t, &t2) < 0)
				{
				  fprintf(stderr, "\nbeetle: nanosleep failed.\n");
				}

				//write average life text or current beetle lifetime
				if(avgLifeOn)
				{
					fprintf(write_to, ".c itemconfigure avgLifeText -text \"Average Life: %.1f\"\n", (totSec + elapsedSec) / (i + 1));
				}
				else
				{
					fprintf(write_to, ".c itemconfigure avgLifeText -text \"Current Beetle Lifetime: %.1f\"\n", elapsedSec);
				}
			}
		}

	}

	//print results
	double avgSec = (double) totSec / (double)numBeetles;
	//fprintf(stdout, "%d by %d square, %d beetle(s), mean beetle lifetime is %.1f\n", boardSize, boardSize, numBeetles, avgSec);

	//finish with wish, leaves window up but disables buttons except exit
	fprintf(write_to, "done\n");
	return 0;
}
コード例 #24
0
ファイル: mainmenu.cpp プロジェクト: PugsyMAME/mame
void menu_main::handle()
{
	/* process the menu */
	const event *menu_event = process(0);
	if (menu_event != nullptr && menu_event->iptkey == IPT_UI_SELECT) {
		switch((long long)(menu_event->itemref)) {
		case INPUT_GROUPS:
			menu::stack_push<menu_input_groups>(ui(), container());
			break;

		case INPUT_SPECIFIC:
			menu::stack_push<menu_input_specific>(ui(), container());
			break;

		case SETTINGS_DIP_SWITCHES:
			menu::stack_push<menu_settings_dip_switches>(ui(), container());
			break;

		case SETTINGS_DRIVER_CONFIG:
			menu::stack_push<menu_settings_driver_config>(ui(), container());
			break;

		case ANALOG:
			menu::stack_push<menu_analog>(ui(), container());
			break;

		case BOOKKEEPING:
			menu::stack_push<menu_bookkeeping>(ui(), container());
			break;

		case GAME_INFO:
			menu::stack_push<menu_game_info>(ui(), container());
			break;

		case IMAGE_MENU_IMAGE_INFO:
			menu::stack_push<menu_image_info>(ui(), container());
			break;

		case IMAGE_MENU_FILE_MANAGER:
			menu::stack_push<menu_file_manager>(ui(), container(), nullptr);
			break;

		case TAPE_CONTROL:
			menu::stack_push<menu_tape_control>(ui(), container(), nullptr);
			break;

		case PTY_INFO:
			menu::stack_push<menu_pty_info>(ui(), container());
			break;

		case SLOT_DEVICES:
			menu::stack_push<menu_slot_devices>(ui(), container());
			break;

		case NETWORK_DEVICES:
			menu::stack_push<menu_network_devices>(ui(), container());
			break;

		case KEYBOARD_MODE:
			menu::stack_push<menu_keyboard_mode>(ui(), container());
			break;

		case SLIDERS:
			menu::stack_push<menu_sliders>(ui(), container(), false);
			break;

		case VIDEO_TARGETS:
			menu::stack_push<menu_video_targets>(ui(), container());
			break;

		case VIDEO_OPTIONS:
			menu::stack_push<menu_video_options>(ui(), container(), machine().render().first_target());
			break;

		case CROSSHAIR:
			menu::stack_push<menu_crosshair>(ui(), container());
			break;

		case CHEAT:
			menu::stack_push<menu_cheat>(ui(), container());
			break;

		case PLUGINS:
			menu::stack_push<menu_plugin>(ui(), container());
			break;

		case SELECT_GAME:
			if (machine().options().ui() == emu_options::UI_SIMPLE)
				menu::stack_push<simple_menu_select_game>(ui(), container(), nullptr);
			else
				menu::stack_push<menu_select_game>(ui(), container(), nullptr);
			break;

		case BIOS_SELECTION:
			menu::stack_push<menu_bios_selection>(ui(), container());
			break;

		case BARCODE_READ:
			menu::stack_push<menu_barcode_reader>(ui(), container(), nullptr);
			break;

		case EXTERNAL_DATS:
			menu::stack_push<menu_dats_view>(ui(), container());
			break;

		case ADD_FAVORITE:
			mame_machine_manager::instance()->favorite().add_favorite(machine());
			reset(reset_options::REMEMBER_POSITION);
			break;

		case REMOVE_FAVORITE:
			mame_machine_manager::instance()->favorite().remove_favorite(machine());
			reset(reset_options::REMEMBER_POSITION);
			break;

		case QUIT_GAME:
			stack_pop();
			ui().request_quit();
			break;

		default:
			fatalerror("ui::menu_main::handle - unknown reference\n");
		}
	}
}
コード例 #25
0
ファイル: mapcnvt.c プロジェクト: Nekrofage/QuestUnicorn
int main(int argc,char** argv) {
  printf("#ifdef MAIN\n");
  printf("MAP_TYPE maps[] ={\n");
  process("map11.map");    /* place the null map */
  process("map11.map");
  process("map12.map");
  process("map13.map");
  process("map14.map");
  process("map21.map");
  process("map22.map");
  process("map23.map");
  process("map24.map");
  process("map31.map");
  process("map32.map");
  process("map33.map");
  process("map34.map");
  process("radon.map");
  process("generic.map");
  process("village.map");
  process("marduk.map");
  process("nichor.map");
  process("eshter.map");
  printf("  };\n");
  printf("#else\n");
  printf("extern MAP_TYPE maps[];\n");
  printf("#endif\n");
  return 0;
  }
コード例 #26
0
ファイル: core.cpp プロジェクト: tr37ion/qTox
void Core::start()
{
    // IPv6 needed for LAN discovery, but can crash some weird routers. On by default, can be disabled in options.
    bool enableIPv6 = Settings::getInstance().getEnableIPv6();
    bool forceTCP = Settings::getInstance().getForceTCP();

    bool useProxy = Settings::getInstance().getUseProxy();

    if (enableIPv6)
        qDebug() << "Core starting with IPv6 enabled";
    else
        qWarning() << "Core starting with IPv6 disabled. LAN discovery may not work properly.";

    Tox_Options toxOptions;
    toxOptions.ipv6enabled = enableIPv6;
    toxOptions.udp_disabled = forceTCP;

    // No proxy by default
    toxOptions.proxy_enabled = false;
    toxOptions.proxy_address[0] = 0;
    toxOptions.proxy_port = 0;

    if (useProxy)
    {
        QString proxyAddr = Settings::getInstance().getProxyAddr();
        int proxyPort = Settings::getInstance().getProxyPort();

        if (proxyAddr.length() > 255)
        {
            qWarning() << "Core: proxy address" << proxyAddr << "is too long";
        }
        else if (proxyAddr != "" && proxyPort > 0)
        {
            qDebug() << "Core: using proxy" << proxyAddr << ":" << proxyPort;
            toxOptions.proxy_enabled = true;
            uint16_t sz = CString::fromString(proxyAddr, (unsigned char*)toxOptions.proxy_address);
            toxOptions.proxy_address[sz] = 0;
            toxOptions.proxy_port = proxyPort;
        }
    }

    tox = tox_new(&toxOptions);
    if (tox == nullptr)
    {
        if (enableIPv6) // Fallback to IPv4
        {
            toxOptions.ipv6enabled = false;
            tox = tox_new(&toxOptions);
            if (tox == nullptr)
            {
                if (toxOptions.proxy_enabled)
                {
                    //QMessageBox::critical(Widget::getInstance(), tr("Proxy failure", "popup title"), 
                    //tr("toxcore failed to start with your proxy settings. qTox cannot run; please modify your "
                       //"settings and restart.", "popup text"));
                    qCritical() << "Core: bad proxy! no toxcore!";
                    emit badProxy();
                } 
                else
                {
                    qCritical() << "Tox core failed to start";
                    emit failedToStart();
                }
                return;
            } 
            else
                qWarning() << "Core failed to start with IPv6, falling back to IPv4. LAN discovery may not work properly.";
        }
        else if (toxOptions.proxy_enabled)
        {
            emit badProxy();
            return;
        }
        else
        {
            qCritical() << "Tox core failed to start";
            emit failedToStart();
            return;
        }
    }

    toxav = toxav_new(tox, TOXAV_MAX_CALLS);
    if (toxav == nullptr)
    {
        qCritical() << "Toxav core failed to start";
        emit failedToStart();
        return;
    }

    qsrand(time(nullptr));

    if (!loadConfiguration())
    {
        emit failedToStart();
        tox_kill(tox);
        tox = nullptr;
        return;
    }

    tox_callback_friend_request(tox, onFriendRequest, this);
    tox_callback_friend_message(tox, onFriendMessage, this);
    tox_callback_friend_action(tox, onAction, this);
    tox_callback_name_change(tox, onFriendNameChange, this);
    tox_callback_typing_change(tox, onFriendTypingChange, this);
    tox_callback_status_message(tox, onStatusMessageChanged, this);
    tox_callback_user_status(tox, onUserStatusChanged, this);
    tox_callback_connection_status(tox, onConnectionStatusChanged, this);
    tox_callback_group_invite(tox, onGroupInvite, this);
    tox_callback_group_message(tox, onGroupMessage, this);
    tox_callback_group_namelist_change(tox, onGroupNamelistChange, this);
    tox_callback_file_send_request(tox, onFileSendRequestCallback, this);
    tox_callback_file_control(tox, onFileControlCallback, this);
    tox_callback_file_data(tox, onFileDataCallback, this);
    tox_callback_avatar_info(tox, onAvatarInfoCallback, this);
    tox_callback_avatar_data(tox, onAvatarDataCallback, this);

    toxav_register_callstate_callback(toxav, onAvInvite, av_OnInvite, this);
    toxav_register_callstate_callback(toxav, onAvStart, av_OnStart, this);
    toxav_register_callstate_callback(toxav, onAvCancel, av_OnCancel, this);
    toxav_register_callstate_callback(toxav, onAvReject, av_OnReject, this);
    toxav_register_callstate_callback(toxav, onAvEnd, av_OnEnd, this);
    toxav_register_callstate_callback(toxav, onAvRinging, av_OnRinging, this);
    toxav_register_callstate_callback(toxav, onAvStarting, av_OnStarting, this);
    toxav_register_callstate_callback(toxav, onAvEnding, av_OnEnding, this);
    toxav_register_callstate_callback(toxav, onAvMediaChange, av_OnMediaChange, this);
    toxav_register_callstate_callback(toxav, onAvRequestTimeout, av_OnRequestTimeout, this);
    toxav_register_callstate_callback(toxav, onAvPeerTimeout, av_OnPeerTimeout, this);

    toxav_register_audio_recv_callback(toxav, playCallAudio, this);
    toxav_register_video_recv_callback(toxav, playCallVideo, this);

    uint8_t friendAddress[TOX_FRIEND_ADDRESS_SIZE];
    tox_get_address(tox, friendAddress);
    emit friendAddressGenerated(CFriendAddress::toString(friendAddress));

    QPixmap pic = Settings::getInstance().getSavedAvatar(getSelfId().toString());
    if (!pic.isNull() && !pic.size().isEmpty())
    {
        QByteArray data;
        QBuffer buffer(&data);
        buffer.open(QIODevice::WriteOnly);
        pic.save(&buffer, "PNG");
        buffer.close();
        setAvatar(TOX_AVATAR_FORMAT_PNG, data);
    }
    else
        qDebug() << "Core: Error loading self avatar";
    
    process(); // starts its own timer
}
コード例 #27
0
ファイル: main.c プロジェクト: beastix/bsdtools
int
main(int argc, char *argv[])
{
	int c, fflag;
	char *temp_arg;

	(void) setlocale(LC_ALL, "");

	fflag = 0;
	inplace = NULL;

	while ((c = getopt(argc, argv, "EI:ae:f:i:lnru")) != -1)
		switch (c) {
		case 'r':		/* Gnu sed compat */
		case 'E':
			rflags = REG_EXTENDED;
			break;
		case 'I':
			inplace = optarg;
			ispan = 1;	/* span across input files */
			break;
		case 'a':
			aflag = 1;
			break;
		case 'e':
			eflag = 1;
			if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
				err(1, "malloc");
			strcpy(temp_arg, optarg);
			strcat(temp_arg, "\n");
			add_compunit(CU_STRING, temp_arg);
			break;
		case 'f':
			fflag = 1;
			add_compunit(CU_FILE, optarg);
			break;
		case 'i':
			inplace = optarg;
			ispan = 0;	/* don't span across input files */
			break;
		case 'l':
			if(setvbuf(stdout, NULL, _IOLBF, 0) != 0)
				warnx("setting line buffered output failed");
			break;
		case 'n':
			nflag = 1;
			break;
		case 'u':
			if(setvbuf(stdout, NULL, _IONBF, 0) != 0)
				warnx("setting unbuffered output failed");
			break;
		default:
		case '?':
			usage();
		}
	argc -= optind;
	argv += optind;

	/* First usage case; script is the first arg */
	if (!eflag && !fflag && *argv) {
		add_compunit(CU_STRING, *argv);
		argv++;
	}

	compile();

	/* Continue with first and start second usage */
	if (*argv)
		for (; *argv; argv++)
			add_file(*argv);
	else
		add_file(NULL);
	process();
	cfclose(prog, NULL);
	if (fclose(stdout))
		err(1, "stdout");
	exit(rval);
}
コード例 #28
0
ファイル: configuration.hpp プロジェクト: vdt/fix8
	/*! Ctor.
	  \param xmlfile xml config filename.
	  \param do_process if true, process the file on construction */
	Configuration(const std::string& xmlfile, bool do_process=false)
		: _xmlfile(xmlfile), _root(XmlElement::Factory(_xmlfile)) { if (do_process) process(); }
コード例 #29
0
ファイル: pnumeric.c プロジェクト: jardous/pnumeric
/*
 * Kalman filter process
 */
static PyObject *
kf_process(PyObject *self, PyObject *args, PyObject *kws)
{
    MatrixObject *A, *B, *C, *D, *x0, *P0, *Q, *R, *x, *P;
    Float *x_est, *y_est, *P_est;
    PyObject *out, *tmp, *tmp1, *x_est_out, *y_est_out, *P_est_out, *result;
    PyObject *mupdate_callback = NULL, *arglist;
    int i, j, k, n, p, q, datalength;
    MatrixObject *y, *u;

    static char *kwlist[] = {"A", "B", "C", "D", "y", "u", "x0", "P0", "Q", "R", "mupdate_callback", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kws, "O!O!O!O!O!O!O!O!O!O!|O:set_callback", kwlist,
            &MatrixType, &A,
            &MatrixType, &B,
            &MatrixType, &C,
            &MatrixType, &D,
            &MatrixType, &y,
            &MatrixType, &u,
            &MatrixType, &x0,
            &MatrixType, &P0,
            &MatrixType, &Q,
            &MatrixType, &R,
            &mupdate_callback))
        return NULL;

    if (A->rows != A->cols) {
        PyErr_SetString(PyExc_ValueError, "A must be a square matrix");
        return NULL;
    }

    n = A->rows;
    p = B->cols;
    q = C->rows;

    if (B->rows != n) {
        PyErr_SetString(PyExc_ValueError, "B must be Nxp matrix");
        return NULL;
    }
    if (C->cols != n) {
        PyErr_SetString(PyExc_ValueError, "C must be qxN matrix");
        return NULL;
    }
    if (D->rows != p || D->cols != q) {
        PyErr_SetString(PyExc_ValueError, "D must be pxq matrix");
        return NULL;
    }
    datalength = y->cols;
    if (y->cols != u->cols) {
        PyErr_SetString(PyExc_ValueError, "y and u data lengths does not match");
        return NULL;
    }
    if (y->rows != q) {
        PyErr_SetString(PyExc_ValueError, "y must be qxlength matrix");
        return NULL;
    }
    if (u->rows != p) {
        PyErr_SetString(PyExc_ValueError, "u must be pxlength matrix");
        return NULL;
    }
    if (x0->rows != n || x0->cols != 1) {
        PyErr_SetString(PyExc_ValueError, "x0 must be Nx1 matrix");
        return NULL;
    }
    if (P0->rows != n || P0->cols != n) {
        PyErr_SetString(PyExc_ValueError, "P0 must be NxN matrix");
        return NULL;
    }
    if (Q->rows != n || Q->cols != n) {
        PyErr_SetString(PyExc_ValueError, "Q must be NxN matrix");
        return NULL;
    }
    if (R->rows != q || R->cols != q) {
        PyErr_SetString(PyExc_ValueError, "R must be qxq matrix");
        return NULL;
    }
    if (!PyCallable_Check(mupdate_callback)) {
        if (mupdate_callback != NULL) {
            PyErr_SetString(PyExc_TypeError, "parameter must be callable");
            return NULL;
        }
    }

    x_est = m_new(n, datalength);
    y_est = m_new(n, datalength);
    P_est = m_new(n, n*datalength);

    if (mupdate_callback != NULL) {
        Py_XINCREF(mupdate_callback);  // Add a reference to new callback
        x = matrix_new(n, 1);
        P = matrix_new(n, n);
        // initialize x and P
        m_copy(x->data, x0->data, n, 1);
        m_copy(P->data, P0->data, n, n);

        for (i=0; i<datalength; i++) {
            tick(A->data, B->data, C->data, D->data,
                n, p, q,
                y->data+i*q, u->data+i*p,
                x->data, P->data,
                Q->data, R->data,
                x_est+i*n, y_est+i*q, P_est+i*n*n);
            // copy x and P values into output array
            m_copy(x->data, x_est+i*n, n, 1);
            m_copy(P->data, P_est+i*n*n, n, n);
            // update the matrixes
            arglist = Py_BuildValue("(i, O, O, O, O, O)", i, A, B, C, D, x);
            result = PyEval_CallObject(mupdate_callback, arglist);
            Py_DECREF(arglist);
        }
        Py_DECREF(x);
        Py_DECREF(P);
    } else { // model update not needed
        process(A->data, B->data, C->data, D->data,
                n, p, q, y->data, u->data, x0->data, P0->data, Q->data, R->data, datalength,
                x_est, y_est, P_est);
    }

    // create lists from matrixes
    x_est_out = PyList_New(datalength);
    for (i=0; i<datalength; i++) {
        tmp = PyList_New(n);
        for (j=0; j<n; j++) {
            PyList_SetItem(tmp, j, PyFloat_FromDouble( *(x_est+i*n+j) ));
        }
        PyList_SetItem(x_est_out, i, tmp);
    }
    y_est_out = PyList_New(datalength);
    for (i=0; i<datalength; i++) {
        tmp = PyFloat_FromDouble( *(y_est+i) );
        PyList_SetItem(y_est_out, i, tmp);
    }
    P_est_out = PyList_New(datalength);
    for (i=0; i<datalength; i++) {
        tmp = PyList_New(n);
        for (j=0; j<n; j++) {
            tmp1 = PyList_New(n);
            for (k=0; k<n; k++) {
                PyList_SetItem(tmp1, k, PyFloat_FromDouble( *(x_est+i*n+j*n+k) ));
            }
            PyList_SetItem(tmp, j, tmp1);
        }
        tmp = PyFloat_FromDouble( *(P_est+i) );
        PyList_SetItem(P_est_out, i, tmp);
    }

    m_free(x_est);
    m_free(y_est);
    m_free(P_est);

    out = PyTuple_New(3);
    PyTuple_SetItem(out, 0, x_est_out);
    PyTuple_SetItem(out, 1, y_est_out);
    PyTuple_SetItem(out, 2, P_est_out);
    Py_INCREF(out); // TODO add Py_INCREF every time when returning object from fnc

    return out;
}
コード例 #30
0
int KruskalWallisCommand::execute(){
	try {
		
		if (abort) { if (calledHelp) { return 0; }  return 2;	}
        
        DesignMap designMap(designfile);
        
        //if user did not select class use first column
        if (mclass == "") {  mclass = designMap.getDefaultClass(); m->mothurOut("\nYou did not provide a class, using " + mclass +".\n\n"); }
        
        InputData input(sharedfile, "sharedfile", nullVector);
        SharedRAbundVectors* lookup = input.getSharedRAbundVectors();
        string lastLabel = lookup->getLabel();
        
        //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
        set<string> processedLabels;
        set<string> userLabels = labels;
        vector<string> currentLabels = lookup->getOTUNames();
        
        
        //as long as you are not at the end of the file or done wih the lines you want
        while((lookup != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
            
            if (m->getControl_pressed()) { delete lookup;  return 0; }
            
            if(allLines == 1 || labels.count(lookup->getLabel()) == 1){
                
                m->mothurOut(lookup->getLabel()+"\n"); 
                
                vector<SharedRAbundVector*> data = lookup->getSharedRAbundVectors();
                process(data, designMap, currentLabels);
                for (int i = 0; i < data.size(); i++) { delete data[i]; } data.clear();
                
                processedLabels.insert(lookup->getLabel());
                userLabels.erase(lookup->getLabel());
            }
            
            if ((util.anyLabelsToProcess(lookup->getLabel(), userLabels, "") ) && (processedLabels.count(lastLabel) != 1)) {
                string saveLabel = lookup->getLabel();
                
                delete lookup;
                lookup = input.getSharedRAbundVectors(lastLabel);
                m->mothurOut(lookup->getLabel()+"\n"); 
                
                vector<SharedRAbundVector*> data = lookup->getSharedRAbundVectors();
                process(data, designMap, currentLabels);
                for (int i = 0; i < data.size(); i++) { delete data[i]; } data.clear();
                
                processedLabels.insert(lookup->getLabel());
                userLabels.erase(lookup->getLabel());
                
                //restore real lastlabel to save below
                lookup->setLabels(saveLabel);
            }
            
            lastLabel = lookup->getLabel();
            //prevent memory leak
            delete lookup;
            
            if (m->getControl_pressed()) { return 0; }
            
            //get next line to process
            lookup = input.getSharedRAbundVectors();
        }
        
        if (m->getControl_pressed()) {  return 0; }
        
        //output error messages about any remaining user labels
        set<string>::iterator it;
        bool needToRun = false;
        for (it = userLabels.begin(); it != userLabels.end(); it++) {
            m->mothurOut("Your file does not include the label " + *it);
            if (processedLabels.count(lastLabel) != 1) {
                m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
                needToRun = true;
            }else {
                m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
            }
        }
        
        //run last label if you need to
        if (needToRun )  {
            delete lookup;
            lookup = input.getSharedRAbundVectors(lastLabel);
            
            m->mothurOut(lookup->getLabel()+"\n"); 
            vector<SharedRAbundVector*> data = lookup->getSharedRAbundVectors();
            process(data, designMap, currentLabels);
            for (int i = 0; i < data.size(); i++) { delete data[i]; } data.clear();
            
            delete lookup;
        }
        
		
        //output files created by command
		m->mothurOut("\nOutput File Names: \n"); 
		for (int i = 0; i < outputNames.size(); i++) {	m->mothurOut(outputNames[i] +"\n"); 	} m->mothurOutEndLine();
        return 0;
		
    }
	catch(exception& e) {
		m->errorOut(e, "KruskalWallisCommand", "execute");
		exit(1);
	}
}