How to use open_func method in autotest

Best Python code snippet using autotest_python

extension.js

Source:extension.js Github

copy

Full Screen

1/**2 * Created by zppro on 16-8-28.3 * 参考字典D1003-预定义树4 */5var path = require('path');6var xlsx = require('node-xlsx').default;7var importDrugConfig = require('../pre-defined/imp-xlsx-drug-config.json');8module.exports = {9 init: function (option) {10 var self = this;11 this.file = __filename;12 this.filename = this.file.substr(this.file.lastIndexOf('/') + 1);13 this.module_name = this.filename.substr(0, this.filename.lastIndexOf('.'));14 this.service_url_prefix = '/services/' + this.module_name.split('_').join('/');15 this.log_name = 'svc_' + this.filename;16 option = option || {};17 this.logger = require('log4js').getLogger(this.log_name);18 if (!this.logger) {19 console.error('logger not loaded in ' + this.file);20 }21 else {22 this.logger.info(this.file + " loaded!");23 }24 this.actions = [25 {26 method: 'tenantInfo',27 verb: 'get',28 url: this.service_url_prefix + "/tenantInfo/:_id/:select",//:select需要提取的字段域用逗号分割 e.g. name,type29 handler: function (app, options) {30 return function *(next) {31 try {32 var tenant = yield app.modelFactory().model_read(app.models['pub_tenant'], this.params._id);33 var ret = app._.pick(tenant.toObject(), this.params.select.split(','));34 this.body = app.wrapper.res.ret(ret);35 } catch (e) {36 self.logger.error(e.message);37 this.body = app.wrapper.res.error(e);38 }39 yield next;40 };41 }42 },43 {44 method: 'tenantChargeItemNursingLevelAsTree',45 verb: 'get',46 url: this.service_url_prefix + "/tenantChargeItemNursingLevelAsTree/:id,:charge_standard,:subsystem",47 handler: function (app, options) {48 return function *(next) {49 try {50 var tenantId = this.params.id;51 var tenant = yield app.modelFactory().model_read(app.models['pub_tenant'], tenantId);52 if (!tenant || tenant.status == 0) {53 this.body = app.wrapper.res.error({message: '无法找到租户!'});54 yield next;55 return;56 }57 var charge_standard = this.params.charge_standard;58 if (!charge_standard) {59 this.body = app.wrapper.res.error({message: '无法找到收费标准!'});60 yield next;61 return;62 }63 var subsytem = this.params.subsystem;64 if (!subsytem || !app.modelVariables[subsytem.toUpperCase()]) {65 this.body = app.wrapper.res.error({message: '无法找到子系统!'});66 yield next;67 return;68 }69 var where = {70 status: 1,71 tenantId: tenantId72 };73 // if(subsytem) {74 // where['subsystem'] = subsytem;75 // }76 var chargeItems = yield app.modelFactory().model_query(app.models['psn_nursingLevel'], {77 where: where78 });79 var charge_standard_object = app._.find(tenant.charge_standards, function (o) {80 return o.charge_standard == charge_standard && o.subsystem == subsytem;81 });82 if (!charge_standard_object) {83 charge_standard = app.modelVariables[subsytem.toUpperCase()].DEFAULT_CHARGE_STANDARD84 }85 var ret = {86 _id: app.modelVariables[subsytem.toUpperCase()].CHARGE_ITEM_PREFIX + app.modelVariables[subsytem.toUpperCase()].CHARGE_ITEM_NURSING_LEVEL_CATAGORY._ID + '-' + charge_standard,87 name: app.modelVariables[subsytem.toUpperCase()].CHARGE_ITEM_NURSING_LEVEL_CATAGORY.NAME,88 children: []89 };90 for (var i = 0; i < chargeItems.length; i++) {91 console.log(i);92 if ((app.modelVariables[subsytem.toUpperCase()].CHARGE_ITEM_PREFIX + app.modelVariables[subsytem.toUpperCase()].CHARGE_ITEM_NURSING_LEVEL_CATAGORY._ID + '-' + charge_standard) == ret._id) {93 ret.children.push({94 _id: app.modelVariables[subsytem.toUpperCase()].CHARGE_ITEM_PREFIX + chargeItems[i]._id,95 name: chargeItems[i].name,96 data: {manual_seletable: true}97 });98 }99 }100 console.log(ret);101 this.body = app.wrapper.res.ret(ret);102 } catch (error) {103 self.logger.error(e.message);104 this.body = app.wrapper.res.error(e);105 }106 }107 }108 },109 {110 method: 'tenantChargeItemCustomizedAsTree',111 verb: 'get',112 url: this.service_url_prefix + "/tenantChargeItemCustomizedAsTree/:id,:charge_standard,:subsystem",113 handler: function (app, options) {114 return function *(next) {115 try {116 var tenantId = this.params.id;117 var tenant = yield app.modelFactory().model_read(app.models['pub_tenant'], tenantId);118 if (!tenant || tenant.status == 0) {119 this.body = app.wrapper.res.error({message: '无法找到租户!'});120 yield next;121 return;122 }123 var charge_standard = this.params.charge_standard;124 if (!charge_standard) {125 this.body = app.wrapper.res.error({message: '无法找到收费标准!'});126 yield next;127 return;128 }129 var subsytem = this.params.subsystem;130 if (!subsytem || !app.modelVariables[subsytem.toUpperCase()]) {131 this.body = app.wrapper.res.error({message: '无法找到子系统!'});132 yield next;133 return;134 }135 var where = {136 status: 1,137 tenantId: tenantId138 };139 if (subsytem) {140 where['subsystem'] = subsytem;141 }142 var chargeItems = yield app.modelFactory().model_query(app.models['pub_tenantChargeItemCustomized'], {143 where: where144 });145 var charge_standard_object = app._.find(tenant.charge_standards, function (o) {146 return o.charge_standard == charge_standard && o.subsystem == subsytem;147 });148 if (!charge_standard_object) {149 charge_standard = app.modelVariables[subsytem.toUpperCase()].DEFAULT_CHARGE_STANDARD150 }151 var ret = {152 _id: app.modelVariables[subsytem.toUpperCase()].CHARGE_ITEM_PREFIX + app.modelVariables[subsytem.toUpperCase()].CHARGE_ITEM_CUSTOMIZED_CATAGORY._ID + '-' + charge_standard,153 name: app.modelVariables[subsytem.toUpperCase()].CHARGE_ITEM_CUSTOMIZED_CATAGORY.NAME,154 children: []155 };156 for (var i = 0; i < chargeItems.length; i++) {157 if ((app.modelVariables[subsytem.toUpperCase()].CHARGE_ITEM_PREFIX + chargeItems[i].catagory + '-' + charge_standard) == ret._id) {158 ret.children.push({159 _id: app.modelVariables[subsytem.toUpperCase()].CHARGE_ITEM_PREFIX + chargeItems[i]._id,160 name: chargeItems[i].name,161 data: {manual_seletable: true}162 });163 }164 }165 console.log(ret);166 this.body = app.wrapper.res.ret(ret);167 } catch (e) {168 self.logger.error(e.message);169 this.body = app.wrapper.res.error(e);170 }171 yield next;172 };173 }174 },175 {176 method: 'saveTenantChargeItemCustomized',//保存收费标准177 verb: 'post',178 url: this.service_url_prefix + "/saveTenantChargeItemCustomized/:id",179 handler: function (app, options) {180 return function *(next) {181 try {182 var tenant = yield app.modelFactory().model_read(app.models['pub_tenant'], this.params.id);183 if (!tenant || tenant.status == 0) {184 this.body = app.wrapper.res.error({message: '无法找到租户!'});185 yield next;186 return;187 }188 var charge_standard = this.request.body.charge_standard;189 var subsystem = this.request.body.subsystem;190 var index = app._.findIndex(tenant.charge_standards, function (o) {191 return o.subsystem === subsystem && o.charge_standard === charge_standard192 });193 if (index === -1) {194 tenant.charge_standards.push(this.request.body);195 } else {196 tenant.charge_standards.splice(index, 1, this.request.body);197 }198 yield tenant.save();199 this.body = app.wrapper.res.default();200 } catch (e) {201 self.logger.error(e.message);202 this.body = app.wrapper.res.error(e);203 }204 yield next;205 };206 }207 },208 {209 method: 'saveTenantConfig',//保存机构配置210 verb: 'post',211 url: this.service_url_prefix + "/saveTenantConfig/:id",212 handler: function (app, options) {213 return function *(next) {214 try {215 var tenant = yield app.modelFactory().model_read(app.models['pub_tenant'], this.params.id);216 if (!tenant || tenant.status == 0) {217 this.body = app.wrapper.res.error({message: '无法找到租户!'});218 yield next;219 return;220 }221 // console.log('saveTenantOtherConfig', this.request.body);222 tenant.name = this.request.body.name;223 tenant.head_of_agency = this.request.body.head_of_agency;224 tenant.other_config = this.request.body.otherConfig;225 yield tenant.save();226 this.body = app.wrapper.res.default();227 } catch (e) {228 self.logger.error(e.message);229 this.body = app.wrapper.res.error(e);230 }231 yield next;232 };233 }234 },235 /**********************订单相关*****************************/236 {237 method: 'completeOrder',//完成订单238 verb: 'post',239 url: this.service_url_prefix + "/completeOrder/:_id",240 handler: function (app, options) {241 return function *(next) {242 try {243 //1、订单状态从[财务确认收款]到[交易成功]244 var orderUpdateData = {order_status: 'A1004', success_on: app.moment()};245 var ret = yield app.modelFactory().model_update(app.models['pub_order'], this.params._id, orderUpdateData);246 //2、更新tenant.open_funcs中对应的func.payed和expired_on247 var order = yield app.modelFactory().model_read(app.models['pub_order'], this.params._id);248 var tenant = yield app.modelFactory().model_read(app.models['pub_tenant'], order.tenantId);249 var order_items = order.order_items;250 for (var i = 0; i < order_items.length; i++) {251 var open_func = app._.findWhere(tenant.open_funcs, {func_id: order_items[i].func_id});252 if (open_func) {253 //已经存在的功能254 var isAfter = app.moment().isAfter(open_func.expired_on);255 if (isAfter) {256 //已经过期257 console.log('isAfter:true');258 open_func.expired_on = app.moment().add(order.duration, 'M');259 }260 else {261 //还未过期262 console.log('isAfter:false');263 open_func.expired_on = app.moment(open_func.expired_on).add(order.duration, 'M');264 }265 }266 else {267 //增加新功能268 open_func = app._.omit(order_items[i].toObject(), ['_id', 'check_in_time']);269 console.log(order_items[i]);270 console.log(open_func);271 open_func.expired_on = app.moment().add(order.duration, 'M');272 tenant.open_funcs.push(open_func);273 //console.log(open_func);274 //console.log(tenant.open_funcs);275 }276 }277 yield tenant.save();278 this.body = app.wrapper.res.ret(orderUpdateData);279 } catch (e) {280 self.logger.error(e.message);281 this.body = app.wrapper.res.error(e);282 }283 yield next;284 };285 }286 },287 {288 method: 'refundOrder',//订单发起退款289 verb: 'post',290 url: this.service_url_prefix + "/refundOrder/:_id",291 handler: function (app, options) {292 return function *(next) {293 try {294 //1、订单状态从[交易成功]到[等待退款]295 var orderUpdateData = {order_status: 'A1006', refund_on: app.moment()};296 var ret = yield app.modelFactory().model_update(app.models['pub_order'], this.params._id, orderUpdateData);297 //2、更新tenant.open_funcs中对应的func.payed和expired_on298 var order = yield app.modelFactory().model_read(app.models['pub_order'], this.params._id);299 var tenant = yield app.modelFactory().model_read(app.models['pub_tenant'], order.tenantId);300 var order_items = order.order_items;301 for (var i = 0; i < order_items.length; i++) {302 var open_func = app._.findWhere(tenant.open_funcs, {func_id: order_items[i].func_id});303 open_func.expired_on = app.moment(open_func.expired_on).subtract(order.duration, 'M');304 }305 yield tenant.save();306 this.body = app.wrapper.res.ret(orderUpdateData);307 } catch (e) {308 self.logger.error(e.message);309 this.body = app.wrapper.res.error(e);310 }311 yield next;312 };313 }314 },315 /**********************冲红相关*****************************/316 {317 method: 'queryVoucherNo',318 verb: 'post',319 url: this.service_url_prefix + "/q/voucher_no",320 handler: function (app, options) {321 return function *(next) {322 try {323 var tenantId = this.request.body.tenantId;324 var modelName = this.request.body.modelName;325 var keyword = this.request.body.keyword;326 var data = this.request.body.data;327 console.log(this.request.body);328 app._.extend(data.where, {329 status: 1,330 //carry_over_flag:true,331 tenantId: tenantId332 });333 if (keyword) {334 data.where.voucher_no = new RegExp(keyword);335 }336 var rows_in_recharge = yield app.modelFactory().model_query(app.models[modelName], data);337 var rows_in_tenantJournalAccount = yield app.modelFactory().model_query(app.models['pub_tenantJournalAccount'], data);338 var rows = app._.union(rows_in_recharge, rows_in_tenantJournalAccount);339 this.body = app.wrapper.res.rows(rows);340 } catch (e) {341 self.logger.error(e.message);342 this.body = app.wrapper.res.error(e);343 }344 yield next;345 };346 }347 },348 /**********************用户密码相关*****************************/349 {350 method: 'userChangePassword',//用户修改密码351 verb: 'post',352 url: this.service_url_prefix + "/userChangePassword/:_id",353 handler: function (app, options) {354 return function *(next) {355 try {356 var user = yield app.modelFactory().model_read(app.models['pub_user'], this.params._id);357 if (!user) {358 this.body = app.wrapper.res.error({message: '无效的用户!'});359 yield next;360 return;361 }362 var oldPasswordHash = app.crypto.createHash('md5').update(this.request.body.old_password).digest('hex');363 if (user.password_hash != oldPasswordHash) {364 this.body = app.wrapper.res.error({message: '旧密码错误!'});365 yield next;366 return;367 }368 var newPasswordHash = app.crypto.createHash('md5').update(this.request.body.new_password).digest('hex');369 user.password_hash = newPasswordHash;370 user.save();371 this.body = app.wrapper.res.default();372 } catch (e) {373 self.logger.error(e.message);374 this.body = app.wrapper.res.error(e);375 }376 yield next;377 };378 }379 },380 {381 method: 'resetUserPassword',//管理中心重设用户密码382 verb: 'post',383 url: this.service_url_prefix + "/resetUserPassword/:_id",384 handler: function (app, options) {385 return function *(next) {386 try {387 var user = yield app.modelFactory().model_read(app.models['pub_user'], this.params._id);388 if (!user) {389 this.body = app.wrapper.res.error({message: '无效的用户!'});390 yield next;391 return;392 }393 console.log('before update');394 var newPasswordHash = app.crypto.createHash('md5').update('123456').digest('hex');395 console.log(newPasswordHash);396 user.password_hash = newPasswordHash;397 user.save();398 this.body = app.wrapper.res.default();399 } catch (e) {400 self.logger.error(e.message);401 this.body = app.wrapper.res.error(e);402 }403 yield next;404 };405 }406 },407 {408 method: 'primitivePsdAlert',//初始密码提示409 verb: 'post',410 url: this.service_url_prefix + "/primitivePsdAlert",411 handler: function (app, options) {412 return function *(next) {413 try {414 var password = this.request.body.password;415 this.body = app.wrapper.res.ret(password === '123456');416 } catch (e) {417 self.logger.error(e.message);418 this.body = app.wrapper.res.error(e);419 }420 yield next;421 };422 }423 },424 /******************APP版本*********************************/425 {426 method: 'upgradeAppServerSide',//管理中心将复制一条服务端端升级记录,并增加一位版本号427 verb: 'post',428 url: this.service_url_prefix + "/upgradeAppServerSide/:appId",429 handler: function (app, options) {430 return function *(next) {431 try {432 var updateHistories = yield app.modelFactory().model_query(app.models['pub_appServerSideUpdateHistory'], {433 where: {app_id: this.params.appId},434 select: 'app_id ver ver_order',435 sort: {ver_order: -1, check_in_time: -1}436 }, {limit: 1});437 if (updateHistories.length == 0) {438 this.body = app.wrapper.res.error({message: '当前App在该操作系统下没有任何版本信息!'});439 yield next;440 return;441 }442 var newUpdateHistory = updateHistories[0].toObject();443 delete newUpdateHistory._id;444 delete newUpdateHistory.id;445 var arrVer = newUpdateHistory.ver.split('.');446 var scale = 100;447 var newVer;448 var ver3 = parseInt(arrVer[2]);449 console.log(newUpdateHistory.ver)450 if (++ver3 == scale) {451 ver3 = 0;452 var ver2 = parseInt(arrVer[1]);453 ver2++;454 if (ver2 == scale) {455 ver2 = 0;456 var ver1 = parseInt(arrVer[0]);457 ver1++;458 if (ver1 == scale) {459 ver1 = 0460 }461 console.log(ver1)462 newVer = ['' + ver1, '' + ver2, '' + ver3].join('.')463 } else {464 newVer = [arrVer[0], '' + ver2, '' + ver3].join('.')465 }466 } else {467 newVer = [arrVer[0], arrVer[1], '' + ver3].join('.')468 }469 newUpdateHistory.ver = newVer;470 newUpdateHistory.ver_order = self.genVerOrder(newUpdateHistory.ver);471 yield app.modelFactory().model_create(app.models['pub_appServerSideUpdateHistory'], newUpdateHistory);472 this.body = app.wrapper.res.default();473 } catch (e) {474 self.logger.error(e.message);475 this.body = app.wrapper.res.error(e);476 }477 yield next;478 };479 }480 },481 {482 method: 'upgradeAppClientSide',//管理中心将复制一条客户端升级记录,并增加一位版本号483 verb: 'post',484 url: this.service_url_prefix + "/upgradeAppClientSide/:appId,:os",485 handler: function (app, options) {486 return function *(next) {487 try {488 var updateHistories = yield app.modelFactory().model_query(app.models['pub_appClientSideUpdateHistory'], {489 where: {app_id: this.params.appId, os: this.params.os},490 select: 'app_id os ver ver_code force_update_flag download_url',491 sort: {ver_order: -1, check_in_time: -1}492 }, {limit: 1});493 if (updateHistories.length == 0) {494 this.body = app.wrapper.res.error({message: '当前App在该操作系统下没有任何版本信息!'});495 yield next;496 return;497 }498 var newUpdateHistory = updateHistories[0].toObject();499 delete newUpdateHistory._id;500 delete newUpdateHistory.id;501 var arrVer = newUpdateHistory.ver.split('.');502 var scale = 100;503 var newVer;504 var ver3 = parseInt(arrVer[2]);505 console.log(newUpdateHistory.ver)506 if (++ver3 == scale) {507 ver3 = 0;508 var ver2 = parseInt(arrVer[1]);509 ver2++;510 if (ver2 == scale) {511 ver2 = 0;512 var ver1 = parseInt(arrVer[0]);513 ver1++;514 if (ver1 == scale) {515 ver1 = 0516 }517 console.log(ver1)518 newVer = ['' + ver1, '' + ver2, '' + ver3].join('.')519 } else {520 newVer = [arrVer[0], '' + ver2, '' + ver3].join('.')521 }522 } else {523 newVer = [arrVer[0], arrVer[1], '' + ver3].join('.')524 }525 newUpdateHistory.ver = newVer;526 newUpdateHistory.ver_order = self.genVerOrder(newUpdateHistory.ver);527 yield app.modelFactory().model_create(app.models['pub_appClientSideUpdateHistory'], newUpdateHistory);528 this.body = app.wrapper.res.default();529 } catch (e) {530 self.logger.error(e.message);531 this.body = app.wrapper.res.error(e);532 }533 yield next;534 };535 }536 },537 /******************数据管理*********************************/538 {539 method: 'importDrug',//将药品的excel文件导入到公共药品库中540 verb: 'post',541 url: this.service_url_prefix + "/importDrug",542 handler: function (app, options) {543 return function *(next) {544 try {545 var file_name = this.request.body.file_name;546 // console.log(this.request.body);547 var file = path.join(app.conf.dir.rawData, file_name);548 // console.log(file);549 console.log('begin parse', app.moment().format('YYYY.MM.DD HH:mm:ss'));550 var worksheets = xlsx.parse(file);551 console.log('end parse', app.moment().format('YYYY.MM.DD HH:mm:ss'));552 var saveRows = [], sheetConfig;553 for (var i = 0, len = worksheets.length, worksheet = worksheets[i]; i < len; i++) {554 //读取导入配置555 for (var key in importDrugConfig) {556 if (key == worksheet.name) {557 sheetConfig = importDrugConfig[key];558 // console.log('importDrugConfig:', key, sheetConfig);559 // 解析colIndex560 var columns = sheetConfig.columns, col, colIndex;561 for (var j = 0, jlen = columns.length; j < jlen; j++) {562 col = columns[j];563 if (sheetConfig.header) {564 colIndex = app._.findIndex(worksheet.data[0], (o) => {565 return o == col.src566 });567 } else {568 colIndex = col.src;569 }570 if (colIndex != -1) {571 col['colIndex'] = colIndex;572 }573 }574 var row, colType, colValue, required, isSkip;575 console.log('begin row each', app.moment().format('YYYY.MM.DD HH:mm:ss'));576 var rowMax = (sheetConfig.to || 0) + 1 > worksheet.data.length ? (sheetConfig.to || 0) + 1 : worksheet.data.length;577 console.log('rowMax:', rowMax)578 for (var rowIndex = sheetConfig.from, rowLen = rowMax; rowIndex < rowLen; rowIndex++) {579 if (worksheet.data[rowIndex].length > 0) {580 row = {};581 isSkip = false;582 for (var k = 0, klen = columns.length; k < klen; k++) {583 col = columns[k];584 colType = col.type;585 required = !!col.required;586 colValue = worksheet.data[rowIndex][col['colIndex']];587 // console.log('col:', col, colType,col['colIndex'], worksheet.data[rowIndex][col['colIndex']]);588 if (colValue) {589 colValue = colValue.replace(/\r/g, '').replace(/\n/g, '');590 if (colType == 'number') {591 row[col.dest] = parseInt(colValue);592 } else if (colType == 'date') {593 row[col.dest] = app.moment(colValue);594 } else {595 row[col.dest] = colValue;596 }597 } else {598 isSkip = required599 }600 }601 if (!isSkip) {602 saveRows.push(row);603 } else {604 console.log('skip row:', rowIndex, worksheet.data[rowIndex]);605 }606 }607 }608 console.log('end row each', app.moment().format('YYYY.MM.DD HH:mm:ss'));609 }610 }611 }612 console.log('begin save row to db', app.moment().format('YYYY.MM.DD HH:mm:ss'));613 var needChunkNumber = 1000;614 if (saveRows.length > needChunkNumber) {615 var arrChunked = app.util.chunkArrayRange(saveRows, 100);616 for (var s = 0, sLen = arrChunked.length; s < sLen; s++) {617 // console.log('arrChunked:',s,arrChunked[s]);618 yield app.modelFactory().model_bulkInsert(app.models['pub_drug'], {619 rows: arrChunked[s]620 });621 }622 } else {623 // console.log('saveRows:', saveRows)624 yield app.modelFactory().model_bulkInsert(app.models['pub_drug'], {625 rows: saveRows626 });627 }628 console.log('end save row to db', app.moment().format('YYYY.MM.DD HH:mm:ss'));629 this.body = app.wrapper.res.default();630 } catch (e) {631 console.log(e);632 self.logger.error(e.message);633 this.body = app.wrapper.res.error(e);634 }635 yield next;636 };637 }638 },639 {640 method: 'syncDrugToTenants',//选中的药品同步到指定的机构641 verb: 'post',642 url: this.service_url_prefix + "/syncDrugToTenants",643 handler: function (app, options) {644 return function *(next) {645 try {646 var tenantIds = this.request.body.tenantIds;647 var drugIds = this.request.body.drugIds;648 if (tenantIds.length == 0) {649 this.body = app.wrapper.res.error({message: '必须选择至少一家养老机构!'});650 yield next;651 return;652 }653 if (drugIds.length == 0) {654 this.body = app.wrapper.res.error({message: '必须选择至少一条药品记录!'});655 yield next;656 return;657 }658 // 只同步有条形码的药659 var drugsToSync = yield app.modelFactory().model_query(app.models['pub_drug'], {660 select: 'barcode img name vender dosage_form specification usage indications_function special_individuals otc_flag medical_insurance_flag reference_price',661 where: {662 status: 1,663 barcode: {$exists: true},664 _id: {$in: drugIds}665 }666 });667 // 查询指定租户下某条码的药品是否存在668 var saveRows = [], drug, tenantId;669 for (var i = 0, len = drugsToSync.length; i < len; i++) {670 // console.log('arrChunked:',s,arrChunked[s]);671 drug = drugsToSync[i].toObject();672 for (var j = 0, jLen = tenantIds.length; j < jLen; j++) {673 tenantId = tenantIds[j];674 if ((yield app.modelFactory().model_totals(app.models['psn_drugDirectory'], {tenantId: tenantId, status: 1, barcode: drug.barcode})).length == 0) {675 drug.full_name = drug.name;676 drug.drugSourceId = drug.id;677 drug._id = undefined;678 drug.id = undefined;679 drug.health_care_flag = drug.medical_insurance_flag;680 drug.price = drug.reference_price;681 drug.tenantId = tenantId;682 saveRows.push(drug);683 } else {684 console.log('exist drug:', drug.name);685 }686 }687 }688 if (saveRows.length > 0) {689 yield app.modelFactory().model_bulkInsert(app.models['psn_drugDirectory'], {690 rows: saveRows691 });692 }693 this.body = app.wrapper.res.default();694 } catch (e) {695 console.log(e);696 self.logger.error(e.message);697 this.body = app.wrapper.res.error(e);698 }699 yield next;700 };701 }702 },703 {704 method: 'clearElderly',705 verb: 'post',706 url: this.service_url_prefix + "/clearElderly",707 handler: function (app, options) {708 return function *(next) {709 try {710 var elderlyId = this.request.body.elderlyId;711 this.body = yield app.system_helper.clearDataWithElderly(elderlyId);712 } catch (e) {713 console.log(e);714 self.logger.error(e.message);715 this.body = app.wrapper.res.error(e);716 }717 yield next;718 };719 }720 },721 {722 method: 'bedMonitorsAggregateQuery',723 verb: 'post',724 url: this.service_url_prefix + "/bedMonitorsAggregateQuery",725 handler: function (app, options) {726 return function *(next) {727 try {728 var rows = yield app.modelFactory().model_aggregate(app.models['pub_bedMonitor'], [729 {730 $lookup: {731 from: "pub_tenant",732 localField: "tenantId",733 foreignField: "_id",734 as: "tenantName"735 }736 },737 {738 $match: {739 // mac:{$ne:[ '$mac',null ]}740 mac: {$ne: null}741 }742 },743 {744 $project: {745 name: '$name',746 mac: '$mac',747 tenant: {tenantId: '$tenantId', stop_flag: '$stop_flag', name: '$tenantName'}748 }749 },750 {751 $group: {752 _id: '$name',753 mac: {$first: '$mac'},754 tenants: {$push: '$tenant'},755 }756 }757 ]);758 this.body = app.wrapper.res.rows(rows);759 } catch (e) {760 console.log(e);761 self.logger.error(e.message);762 this.body = app.wrapper.res.error(e);763 }764 yield next;765 };766 }767 }768 ];769 return this;770 },771 genVerOrder: function (ver) {772 var arr = ver.split('.');773 return parseInt(arr[0]) * 10000 + parseInt(arr[1]) * 100 + parseInt(arr[2]);774 }775}.init();...

Full Screen

Full Screen

back_conversion.py

Source:back_conversion.py Github

copy

Full Screen

...154 else:155 open_func = codecs.open156 kwargs = {'errors': 'ignore'}157158 with open_func(conllu_file, 'rb') as f:159 reader = codecs.getreader('utf-8')(f, **kwargs)160 #writer = codecs.getwriter('utf-8')161 buff = []162 count=0163 length_count=0164 bufdict={}165 write_mode=False166 devdict={}167 loop_count=0168 copdict={}169 reldict={}170 currentline=0171 bufdict[currentline]=0172 for line in reader:173 line = line.strip()174 #pdb.set_trace()175 #if line:176 if not line:177 #pdb.set_trace()178 count+=1179 try:180 if bufdict[currentline]==5:181 #pdb.set_trace()182 pass183 except:184 pass185 currentline+=1186 bufdict[currentline]=0187 else:188 pass189 #'''190 bufdict[currentline]+=1191192 sent=line.split('\t')193 194 #pdb.set_trace()195 #'''196 '''197 if line and not line.startswith('#'):198 if not re.match('[0-9]+[-.][0-9]+', line):199 buff.append(line.split('\t'))200 #buff.append(line.split())201 '''202 print(count)203 print(max(list(bufdict.values())))204 # pdb.set_trace()205 return206207208def write_sentence(conllu_file, first_set=False,maxlength=999,tb='ptb',extra_name='_modified'):209 #pdb.set_trace()210 if conllu_file.endswith('.zip'):211 open_func = zipfile.Zipfile212 kwargs = {}213 elif conllu_file.endswith('.gz'):214 open_func = gzip.open215 kwargs = {}216 elif conllu_file.endswith('.xz'):217 open_func = lzma.open218 kwargs = {'errors': 'ignore'}219 else:220 open_func = codecs.open221 kwargs = {'errors': 'ignore'}222223 with open_func(conllu_file, 'rb') as f:224 reader = codecs.getreader('utf-8')(f, **kwargs)225 tags=conllu_file.split('.')226 #tags.insert(1,'en')227 #tags.insert(2,tb)228 229 tags[-2]=tags[-2]+extra_name230 fout = open('.'.join(tags), 'wb') 231 #pdb.set_trace()232 #fout = open('', 'wb') 233 #pdb.set_trace()234 writer = codecs.getwriter('utf-8')(fout, **kwargs)235 buff = []236 count=0237 bufdict={}238 write_mode=False239 devdict={}240 currentline=0241 bufdict[currentline]=0242 writecount=0243 for line in reader:244 line_ = line.strip()245 #pdb.set_trace()246 247 if not line_:248 count+=1249 if (not currentline==-1) and bufdict[currentline]<maxlength:250 #pdb.set_trace()251 writecount+=1252 #writer.write('#'+str(currentline)+'\n')253 for buf in buff:254 writer.write(buf)255 writer.write('\n')256 buff=[]257 currentline+=1258 bufdict[currentline]=0259 elif line_[0]=='#':260 continue261 else:262 #pdb.set_trace()263 try:264 bufdict[currentline]+=1265 data=line_.split('\t')266 if '.' in data[0]:267 continue268 deps=[]269 dependency=data[-2].split('|')270 for dep in dependency:271 depid=dep.split(':')[0]272 if '.' not in depid:273 deps.append(dep)274 data[-2]='|'.join(deps)275 #pdb.set_trace()276 if len(data)==8:277 data.append('_')278 data.append('_')279280 # data[-2]=':'.join([data[-4],data[-3]])281 buff.append('\t'.join(data)+'\n')282 except:283 pdb.set_trace()284285 '''286 if line and not line.startswith('#'):287 if not re.match('[0-9]+[-.][0-9]+', line):288 buff.append(line.split('\t'))289 #buff.append(line.split())290 '''291 if (not currentline==-1) and bufdict[currentline]<maxlength and len(buff)>0:292 #pdb.set_trace()293 writecount+=1294 #writer.write('#'+str(currentline)+'\n')295 for buf in buff:296 writer.write(buf)297 writer.write('\n')298 fout.close()299 print(writecount)300 # pdb.set_trace()301 return302303def count_dependency(conllu_file, first_set=False):304 #pdb.set_trace()305 if conllu_file.endswith('.zip'):306 open_func = zipfile.Zipfile307 kwargs = {}308 elif conllu_file.endswith('.gz'):309 open_func = gzip.open310 kwargs = {}311 elif conllu_file.endswith('.xz'):312 open_func = lzma.open313 kwargs = {'errors': 'ignore'}314 else:315 open_func = codecs.open316 kwargs = {'errors': 'ignore'}317318 with open_func(conllu_file, 'rb') as f:319 reader = codecs.getreader('utf-8')(f, **kwargs)320 #writer = codecs.getwriter('utf-8')321 buff = []322 count=0323 length_count=0324 bufdict={}325 write_mode=False326 devdict={}327 loop_count=0328 copdict={}329 reldict={}330 currentline=0331 bufdict[currentline]=0332 distance_dict={}333 for line in reader:334 line = line.strip()335 #pdb.set_trace()336 #if line:337 if not line:338 #pdb.set_trace()339 count+=1340 try:341 if bufdict[currentline]==5:342 #pdb.set_trace()343 pass344 except:345 pass346 currentline+=1347 bufdict[currentline]=0348 else:349 pass350 #'''351 bufdict[currentline]+=1352353 sent=line.split('\t')354 # pdb.set_trace()355 distance=int(sent[6])-int(sent[0])356 if distance not in distance_dict:357 distance_dict[distance]=0358 distance_dict[distance]+=1359 print(count)360 res=[distance_dict[key] for key in distance_dict if abs(key)>10 ]361 print(max(list(bufdict.values())))362 # pdb.set_trace()363 return364365366def count_projective(conllu_file, first_set=False):367 #pdb.set_trace()368 if conllu_file.endswith('.zip'):369 open_func = zipfile.Zipfile370 kwargs = {}371 elif conllu_file.endswith('.gz'):372 open_func = gzip.open373 kwargs = {}374 elif conllu_file.endswith('.xz'):375 open_func = lzma.open376 kwargs = {'errors': 'ignore'}377 else:378 open_func = codecs.open379 kwargs = {'errors': 'ignore'}380381 with open_func(conllu_file, 'rb') as f:382 reader = codecs.getreader('utf-8')(f, **kwargs)383 #writer = codecs.getwriter('utf-8')384 buff = []385 count=0386 length_count=0387 bufdict={}388 write_mode=False389 devdict={}390 loop_count=0391 copdict={}392 reldict={}393 currentline=0394 bufdict[currentline]=0395 sentences=[]396 sentence=[]397 for line in reader:398 line = line.strip()399 #pdb.set_trace()400 #if line:401 if not line:402 #pdb.set_trace()403 count+=1404 try:405 if bufdict[currentline]==5:406 #pdb.set_trace()407 pass408 except:409 pass410 currentline+=1411 bufdict[currentline]=0412 if sentence!=[]:413 sentences.append(sentence.copy())414 sentence=[]415 else:416 pass417 #'''418 bufdict[currentline]+=1419 if line[0]=='#':420 continue421 sent=line.split('\t')422 sentence.append(sent)423 # pdb.set_trace()424 proj=0425 nproj=0426 for sentence in sentences:427 flag=0428 for token1 in sentence:429 for token2 in sentence:430 # pdb.set_trace()431 start1=int(token1[0])432 start2=int(token2[0])433 end1=int(token1[6])434 end2=int(token2[6])435 x1=min(start1,end1)436 x2=min(start2,end2)437 y1=max(start1,end1)438 y2=max(start2,end2)439 # pdb.set_trace()440 # if (start1>start2 and end1>end2) or (start1<start2 and end1<end2):441 # nproj+=1442 # flag=1443 # if (end1>start2 and start1>end2) or (end1<start2 and start1<end2):444 # nproj+=1445 # flag=1446 if (x1<x2<y1<y2) or (x2<x1<y2<y1):447 nproj+=1448 flag=1449 break450 if flag: 451 break452 if flag==0:453 proj+=1454455 print(proj)456 print(nproj)457 print(proj/(proj+nproj))458 # pdb.set_trace()459 # res=[distance_dict[key] for key in distance_dict if abs(key)>10 ]460 # print(max(list(bufdict.values())))461 # pdb.set_trace()462 return463464def pf(sentbuf):465 for sent in sentbuf:466 print(sent)467468def count_additional(conllu_file, first_set=False, write=False, extra_name='_modified'):469 #pdb.set_trace()470 if conllu_file.endswith('.zip'):471 open_func = zipfile.Zipfile472 kwargs = {}473 elif conllu_file.endswith('.gz'):474 open_func = gzip.open475 kwargs = {}476 elif conllu_file.endswith('.xz'):477 open_func = lzma.open478 kwargs = {'errors': 'ignore'}479 else:480 open_func = codecs.open481 kwargs = {'errors': 'ignore'}482483 with open_func(conllu_file, 'rb') as f:484 reader = codecs.getreader('utf-8')(f, **kwargs)485 if write:486 tags=conllu_file.split('.')487 tags[-2]=tags[-2]+extra_name488 fout = open('.'.join(tags), 'wb') 489 writer = codecs.getwriter('utf-8')(fout, **kwargs)490 buff = []491 count=0492 length_count=0493 bufdict={}494 write_mode=False495 currentline=0496 bufdict[currentline]=0497 addition_flag=0498 extra_node=0499 total_add_token=0500 total_tokens=0501 appear_add_count=0502 bad_add_count=0503 sentbuf={'0':['0','root','_','_','_','_','_','_','_','_']}504 addbuf=[]505 reldict={}506 repeat_edge=0507 for line in reader:508 line = line.strip()509 #pdb.set_trace()510 #if line:511 if not line:512 #pdb.set_trace()513 if write:514 writer.write(line+'\n')515 count+=1516 try:517 if bufdict[currentline]==5:518 #pdb.set_trace()519 pass520 except:521 pass522 currentline+=1523 bufdict[currentline]=0524 if addition_flag:525 # pdb.set_trace()526 extra_node+=1527 addition_flag=0528 for node in addbuf:529 sent=sentbuf[node]530 dependency=sent[-2].split('|')531 if len(dependency)>1:532 parentid=dependency[0].split(':')[0]533 if sent[1]=='_':534 bad_add_count+=1535 else:536 for x in dependency:537 if 'conj' in x:538 parentid=x.split(':')[0]539 #xcomp 540 541 else:542 parentid=dependency[0].split(':')[0]543 parent=sentbuf[parentid]544 assert parentid==parent[0], 'parent not right!'545 if parent[1]==sent[1]:546 appear_add_count+=1547 total_tokens+=len(sentbuf)548 sentbuf={'0':['0','root','_','_','_','_','_','_','_','_']}549 addbuf=[]550 elif line.startswith('#'):551 if write:552 writer.write(line+'\n')553 continue554 else:555 pass556 #'''557 bufdict[currentline]+=1558559 sent=line.split('\t')560 # pdb.set_trace()561 dependency=sent[-2].split('|')562 if len(dependency)>1:563 headids=[x.split(':')[0] for x in dependency]564565 if len(set(headids))<len(dependency):566 repeat_edge+=1567 rels=[':'.join(x.split(':')[1:]) for x in dependency]568 current_rel_dict={}569 for index, headid in enumerate(headids):570 if headid not in current_rel_dict:571 current_rel_dict[headid]=[]572 current_rel_dict[headid].append(rels[index])573 # pdb.set_trace()574 for headid in current_rel_dict:575 if len(current_rel_dict[headid])>1:576 newrel='+'.join(current_rel_dict[headid])577 if newrel not in reldict:578 reldict[newrel]=0579 reldict[newrel]+=1580 current_rel_dict[headid]=[newrel]581 write_dependency=[]582 for key in current_rel_dict:583 write_dependency.append(key+':'+current_rel_dict[key][0])584 sent[-2]='|'.join(write_dependency)585 # pdb.set_trace()586587588589590591 if '.' in sent[0]:592 total_add_token+=1593 addition_flag=1594 addbuf.append(sent[0])595 sentbuf[sent[0]]=sent596 #pdb.set_trace()597 #'''598 if write:599 writer.write('\t'.join(sent)+'\n')600 '''601 if line and not line.startswith('#'):602 if not re.match('[0-9]+[-.][0-9]+', line):603 buff.append(line.split('\t'))604 #buff.append(line.split())605 '''606 if len(sentbuf)>1:607 #pdb.set_trace()608 count+=1609 try:610 if bufdict[currentline]==5:611 #pdb.set_trace()612 pass613 except:614 pass615 currentline+=1616 bufdict[currentline]=0617 if addition_flag:618 # pdb.set_trace()619 extra_node+=1620 addition_flag=0621 for node in addbuf:622 sent=sentbuf[node]623 dependency=sent[-2].split('|')624 if len(dependency)>1:625 pdb.set_trace()626 else:627 parentid=dependency[0].split(':')[0]628 try:629 parent=sentbuf[parentid]630 except:631 pdb.set_trace()632 assert parentid==parent[0], 'parent not right!'633 if parent[1]==sent[1]:634 appear_add_count+=1635 # print("Total Sents:", count)636 # print("Total additional Sents:", extra_node)637 # print("Total additional Sents Percentage:", extra_node/count)638 # print("Total additional appeared Tokens:",appear_add_count)639 # print("Total additional Bad Tokens:",bad_add_count)640 # print("Total additional Tokens:",total_add_token)641 # print("Total Tokens with Repeat Edges:",repeat_edge)642 # print("Total Tokens:",total_tokens)643644 # print("Total additional appeared Tokens %:",appear_add_count/total_tokens)645 # print("Total additional Bad Tokens %:",bad_add_count/total_tokens)646 # print("Total additional Tokens %:",total_add_token/total_tokens)647 print(reldict)648 newlist=[]649 for key in reldict:650 vals=key.split('+')651 if set(vals) not in newlist:652 newlist.append(set(vals))653 else:654 pdb.set_trace()655 if write:656 writer.close()657 # pdb.set_trace()658 return659660def back_conversion(conllu_file, first_set=False, write=False, empty_node=False, extra_name='_back'):661 #pdb.set_trace()662 if conllu_file.endswith('.zip'):663 open_func = zipfile.Zipfile664 kwargs = {}665 elif conllu_file.endswith('.gz'):666 open_func = gzip.open667 kwargs = {}668 elif conllu_file.endswith('.xz'):669 open_func = lzma.open670 kwargs = {'errors': 'ignore'}671 else:672 open_func = codecs.open673 kwargs = {'errors': 'ignore'}674675 with open_func(conllu_file, 'rb') as f:676 reader = codecs.getreader('utf-8')(f, **kwargs)677 if write:678 tags=conllu_file.split('.')679 tags[-2]=tags[-2]+extra_name680 fout = open('.'.join(tags), 'wb') 681 writer = codecs.getwriter('utf-8')(fout, **kwargs)682 buff = []683 count=0684 length_count=0685 bufdict={}686 write_mode=False687 currentline=0688 bufdict[currentline]=0689 addition_flag=0 ...

Full Screen

Full Screen

commontools.js

Source:commontools.js Github

copy

Full Screen

1/**2 * CommonTools(JS Basic Functions)3 * @type {CommonTools}4 * @data:2019-10-125 * @author:lewk6 * @use CommonTools.xxx(params);7 */8CommonTools = new CommonTools();9function CommonTools() {10 this.map1="map_1";11 this.map2="map_2";12 this.checkName = function (input) {13 if (input.val() === '') {14 input.focus();15 $(".name_input_star").css("color", "red");16 return false;17 } else {18 $(".name_input_star").css("color", "black");19 return true;20 };21 }22 this.checkType = function (input) {23 if (input.select2("val") === null) {24 input.focus();25 $(".types_input_star").css("color", "red");26 return false;27 } else {28 $(".types_input_star").css("color", "black");29 return true;30 };31 }32 this.getIconByTypeName = function (name) {33 for (var i = 0; i < pois_types.length; i++) {34 if (pois_types[i].name === name) {35 return pois_types[i].src;36 }37 }38 return null;39 }40 this.getTypeByTypeValue = function (value) {41 for (var i = 0; i < pois_types.length; i++) {42 if (pois_types[i].value === value) {43 return pois_types[i];44 }45 }46 return null;47 }48 this.getFirstType = function (_types) {49 var _types_arr = _types.split(/{|,|}/);50 _types_arr = this.ArrayUniqueAddClearNull(_types_arr);51 if (_types_arr.length > 0) {52 return _types_arr[0];53 }54 }55 this.ArrayUniqueAddClearNull = function (arr) {56 return this.UniqueArr(this.ClearNullArr(arr));57 }58 this.ClearNullArr = function (arr) {59 for (var i = 0, len = arr.length; i < len; i++) {60 if (!arr[i] || arr[i] == '' || arr[i] === undefined) {61 arr.splice(i, 1);62 len--;63 i--;64 }65 }66 return arr;67 }68 this.UniqueArr = function (arr) {69 var hash = [];70 for (var i = 0; i < arr.length; i++) {71 if (hash.indexOf(arr[i]) == -1) {72 hash.push(arr[i]);73 }74 }75 return hash;76 }77 this.sortNumber = function (a, b) {78 //a,b表示数组中的任意两个元素,若return > 0 b前a后;reutrn < 0 a前b后;a=b时存在浏览器兼容79 return a - b //升序80 }81 this.GetLength = function (str) {82 var realLength = 0, len = str.length, charCode = -1;83 for (var i = 0; i < len; i++) {84 charCode = str.charCodeAt(i);85 if (charCode >= 0 && charCode <= 128) realLength += 1;86 else realLength += 2;87 }88 return realLength;89 }90 this.tip_alert_top = function (text, _width, _tpye, _time) {91 _width = _width ? _width : 300;92 _tpye = _tpye ? _tpye : 5;93 _time = _time ? _time : 1000;94 layer.msg(text, {95 offset: 't',96 area: [_width + 'px', '50px'],97 anim: _tpye,//5=闪现;6=晃动98 time: _time,99 });100 }101 this.line_colors = [102 {103 id: "fill_color_001",104 name_en: "Red",105 name_cn: "红色",106 value: "#FF0000"107 },108 {109 id: "fill_color_002",110 name_en: "Orange",111 name_cn: "橙色",112 value: "#FF7F00"113 },114 {115 id: "fill_color_003",116 name_en: "Yellow",117 name_cn: "黄色",118 value: "#FFFF00"119 },120 {121 id: "fill_color_004",122 name_en: "Green",123 name_cn: "绿色",124 value: "#00FF00"125 },126 {127 id: "fill_color_005",128 name_en: "Cyan",129 name_cn: "青色",130 value: "#00FFFF"131 },132 {133 id: "fill_color_006",134 name_en: "Blue",135 name_cn: "蓝色",136 value: "#0000FF"137 },138 {139 id: "fill_color_006",140 name_en: "Purple",141 name_cn: "紫色",142 value: "#9932CD"143 },144 {145 id: "fill_color_006",146 name_en: "Black",147 name_cn: "黑色",148 value: "#000000"149 },150 {151 id: "fill_color_006",152 name_en: "White",153 name_cn: "白色",154 value: "#FFFFFF"155 }156 ];157 this.btn_group = [158 {159 func: "SwitcherBase02",160 id: this.map1,161 top: 10,162 left: 200,163 open_label: "显示点",164 close_label: "隐藏点",165 open_func: OptCheck.show_layer_point_left,166 close_func: OptCheck.hide_layer_point_left167 }, {168 func: "SwitcherBase02",169 id: this.map1,170 top: 10,171 left: 280,172 open_label: "显示线",173 close_label: "隐藏线",174 open_func: OptCheck.show_layer_line_left,175 close_func: OptCheck.hide_layer_line_left176 }, {177 func: "SwitcherBase03",178 id: this.map1,179 top: 10,180 left: 360,181 open_label: "全显示",182 close_label: "清除",183 open_func: OptCheck.show_layer_all_left,184 close_func: OptCheck.clear_layer_all_left185 }, {186 func: "SwitcherBase02",187 id: this.map2,188 top: 10,189 left: 200,190 open_label: "显示点",191 close_label: "隐藏点",192 open_func: OptCheck.show_layer_point_right,193 close_func: OptCheck.hide_layer_point_right194 }, {195 func: "SwitcherBase02",196 id: this.map2,197 top: 10,198 left: 280,199 open_label: "显示线",200 close_label: "隐藏线",201 open_func: OptCheck.show_layer_line_right,202 close_func: OptCheck.hide_layer_line_right203 }, {204 func: "SwitcherBase02",205 id: this.map2,206 top: 10,207 left: 360,208 open_label: "显示分段",209 close_label: "隐藏分段",210 open_func: OptCheck.show_layer_line_subsection_right,211 close_func: OptCheck.hide_layer_line_subsection_right212 }, {213 func: "SwitcherBase03",214 id: this.map2,215 top: 10,216 left: 456,217 open_label: "全显示",218 close_label: "清除",219 open_func: OptCheck.show_layer_all_right,220 close_func: OptCheck.clear_layer_all_right221 }222 ];...

Full Screen

Full Screen

mime.py

Source:mime.py Github

copy

Full Screen

...68 '''Simulate double-clicking on the filename in a file manager. Order of69 preference is:70 1) @string mime_open_cmd setting71 2) _mime_open_cmd, defined per sys.platform detection72 3) open_func(fpath), defined per sys.platform detection73 4) mailcap file for mimetype handling74 '''75 global open_func76 c = keywords.get('c')77 p = keywords.get('p')78 if not c or not p:79 return None80 if p.h.startswith('@mime'):81 fname = p.h[6:]82 # honor @path83 d = c.scanAllDirectives(p)84 path = d.get('path')85 fpath = g.os_path_finalize_join(path, fname)86 # stop here if the file doesn't exist87 if not g.os_path_exists(fpath):88 g.error('@mime: file does not exist, %s' % fpath)89 return True90 # user-specified command string, or sys.platform-determined string91 mime_cmd = c.config.getString('mime-open-cmd') or _mime_open_cmd92 if mime_cmd:93 if '%s' not in mime_cmd:94 mime_cmd += ' %s'95 open_func = exec_string_cmd(mime_cmd)96 #no special handler function specified (unknown platform),97 #try mailcap/mimetype entries explicitly98 if open_func is None:99 (ftype, encoding) = mimetypes.guess_type(fname)100 if ftype:101 caps = mailcap.getcaps()102 (fullcmd, entry) = mailcap.findmatch(caps, ftype,103 filename=fpath,104 key='view')105 if fullcmd:106 # create a function which merely executes the fullcmd in107 # a shell for e.g. PATH access108 open_func = exec_full_cmd(fullcmd)109 else:110 g.error('@mime: no mailcap entry for %s: %s' % (ftype, fname))111 g.trace('mailcap command:', fullcmd)112 else:113 g.error('@mime: unknown file type: %s' % fname)114 # use the custom open_func to open external file viewer115 if open_func:116 open_func(fpath)117 else:118 g.error('@mime: no known way to open %s' % fname)119 # block execution of e.g. vim plugin120 return True121 # not an @mime node122 return val123#@-others124#@@language python125#@@tabwidth -4126#@+<< guess file association handler >>127#@+node:dan.20090203174248.35: ** << guess file association handler >>128#@+at Search for the best method of opening files. If running a desktop manager,129# do the action corresponding to a double-click in the file manager.130#...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful