Home

EzCapture

image

Contents

1. GRAPHIC ALTERATIONS function HideAllInputs document getElementById texta style visibility hidden document getElementBylId oka style visibility hidden document getElementBylId cancela style visibility hidden document getElementBylId checkbl style visibility hidden document getElementBylId checkb2 style visibility hidden document getElementBylId checkb3 style visibility hidden document getElementBylId checkb4 style visibility hidden document getElementById checkb5 style visibility hidden document getElementById textb style visibility hidden document getElementById okb style visibility hidden document getElementById labela style visibility hidden document getElementById labelb style visibility hidden document getElementById labelc style visibility hidden document getElementById labeld style visibility hidden document getElementById labele style visibility hidden document getElementById labelf style visibility hidden document getElementById labelg style visibility hidden document getElementById labelh style visibility hidden document getElementById style visibility hidden function RevealTopInput
2. 20 if PARAMS debug d command line control SDEBUG 1 if SPARAMS logprint d SLOGPRINT 1 im sPrint n Opening file lt SRAWFILENAME gt N with timestamp TIMESTAMP arguments PARAMS 0 sOpenLog LOGPRINT EZDIR SRAWFILENAME TIMESTAMP start writing to error c HERE we sequentially read in _three_ files SRAWFILENAME sbp csv SRAWFILENAME dbp csv SRAWFILENAME hr csv we then append thes 1 sbp open FILE SEZDIR rawdata SRAWFILENAME sbp csv or amp Die Unable to open sbp f my INDATA FILE close FILE f print LOGFILE n nDebugging A lt INDATA gt n n 2 dbp open FILE2 SEZDIR rawdata SRAWFILENAME dbp csv or amp Die Unable to open dbp 1 my hdr Shdr lt FILE2 gt 4 discard first line my IN2 lt FILE2 gt close FILE2 print LOGFILE n nDebugging B lt IN2 gt n n 3 hr open FILE3 SEZDIR rawdata SRAWFILENAME hr csv or amp Die Unable to open hr fil Shdr lt FILE3 gt discard first line my IN3 lt FILE3 gt close FILE3 f print LOGFILE n nDebugging C lt IN3 gt n n INDATA INDATA IN2 01N3 concatenate my ALLDATA my ZEROES my YCALS my tCAL reference values my CALAlo 5
3. 9 WORKING PHP CODE 157 PrintPoplist ShandDB personrole SELECT personrole PERSONROLE rText from PERSONROLE WHERE personrole gt 0 ORDER BY personrole print lt lt lt HTML3 lt td gt lt tr gt lt tr gt lt td gt lt td gt lt td gt Please state main area of practice lt td gt lt td gt HTML3 PrintPoplist ShandDB currentlocation SELECT currentlocation CURRENTLOCATION LocationText from CURRENTLOCATION WHERE currentlocation gt 0 ORDER BY currentlocation print lt lt lt HTML4 lt td gt lt tr gt lt tr gt lt td gt lt td gt lt td gt Does anaesthetist have a particular anaesthetic interest lt t HTML4 PrintPoplist ShandDB currentspecialty SELECT currentspecialty CURRENTSPECIALTY SpecialText from CURRENTSPECIALTY WHERE currentspecialty gt 0 ORDER BY currentspecialty print lt lt lt HTML5 lt td gt lt tr gt tr td td td lt INPU YPE submit NAME submit VALUE Enter new person gt lt td gt lt td align right lt INPU YPE reset VALUE Clear Form onClick return ConfirmClear gt lt td gt lt tr gt lt table gt lt FORM gt lt p gt lt a href mainpage php Return to main page lt a gt body html HTML5 The most interesting feature of the above page is the hidden POST variable called confirmation forced to zero so that eZ admin personadded php kno
4. EZPATH ez SREPLAYPATH SEZPATH ez replayA SLISTNAME REPLAYPATH SSLIST TXT get current file if left off in middle CurrentFile txt 5 EZ REPLAY REPLAYING DATA VIA SAFERSLEEP 97 SCURRFILENO FileReadLin DEBUG ONLY CURRFILENO 1 if error lt gt 0 then Exit EndIf sgBox ONTOP FATAL REPLAYPATH amp CurrentFile txt 1 open read close if failed Error Failed to 7 at present do not rewrite this so must MsgBox ONTOP Debug SFD GetFileList LISTNA If SFD 0 0 Then sgBox ONTOP Fatal EndIf SCURRENTFILE ED 1 SCAPTURECOUNT SFD 2 File index is E SCURRFILENO Error Line not 7 here might check th open CurrentFile txt be updated manually amp SCURRFILENO 10 T found in file list No SCURRFILENO above are valid and reasonable E sgBox ONTOP Debug File is SCURRENTFILE amp Count amp SCAPTURECOL SCAPTUREINTERVAL SONEMINUTE SLACKTIME PSPNAIT PSPWAIT2 Sstub StringSplit CURR ENTFILE 7 SFAKENHI SS amp Sstub 1 MsgBox ONTOP DEBUG Fake NHI is SSAVEPATH ez ez captur images SSAVENAME SSAVEPATH amp CURRENTFILE will remove suffix
5. H E S TABLE s w NW im 7 DATABASE DEFINITION 130 Squery Smatches ver 0 64 Stblname matches 1 if tblname METATABLE Siq INSERT INTO METATABLE metatable TableName VALUES SMETACOUNT tblname SMETACOUNT 1 if mysql_query iq handDB print Xn Error with metadata tblname y H if mysql query query ShandDB print An Error during SQL execution mysql error return 0 fail query print lt br gt Number of lines submitted linecount return 1 success function FetchNextLine 8 query fdata STATIC LINE on first pass made zerol while LINE lt count fdata Stxt Sfdata SLINE get next line SLINE ld if preg match txt if not comment Squery query txt if preg match s S txt terminal return 1 y y Y SLINE 0 4 in case re invoke FetchNextlLine return 0 no more lines D The relevant SQL initialisation file is called lt i gt eZ sql lt i gt and must be present in the sql subdirectory of the current directory or creation will fail php if is null handDB provided connected if is eZ populated handDB if batch sql statements handDB sql eZ sql print
6. movement between data series e g from SBP to DBP is so important we define the function sub NextSeries my St z y2 St 52 y2 _ sRecalibrate t z y2 SIDX SSTORECOUNT 1 for debugging amp Print n n n DEBUG transition SIDX at line LINECOUNT 2 Here s the subsidiary routine sub Recalibrate my St z y2 St 52 y2 2Q0 amp StoreZero t 52 sStoreYCal t y2 if 1 amp ISIN 52 ZERO amp Die Repeat zeroing failed z can happen if my if 2 EZ CAPTURE MANUAL DATA CAPTURE 28 amp ISIN y2 MAXVAL amp Die Repeat Y calibration failed Sy2 can happen Stcorr t 5 5 was added by default Stcorr SDURATION amp Print n WARNING Durations don t match Baseline is DURATION this is tcorr 0 NARNINGS EXITCODE SERIESCOUNT amp Print n nExit code SERIESCOUNT 0 durations don t match for given epoch hmm 2 3 5 FiO EtCO After determining the number of values to acquire which is simply the DURA TION measurement divided by 5 we acquire first SpO2 and then EtCO2 values if present allowing the user to enter NA values where appropriate sub ReadSpO2andETCO2 my my amp Print Tod SIDX 3 open FILE amp Die Unable my Shdr my close FILE my if EZDIR EZDIR
7. If perlok 0 Then MsgBox SONTOP Note Conversion was successful TestmDAT mDAT SEZPATH SFILENAME m check if can enable Else sgBox SONTOP Debug Return code was amp perlok here might check that target csv file exists and if so enable next step EndIf SGOODITEMS bitAND perlok 31 if last 5 bit flags SetGoodItems GOODITEMS SvSBP vDBP vHR S vSpO2 vETCO2 bits that are set indicate errors 2 EZ CAPTURE MANUAL DATA CAPTURE 45 StoreParam EZPATH FILENAME SEZ VALIDFLAGS GOODITEMS Store valid Case msg mDAT perlok RunWait GComSpec amp c perl amp _ SEZPATH amp ez xlatelez csv2dat pl amp SFILENAME m datrules txt SEZPATH If perlok 0 Then MsgBox SONTOP Note Conversion was successful TestFile mSS SEZPATH dat FILENAME m dat Else MsgBox ONTOP Debug Return code vas amp perlok EndIf Case msg mSS If AddToSSList EZPATH SFILENAME m SDURATION gt Then if success SISLISTED BitOR SISLISTED 1 bit 0 set manual StoreParam SEZPATH FILENAME EZ ISLISTED SISLISTED Store listed sgBox ONTOP Success Added to play list amp FILENAME 6 m DAT If SISLISTED 3 Then 7 if
8. SK SALTSIZE global constant SI Ssalt SK print lt p gt Debug index of salt item is SI Snow time STIMEOUT SALTTIMEOUT 5min global Sqry SELECT sTime sValue FROM SALT WHERE salt I list STIME SSVALUE GetSQL ShandDB Sqry check salt print lt p gt Debug time is STIME salt is SVALUE 5 2 rand hmm if SSVALUE Ssalt oops print lt p gt Debug failed Values SVALUE Ssalt readfile busy htm exit hmm might differentiate this from next or log 8 PHP ACCESS CODING 139 H Sqry UPDATE SALT SET sValue U2 WHERE salt SI DoSQL handDB ary prevent salt reuse if Snow STIME gt TIMEOUT timed out print p Debug timeout SSTIME TIMEOUT amp lt Snow readfile busy htm exit now have valid SALT value Get user password Sqry SELECT person pPassword FROM PERSON WHERE pLoginName Susername list Suk SMD5PWD GetSQL ShandDB Sqry md5 password if strlen SMD5PWD lt 31 hack for startup SMD5PWD md5 SMD5PWD ff print lt p gt Debug md5 pwd for username is 5 5 SCHECKVAL md5 salt MD5PWD concatenate then md5 print lt p gt Debug salted password md5 is SCHECKVAL if psud CHECEVAL Force Html InitialLogon Inval
9. We concatenate in a value to sort out the potential if infrequent problem where two data values are stored against the same time We might later test for and warn about this anomaly Similar are StoreZero and StoreYCal and a smaller stack to store the few X axis time calibrations we do sub StoreZero my St Sz St z _ amp Print n Debug ZERO is z 3 SZEROES St z sub StoreYCal my 56 Sy St Sy _ amp Print n Debug Y cal is Sy 3 SYCALS t Sy push YCALS Sy discard t sub StoretCal my 56 x St x _ amp Print n Debug X cal is x n 3 StCAL St x 2 3 3 Tests of calibration We must be able to test Y calibration At the same time based on the Y calibra tion value we determine the type of record and hence set the alpha value We also return the MINVAL TestYCal returns three pairs of values corresponding to low and high values for maximum alpha and minimum values for one of three possible anaesthetic forms sub TestYCal my 56 c 2 EZ CAPTURE MANUAL DATA CAPTURE 25 St c _ sStoreYCal t c my tiny 1 my alphaAlo 2 25 0 10 my alphaAhi 2 25 0 10 my alphaBlo 4 43 2 Not 10 min Must have 5 min my alphaBhi 4 63 2 my alphaClo 3 11 my alphaChi 3 31 my minlo tiny t 10 my minhi tiny t 10 if amp ISIN
10. enter fak Seems ok MsgBox SONTOP WinWaitActive Edit mv patient details Enter fake details Debug Patient Send Demo Sleep 50 Send TAB Sleep 50 Send CURR Sleep 50 Send TAB Sleep 50 Send 26 12 1900 Sleep 50 Send TAB Sleep 50 Send E Sleep 50 Send TAB Sleep 50 Send ENTER Sleep 500 ENTFIL MAINVINDO e g MsgBox S ONTOP If WinExists MAINW sgBox ONTOP E Exit Else NAME rr MsgBox ONTOP rr SAFERsleep SAFERsleep SSS0012 Debug y INDOWNAME ror Success Wait for mai Window not fou Window fou The menu exists tive Start New Anaesthetic amp FAKENHI Demo S0012 s n vindov Anaesthetic c 0 Then rid 4 nd amp SMAINWINDOWNAM Gl amp SMAINWINDOWNAM hart amp SMAINWINDOWNAM D EMO MODE 5 EZ REPLAY REPLAYING DATA VIA SAFERSLEEP Sleep 30 EndIf WinActivat ControlCli MouseClick left Send Send ggg 00 7 just in cas mv e SMAINWINDOWNAM ck MAINWINDOWNA 132 P 352 Lk py HOP Pi Send ENT ER start anaesthetic Sleep 1000 o gt next Sxy SWINX SWINY SWINW SWINH SWINH2 5 Sxy Con MouseClic K
11. if preg match PASSWORD i Sfnam no password SHDR fnam ftype SFLDLIST fnam y j 1 im SFLDLIST rtrim FLDLIST trim terminal comma if mysql fetch array RSLT if any rows print HDR print header next get and print all data Sqry SELECT FLDLIST FROM tname WHERE Skeyname gt Skeymin print n S debug sql qry SALLDATA SQLManySQL ShandDB Sqry get all table data foreach ALLDATA as DROV print n nev rov foreach SDROW as SDT replace CR within data with n SDI str_replace n An SDI replace comma with SDI str replace N SDI print NU SDIXT m im y 10 ANCILLARY CODE 189 10 Ancillary code The following ancillary functions are used throughout the database They are all contained within ancillary php The image tinyezlogo png is also required as is the trivial vbar png 10 1 General purpose functions 10 1 1 eZHeaderGreet Return text string and add in header with image function eZHeaderGreet success SMINUSERSTATUS SMAXUSERSTATUS Stitle Sprevious previous is or 1 matches list SUSER SUSERSTATUS SOLDPAGE PullOutUserInfo success if USERSTATUS SMINUSERSTATUS SUSERSTATUS gt SMAXUSERSTATUS readfile failedaccess htm exit fail y print lt br
12. Dinarray i 1 gt gt 2 gt gt 8 i 1 4 amp OxFF lt lt 8 binarray i 2 gt gt 2 gt gt 8 i 2 4 OxFF for var j j 4 j if i 8 j 6 gt binarray length 32 str b64pad else str tab charAt triplet gt gt 6 3 amp 0x3F return str 8 PHP ACCESS CODING 145 8 2 Validate user Note that invocation of ValidFx php implies availability of all the functions in ancillary php The following script contains the function validate_login which should be in voked at the start of all PHP scripts which wish to access eZ This function checks that the current user is actually logged on and if so permits access to the relevant page If the user isn t logged on then a log in screen is popped up Do not confuse this with the initial log on performed by the script InitialLogon php The reason why we need to validate the user for every page is that HTML is stateless we need to identify a particular user by comparing a cookie stored on their machine with a value in the database This value is the session ID SID Once the invoking page has said require_once ValidFx php it can actually invoke validate_login We submit the parameter value SHOW_USER to this func tion although at present this value isn t checked or used The script sets the global USERKEY to the user primary key from the SQL database table PERSON and handDB becomes an open handle on the database
13. Sqry SHOW TABLES good in mySQL if Stbllist SQLManySQL handDB qry show tables Sqry SELECT TableName FROM METATABLE ORDER BY metatable Stbllist SQLManySQL handDB qry get tables tbllist Flatten tbllist foreach tbllist as t Skeymin 1000 default if t UIDS vital Skeymin 1 clumsy hack minimum key PrintTableCsvData ShandDB t keymin im print n n END OF DATA s function PrintTableCsvData handDB tname keymin print AnssDEBUGGING Table is tname minimum key keymin HDR n n S TableName Stname 4 record table name Skeyname strtolower Stname lower case key our rule Include column meta data here SHDR An ColumnData we have the minimum possible key Skeymin but the actual minimum might be larger so check this Sqry SELECT MIN Skeyname FROM tname WHERE Skeyname gt keymin list km GetSQL ShandDB qry get actual min if strlen km gt 0 Skeymin km im get the very first rov so ve can get field attribs Sqry SELECT FROM tname WHERE keyname keymin SRSLT mysql_query Sqry SFLDS mysql num fields RSLT j 0 SHDR SFLDS print n Debug Number of fields is SFLDS FLDLIST while j lt FLDS f for each field 9 WORKING PHP CODE 188 Sfnam mysql_field_name RSLT j Sftype mysql field type RSLT 3
14. 10 6 3 SQLManySOL 244625445 xk FetehKey so corran 7 10 41 T K lt o cepa spera nemes tenia 10 7 2 An initial solution 10 7 3 A refined solution CONTENTS 4 10 7 4 Working code 264 vr Rr Rr x Rx 206 11 Hardware software useful files amp Change Log 209 ULA ChangeLog Loss ouo ss x 2739 HH de DOR ORO a a d 212 11 1 1 Changes Tor versi n 0 37 lt o s s necs ooo ae RE n 213 12 Still to Do 214 1 INTRODUCTION 5 1 Introduction This is a suite of programs that accomplishes the following Reliable measurement of hand written anaesthetic records combined with recording of these measurements in the form of database CSV files that can be read by most database and analysis software Partial automation of the above measurement process with relevant checks Translation of CSV files into a data format DAT readable by the SAFER sleep IDAS program Sequential display of IDAS DAT files in a standard format familiar to anaesthetists who use the program for everyday patient data recording and display Sequential minute by minute capture of display screens from IDAS and storing of captured screens as PNG data files Sequential presentation of PNG images in real time or if desired faster by serving them up in a web page This application allows the anaesthetist to annotate the anaesthetic as it progresses Storage of annotations to an internet da
15. 30611744 1560198380 1309151649 145523070 1120210379 718787259 343485551 142 8 PHP ACCESS CODING return safe add bit rol safe add safe add a q safe_add x t s b function md5_ff a b c d x s t return md5 cmn b amp c COB s d ay Din x Sp o function md5 gg a b c d x s t return md5 cmn b amp d c amp CAY a X S t function mas hh a d x s t return md5 cmn b c d a b x s t function md5 ii a b C d x s t return md5 cmn c b d a b x s t x Calculate the HMAC MD5 of a key and some data function core_hmac_md5 key data var bkey str2binl key if bkey length gt 16 bkey core_md5 bkey key length chrsz var ipad Array 16 opad Array 16 for var 1 i 16 i ipadlil bkey i 0x36363636 opad i bkeylil 0x5C5C5C5C var hash core md5 ipad concat str2binl data 512 data length chrsz return core_md5 opad concat hash 512 128 x Add integers wrapping at 2732 This uses 16 bit operations internally to work around bugs in some JS interpreters function safe_add x y var lsw x 6 OxFFFF y OxFFFF var msw x gt gt 16 y gt gt 16 lsw gt gt 16 return msw lt lt 16 lsv amp OxFFFF x Bitwise rotate a 32 bit number to the left function bit rol num cnt return n
16. Case msg SbDBP Soverw 1 If IsRawFile dbp SFILENAME 1 Then Soverw MsgBox SONTOP 1 Warning Raw DBP data already captured Overwrite If Soverw 1 Then cancel 2 create single backup fnm EZPATH amp rawdataN FILENAME amp dbp csv FileCopy fnm fnm amp BAK 1 overwrite if exists EndIf EndIf If Soverw 1 Then GuiSetState G8 SW MINIMIZE GetSequence dbp SFILENAME SDATETIME SFAKEDCMS myCheck xDBP SFIVEITEMS BitOR SFIVEITEMS 2 GuiSetState SW_RESTORE EndIf Case msg bHR Soverw 1 If IsRawFile hr FILENAME 1 Then Soverw MsgBox SONTOP 1 Warning _ Raw HR data already captured Overwrite If Soverw 1 Then cancel 2 create single backup Sfnm EZPATH amp rawdataX FILENAME amp hr csv FileCopy fnm fnm amp BAK 1 overwrite if exists EndIf EndIf If Soverw 1 Then GuiSetState G8 SW MINIMIZE GetSequence hr SFILENAME DATETIME FAKEDCMS myCheck xHR SFIVEITEMS BitOR SFIVEITEMS 4 GuiSetState 0SW RESTORE EndIf Case msg bSpO2 Soverw 1 If IsRawFile spo2 SFILENAME 1 Then Soverw MsgBox SONTOP 1 Warning Rav SpO2 data already captured Overwrite 2 EZ CAPTURE
17. Y 10 4 User information 10 4 1 PullOutUserInfo Given a user string pull out user and associated details Returns a list of the three items in that order function PullOutUserInfo Suserstring Smatches if preg match USER STATUS OLDPAGE Suserstring matches print lt br gt Error Bad user data Terminated String was amp lt Suserstring gt exit im array shift matches remove first element uhich is the vhole match return matches 10 4 2 GetLinkedUserDetails The following is like GetUserDetails from eZ_admin_personadded php but the added parameter link is something along the lines of lt a href eZ_do_editlogon php editlogon USERID gt Go lt a gt A required component is the text string USERID replaced with the relevant key contained in the list link The URL represents a GET not POST to the page specified e g eZ_do_editlogon function GetLinkedUserDetails handDB unames link Sunames is array of IDs key of PERSON table this fx is cumbersome and slow returns array of arrays each subarray containing 10 ANCILLARY CODE 196 forename surname role date started practice as year 01 01 and link URL contains ID Sopt array ie 0 foreach Sunames as Sp Sdetl array Sdet1 0 FetchForename handDB p Sdetl 1 FetchSurname handDB p Sdet1 2 F
18. define SALTSIZE 100 define SALTTIMEOUT 300 4 seconds F a F py 4 Convenient globals SCONNECTIONPATH eZ database connect php above is for anaesthetist com setup ShandDB SUSERKEY SDEBUGGING 0 5 nasty hacks SCLUMSY_INDEX 0 SCLUMSY INDEX2 y sh y ah 7 10 1 Database creation script Here we create a combined HTML PHP script called database create php To create the database ensure the file eZ sql is in the correct location specified below and then simply access the file database create php with your web browser http www anaesthetist com eZ database create php This is a one off page which will do nothing once the database has been cre ated In fact it might be wise to completely remove this page from our server once we ve made the database Once created the database can of course be viewed us ing phpMyAdmin lt head gt lt title gt Create th Z database lt title gt lt head gt lt body gt lt h2 gt Create a database lt h2 gt DT s wise to immediately alter the password using phpMyAdmin if you ve not inserted an encrypted password in the SQL creation file 7 DATABASE DEFINITION 129 lt p gt Here we read a SQL script file parse it and submit the CREATE statements contained within to mySQL We will use this facility to create an entire database
19. le SEZDIR my LE I my logf O none Slevel _ SDEBUG gt SLOGPRINT print LOGFIL Sis my STODAY i n Fatal eve 12 http perl level fatal 128 0 Log Slevel l overvi W 2 detail is debugging level 3 picky if level return print LOGFILE gt Slogfile print n Writing to log file E Sp f console print ENAME log SFILENAME iar TODAY LOG ENAME Q not logging if is 0 always print clumsy ldoc perl org functions exit html or die CRASH Could not open LOG logfile Slogfile n 3 RETRIEVE FILES FROM SAFERSLEEP USING PERL 76 sub CloseLog my Sislog Sislog if Sislog close LOGFILE y _ sub GetLocalTime my sec min Shour Smday mon year Swday yday isdst sec min hour Smday mon year Swday yday isdst CORE localtime time Syear 1900 fix y2k Ssec amp DoubleDigit sec Smin amp DoubleDigit min Shour amp DoubleDigit Shour Smday amp DoubleDigit mday Smon amp DoubleDigit mon Smon january is zero return year mon mday hour min sec sub DoubleDigit Si i 0 if length i gt 1 return i im return 0 i concatenate
20. 10 ANCILLARY CODE 202 10 7 FetchKey Within ancillary php we initially had a FetchKey function as follows but there are substantial albeit infrequent problems with this approach function FetchKey ShandDB Sky start atomic list Skeyval GetSQL handDB SELECT uSky FROM UIDS WHERE uids 1 get key value Skeyval the problem is here DoSQL handDB UPDATE UIDS SET u ky keyval WHERE uids 1 set new key value Fend atomic Skeyval return keyval The above doesn t cater for two competing processes and the requirement that such key increments must be atomic We therefore describe a generic mechanism for ensuring retrieval of sequential keys in an SQL database 10 7 1 The problem The problem is as follows 1 There is no standard mechanism for generating auto incrementing keys and most solutions require either proprietary modifications to the SQL standard or use of non core measures such as invocation of appropriate functions written in a language acceptable for extending SQL 2 If we try something along the lines of the above where two SQL statements are used with an intervening increment there are many potential points of breakdown As the two SQL statements with the intervening increment are not atomic another process can interrupt retrieving the same value and then can use this same key also writing the key value onc
21. Return to main page Figure 8 Editing a person s details 5 Editing someone s details Here we have the facility to edit a person s details This introductory page eZ edit person php allows us to select a particular person When the administrator clicks on a link control is transferred to the page eZ do edit php header Cache control no cache STHISPAGE eZ edit person php require once ValidFx php our login validation script SMINUSERSTATUS eZ ADMINISTRATOR MIN SMAXUSERSTATUS EVERYONE success validate login SHOW USER list SMYHEADER SUSERSTATUS eZHeaderGreet success print lt lt lt HTML1 SMINUSERSTATUS SMAXUSERSTATUS Edit somebody s details 0 lt DOCTYPE HTML PUBLIC W3C DTD HTML 4 01 Transitional EN gt lt html lang en gt lt head gt lt title gt Edit details lt title gt LINK href css eZstyle css type text css rel stylesheet head body SMYHEADER lt p gt lt a href mainpage php Return to main page lt a gt H1 5 lt h3 gt Select a user sorted by surname lt h3 gt TML1 link lt a href eZ_do_edit php editperson USERID gt Go lt a gt PrintActiveUserlist ShandDB link print lt lt lt HTML3 lt table gt lt div gt 9 WORKING PHP CODE 172 lt p gt lt a href mainpage p
22. THIS MAKES A PNG 60 5 EZ REPLAY REPLAYING DATA VIA SAFERSLEEP 101 Else SCURRFILENO CURRFILENO 1 SFD GetFileList SLISTNAME CURRFILENO If SFD 0 0 Then ISMORE 0 Else SCURRENTFILE SFD 1 SCAPTURECOUNT SFD 2 here might check the above are valid and reasonable MsgBox ONTOP Debug File is amp CURRENTFILE Count 6 SCAPTURECOUD WinActivate MAINWINDOWNAME MouseClick left 946 426 hack hack Sleep 100 hack Send ENTER do you want to end anaesthetic YES Sleep 100 25 hack Send TAB ENTER do NOT print Here to start another anaesthetic Send ENTER Sleep 3000 enough time to save etc Send ENTER Start new anaesthetic EndIf ndif ri Wend 7 END BIG OUTER LOOP FOR SINGLE ANAESTHETICS E ND OF MAIN SECTION EndCapture is FUNCTIONS l LeadZero n This checks length and if under 3 prepends zeroes Func LeadZero n While StringLen n 3 n 0 amp n Wend Return n EndFunc Func CheckAntibiotic If WinExists Antibiotic Warning 1 Then WinActivate Antibiotic Warning Send ENTER EndIf EndFunc 7 EndCapture close all applications 5 EZ REPLAY REPLAYING DATA VI
23. amp SFAKENHI i ACTUALLY RUN THINGS run safersleep 7 here might get path to idas from registry h C Program Files Safer S1 Sidaspa If FileExists idaspath sgBox ONTOP Error Exit EndIf Run Sidaspath If WinWaitActive SAFERsleep 30 0 Then sgBox ONTOP Error Exit EndIf Sleep 15000 5 clumsy CLUMSILY 0 Then IDAS exe not found Failed to load SAF If WinExists Information Then WinActivate Information Send ENTER PI but for now p IDAS Client IDAS exe amp Sidaspath allow 30s for boot ERsleep this is for the bloody INFORMATION box 5 EZ REPLAY REPLAYING DATA VIA SAFERSLEEP 98 if cannot connect to server Else MsgBox ONTOP Dx Info box NOT detected Click OK Send ENTER allow manual wait or not EndIf Sleep 3000 If WinExists SAFERsleep Login Screen Then MsgBox ONTOP Dx Login Screen detected Send ENTER Hit enter at Login screen Else MsgBox ONTOP Dx Login Screen NOT detected Click OK Send ENTER Hit enter at Login screen EndIf Sleep 3000 If WinExists Info
24. lt body bgcolor CCCCCC gt lt FORM name myform action lt FIX ME FILL IN ACTION gt lt table cellpadding 0 cellspacinge 07 vidthe 10056 border 0 gt main table gt lt tr gt td width 10 lt span class gt lt div align center invisiblevarning id loadingLabel gt Loading lt span gt lt img name cl ock src images clk0 png alt width 48 height 48 gt lt b class invisiblewarning id elapsedLabel gt Elapsed nbsp time lt br gt lt b gt lt span class invisiblewarning id elapsedTime gt lt span gt lt div gt lt td gt lt td width 90 6 bgcolor 4CCCCCC colspan 3 align center gt img class prominent src images INTRO png alt width 824 height 446 name mainimage border 3 td tr tr td colspan 3 bgcolor white hr td tr tr bgcolor whi td colspan 3 lt b gt Case S0012 lt lt td gt lt tr gt te gt lt patient info at bottom gt align left gt b gt Appendectomy A well young man amp nbsp nbsp nbsp amp nbsp lt tr gt lt td colspan 3 bgcolor white hr td tr tr bgcolor white td align center gt lt p gt lt input t ype button onClick DoNext ide nextbutton value snbsp nbsy 6 EZ SHW AN INTERACTIVE WEB BASED APPLICATIO
25. numobs spo2 RANFIL ENAME SRAWFIL ENAME l int n n OBS COUNT EZDIR Shdr lt FILE SPO2 gt lt FILE gt sz 1 sz ES SPO2 Snumobs SEXITCODE amp y Print 8 sXferData 6SPO2 2 IDX 4 open FILE etco2 l signal EZDIR SDURATION 4 5 Snumobs f signal SpO2 rawdata SRAWFIL to open spo2 file rawdata SRAWFIL first SDURATION SDURATION _ SDURATION 1 ENAM E spo2 csv ENAM or E line will not 1 signal be skipped as balances header line problem with spo2 data count or use SSERIESCOUNT n nExit code 8 ETCO2 rawdata SRAWFIL amp Die Unable to open etco2 file rawda observations Snumobs sz 0 ENAME etco2 csv or ta SRAWFILENAME 2 EZ CAPTURE MANUAL DATA CAPTURE 29 Shdr lt FILE gt my ETCO2 lt FILE gt close FILE my sz 1 SPO2 if sz numobs SEXITCODE 16 signal problem with etco2 data or use SSERIESCOUNT amp Print n nExit code 16 observations numobs sz 0 y amp XferData ETCO2 sub XferData my X 8
26. Person integer Persdata integer Anrecord integer Onesession integer Rating integer Ge SEE NE EE T auxPerson integer auxPersdata integer TThey would have to be manually updated within the database 7 DATABASE DEFINITION auxAnrecord integer auxOnesession integer auxRating integer INSERT INTO UIDS uids uPerson uPersdata uAnrecord uOnesession auxPerson auxPersdata auxAnrecord auxRating VALUES 1 1000 1000 1000 1000 1000 1000 1000 1000 INSERT INTO PERSON person pLoginName pPassword VALUES 1 Superuser PasswordGoesHere INSERT INTO PERSDATA persdata Person pdForename pdSurname PersonRole VALUES 1 1 Mr Superuser 19297 124 The last fevv statements create a single super user vvho vvill be able to log on vvith the username Superuser and the relevant passvvord Note that as things stand this naked password is inserted into the database and will allow the Su peruser to log on It is wise for him her to then immediately alter the password even smarter would be to insert an md5 encoded password into the above code 7 DATABASE DEFINITION PERSONROLE CURRENTSPECIALTY PERSDATA CURRENTLOCATION gt ONESESSION RATING 1 125 PERSON FORENSIC ANRECORD Table 3 Database table relationships 7 8
27. c CALA amp Print n Debug record type is A 1 return c tiny S c tiny SalphaAlo SalphaAhi Sminlo minhi elsif amp ISIN c CALB amp Print An Debug record type is B 1 return c tiny S c tiny SalphaBlo alphaBhi minlo minhi elsif amp ISIN Sc CALC amp Print n Debug record type is C 1 return c tiny S c tiny SalphaClo alphaChi minlo minhi else amp Die n Bad Y calibration value c 1 Check the x time axis value sub TesttCal my t x t x _ amp StoretCal t x sanity checks here e g gt 10 min and 8 hours next determine duration in minutes my avgalpha ALPHAhi ALPHAlo 2 avg nominal alpha range my d 5 int x Savgalpha 5 Savgalpha return Sd 2 EZ CAPTURE MANUAL DATA CAPTURE 26 In determining the duration we add a little bit to x in order to prevent a truncation error We repeat a similar test at the end the final datum sub TesttFinal my 56 x St x _ amp StoretCal t x next determine duration in minutes my Savgalpha SALPHAhi SALPHAlo 2 avg nominal alpha range my d 5 int x avgalpha 5 avgalpha if d SDURATION amp Print An WARNING initial DURATION and N final duration d don t match 0 SWARNINGS SEXITCODE 32 bad x du
28. get parameters for 5 0 16 xy 3 0 83 0 85 x 1 1 1 xy 3 rolGetPos SMAINWINDOWNAME left 20 xy 0 e r debug name on test station main window WinGetPos MAINWINDOWNAME xy 0 Sxy 1 Sxy Sxy ii mn Pr LOOP for MYCO CheckA n R UNT EP EA EDLY CAPTURE AND tibiotic SWHOLEF h ILE If File FileD EndIf Local h hbmp _ScreenCapture_Savelmage WHOL WinActiva Sleep SCA next ZR SSAVENAME Exists SWHOLEFILE elete SWHOLEFILE amp amp if we use AutoIt to capture t bmp ScreenCapture Captur te SMAINWINDOWNAME PTUREINT ERVAL SAVE 1 to SCAPTURECOUNT ensure clear antibiotic warning CLASS TcxCustomComboBoxInnerEdit CLASS TdxNavBar 0 07 SWINH2 Sxy 1 100 INSTANCE ugh X y W h INSTANCE 1 hack E clumsy amp LeadZero MYCOUNT PNG PNG ne screen e ut EFILE amp need end of repeat capture loop rr Sresponse MsgBox ONTOP 1 7 wait 1 min or default to If Sresponse 2 Then SISMORE 0 Debug yes Then SWINX PNG R Next anaesthetic under XP Nin2K ve can vrite a PNGI SWINY SWINW SWINH Shbmp
29. inner table gt lt tr gt lt td width 60 gt lt ol gt lt p gt lt li gt lt a href eZ_add_person php gt Add a person lt a gt lt p gt lt li gt lt a href eZ_edit_person php gt Edit a person lt a gt lt p gt lt li gt lt a href eZ_edit_logon php gt Edit log on lt a gt lt p gt lt li gt lt a href eZ_view php gt View delete data lt a gt lt p gt lt li gt lt a href eZ_backup php gt Back up and restore data lt a gt lt ol gt lt td gt lt td valigne top width 40 gt amp nbsp lt br gt lt a href eZ_demo php gt D lt tr gt table end inner tbl gt HTML2b print lt lt lt HTML3 lt p gt lt table width 100 gt lt tr gt lt td gt lt a href logout php gt Log out lt a gt lt td gt lt td align right lt a href GPL htm gt Documentation lt a gt amp nbsp lt td gt lt tr gt 9 WORKING PHP CODE 151 lt table gt lt td gt lt tr gt lt table gt lt end middle tbl gt td tr table end OUTER TBL gt body html HTML3 9 2 Assess an anaesthetic 9 2 1 Demonstration page The functionality is as for the demonstration module 1 Identification of the user as usual 2 Presentation of the first screen Timing so the anaesthetic by default advances at 1 minute per minute 4 The user can scan forward in time 5 The user can annotate the anaesthetic at will statin
30. lt p gt First let s connect to the database We use th Z_database_connect script which must be installed in the correct directory lt php GLOBAL ShandDB SDEBUGGING 1 O off require_once eZ_GLOBALS php require_once SCONNECTIONPATH ShandDB eZ database connect if is null handDB print lt p gt lt b gt Connected to eZ database lt b gt else print lt p gt Database connection FAILED 2 gt lt p gt We now have an open connection to the database with a handle in lt i gt ShandDB lt i gt We ll test to see whether the database creation script has already been run using a function called lt b gt is_eZ_populated lt b gt which checks for the existence of the UIDS table and if the table doesn t exist we run the whole creation script lt php function is eZ populated ShandDB query SELECT uids FROM UIDS WHERE uids 1 Sok mysql query query ShandDB return ok function batch sql statements handDB fname GLOBAL SDEBUGGING SMETACOUNT 1 Sfdata file Sfname slurp in array of lines here process lines as per our usual parser In the call to FetchNextLine Squery is by reference query Slinecount 0 while FetchNextLine query fdata linecount if SDEBUGGING print lt br gt Debugging Squery else t print aty y if preg match Ns CREA
31. pre post y if f Nd return 1 000000 y return Sf unchanged A debugging print routine sub Print my p level level is debugging level O none l overview Sp Slevel _ if SDEBUG gt level f if level is always print if SLOGPRINT print LOGFILE p return print p console print Here are our standard logging routines sub OpenLog my islog EZPATH LOCALFILE Sislog EZPATH SLOCALFILE _ if islog return if not logging my STODAY amp GetLocalTime my logfile EZPATH log SLOCALFILE c2d TODAY LOG open LOGFILE gt logfile or die CRASH Could not open LOG logfile sub GetLocalTime my sec min Shour Smday mon year Swday yday isdst sec min hour Smday mon year Swday yday isdst CORE localtime time Syear 1900 fix y2k sec amp DoubleDigit sec 2 detail 3 pic 1Nn De 4 FORMAT TRANSLATION EZ XLATE 94 min amp DoubleDigit min Shour amp DoubleDigit Shour Smday amp DoubleDigit mday Smon amp DoubleDigit mon Smon january 15 zero return year mon mday hour min sec sub DoubleDigit 53 i 8 if length i gt 1 return i y return 0 i concatenate my sub CloseLog
32. print p console print y 2 EZ CAPTURE MANUAL DATA CAPTURE 23 2 3 2 Utilities A death routine for fatal errors sub Die my Se Se _ my 1 SLINECOUNT 1 amp Print n n DIED Data line 1 Index SIDX Mn Message e SEXITCODE 128 ib fatal amp Print n nExit code 128 0 exit SEXITCODE caution SEE http perldoc perl org functions exit html die n Fatal Here s how we read a line we use the INDATA array previously shlurped in sub ReadLine SINDATA SLINECOUNT SLINECOUNT chomp get rid of cr lf amp Print An Check LSLINECOUNT datum is lt _ gt 2 if 1 7 d dt d amp Die An Bad datum at line SLINECOUNT value is my ln 1 d 2 Sln SLINECOUNT 1 amp Print Ain Bad line number LINECOUNT value is SWARNINGS F temporarily remmed out return d We require a Store routine where we append data to the relevant time within ALLDATA sub Store my St Sy St Sy _ my a if length SALLDATA St gt 0 SALLDATA S t else LAR 2 EZ CAPTURE MANUAL DATA CAPTURE 24 Sa timee t 4 start with time im my Sv SVARIABLES SIDX SALLDATA St Sa v Sy amp Print n gt SSTORECOUNT Store Sy at time St type is v 2 SSTORECOUNT
33. return false salt SSALT now md5 required alert Debug You input password password myform pswd value hex_md5 salt hex_md5 password alert Debug encrypted value for hex_md5 password is return true lt script gt lt head gt lt body gt lt div align center gt lt h2 gt eZ log in to lt i gt live lt i gt database lt h2 gt lt FORM name initiallogon ACTION InitialLogon php METHOD POST onSubmit return SubmitLogon this gt lt input type hidden name salt value SSALT gt lt table gt lt tr gt lt td gt User Name lt td gt lt td colspan 2 gt lt input type text name username size 16 gt lt td gt lt tr gt lt tr gt lt td gt Password lt td gt lt td gt lt input type password name pswd size 16 gt lt td gt lt td gt lt input type submit name submit value Log in gt lt td gt lt tr gt lt table gt lt form gt lt div gt lt body gt lt html gt HTMLO Formerly we used login htm which is now largely just a redirection stub how ever the advantage of still providing this page to users as the initial logon is that it confirms that Javascript is enabled without which eZ won t work Here s the file lt head gt myform f 8 PHP ACCESS CODING 135 lt title gt Log in to eZ redirection lt title gt lt script type text javascript lt i gt
34. window location replace login php f c script HEAD BODY lt h2 gt Loading eZ h2 lt p gt If nothing happens in a few seconds click a href http www anaesthetist com eZ login php gt here lt a gt but it s likely that Javascript is disabled on your machine and you will need to enable it before continuing BODY Here s rescue htm mentioned previously lt head gt lt title gt Something bad happened lt title gt lt head gt lt body gt lt h2 gt Woops Database connection failed lt h2 gt Click here lt a href http www anaesthetist com gt Return to Anaesthetist s main page lt a gt lt body gt We also require a helper HTML file busy htm which we invoke if there is no login slot available after 20 tries This is at present a stub but later we might have a Javascript 30 second count down after which the user can try again to log in lt HEAD gt lt title gt Very busy at present lt title gt LINK href css eZstyle css type text css rel stylesheet gt lt HEAD gt lt BODY gt lt h2 gt Hmm We seem to be lt i gt very lt i gt busy lt h2 gt lt p gt or you left the login screen idle for over five minutes and we got tired waiting lt p gt Please wait about 30 seconds and then click lt a href http www anaesthetist com eZ login php gt here lt a gt to try again lt BODY gt FIX THE ABOVE TO MAKE IT MORE
35. 181 Back up all data CSV export When you save the file save the on nad file and do not view edit save it using Excel as Excel will likely subtly alter the format ootnote Especially timestamps causing pain Restore The following section must only be used to restore an uploaded CSV file over a brand new recreation of a database You will probably never have to use it The database name should be that of a CSV file already uploaded to the cw subdirectory Do not specify the suffix or the directory only the file name Database name Restore database The file name as uploaded must end in a lowercase csv and is case sensitive Return to main page Figure 12 Backup and restore 9 7 Backup Here we encourage easy backup of all data apart from encrypted passwords to a CSV file which can be re imported if the dire need arises header Cache control no cache STHISPAGE eZ backup php require_once ValidFx php f our login validation script SMINUSERSTATUS eZ_ADMINISTRATOR_MIN SMAXUSERSTATUS EVERYONE Ssuccess validate login SHOW USER list SMYHEADER SUSERSTATUS eZHeaderGreet success SMINUSERSTATUS SMAXUSERSTATUS Backup data 0 print lt lt lt HTML1 lt DOCTYPE HTML PUBLIC W3C DTD HTML 4 01 Transitional EN gt lt html lang en gt lt head gt lt title gt Extract data lt
36. Alt F File Sav Sleep 300 Send a PE as Sleep 200 Send SWHOLEFILE Sleep 200 Send TAB tab to file type Sleep 200 Send C CSV Sleep 200 Send ENTER accept CSV Sleep 200 Send ENTER save amp SFAKEDCMS amp seconds for EXC 2 EZ CAPTURE MANUAL DATA CAPTURE 55 Sleep 300 If WinExists Microsoft Excel The selected file type does not Then Send ENTER Windoze being helpful EndIf Sleep 300 If WinExists Microsoft Excel not compatible with CSV Then Send ENTER Windoze being helpful EndIf Sleep 500 Send fx CLOSE Excel Sleep 200 Windows will ask Do you want to save Send n ip sod next close DCMS CloseDCMS SFAKEDCMS EndFunc DCMS Func OpenDCMS SFAKEDCMS If SFAKEDCMS lt gt 0 Then return do nothing EndIf SDCMSEXEC C Program Files USB DCMS FOR MEASURING TOOLS Receive exe Run SDCMSEXEC WinWaitActive DCMS 77 open port Controlclrck DEMS CLASS ThunderRT6CommandButton INSTANCE 7 establish connection 3 tries works Controlclack gt 2 CLASS ThunderRT6CommandButton INSTANCE 111 Sleep 300 ControtGQlrck DCMS m CLASS ThunderRT6CommandButton INSTANCE 1 Sleep 300 ControlCl
37. ClearMinTimer trivi al clear timeout function ClearMinTimer clearTimeout MINUTI ETIMER function MessageOff document getElementById elapsedTime style visibility hidden 74 3 Display Elapsed time function MessageOn jane while MYW document getE ementById elapsedTime jane firstChil Ld jane removeChild jane firstChild document createTextNode jane appendChild MYW jane style visibility visible THISIMAG a min 6 EZ SHW AN INTERACTIVE WEB BASED APPLICATION 109 MessagePaused similar to the above but indicate pause function MessagePaused jane document getElementById elapsedTime while jane firstChild jane removeChild jane firstChild y MYW document createTextNode paused jane appendChild MYW jane style visibility visible function RemindAfterlmin SkipToNextlmage SkipToNextImage automatic movement to next image function SkipToNextImage HideThanks ClearMinTimer SetMinTimer ONEMINUTE ShowNext Image MoveToNextImage invoked after storing data below function MoveToNextImage TIMESTAMP GetTimestamp ShowNext Image SetMinTimer ONEMINUTE SpeedTime DoNext Invoked on c
38. MANUAL DATA CAPTURE 44 If Soverw 1 Then cancel 2 create single backup fnm SEZPATH amp rawdataN FILENAME amp spo2 csv FileCopy fnm fnm amp BAK 1 overwrite if exists EndIf EndIf If Soverw 1 Then GuiSetState 8SW MINIMIZE If GetKbSequence spo2 SFILENAME SDATETIME SDURATION 1 Then myCheck xSpO2 SFIVEITEMS BitOR SFIVEITEMS 8 Gl EndIf GuiSetState SW_RESTORE EndIf Case msg SbETCO2 Soverw 1 If IsRawFile etco2 FILENAME 1 Then Soverw MsgBox SONTOP 1 Warning _ Rav ETCO2 data already captured Overvrite If Soverw 1 Then cancel 2 create single backup Sfnm EZPATH rawdataX FILENAME amp etco2 csv FileCopy fnm fnm amp BAK 1 overwrite if exists EndIf EndIf If Soverw 1 Then GuiSetState G8SW MINIMIZE If GetKbSequence etco2 FILENAME DATETIME DURATION 1 Then myCheck xETCO2 SFIVEITEMS BitOR FIVEITEMS 16 EndIf GuiSetState SW_RESTORE EndIf Case msg SmCSV Sperlok RunWait ComSpec amp c perl amp SEZPATH 6 ez capturNez captur pl _ amp SFILENAME amp amp SDATETIME amp amp SDURATION EZPATH
39. SFORENAME Sanitise SURNAME CheckCode GENDER Bad gender value in the following NULL is returned on failure CheckCode PERSONROLE Bad role code CheckCodeNull CURRENTSPECIALTY CheckCodeNull CURRENTLOCATION Ssimilarnames array null array if SCONFIRM 1 don t check for similar names do nothing elseif SCONFIRM 0 check for similar names sur SSURNAME Ssur strtoupper Ssur upper case Ssimilarnames SQLManySQL handDB Gl SELECT distinct Person FROM PERSDATA WHERE UPPER pdSurname sur OR UPPER pdForename sur 4 check for switch get identical surnames might use more substantial algorithm soundex or better else readfile lostdata htm exit y now insert OR confirm if count similarnames lt 1 if ok simply store SNEWID InsertPerson handDB FORENAME SSURNAME SSTARTYEAR SGENDER PERSONROLE SCURRENTSPECIALTY SCURRENTLOCATION if SNEWID gt print lt lt lt HTML2A 9 WORKING PHP CODE lt p gt New user added lt p gt SFOR ENAME F Role code HTML2A if y strlen S print print lt lt lt HTML2X lt p gt It is now wise to add LOGIN deta
40. SWARNINGS 1 EndIf If SWARNINGS gt 0 Then sgBox ONTOP Warning In reading file amp Sfnam _ amp there was were amp SWARNINGS amp line s containing bad data EndIf FileClose f Sarr 0 SALEN Size Return Sarr return an ARRAY EndFunc The reverse function Vomit writes an array that was Slurped Badly written and nasty Func Vomit fnam ARR Dim SALEN 1 SARR 0 get item count here might check this vs EZ DURATION i 17 Sf FileOpen fnam 2 rewrite Dim SVALS SEZ MAXLINES 1 7 cumbersome SVALS SEZ CASENUMBER casenumber SVALS SEZ CASEDATE date VALS SEZ CASETIME time SVALS SEZ VALIDFLAGS valid VALSI EZ ISLISTED listed SVALS SEZ CASEEND end SVALS SEZ SURGERY surgery SVALS SEZ DESCRIPTION description SVALS SEZ DURATION duration While i lt SALEN v SVALS Si amp amp SARR Si FileWriteLine Sf Sv i i 1 Wend FileClose f EndFunc Func ValidTimestamp Sd t Sf KiwiJulian Sd t Sbackdate KiwiGregorian Sf if Sbackdate lt gt Sd amp St 00 Then MsgBox SONTOP Debug We compared amp Sd amp amp St amp 00 with amp Sbackdate 2 EZ CAPTURE MANUAL DATA CAPTURE 65 Return 0 EndIf Return f EndFunc
41. Start time must be in the form HH MM End time must be in the form HH MM Scasetime s Scasedat amp Scaseti 6 Send 6 julian date amp casetime Please check time 6 amp Scasetime Return 0 EndIf here calculate duration MsgBox SONTOP Debug Difference betw n amp jend and Sjstart 2 EZ CAPTURE MANUAL DATA CAPTURE Sduration If duration 0 62 jend Sjstart Then next day Sduration duration 0 5 EndIf duration Int 0 5 duration 60724 get minutes Return duration EndFunc 7 Slurp file first line data in Format is date DD MM YYYY r second line time HH MM third line valid 31 Sfnam Func Slurp valid flags Dim SALEN SEZ MAXLINES Dim Sarr SALEN 1 Sarr 0 0 77 signals failure Sf FileOpen fnam 0 read only if Sf 1 Then Return Sarr fail EndIf SWARNINGS 0 the following is extraordinarily cumbersome and needs to be revised Sv FileReadLine Sf case number s StringSplit v If s 1 casenumber Then Sarr EZ_CASENUMBER s 2 Else SWARNINGS SWARNINGS 1 EndIf Sv FileReadLin S first date s StringSplit v If s 1 date Then Sarr SEZ_CASEDATE 55121 get date Else SWARNINGS SWARNINGS 1 EndIf Sv FileR
42. e NCLEAR lt 2 signals illegible datum ERO lt ZERO lo ZERO hi nd routine SetlnitialValues Utilities Here s how we read a line routine ReadLine datum implicit linecount read line linecount increment linecount read line number if line number linecount gt fail Bad line number read datum from line return datum end routine ReadLine We require a Store routine 2 EZ CAPTURE MANUAL DATA CAPTURE 15 routine Store t y x ALLDATA t msg concatenate variables idx ALLDATA t lt concatenate x msg y append value end routine Store We concatenate in a value to sort out the potential if infrequent problem where two data values are stored against the same time We might later test for and warn about this anomaly Similar are StoreZero and StoreYCal and a smaller stack to store the few x axis time calibrations we do routine StoreZero x y push ZEROES x push ZEROES y end routine StoreZero routine StoreYCal x y pushi YCALS x push YCALS y end routine StoreYCal routine StoretCal x y push tCALS x push tCALS y end routine StoretCal Tests of calibration We must be able to test Y calibration At the same time based on the Y calibration value we determine the type of record and hence set the alpha value We also return the MINVAL routine TestYCal t c Store YCal t 1c ti
43. if force rest to NA Sc y Gl sub ValidParam my Sinp Sdattype 70 Please try again 2 EZ CAPTURE MANUAL DATA CAPTURE 71 inp dattype _ if inp return l if inp n i return 2 if inp x i return 3 if inp 1 w dt d w is it numeric return 0 fail if Sdattype eq spo2 if Sinp lt 50 Sinp gt 100 return 0 y elsif dattype eq etco2 if Sinp 1 Sinp gt 100 bugger n return 0 or warn and confirm if gt nnn else amp Die return 1 Bad parameter type Sdattype here are the Store and Unstore routines The latter is redundant sub Store my t Sy t Sy _ SALLDATA St Sy sPrint An gt SSTORECOUNT Store Sy at time 56 2 SSTORECOUNT COre t parameter is St is time g etco2 d to address mmHg vs kPa allow whitespace FIX ME 2 EZ CAPTURE MANUAL DATA CAPTURE t SALLDATA St redundant y Writing data sub WriteKbData my SRAWPATH SRAWFILENAME SDATTYPE SRAWPATH SRAWFILENAME SDATTYPE _ my Soutname SRAWPATHSRAWFILENAME SDATTYP open OUTFILE gt Soutname or amp Die CRASH Could not open OUTPUT FILE Soutname print OUTFI my KBCOUNT
44. my Here s a routine that loads the connection string and returns it The specified file is opened and the string retrieved it s the first non null line that doesn t start with a sign sub GetConnectionString my EZDIR SCONFILENAME EZDIR CONFILENAME _ my conf EZDIR SCONFILENAME open CONF conf or amp Die Can t open conf my seek 20 max lines my Sopt while seek gt 0 lt CONF gt naive 3 RETRIEVE FILES FROM SAFERSLEEP USING PERL 77 if length _ gt 2 amp amp 1 w S chomp Sopt _ amp Print n Connection string lt Sopt gt 3 close CONF return Sopt return string y Sseek close CONF sDie Connection string not found in lt conf gt 3 1 The connection string Here s the file connect string txt containing the database connection string It is written directly to the ez directory Connection string for SAFERsleep database Driver SQL Server Database SaferSleep Server AHSL242 ServerName IDASApplicationSe 4 FORMAT TRANSLATION EZ XLATE 78 4 Format translation ez xlate We have three tasks here 1 Turn a SAFERsleep IAR file into an XML file Section 2 4 5 2 Translate an XML file into a CSV file Section 4 1 2 3 Turn a CSV file into a DAT file for replay via SAFERsleep Section 4 2 The following sections address the last two task
45. my islog Sislog if Sislog close LOGFILE im _ A death routine for fatal errors sub Die my Se Se _ my 1 SLINECOUNT 1 amp Print n n DIED Data line 1 n Message Se 0 SEXITCODE 0x80 exit SEXITCODE die n Fatal 4 2 2 A DOS batch file csv2dat Here s the batch file csv2dat bat used to invoke the CSV translation from the DOS command line It assumes a single parameter and redundantly submits the standard translation rule file echo off cls rem Translate XML to CSV 4 FORMAT TRANSLATION EZ XLATE 95 perl ez xlatelez csv2dat pl 1 datrules txt ECHO Error level ECHO SERRORLEVELS It should be placed in the ez directory The two arguments are respectively the path to the source file and the destination directory And here s a test file test c2d bat that requires no arguments echo off cls echo Translate CSV to SAFERsleep DAT file test only perl ez xlatelez csv2dat pl test datrules txt debug 3 logprint 0 ECHO Error level ECHO SERRORLEVELS Here s a similar test to convert captured data called test c2d bat that takes the output out T0001 csv from the test captur bat file and converts it to a DAT echo off cls echo Translate CSV to SAFERsleep DAT file a test of CAPTURED data perl ez xlateNez csv2dat pl out T0001 csv ECHO
46. script gt lt head gt lt body gt SMYHEADER HTMLO SDEBUGGING 1 print lt lt lt HTML2 lt FORM name eZ_assess ACTION eZ admin personadded php METHOD POST onSubmit return CheckInput this gt lt input type hidden name confirmation value 0 gt lt h3 gt Person s details lt h3 gt lt table width 655675 tr td td td Forename td td lt input type text name forename size 32 onChange ValidForename this 1 gt lt td gt lt tr gt lt tr gt lt td gt lt td gt lt td gt Surname lt td gt lt td gt lt input type text name surname size 32 onChange ValidSurname this 1 gt lt td gt lt tr gt lt tr gt lt td gt lt td gt lt td gt Year lt i gt primary anaesthetic qualification lt i gt gained lt td gt lt t lt input type text name startyear size 5 onChange ValidStartYear this 1 gt lt td gt lt tr gt lt tr gt lt td width 5 gt amp nbsp lt td gt lt td width 14 gt Gender lt td gt lt td width 81 gt lt select name gender size 1 gt lt option selected value 0 gt lt option gt lt option value 1 gt F lt option gt lt option value 2 gt M lt option gt lt select gt lt td gt lt tr gt lt tr gt lt td gt lt td gt lt td gt Role lt td gt lt td gt HTML2
47. title gt LINK href css eZstyle css type text css rel stylesheet gt script type text javascript function CheckRestore myform if myform csvname value length 2 alert Invalid CSV name Need at least 1 character return false if confirm Restore Are you sure 9 WORKING PHP CODE 182 return false return true y 22 lt script gt lt head gt lt body gt SMYHEADER h3 Back up h3 th sing Excel the file sav u as p a href backup all php Back up all data lt a gt CSV export When you save lt i gt original lt i gt file and do b not b view edit save it Excel wil l likely subtly alter the format footnote Especially tir lt h3 gt Restore lt h3 gt lt div class narrow gt The following section must lt i gt only lt i gt be used to restore an uploaded CSV file over a lt i gt brand new lt i gt recreation of a database You will probably never have to use it The database name should be that of a CSV file already uploaded to the lt i gt csv lt i gt subdirectory Do not specify the suffix or the directory only the file name lt p gt lt FORM name restoredatabase ACTION restore_db php METHOD POST onSubmit return CheckRestore this gt lt br gt Database name lt input type text name csvname size 16 gt amp nbsp amp nbsp
48. 0 NBP NBP s NBP d NBP m In the above file always placed in the csv directory and called datrules txt all lines starting with are comments Other lines act as templates where SD 0 is a place holder for the time and values in curly braces indicate the names of columns from which values will be obtained for every line i e for each particular time After substitution of values into the template a line is written to the destination file however if the value in the source is NA no line is written 4 2 1 Perl code to translate to DAT Let s implement the above In addition we will render all floating point numbers with six digits after the decimal point all zeroes as encountered in the DAT files We add epsilon and then brutally truncate Perl program to translate from CSV format to IDAS DAT format usr local bin perl w use POSIX qw floor for date calculations my SDEBUG 3 O no debugging l overview 2 detail 3 nitpicking my LOGPRINT 1 print to log my SLINECOUNT 0 my SWARNINGS 0 see usage my SEPSILON 0 0000005 tiny number my SEZPATH ez my SOUTPATH EZPATH dat my LOCALPATH EZPATH csv my SEXITCODE 0 code on exiting Perl f the following are global my SLOCALFILE SARGV 0 source filename e g S0013 m NO suffix my SRULEFILE SARGV 1
49. 2 My special classes invisible visibility hidden invisiblevarning visibility hidden color black font size 120 font weight bold prominent border width border style border color heavybox border width border style border color margin top margin right thick solid black thick solid 2F1D1D 1 gt px 116 6 EZ SHW AN INTERACTIVE WEB BASED APPLICATION 117 margin bottom 1 margin left 1 3 Useful SPAN and other tags 4 Pseudo stuff a hover color red background color black X area for testing follows the end of the style sheet 7 DATABASE DEFINITION 118 7 Database definition The database is written in SQL and implemented on the Web using mySQL We have elsewhere discussed our method for partially automating capture of data on manually written anesthetic records Here we take these data and run them through the SaferSleep process We capture the resulting screens as PNG graphics and then display the graphics on the web An anaesthetist scrolls through such a graphic record sequentially and indicates points of significance where she he would likely have intervened given their basic knowledge of the anaesthetic and prior data on the display Where someone has already intervened based on the record a subsequent intervention should only be in the context of the previous intervention having been performed when they stat
50. 8 my d Sc t Sinp c 0 foreach d X chomp d if length d gt 1 ignore blank lines t 5 Sc time in minutes 5 count if d 1 amp Store St 1 signals NA elsif Sd 17 Nw dt d d w amp Die Bad data line c value lt d gt else Sinp 2 if 1 c SWARNINGS sStore t inp store value c bump count 2 3 6 Write data Note that in the following we should perhaps round the output data to four sig nificant digits but at present we don t adulterate them sub WriteAllData my TIMESTAMP STIMESTAMP Ile QL T amp Print n Warning time mismatch c 1 EMP 1 2 EZ CAPTURE MANUAL DATA CAPTURE 30 my d c O for starters simply print each datum to the log c 1 if DEBUG amp Print n Debug raw data 1 foreach d ALLDATA if length d gt 0 amp Print n gt c Sd 1 Sc 1 F3 1 get a solid Y calibration value what about subtracting avg zeroes my ycal amp GetYCal 2 Pull out data values using tags first open file for writing open OUTFILE gt csv RAWFILENAME m csv or amp Die CRASH Could not open OUTPUT FILE csv outSRAWFILENAME n m suffix indicates it s a manual file s is SAFERsleep print OUTFILE Time NBP s NBP d HR Sp02 ETCO2 NBP m rawSBP
51. Database structure Table 3 provides a simple overview of the table relationships in our database An arrow from table A to table B indicates that table A references table B Major tables are shown as blocks 7 DATABASE DEFINITION 126 7 9 Testing the database We tested the database in two phases Testing on a DOS machine We first run Dogwagger 2 1 to generate the SQL code in the file eZ sql in the directory ez ez shw sql We create a database called eZ in a convenient SQL for example the old freeware Ocelot SQL and then submit the code manually 2 Internet testing In our testing it s wise to consider everything but in particular file names and directory paths to be case sensitive We create a database in mySQL and upload a PHP script that submits our eZ sql file as follows We log onto anaesthetist com using FTP commander and in the public_html folder make a directory called eZ as well as a subdirectory of eZ called sql We then upload the file eZ sq from our local PC directory ez ez shw sql to the sql directory and the PHP script database create php described in Section 7 10 to the eZ directory Before we run the PHP script we log on to anaesthetist com using CPANEL and create the database anaes2_eZ from within the mySQL database section Af ter creating the database we add the system administrator with all privileges We manually insert the administrator and password into the connection script script called
52. Error level ECHO SERRORLEVELS 5 EZ REPLAY REPLAYING DATA VIA SAFERSLEEP 96 5 ez replay Replaying data via SAFERsleep It is vitally important to note that the following code should only be run after SAFERsleep has been reconfigured to point to a testing server and not the live database This prevents the actual database from becoming clogged with dummy copies of records You should also disable the antibiotic warning in the IDAS ini file We launch IDAS in demonstration mode and play the DEMO DAT file suit ably modified by us grabbing screens from the program every minute and storing each screen as a sequentially numbered PNG file 5 1 AutoIt code for monitor replay Here s the code mv AutoIt Version 3 0 Program to copy a DAT file to the IDAS file DEMO DAT Then run IDAS in demonstration mode and repeatedly capture screen every minute using AutoIt 1 and writing each captured image as a PNG file Repeat for multiple DAT files AutoIt includes Include lt ScreenCapture au3 gt miscellaneous variables Const SONTOP 0x40000 SSLACKTIME 300 Pr MS SPSPWAIT 2000 ms SPSPWAIT2 2000 77 ms SONEMINUTE 60000 77 ms 60s SONEMINUTE 10000 10 s for debugging i PREPARATION Load numbers etc Identify a file Global CURRENTFILE Global SCAPTURECOUNT
53. Func KiwiJulian d St ds StringSplit d Sdd Sds 1 77 day Smm Sds 2 month yy Sds 3 year tt StringSplit t Shr Stt 1 Smi Stt 2 Sss 0 return Julian yy mm dd hr mi ss EndFunc Func Julian fy Sfm fd fh fmi 525 Sal 367 Sfy a2 Int 7 fy Int fm19 12 4 a3 Int 3 Int Sfy Sfm 9 7 100 1 4 Sas Int 275 fm 9 d 1721028 5 Sab fh fmi fs 60 60 24 Sf Sal a2 a3 a4 a5 return f EndFunc Given Julian date float make Gregorian date time Func KiviGregorian jd SEPSILON 0 00001 jd SEPSILON 2 Floor jd 1721118 5 SR jd 1721118 5 2 SG 52 0 25 SA Floor G 36524 25 SB A Floor A 4 year Floor B G 365 25 SC SB Z Floor 365 25 year month int 5 C 456 153 day Int C int 153 month 457 5 SR If Smonth gt 12 Then Syear Syear 1 Smonth Smonth 12 EndIf next HH MM SS gd 0 5 jd Int jd 2 EZ CAPTURE MANUAL DATA CAPTURE 66 If gd gt 1 Then Julian starts at midday gd gd 1 EndIf gh gd 7 Clumsy gh gh 24 gmi gh gh Int gh Sgmi Sgmi oh gmi gmi 60 gs gmi gmi Int gmi gs gs gmi gs Int gs 60 return DoubleDigit day amp _ s DoubleDigit mont
54. If IsRawFile spo2 SFILENAME 1 Then myCheck xSpO2 Smy5 BitOR my5 8 EndIf If IsRawFile etco2 FILENAME 1 Then myCheck xETCO2 Smy5 BitOR my5 16 EndIf return Smy5 ndFunc ri routine to tick Valid boxes five based on flags in GOODITEMS Func SetGoodItems GOODITEMS vSBP vDBP vHR S vSpO2 vETCO2 myUncheck SvSBP If bitAND GOODITI myCheck SvSBP EndIf T Gl MS 1 0 Then myUncheck SvDBP If bitAND GOODITI myCheck vDBP EndIf Gl MS 2 0 Then myUncheck SvHR If bitAND GOODITI myCheck SvHR EndIf E MS 4 0 Then myUncheck vSpO2 If bitAND GOODITI myCheck vSpO2 EndIf E MS 8 0 Then myUncheck vETCO2 If bitAND GOODITEMS 16 0 Then myCheck vETCO2 EndIf EndFunc Func TestmDAT mDAT EZPATH FILENAME SUFFIX if csv file has been made enable DAT conversion NO rather test if successful return from Perl invocation FIX M P If FileExists SEZPATH csv SFILENAME amp SSUFFIX amp csv Then myEnable SmDAT EndIf ndFunc 1 2 EZ CAPTURE MANUAL DATA CAPTURE 50 test whether fil xists and if it does enable the relevant button Func TestFile btn SWHOLEPATH FILENAME SSUFFIX If Fi
55. It s a good idea to set the variable THISPAGE prior to calling routines from ValidFx php although a null value the default is also acceptable Here s the initial code header Cache control no cache require eZ_GLOBALS php require ancillary php require SCONNECTIONPATH validate_login Now for the function that actually performs the log in validation If an SID already exists for this user stored in a cookie and checked against the database then val idate_login succeeds but otherwise we pop up an error Oops page On success we not only provide a handle to the database but we also provide information about the user including their status and the last page they visited function validate_login Sshowuser GLOBAL handDB GLOBAL USERKEY GLOBAL THISPAGE 1 connect to database handDB eZ database connect But it s a particularly bad idea to encourage a user to visit a page which was accessed using a POST method so we routinely comment out the SUSERKEY allocation on these pages 8 PHP ACCESS CODING 146 if ShandDB mysql close handDB print An Failed to connect to database here have rescue HTML code readfil rescue htm exit y 2 retrieve cookie If null present NEW login screen SSID COOKIE eZ SID print p Debug cookie SID is SID if strlen SID lt 1 m
56. OUTFILE print OUTFILE ansver close OUTFILE SmyODBC gt Close amp CloseLog LOGPRINT exit SEXITCODE Here are the SQL handling routines sub SQLFetchDatum my SmyODBC S SQLstmt myODBC SQLstmt amp DoSQL myODBC my Sdat myODBC FetchRow dat myODBC Data return dat e SSQLstmt get data sub DoSOL my myODBC myODBC retcode SQLstmt SQLstmt Q my Sretcode if myODBC gt Sql SQLstmt Sretcode if problem my sqlErrors 74 3 RETRIEVE FILES FROM SAFERSLEEP USING PERL if amp Die else Sretcode lt 1 ERROR SQL failed code SsqlErrors myODBC sError N 911N NI1N N ON IE H H sqlErrors amp Print SQL problem retcode EXITCODE 1 Sretcode signal warning 75 n lt SQLstmt gt n lt SSQLstmt gt sql Errors n Subsidiary routines follow in the next sections They are pretty standard The log file is identified by iar after the file name sub Die my e Se _ amp P SEXITCODE rant 128 n Se nl Exit code 4 exit SEX cautio ITCODE n SEE die sub Print my Sp TL if y sub OpenLog Sislog EZDIR SFI Sislog SEZDIR SFI i return Y amp GetLocalTime
57. SMYHEADER HT o if pwd indexof gt 1 quadruplicate PHP Javascript return true if pwd indexOf gt 1 return true if pwd indexOf gt 1 return true if pwd indexOf gt 1 return true return false gt lt script gt head gt ody gt LO here GET user ID or fail THERLOGONID GET editlogon CheckCode OTHERLOGONID Bad log on or fail hmm We might check that the user is entitled to log on privileges For now accept all o o I HERSURNAME FetchSurname handDB SOTHERLOGONID HERFORENAME FetchForename handDB SOTHERLOGONID 9 WORKING PHP CODE 167 Sqry SELECT pLoginName FROM PERSON WHERE person SOTHERLOGONID list SOTHERLOGIN GetSQL ShandDB qry get user login print lt lt lt HTML2 lt p gt lt a href mainpage php Return to main page lt a gt or lt FORM name eZ_do_editlogon2 ACTION eZ_do_editlogon2 php METHOD POST onSubmit return CheckInput this gt lt input type hidden name otheruserid value SOTHERLOGONID gt lt table width 80 cellpaddinge 1 cellspacing 1 lt tr gt lt td gt lt b gt 1 FIRST please enter YOUR password lt b gt lt td gt lt td gt lt input type password name mypswd size 16 gt lt br g
58. SR if month gt 12 year year 1 Smonth month 12 im Hh my gd 0 5 jd int jd if gd gt 1 Julian starts at midday gd 1 y my gh gmi gs gh gd clumsy gh 24 gmi Sgh gh int gh gmi gh 2 EZ CAPTURE MANUAL DATA CAPTURE Sgmi 60 gs gmi gmi int gmi gs Sgmi gs 60 return year amp DoubleDigit month amp Doub amp DoubleDigit gh amp DoubleDigit amp Doub sub DoubleDigit my 1 1 8 if length i gt 1 return i 1 return 051 2 3 7 Error log gmi concatenate leDigit int gs 35 leDigit int day We need the error log for forensic purposes and debugging All debugging is written here unless logging is turned off in which case it s written to the console sub OpenLog my islog Sislog if Sislog my STODAY my Slogfile EZDIR open LOGFILE gt Slogfile or die print n Writing to log file sub CloseLog my Sislog S islog _ if Sislog close LOGFIL hy Gl EZDIR SRAWFI EZDIR SRAWFI return amp GetLocalTime ENAME IM ESTAMP E ENAME d IM if not logging ESTAMP Q log SRAWFIL ENAM E capt TODAY LOG CRAS H Could not open LOG logfile S Xn Slo
59. Sdetl array Sdet1 0 FetchForename ShandDB p Sdetl 1 FetchSurname handDB p Sdet1 2 FetchRole handDB p list det1 3 GetSQL handDB SELECT FirstQualified FROM PERSON WHERE person p yr of 152 qualification detl141 p Sopt Si detl i 1 return Sopt HTML file lostdata htm 162 returns array of arrays each subarray containing forename If odd or missing data are submitted to a PHP script which processes POST data the following tiny page will be displayed lt head gt lt title gt Lost data lt title gt lt head gt lt body gt lt h2 gt Lost information lt h2 gt lt p gt The POST data submitted to this form do not contain the expected information This suggests that you ve randomly accessed this page or inserted really weird text in the previous one lt p gt Click lt a href http www intensivist com strict mainpage php here lt a gt to return to the main page lt p gt lt hr gt lt body gt 9 WORKING PHP CODE 163 Edit person s details User Superuser Return to main page or 1 FIRST please enter YOUR password This is a security measure 2 Enter user log on password for Darran Lovves darranl If exists can be left the same Enter new password a User log on name b New password Re type new password Gol Clear Form Fig
60. USER FRIENDLY ALSO CHECK WHY IT SOMETIMES GETS PRESENTED INAPPROPRIATELY 8 PHP ACCESS CODING 136 8 1 1 InitialLogon php The following script is invoked from the form specified by login php Section 8 1 5 If the submitted parameters username and password are garbage we return to login php Only after we ve sanitised these values do we try to connect to the database after which we log on if we can using the processLogon function described in Section 8 1 2 This script requires ValidFx php Section 8 2 and on success passes con trol mainpage php Section 9 1 The variable SLOGGED IN is set and passed to mainpage php otherwise mainpage will again try to confirm that the user is logged in The function CheckCode is contained in ancillary php The component function Force Html InitialLogon makes use of two tiny HTML files oops1 htm and oops2 htm GLOBAL SUSERKEY GLOBAL handDB GLOBAL THISPAGE THISPAGE se require once ValidFx php our login validation script Susername POST username Spswd POST pswd Ssalt POST salt print p Debugging password is pswd salt is salt if strlen Susername gt 32 strlen Spswd gt 80 strlen Susername lt 4 strlen pswd lt 6 print lt p gt Bad password user name Force_Html_InitialLogon Invalid password username exit im Sanitise username Sanitise S
61. a heart rate under 40 This way we easily encode interpolated time values but still preserve the information such as it is for the rare cases where extremely low values are recorded e A value greater than ZERO and less than the maximum value of a signals an added reading between 5 minute intervals After these two values we insert the Y offset of the point in question Note than an offset of ZERO should never occur as this is on the line and a conventionally recorded datum A value between alpha and MINVAL signals an error e A value of MAXVAL or greater signals that the measured value exceeds the maximum range Note that this value should not be interpreted as an actual reading but merely a signal that the range is exceeded or out of the calibration range We will soon explore some pseudocode as an overview of our approach and follow this by actual Perl code Finally we will describe how to automate parts of this process using Autolt Rationale The above approach might seem baroque but has the following advantages 1 We provide proof of the zero value and Y calibration values for the calipers at the start of every set of measurements 2 At the start and end we confirm the duration of the record and also provide a means of confirming the value of a so that measurements taken between normal time intervals eg at intervals of under five minutes are reliably indicated 3 Measurement is intuitive a
62. a measurement in the range of MAX VAL indicating the initial Y axis calibration value 20 200 mmHg Then we enter the X axis time calibration measurement measured as de scribed above Here follow measurements of Systolic BP Each value represents an off set in millimeters from the 20 mmHg or min 1 baseline taken at 5 min intervals The value should never be below MINVAL Special values are discussed below After the last measurement simply stop recording Export to Excel our Autolt script will take you back to the main GUI For the diastolic BP series zero and Y calibrate once more but do not per form the X calibration at any time Just terminate after the last DBP read ing For the heart rate series zero and Y calibrate and acquire readings as usual but Finally as part of the heart rate series repeat the zero the Y calibration and as a last reading repeat the X axis calibration measurement according to the previously specified rules The following data values are special e As already mentioned a value of ZERO followed by a large number signals a zeroing calibration pair 2 EZ CAPTURE MANUAL DATA CAPTURE 12 A double ZERO is entered for every missing 5 minute reading The two values must be identical e A ZERO followed by a value between ZERO and MINVAL is used to sig nal the special case where a recorded reading is under 40 for example a diastolic BP under 40 or
63. as international date my Sts min ts min 0_ my Syy mm dd Shr mi ss if Sts 17 d 2 d 2 Ad 4 4 2 2 sDie Bad Date ts Kivi format DD MM YYYY HH MM ye 544 mm Syy Shr Smi 51 2 S3 54 55 my gooddate yy mm dd hr mi 00 sPrint n Input date lt Sgooddate gt adding min min 3 Sf amp Julian yy mm dd Shr mi 0 Sf min 24 60 minutes as a day fraction amp Print An Julian f 3 Syy mm Sdd Shr mi ss sGregorian f Print An Gregorian Syy mm dd Shr mi ss 3 return yy mm dd hr mi 00 2 EZ CAPTURE MANUAL DATA CAPTURE 34 sub Julian my fy fm fd fh fmi fs ff fy fm fd fh fmi fs ff _ my f f 367 fy int 7 Sfy int fmr9 12 4 int 3 int Sfy Sfm 9 7 100 1 4 t int 275 Sfm 9 d 1721028 5 Sfh fmi fs 0 ff 60 60 24 return f sub Gregorian my 33 3d _ my SEPSILON 0 000001 jd SEPSILON my 2 SR G SA SB SC my Syear month day Hh Z floor jd 1721118 5 SR jd 1721118 5 2 SG 52 0 25 SA floor G 36524 25 SB A floor A 4 year floor B 5G 365 25 SC SB Z floor 365 25 year month int 5 SC 456 153 day C int 153 Smonth 457 5
64. because mysql error if SDEBUGGING print Mn You managed to connect to the database r if mysql_select_db anaes2_eZ ShandDB die You didn t manage to connect to eZ else if DEBUGGING print You are connected to eZ return ShandDB Note that the relevant values for name_sysadmin and PASSWORDHERE must be inserted manually and the script then stored in the directory above the public_html directory on anaesthetist com eZ GLOBALS php The following are a few globals mainly constants required by our program The database time out precedes the cookie time out so we can identify the time out and generate an appropriate message 1 time out before forcing log off define eZ TIMEOUT 60 60 1 hour define COOKIE EXTRA WAIT 10000 before cookie expiry 4We are here taking the approach of running PHP under Apache rather than the optimal ap proach of running PHP as a CGI script 7 DATABASE DEFINITION 128 2 useful constants define SHOW USER 1 define MAXFETCHTRIES 1000 see usage define MAXKEY 100000000 likewise define FETCHTIMEOUT 2000 milliseconds m m P 3 Used to test status of person logging on define eZ ADMINISTRATOR MIN 128 define eZ ASSESSOR MIN 19 define eZ ASSESSOR MAX 63 define EVERYONE 1000 define NOBODY 0
65. both flags set myEnable SREPL EndIf or make this a rtn Else sgBox ONTOP Oops Failed to add amp SFILENAME to playlist EndIf Case msg SSGET perlok RunWait GComSpec 6 c perl amp _ SEZPATH amp ez xlateNgetcrypt pl amp SFILENAME amp connect string txt debug 3 logprint 1 SEZPATH If perlok 0 Then MsgBox SONTOP Note Retrieval was successful TestFile sXML EZPATH amp iar FILENAME iar Else MsgBox SONTOP Problem See log Return code was amp S perlok EndIf Case msg sXML If Iar2Xml SEZPATH SFILENAME 1 Then failure MsgBox SONTOP Oops There seems to have been a problem See the LOG Else MsgBox SONTOP Note Apparent success TestFile sCSV SEZPATH amp xml FILENAME xml EndIf Case msg sCSV 77 MsgBox SONTOP Test XML to CSV perlok RunWait GComSpec amp c perl amp _ SEZPATH 6 ez xlateNez xml2csv pl 2 EZ CAPTURE MANUAL DATA CAPTURE 46 amp SFILENAME amp debug 2 logprint 1 SEZPATH If perlok 0 Then MsgBox SONTOP Note Conversion was successful TestFile sDAT EZPATH amp csv FILENAME s csv se MsgBox ONTOP Problem See log Return code was amp perlok EndIf 1 S is for safers Case msg sDAT Sperlo
66. code if strlen SNEWLOCATION lt 1 SNEWLOCATION SNEWLOCATION NULL else CheckCode NEVLOCATION Bad location code SOTHERSURNAME FetchSurname handDB SOTHERLOGONID SOTHERFORENAME FetchForename handDB SOTHERLOGONID qry UPDATE PERSDATA SET pdForename NEVFORENAME pdSurname SNEWSURNAM PersonRole SNEWROLE CurrentSpecialty NENSPECIALTY CurrentLocation SNEWLOCATION E 9 WORKING PHP CODE 178 WHERE person OTHERLOGONID DoSQL ShandDB qry update user data Sqry UPDATE PERSON SET FirstQualified SQUALYEAR WHERE person OTHERLOGONID DoSQL ShandDB Sqry set new qual yr list SROLETXT GetSQL ShandDB SELECT rText FROM PERSONROLE WHERE personrole SNEWROLE get role list SSPECTXT GetSQL ShandDB SELECT LocationText FROM CURRENTLOCATION WHERE currentlocation SNEWLOCATION get role list SLOCTXT GetSQL ShandDB SELECT SpecialText FROM CURRENTSPECIALTY WHERE currentspecialty SNEWSPECIALTY get role print lt lt lt HTML3 lt p gt Data have been up
67. data input function Sanitise amp S txt first remove whitespace at start end Smatches preg match s s txt matches txt matchesl11 4 get 1 or use ltrim rtrim txt preg_replac Stxt f get rid of pipes Stxt preg_replac INV 77 Stxt and backticks Stxt preg_replac r Stxt double quote gt single Stxt preg_replac m r 7 Stxt duplicate any quote if SDEBUGGING print lt br gt lt b gt Sanitised lt b gt amp lt S txt amp gt im return vith altered txt It s by reference 10 ANCILLARY CODE 191 10 1 4 WhatYearIsIt Simply retrieve the current year function WhatYearIsIt return date Y y 10 2 Handling lists 10 2 1 PrintPoplist PrintPoplist obtains the desired primary key the first item specified in the SQL SELECT statement and elems extra items elems is not an explicit param eter The elems extra items are concatenated into a single string Each key elems concatenation pair is printed as an option within an HTML lt SELECT gt statement function PrintPoplist handDB listname Squery print lt select name Slistname gt lt option selected value 0 gt lt option gt n ShandQ mysql_query query ShandDB if is resource handQ f debug print lt br gt SQL QUERY error mysql error im count 0 whi
68. datastring var firstcomment NoPipes document myform intervention value var secondcomment NoPipes document myform variablecomment value var sbp OneZero document myform sbp checked var dbp OneZero document myform dbp checked var hr OneZero document myform hr checked var Spo2 OneZero document myform spo2 checked var etco2 OneZero document myform etco2 checked datastring t TIMESTAMP cl firstcomment c2 secondcomment sbp alert Debug data are datastring ClearAllValues ALLDATA DATUMCOUNT datastring DATUMCOUNT ShovThanks oveToNextImage alert Thank you Please continue NextOn ArtOn HideAllInputs alert Should have moved this would not be displayed function ClearAllValues documen documen documen document document document document ct 355335353833 gum ct rt form intervention value Form variablecomment value form sbp checked 0 form dbp checked 0 form hr checked 0 form spo2 checked 0 form etco2 checked 0 function NoPipes c var pindex c indexof while b4 af C pindex 1 c substring 0 pindex tr c substring pindex 1 b4 aftr 6 EZ SHW AN INTERACTIVE WEB BASED APPLICATION 113 pindex c indexOf y return c function OneZero v fut v2 0 return return 1 0
69. if nov STIME gt STIMEOUT if timed out Squiet 4 force exit signal found row im els SET UP the SALT table can later remove 6075 while c K r rand Sqry INSERT INTO SALT salt sTime sValue VALUES c 100 r force time out DoSQL handDB Sqry insert salt row c 1 y y Squiet 1 prevent infinite loop im if Squiet 20 tries failed if quiet readfile busy htm exit y we now have valid row SI and salt value J Sqry UPDATE SALT SET sTime Snow sValue J WHERE salt 1 DoSQL ShandDB Sqry store salt J value SSALT U ff print p Debug row is I and salt is J lt p gt print lt lt lt HTMLO lt DOCTYPE HTML PUBLIC W3C DTD HTML 4 01 Transitional EN gt lt html lang en gt n lt head gt lt title gt Log in to eZ lt title gt lt LINK href css eZstyl script src js md5 lt script type text j avascript function SubmitLogon myform css type text css type text javascript gt lt script gt CLS rel stylesh 8 PHP ACCESS CODING 134 if myform username value length lt 4 alert Invalid user name Must be at least 4 characters return false im password myform psvd value if password length lt 6 alert Invalid password At least 6 characters are required
70. if Starget eq sbp SNIBs Sval elsif target eq dbp SNIBd Sval end mean values Print An Datum val leaves lt d gt i Si target Starget 3 if Si lt 3 for the first three values Sv Si SNASTYOFFSET 1 val 4 keep raw copy if val gt val Sycal Sval SBASELINE add 20 y y if val 0 val only option for nov Sv i val i y HERE OBTAIN THE MEAN BLOOD PRESSURE if NIBs eq NA E 5We might even store the relative time offset but don t bother 2 EZ CAPTURE MANUAL DATA CAPTURE 32 SNIBd eq NA SNIBm NA els m d 1 3 of pulse pressure SNIBm SNIBd NIBs NIBd 3 SNIBm Sycal SNIBm SBASELINE add 20 im Sv SNASTYOFFSET NIBm store value in correct column END OBTAIN MEAN BP if length d gt 1 1 allows for final comma HMM CHECK ME amp Print An Warning extraneous data in line lt d gt 0 SWARNINGS im my Sp my modtime amp KiwiAddMinutes STIMESTAMP time modtime s T SAFERsleep format has T IPO print OUTFILE Nn modtime foreach Sp v print OUT y y FILE s Do Here s a simple routine that pulls out a datum given the name It also returns the original string wi
71. lt INPUT TYPE submit NAME submit VALUE Restore database lt form gt lt p gt The file name as uploaded must end in a lowercase csv and is case sensitive lt div gt lt p gt lt a href mainpage php Return to main page lt a gt body html HTML1 restore db php We read in a CSV and restore the database if possible header Cache control no cache require once ValidFx php our login validation script SMINUSERSTATUS eZ ADMINISTRATOR MIN SMAXUSERSTATUS EVERYONE 9 WORKING PHP CODE 183 Ssuccess validate login SHOW USER list SMYHEADER SUSERSTATUS eZHeaderGreet success SMINUSERSTATUS SMAXUSERSTATUS Restoring database 0 print lt lt lt HTMLO lt DOCTYPE HTML PUBLIC W3C DTD HTML 4 01 Transitional EN gt lt html lang en gt lt head gt lt title gt View comments lt title gt LINK href css eZstyle css type text css rel stylesheet head body SMYHEADER HTMLO GLOBAL SDEBUGGING SDEBUGGING 1 jvs temporary SBIGNAME POST csvname if strlen BIGNAME 5 0 require csv read php mysql_query START TRANSACTION Sok ReadBigCsv ShandDB SBIGNAM if Sok gt 0 print lt p gt There was were Sok error s mysql_query ROLLBACK else mysql_query COMMIT y else prin
72. out 3 values sys dia mean or if not there insert 3 NAs my t n foreach St sort keys SALLTIMES print COUTFILE An t n SALLTIMES St get sequence number of time or could just increment fr foreach h headers Sv S LABELS h n if exists TRIPLETS h pressure in format S D M if defined v if Sv 9 N C 5 NCC 92 9 might have debug stmt here print COUTFILE 1 2 3 else print COUTFILE NA NA NA amp Print An WARNING bad value h line n v SWARNINGS SEXITCODE 0x01 signal warning y else print COUTFIL E NA NA NA r b else if defined v print COUTFILE v else r 4 FORMAT TRANSLATION EZ XLATE 82 print COUTFILE NA E y y y close COUTFILI E if SWARNINGS gt 0 print An NOTE There was were SWARNINGS varning s Please consult the log Y print An Finished n amp CloseLog LOGPRINT exit SEXITCODE A debugging print routine sub Print my Sp Slevel level is debugging level O none l overview 2 detail 3 pi p level _ if SDEBUG gt level if level is always print if SLOGPRINT print LOGFILE p return y print p console print y Here s the logging routine with
73. print lt p gt Tried 1t q8gt giving j if strlen j 1 Sok y y if Sok if failed list Slocktime GetSQL handDB SELECT auxSky FROM UIDS get lock time if strlen locktime lt 1 die lt p gt KEY FETCH FAILURE Null ky print lt p gt Debug Key clash Sky debug only if Slocktime gt Snow if wrapped Snow 1000000000 if nov locktime gt FETCHTIMEOUT DoSQL handDB UPDATE UIDS SET auxSky u ky l uSky u ky 1 HERE aux ky locktime lock generator ff print lt p gt Debug unlocking generator Sky locktime debug only next sleep a bit usleep rand 510000 4 up to 10ms L3 EA y if Sok 4 if fail after MAXFETCHTRIES really fail die lt p gt Aagh key generation failed Sky set the new value unlocking might simply use j in the following DoSQL handDB UPDATE UIDS SET auxSky u ky 1 uSky u ky 1 10 ANCILLARY CODE 208 WHERE auxSky Snow release lock return 3 We might wish to use the TryDoSQL variant and print a reassuring warning instead of the more general failure of DoSQL in the last statement Note that in the above we return as the new key the original key value from the database not the incremented value as in our previous examp
74. rawDBP rawHR names correspond to SAFERsleep DAT names NBP m is calculated below foreach d ALLDATA if length d gt 0 amp Print n n Extracting lt d gt 3 if Sd if no terminal comma Sd Sd ensure terminal comma y amp PullLine d ycal STIMESTAMP y close OUTFILI El Here s the routine to extract all data for one ALLDATA line and write to output We first extract the data to an array v Because we also wish to record the mean blood pressure a value calculated from the systolic and diastolic and the raw values we introduce the variable NASTYOFFSET which is the offset in v of the mean pressure Raw values are stored sequentially to the right of this 2 EZ CAPTURE MANUAL DATA CAPTURE 31 offset sub PullLine my d ycal TIMESTAMP d ycal STIMESTAMP _ my time my NASTYOFFSET Br use to offset rav datuml at NASTYOFFSET we have NBP m followed by rawSBP rawDBP rawHR if d 17 time 1d amp Die n Bad timestamp in line lt Sd gt Stime 51 Sd 52 my Starget my v my i 0 my val my NIBs NIBd NIBm foreach target VARIABLES Sval d amp PullDatum target d here pull out values for later mean BP determination
75. recorded values for an automated record versus interpolated values for the manual one It may well be necessary to interpolate on the manual record THINK CAREFULLY ABOUT THIS 9 WORKING PHP CODE 153 Add a new person User Superuser Person s details Forename Jane Surname Doe Year primary anaesthetic 1994 guakficaton gained Gender F y Role anaesthetist Please state main Mainly public area of practice Does anaesthetist have a favoured Cardiothoracics i y area of practice Enter new person Clear Form Return to main page Figure 5 Adding a new anaesthetist assessor 9 3 Entering a person Here we enter basic information about a person The person might be an anaes thetist assessor or a superuser When the administrator clicks on the Add new button the data are submitted as POST data to the PHP script called eZ_admin_personadded php Preliminary processing is first performed by the Javascript in the header of the page For superusers we can leave out values for First Qualified Current Spe cialty and Current Location At present we won t capture ethnicity email tele phone and physical address eZ add person php Full PHP HTML code follows Setting up a login name and password is yet another screen header Cache control no cache GLOBAL SDEBUGGING GLOBAL ShandDB STHISPAGE eZ add person php require once ValidFx ph
76. them to the database We accommodate encryption of both the supervisor password double md5 and of the new user password md5 xor ed with the md5 of the supervisor password header Cache control no cache STHISPAGE eZ do editlogon2 php require once ValidFx php our login validation script SMINUSERSTATUS eZ_ADMINISTRATOR_MIN SMAXUSERSTATUS EVERYONE Ssuccess validate login SHOW USER list SMYHEADER SUSERSTATUS eZHeaderGreet success SMINUSERSTATUS SMAXUSERSTATUS Edit person s details 0 LT print HTMLO lt DOCTYPE HTML PUBLIC W3C DTD HTML 4 01 Transitional EN gt html lang en lt head gt lt title gt Edit person s details lt title gt LINK href css eZstyle css type text css rel stylesheet gt lt head gt lt body gt SMYHEADER HTMLO SOTHERLOGONID POST otheruserid SMYPSWD 5 POST mypswd SUSERLOGON POST userlogon SNEWPWD1 POST newpasswordl CheckCode OTHERLOGONID Error in logon or fail Sanitise MYPSWD Sanitise SUSERLOGON Sanitise SNEWPWD1 f first check mypswd this is md5 md5 plaintextpvd 9 WORKING PHP CODE 169 Sqry SELECT pPassword FROM PERSON WHERE person SUSERKEY list SMD5PWD GetSQL ShandDB S
77. y UNT lt data gt lt time gt St 1 511 2 Sv 3 ray of labels each of which will refer to an unnamed lt time gt lt label gt lt label gt lt value gt lt value gt lt exists ALLTIMES t SALLTIMES St STIMECOUNT M STIMECOUNT amp Print An line t c S TIMECOUNT 2 Snow SALLTIM ES St here s the tricky bit if label not yet defined make array exists SLABELS S1b1 my lblarry SLABELS 1b1 y O lblarry SLABELS 1b1 now Sv against this label store value for this rint n Storing value v for label lbl at time Snow 3 4 FORMAT TRANSLATION EZ XLATE 81 my STRIPLETS STRIPLETS NBP 1 signal a pressure next debug recover all values First the headers if header in triplets then make THREE headers print COUTFILE Time my Gheaders keys SLABELS my h foreach h headers if exists TRIPLETS h amp Print An Triplet header h s h d Sh m 3 print COUTFILE h s h d h m systolic diastolic mean b else amp Print An Header Sh 3 print COUTFILE Sh print header name y y next print line by line there is a catch for names in the TRIPLETS list pressures we must either pull
78. 2 e csv2dat bat Invokes a Perl program to translate source file to a DAT file stored in ez dat FIX ME The batch file test c2d bat does this on a sample file Section 4 2 2 The preceding files therefore mediate two pathways of data acquisition The first is manually via measurements obtained from digital calipers stored as CSV files in ez rawdata and then translated to processed CSV files stored in ez csv followed by translation to SAFERsleep DAT files for submission to IDAS The second is automatically stored in SAFERsleep retrieved from the server as TAR files stored in ez iar decoded to XML in ez xml and then translated sequen tially to CSV and DAT files Replay a data file through IDAS e replay bat Replay a file through SAFERsleep Section 5 2 using Autolt and screen capture sequential images every minute TOnce we ve overcome the paranoid security features 2 EZ CAPTURE MANUAL DATA CAPTURE 8 2 ez capture Manual data capture It is tedious to repeatedly measure values on an anaesthetic record chart but these measurements are necessary when capturing data from manually recorded charts so that they can be compared with automated records In this section we will in troduce our approach to data capture use pseudocode to sketch the code we will use to process data and then construct a Perl program that does this processing 2 1 Introductory notes We initially thought that the process mi
79. 2 EZ CAPTURE MANUAL DATA CAPTURE 52 23 if it doesn t insert the entry and return MINUS the index on failure return 0 H Also create a log file FILENAMESSUFFIX play LOG Func AddToSSList SEZPATH FILENAME SUFFIX S DURATION Spartname SFILENAME amp SUFFIX do NOT add DAT here fpath SEZPATH amp ez replayNSSLIST TXT Slogname EZPATH amp log amp SFILENAME 6 SUFFIX play LOG might confirm SDURATION is numeric epochs 1 Int SDURATION 4 5 NO we want minutes If FileExists fpath 0 Then Sfh FileOpen fpath 2 Create new file If fh 1 Then FileWriteLine Slogname Error 1 Bad file amp Sfpath 7 write to log Return 0 FAILED HORRIBLY EndIf FileWriteLine fh Header line FileWriteLine fh partname amp SDURATION FileClose fh might test for success FileWriteLine Slogname New entry at line 1 Return 1 written to line 1 EndIf Slineno ScanFile fpath partname logname 3 If lineno 1 Then FileWriteLine logname Error 2 Bad file 6 fpath Return FAILED HORRIBLY EndIf If lineno gt 0 Then WAS found FileWriteLine Slogname Entry found at line amp lineno Return lineno EndIf not found so append to file FileWriteLine fpath partname
80. 446 later taller MYIMAGES BUFFERING onload DOnext var serial MakeSerial BUFFERING 3 serial number var myname png PATIENTID serial PNG alert Debug File is myname MYIMAGES BUFFERING src myname function PreloadImages NextOff IntOff ArtOff if document getElementById loadingLabel document getElementById loadingLabel style visibility visible BUFFERING 1 loadNext Image function MakeSerial i lgth while i toString length lgth 1 i toString y return 1 see http www sean co uk a webdesign javascriptdelay shtm function pausecomp millis 6 EZ SHW AN INTERACTIVE WEB BASED APPLICATION var date new Date var curDate null do curDate new Date while curDate date lt millis function GetTimestamp var date new Date var yyyy date getFullYear var mm MakeSerial 1 date getMonth 2 zero based var dd MakeSerial date getDate 2 var hh MakeSerial date getHours 2 var mi MakeSerial date getMinutes 2 var ss MakeSerial date getSeconds 2 return yyyy ua 2 A mi TIMERS IMAGES SetMinTimer wrapper for setTimeout links timer to function RemindAfterlmin function SetMinTimer t MINUTETIMER setTimeout RemindAfterlmin t
81. 5 name qualyear value SQUALYEAR gt lt td gt lt tr gt lt tr gt lt td colspan 2 lt INPUT TYPE submit NAME submit VALUE Go gt lt td gt lt tr gt lt table gt lt form gt lt div gt HTML3 print lt lt lt HTML8 lt p gt lt a href eZ_edit_person php gt Back to list of people lt a gt lt p gt lt a href mainpage php Return to main page lt a gt body html 9 WORKING PHP CODE 176 HTML8 Details updated User Superuser Data have been updated for Johan van Schalkwyk Name is now Johan van Schalkwyk role specialty and location are superuser Mainly public Back to previous page Return to main page Figure 10 Updated eZ_update php We accept personal details from the preceding page and update the database ac cordingly Submitted items are otheruserid newrole newlocation newspecialty newsurname and newforename Each of these values should be valid with a few exceptions e If the new role is not a registrar then newspecialty can and must be null zero e If the new role is neither registrar nor nurse then newlocation can and must be null zero header Cache control no cache STHISPAGE eZ_update php require_once ValidFx php f our login validation script SMINUSERSTATUS eZ_ADMINISTRATOR_MIN SMAXUSERSTATUS EVERYONE success validate login SHOW USER list SMYHEADER
82. 6 errmsg errmsg 9 WORKING PHP CODE 165 User password minimum length confirmation must be 6 characters errorcount y if pwdl pwd2 errmsg errmsg Confirmatory password doesn t match errorcount y if errorcount gt 0 alert errmsg return false y now encrypt passwords mypwd hex md5 mypwd first encryption pwdl hex md5 pvd1 alert Debug md5 pwd is pwdl pwdl XorStringJ pwdl mypwd alert Xor md5 pwd is pwdl if pwdl length lt 30 alert Oops return false 1 727 end xor section mypwd hex md5 mypwd 2nd encryption myform mypsud value mypwd myform newpasswordl value pwdl myform newpassword2 value return true function XorStringJ strA strB lgth strA length if lgth strB length return y outs while lgth gt 0 lgth 1 ichA Fixch strA charCodeAt lgth ichB Fixch strB charCodeAt lgth ichA 7 ichB ichA Unfix ichA outs String fromCharCode ichA outs here might confirm length of outs lgth return outs function Fixch c convert hex digit to hex value 9 WORKING PHP CODE 166 return c actual hex value function Unfix c convert hex value to hex digit if c gt 9 c 7 32 force LOWER case md5 rule im c 48 return c function NastyString pwd lt lt b
83. 8 amp SDURATION clumsy beyond belief Slineno ScanFile fpath partname logname 3 If lineno 1 Then FileWriteLine logname Error 4 Bad file amp fpath Return jj FAILED HORRIBLY EndIf If Slineno gt 0 Then FOUND FileWriteLine Slogname Entry inserted at line amp Slineno Return lineno EndIf 2 EZ CAPTURE MANUAL DATA CAPTURE 53 FileWriteLine logname Error 3 Bad file amp fpath Return 0 FAILED EndFunc Func ScanFile path uhat logname DEBUG file FileOpen path 0 If file 1 Then If SDEBUG 3 Then FileWriteLine logname FILE NOT OPENED EndIf Return 1 7 fail horribly EndIf 7 read only If SDEBUG 3 Then FileWriteLine Slogname Searching for amp what EndIf Read in lines of text until the EOF is reached Slcount 1 While 1 line FileReadLine file If error 1 Then ExitLoop end of file 1n StringSplit line If ln 1 what Then If SDEBUG 3 Then FileNriteLine logname Found at line amp lcount EndIf FileClose file Return lcount EndIf If DEBUG 3 Then FileNriteLine logname Comparing amp line EndIf lcount lcount 1 Wend If SDEBUG 3 Then FileWriteLine Slogname Not found EndIf F
84. 9 0 my CALAhi 61 0 my SCALBlo 56 3 2 EZ CAPTURE MANUAL DATA CAPTURE 21 my SCALBhi 58 3 my SCALClo 83 8 my SCALChi 85 9 my SZEROlo 0 02 20 microns my SZEROhi 0 02 my CALA CALAlo CALAhi my CALB CALBlo CALBhi my CALC 5 CALChi my ZERO ZEROlo ZEROhi my SNA 1 my SUNCLEAR 2 my datumA amp ReadLine if amp ISIN SdatumA ZERO amp Die Bad initial zeroing datumA y amp StoreZero STIME SdatumA my datumB amp ReadLine amp Print An Debug Y cal value is datumB 1 my MAXVALlo MAXVALhi ALPHAlo SALPHAhi MINVALlo MINVALhi amp TestYCal TIME datumB my MINVAL S MINVALlo SMINVALhi my MAXVAL S MAXVALlo SMAXVALhi my MAXVALm MAXVAL1O MAXVALhi 2 my datumC amp ReadLine amp Print An Debug X cal value is datumC 1 y SDURATION amp TesttCal S TIME SdatumC amp Print n Duration SDURATION 1 y Struealpha SdatumC int SDURATION 5 y ALPHA 52 1 truealpha 0 10 4 0 10 is tolerance y SALPHAm Struealpha amp Print n True alpha Struealpha n 1 here check derived DURATION vs STRUEDURATN as STRUEDURATN is in minutes and truealpha corresponds to 5 min datumC truealpha should equal int STRUEDURAT
85. A DOS batch file xm l2es8v Translate from CSV to DAT 6084548645 4 2 1 code to translate to DAT 4 2 2 ADOS batch file csv2dat 5 ez replay Replaying data via SAFERsleep 2 Du Autolt codefor monitorreplay Invoke ez replay from DOS 2 5 25 2o oe 4080040800040 6 ez shw An interactive web based application 6 1 HTML Code 9 8b ee bd RR TR 39 4 6 1 1 Main page display and data acquisition 6 1 2 Cascading style sheet aS 7 Database definition 711 73 17 3 7 4 ie 7 6 Tl 7 8 7 9 7 10 PERSON aig Ra a CIA ox gu deo xaki PRO a A PERSDATA CURRENTSPECIALTY CURRENTLOCATION 4 4 4 es ANREUORD gt sos dose a we Soe ee Ee BO ONESESSION 4 42 o mcm a RATING uoce dle doe Bee oe Beles ode a d n e Ros Polls SAT 2d oom et be he bo 7 LS ue TT Database SUC BOS Testing the database 22 444 eh ha RR Rae Ree KE OS PHP Creating the SOL database 44 7 10 1 Database creation script S PHP access coding 8 1 8 2 8 3 io gt oca oS ee OS e oh di 5I TnitialLogon php lt gt ola Rx aace ALAR eS 6 1 ss ow db he RUP BES ALS 13 Javasonipt le MIDI udo Sow bow ROR EEE ES WHE USER CETTE Logging out logouliylib 2 245 299 xs CONTENTS 9 Working PHP code 91 02 93 9 4 9 3 9 6 97 The main page mainpa
86. A SAFERSLEEP 102 Func EndCapture MouseClick left 946 426 hack hack Sleep 100 hack Send ENTER Sleep 100 hack Send TAB ENTER Here to start another anaesthetic Send ENTER 777 but we will Send TAB ENTER Sleep 50 7 hack Send ENTER 7 Close MWSnap WinClose MWSnap Exit done EndFunc PI Pr GetFileList Func GetFileList fname lineno get file list with number of frames to capture Dim FDAT 31 SFDAT 0 0 no data Sln 1 lineno first line is a header line Smyline FileReadLine fname ln If error lt gt 0 Then 21 if failed Return SFDAT FAIL Exit EndIf MsgBox ONTOP Debug Line value for line amp Sin 6 lineno 6 15 FDAT StringSplit myline If SEDAT O lt 2 Then Dim SFDAT 3 SFDAT O failed EndIf Return FDAT EndFunc 5 2 Invoke ez replay from DOS The file replay bat can be used to invoke the Autolt script that plays DAT files back through IDAS and screen captures the display every minute echo off 5 EZ REPLAY REPLAYING DATA VIA SAFERSLEEP 103 cls rem Invoke AutoIt script to playback DAT files z replaylez replay au3 It should be placed in the ez directory At present it takes no arguments 6 EZ SHW AN INTERACTIVE WEB BASED APPL
87. AL DATA CAPTURE 48 If Sst 0 Then ji prevent flicker GUICtrlSetState Sctl GUI ENABLE EndIf EndFunc 77 a simple control disabling routine Func myDisable ct1 GUICtrlSetState ctl GUI DISABLE EndFunc Similar check uncheck Func myCheck ct1 GUICtrlSetState ctl GUI_CHECKED EndFunc Func myUncheck ct1 GUICtrlSetState ctl GUI UNCHECKED EndFunc A routine to check whether a particular raw datum file exists Sseq might be one of sbp dbp etc Func IsRawFile Sseq SFILENAME SEZPATH ez SPATHNAME EZPATH amp rawdataN SFILENAME FILENAME seq amp csv SWHOLEFILE SPATHNAME amp SFILENAME If FileExists WHOLEFILE Then return 1 success EndIf eturn 0 eee a ndFunc rj ri on a routine to determine whether to tick various acquisition boxes Func CheckRaw xSBP xDBP xHR xSp02 xETCO2 SFILENAME my5 0 If IsRawFile sbp SFILENAME 1 Then myCheck SxSBP Smy5 BitOR my5 1 EndIf If IsRawFile dbp SFILENAME 1 Then myCheck xDBP Smy5 BitOR my5 2 EndIf If IsRawFile hr FILENAME 1 Then myCheck SxHR my5 BitOR my5 4 EndIf 2 EZ CAPTURE MANUAL DATA CAPTURE 49
88. AME FetchSurname handDB SOTHERLOGONID 9 WORKING PHP CODE SOTHERFORENAME FetchForename handDB SOTHERLOGONID print lt lt lt HTML3 lt p gt Log on password have been updated for user SOTHERFORENAME SOTHERSURNAME Log on name is SUSERLOGON lt p gt lt a href mainpage php Return to main page lt a gt lt p gt lt a href eZ edit logon php Edit another logon lt a gt body html HTML3 function XorString strA strB Slgth strlen strA if lgth strlen strB return y Souts while lgth gt 0 lgth 1 SichA Fixch strAl lgthl SichB Fixch strB lgth Sc Unfix ichA SichB Souts c Souts clumsy y return Souts function Fixch c convert hex digit to hex value i ord c convert chr to integer if i gt 90 Ox5a if lower case Si 32 0x20 i 48 0x30 if i gt 9 i 7 im return i actual hex value function Unfix i convert hex value to hex digit if Si gt 9 Si 3247 FORCE lower case as in md5 im Si 48 return chr i 170 9 WORKING PHP CODE 171 9 2 Edit somebody s details User Superuser Return to main page Select a user sorted by surname Porename Surname Role Started Darran Lowes superuser 2000 Mr Superuser superuser
89. ASTTIME the above clumsily prints to DOUTFILE y show progress for command line pert my r foreach r RULES my opt amp ExtractDAT Sr QD if length Sopt gt 0 print DOUTFILE Sopt n y y close DOUTFILE if SWARNINGS gt 0 warning s 88 4 FORMAT TRANSLATION EZ XLATE 89 amp CloseLog S LOGPRINT exit SEXITCODE sub InterpolateTime my nov then Snow then 0_ my sEPSILON 5 up to 25 seconds is fine if now 17 d 4 d 2 d 2 T NG 2 d 2 Ad 2 amp Die Bad date in CSV file nov y my jdnow amp Julian 1 2 3 4 5 6 0 if then Nd 4 Nd12 Nd 2 T Nd 21 d 2 d 2 sDie Bad old date in CSV file then y my jdthen amp Julian 1 2 3 4 5 6 0 my sec jdnow jdthen sec int sEPSILON 60 60 24 Ssec if sec lt 0 amp Die Bad time change sec in CSV Snow 5 then y if sec 60 4 sampling interval is 30s amp Print n Sampling interval sec Snow then gt jdnow jdthen An 3 return y if sec gt 15 60 ridiculuous amp Die Time interval sec too long Snow gt then y Print in Sampling interval sec Snow then gt jdnow jdthen An 3 my Sdelta 1 0 2 60 24 30 seconds my yy m dd hr mi se while sec gt 59 sec 30 here could print any old
90. AT is valid once CSV made myDisable SsDAT TestFile sDAT SEZPATH 6 csv FILENAME s csv Add to sS list ss is valid once DAT made myDisable sSS TestFile sSS EZPATH amp dat FILENAME s dat test for dud buttons If mCSV 0 Then MsgBox ONTOP Error Bad button mCSV EndIf GUI MESSAGE LOOP GuiSetState display the GUI While 1 Dim msg GuiGetMsg If SFIVEITEMS 31 Then if all 5 acquired myEnable mCSV ugh EndIf Select START GIANT SELECT STATEMENT Case msg SbQuit GUIDelete mygui Return 0 0 quit Case msg SbNew GUIDelete Smygui Return 1 1 resume Case msg bSBP Soverw 1 If IsRawFile sbp SFILENAME 1 Then Soverw MsgBox SONTOP 1 Warning _ Raw SBP data already captured Overwrite If Soverw 1 Then cancel 2 create single backup fnm SEZPATH amp rawdataN FILENAME amp sbp csv FileCopy fnm fnm amp BAK 1 overwrite if exists EndIf EndIf If Soverw 1 Then 2 EZ CAPTURE MANUAL DATA CAPTURE 43 GuiSetState SW_MINIMIZE GetSequence sbp FILENAME DATETIME FAKEDCMS myCheck xSBP SFIVEITEMS BitOR SFIVEITEMS 1 say data acquired GuiSetState SW_RESTORE EndIf
91. ColumnDatanN SL Sfx identified Nd 4 and final comma not needed a check fx121 L fx Sheadarray FixNevHead headarray print r headarray if count Sheadarray print lt p gt Bad return y else do nothing nul Serrcount 1 debug lt 1 1 head array it s just a comment els likely to be data if strlen L gt 3 arbitrary L rtrim SL SL rtrim L remove terminal comma Serrcount SaveCsvLine strtoupper csvname Sheadarray SL ShandDB return y Serrcount function FixNewHead HA SOPT array i foreach SHA as L ugh print lt br gt debug head item S L if preg match wt wt SL fx print n lt p gt Error Bad CSV head item L 9 WORKING PHP CODE 186 return Sitm Sfx 1 Stype Sfx 2 if Stype int SOPT i Sitm elsif Stype string SOPT i Sitm elsif type date SOPT Si DATE S itm elsif Stype timestamp SOPT i TIMESTAMP itm ultimately will need more float time else print n lt p gt Error Bad CSV item type in L return As Si 1 bump output index y return SOPT y CSV back up backup all
92. Contents 1 Introduction EzCapture Interactive measurement and display of anaesthetic records Version 0 37 J M van Schalkwyk D Lowes January 1 2009 11 A note on the directory structure 13 uus gosa ssa doom Sete oe a 05 A ez capture Manual data capture 2 1 Introd ct ry notes 4 2h 844 46h 424244444465 2 2 Algorithm pseudocode sss ke eee a roads 2 3 Perl code raw data to CSV 2 c24c244 44844 eb 7 e4 231 2 2323 2 3 4 2 3 9 2 3 6 27 Main Tine os co cosas asas UD a a dd e a Tests of calibration Main data processing eso dee eee Bowe REO KOS MO POO elec eee we we e mw es White date ci cis dox wha E See Se III 24 A comprhensiyve G L u Ses GS be um a 2 4 1 2 4 2 2 4 3 2 4 4 2 4 5 Invoke Notepad s os sos om wo dw a Queue entries for replay by SAFERsleep Advanced Datum acquisition Keyboard input gt lt br ar u eS ES Decrypt SAFERsleep IAR file to XML 2 5 Obtain basic record information 251 DOS invocation of ez GUI 2 6 Ped keyboard 2 2 bz ses sru stue woes ee Se EU CONTENTS 3 Retrieve files from SAFERsleep using Perl 3 1 The connection string 2229 R ak b d 4 Format translation ez xlate 4 1 4 2 Translate from XML to CSV 4 1 1 code translate to CSV 4 1 2
93. DD MM YYYY and the time is limited to hours and minutes HH MM This interface screen is shovvn in Fig 3 Func XGetFileAndTimestamp make a simple GUI to check the log in Local x y v h pitch skip x 50 y 10 w 120 h 35 Sskip 150 2 EZ CAPTURE MANUAL DATA CAPTURE Spitch 50 Dim SFAT 1 Dim SEZPAT Dim valid Dim Sislis Dim Smygui 720 FONT Sfont Com GUISetFont File na labels SEZ_MAXLINES return array H ez flags 31 Set invalid ted 0 1 manual file listed m 2 ss file listed 5 GuiCreate Enter Case Number 600 40 10 SWS_CAPTION WS_EX_TOPMOST ic Sans MS 9 400 1 font Size 9 font me GuiCtrlCr SX 7 Date an GuiCtrlCre SX Other 1 GuiCtrlCre SX GuiCtrlCre x text Dim casel Dim myDAT Dim myTIM Dim myEND Nature o Dim mySUR Patien Dim myD LOC S Done BUT Dim butto GUICtrlSet IMAGE 7 Dim Spi yev Dim bQuit ateLabel Pleas nter case number e g S0001 Sy pitch u 4 h d time ateLabel Enter anaesthetic date DD MM YYYY 59 start time Sy 2 3 pitch w 5 h abels ateLabel What surgery was performed Sy 4 3 Spitch u 4 h ateLabel Briefly describe the patient s co morbidities Sy 6 3 Spitch w 4 h Fl Y E
94. EZ_DURATION FAT S EZ_ISLISTED TIME END amp Sduration duration Sislisted number of items FIX THE Exists Feu Et Then SEU FOLLOWING 2 EZ CAPTURE MANUAL DATA CAPTURE 61 SFAT SEZ VALIDFLAGS 1 validflags and here WRITE file fn EZPATH 6 ez info amp SFAT SEZ CASENUMBER 6 inf Vomit fn SFAT write file INF file for this case Return SFAT Else GuiCtrlSetState caseID GUI FOCUS fix mouse focus problem hack EndIf EndIf WEnd EndFunc Subsidiary functions The following functions are used above Func ValidateAllInputs casenumber casedate Scasetime Send If StringLen casenumber lt gt 5 Then sgBox SONTOP Woops Case number must be 5 characters long No blanks Return 0 EndIf If StringLen casedate 10 Then sgBox SONTOP Return 0 Woops EndIf If StringLen casetime 5 Then SgBox SONTOP Woops Return 0 EndIf If StringLen end lt gt 5 Then sgBox ONTOP Woops Return 0 EndIf jstart ValidTimestamp Scasedate If jstart 0 Then MsgBox ONTOP Bad date Please check date time Return 0 5 casedate EndIf Sjend ValidTimestamp casedate end If jend 0 Then MsgBox SONTOP Bad end time Date must be in the form dd mm yyyy
95. GE SOLDPAGE UPDATE PERSON SET pValue 5 5 pExpiration Sexpiry WHERE person SUSERKEY if mysql_query qry handDB print lt br gt DEBUG SQL error in storing page mysql_error user Srow pLoginName 6 Determine user status Sqry SELECT MAX PersonRole AS userStatus FROM PERSDATA WHERE Person SUSERKEY list Suserstatus GetSQL handDB Sqry get user status f print lt br gt Dbg User status for USERKEY is Suserstatus 7 Set cookie return user details setcookie eZ SID SSID Sexpiry COOKIE_EXTRA_WAIT Soutvalue USER Suser STATUS Suserstatus OLDPAGE SOLDPAGE return outvalue success ForceLogin This simple function reads an html file which in turn allows a re try of login htm itself described in section 8 1 A message is printed function ForceLogin msg fancy dressing up might go here print lt p gt Debugging ForceLogin msg SMSG msg reminder readfile oopsl htm print msg readfile oops2 htm 8 PHP ACCESS CODING 148 8 3 Logging out logout php STHISPAGE irrelevant require ValidFx php our
96. GuiCtrlCreateInput x skip Sy 3 Spitch w GuiCtrlCreatelnput x 2 Sskip Sy 3 Spitch w f surgery TON GuiCtrlCreateInput x skip 2 y pitch w h GuiCtrlCreatelnput x Sy 3 Spitch Sh GERY GuiCtrlCreatelnput x Sy 5 pitch w 5 h description CRIPTION GuiCtrlCreatelnput x Sy 7 Spitch Sw 5 GuiCtrlCreateButton Done x y 9 pitch w Sh BkColor SbuttonID 0x00CC00 green button not now cID GUICtrlCreatePic pathtoimagegoeshere gif 550 50 408 308 GuiCtrlCreateButton Quit x 3 15 skip Sy 9 Spitch HH MM Sh Sw Sh end t 2 EZ CAPTURE MANUAL DATA CAPTURE GUICtrlSetBkColor GUI MESSAGE GuiSets While 1 Dim Sms g GuiGe LOOP tate 2 SbQuit display the GUI tMsg If msg caselD Then SFAT P P SFA EF If G G G G G here migh If FileExists get fi L ne UI UI UI UI UI SFAT 0 EZ CAS ENUMB ER rst 61 ZPA all EZPA Hs E Hs xt CtrlSe CtrlSe CtrlSe CtrlSe CtrlSe Sislisted Svalid End EndIf EndIf If Smsg Exit EndIf If Smsg If writ gt 0 tDa tDa tDa tDa tDa flags Then xFF0000 ace ez info values from ez info lues to control GUICtrlRead caseID pre
97. ICATION 104 6 ez shw An interactive web based application Here we provide stand alone HTML code that demonstrates the core functionality of our web application Note that the actual HTML used in our project is written dynamically by our PHP code but is very similar to the following code which is intended mainly for demonstration and debugging purposes This application sequentially displays PNG files within a web page that allows the anaesthetist viewing the page to scroll through the record in faster than real time and annotate the record where they believe they would have intervened A record is kept of the viewing anaesthetist s progress and these data are written to an SQL database for later analysis 6 1 HTML code Here we describe the pages used in displaying the records The pages are written in HTML user interaction and data gathering are implemented using JavaScript Ecmascript We still need to do the following here 1 Display the number of minutes elapsed rather than the clumsy reminder after 1 minute one minute has elapsed 2 Add in an artefact button 3 Ensure minute by minute default play continues 4 We really need to interpolate values every minute otherwise we are screwed by the automatic recording 6 1 1 Main page display and data acquisition The main HTML page is called mainpage htm lt DOCTYPE HTML PUBLIC W3C DTD HTML 4 01 Transitional EN http www w3 org TR htm14 loose
98. Main routine Let s create a pseudocode representation of the process The overall plan is to initialise certain variables check the basic calibration measurements and then process each data line in turn variables sbp dbp hr Spo2 etos2 idx 0 index into variables SetInitialValues datumA ReadLine t lt 0 if not datumA in ZERO gt fail Bad initial zeroing StoreZero t datumA datumB lt ReadLine MAXVAL ALPHA MINVAL TestYCal datumB datumC lt ReadLine DURATION lt TesttCal datumC linecount 0 until end of file ReadLine datum t lt ProcessDatum t datum t is an integer end until datumC lt ReadLine TesttCal datumC final check of data 2 EZ CAPTURE MANUAL DATA CAPTURE 14 Might also compare result to DURATION ReadFiO2andEtCO2 PostProcess or fail Bad post processing WriteAllData or fail Data write failed Initialisation Here s the initialisation process ALLDATA contains descriptions of data at any time indexed by time as an integer routine SetInitialValues clear ALLDATA clear ZEROES Stack of zeroes clear YCALS stack of Y calibration values clear tCAL stack of time calibration values reference values CALA lt 59 0 61 0 CALEB lt 56 3 58 3 CALC 83 8 85 9 ZERO lo 04 05 ZERO hi 904205 NA 1 signals NA U Z
99. N lt p gt lt input type button onc lt p gt lt input type button onc lt td gt lt td valigne top align cente intervention box goe lt br gt lt br gt lt span class invi lick Intervene lick alert Her 115 id intbutton value INTERVENE will deal with artefacts id r s here gt sible id label lt br gt lt input class invis ible type text lt p gt lt input class invisible type butto lt input class invisible type butto td td table width 100 border 075 a gt State intervention lt span gt size 50 name intervention ic onClick ShovTheRest id oke onClick CancelIntervention n T lt tr gt lt td colspan 2 gt lt span class invisible id labelb gt lt b gt Variable s you 1 lt td gt lt tr gt lt tr gt lt td width 30 gt input class invisible type checkbox name sbp ide checkb1 onClick lt span class invisible id labelc gt Systolic BP lt span gt lt br gt input class invisible type checkbox name dbp id checkb2 onc lt span class invisible id labeld Diastolic BP lt span gt lt br gt input class invisible type checkbox name hr id checkb3 onCl lt span class invisi
100. N 4 5 but we can simply say if DURATION 5 1 int STRUEDURATN 4 5 amp Print n WARNING duration mismatch DURATION TRUEDURATN 0 SWARNINGS 3 m 3 3 while SIDX lt MAXIDX my 54 amp ReadLine 2 EZ CAPTURE MANUAL DATA CAPTURE 22 STIME amp ProcessDatum TIME d y my datumC amp ReadLine sTesttFinal TIME S datumC amp ReadSpO2andE CO2 SEZDIR SRAWFILENAME S DURATION amp Print n END of data acquisition n n 1 amp WriteAllData STIMESTAMP if SWARNINGS gt 0 sPrint Nn NOTE There was were SWARNINGS varning s Please consult the log 0 SEXITCODE 32 y print An Finished n amp CloseLog S LOGPRINT exit SEXITCODE A simple routine to check whether something x is within a range sub ISIN my x v Sx v _ if x gt v 0 amp amp x lt v 1 amp Print An Check x is between v 0 and v 1 3 return 1 y amp Print An Check x is NOT between v 0 and v 1 3 return 0 A debugging print routine sub Print my Sp level level is debugging level O none l overview 2 detail 3 picky Sp level _ if SDEBUG gt level f if level is 0 always print if SLOGPRINT print LOGFILE p return y
101. N INTERACTIVE WEB BASED APPLICATION 111 HERE WILL SAVE MOVE TO NEXT PATIENT return y Messageon document images mainimage src MYIMAG Gl S THISIMAGE src function HideThanks document getElementByld thanks1 style visibility hidden function ShowThanks document getElementByld thanks1 style visibility visible DATA RECORDING ALLDATA new Array 200 hmm what is maximum DATUMCOUNT 0 function Intervene HideThanks NextOff ArtOff ClearMinTimer StopClock setTimeout ClearMinTimer 2000 just in case clear set by NEXT 722272 MessagePaused TIMESTAMP GetTimestamp RevealTopInputs function ShowTheRest firstcomment NoPipes document myform intervention value if firstcomment length lt 3 alert Please describe your interventionl return false im RevealBottomInputs document getElementById oka style visibility hidden hide self alert Intervention recorded function CancellIntervention alert Intervention Cancelled Messageon SetMinTimer ONEMINUTE SetClock TICKTIME 6 EZ SHW AN INTERACTIVE WEB BASED APPLICATION 112 ClearAll NextOn ArtOn HideA11I Values nputs function StoreAndThanks var
102. NAME capt Case msg imDAT LogNotepad EZPATH FILENAME m c2d 2 EZ CAPTURE MANUAL DATA CAPTURE 47 Case msg imADD LogNotepad EZPATH FILENAME m play Case msg SisGET LogNotepad EZPATH FILENAME iar Case msg isXML LogNotepad EZPATH FILENAME xml Case msg isCSV LogNotepad EZPATH SFILENAME x2c Case msg SisDAT LogNotepad EZPATH FILENAME s c2d Case msg isADD LogNotepad EZPATH FILENAME s play view actual resulting files in Notepad or even Excel Case msg SvwCSV ViewNotepad EZPATH csv FILENAME amp m csv Case msg SvwCSV2 ViewNotepad EZPATH csv FILENAME amp s csv Case msg SvwXML ViewNotepad EZPATH xml FILENAME xml Case msg SvwDAT ViewNotepad EZPATH dat FILENAME amp m dat Case msg SvwDAT2 ViewNotepad EZPATH dat FILENAME amp s dat Case msg SvwSS ViewNotepad EZPATH ez replay SSLIST txt EndSelect Wend EndFunc Simple subsidiary routines 77 a simple enabling routine Func myEnable ct1 Sst bitAND GUICtrlGetState ctl GUI ENABLE 2 EZ CAPTURE MANU
103. ONFILENAME if CONSTRING 17 4 7 amp Die An Connection String must be quoted CONSTRING else SCONSTRING 1 im my myoODBC ODBC connection my dead 0 sPrint n Connection string is lt SCONSTRING gt 2 SmyODBC new Win32 ODBC SCONSTRING or dead 1 if Sdead amp Die Error Win32 0DBC Error y my SOUTTEXT unless myODBC Connection amp Die CRASH Failed to connect Dearie me n 3 RETRIEVE FILES FROM SAFERSLEEP USING PERL y amp Print An ODBC connection worked n 2 SmyODBC gt SetMaxBufSize 500000 4 set buffer size my stmt SELECT AnaestheticMonitorData Data FROM AnaestheticMonitorData AnaestheticPatient Patient WHERE AnaestheticMonitorData AnaestheticId AnaestheticPatient AnaestheticId AND AnaestheticPatient PatientId Patient PatientId AND Patient NHI SREALNUM amp Print n SQL query is lt Sstmt gt 3 my Sanswer amp SQLFetchDatum SmyODBC stmt my Sanlen length Sanswer if anlen 256 arbitrary minimum amp Die Error Tiny IAR file REALNUM fetch failed Length just Sanlen im here open IAR file write and exit my dead 0 open OUTFILE gt ez iar SCASENUM IAR or dead 1 if dead amp Die CRASH Could not open OUTPUT FILE ez iar CASENUM IAR 51 im binmode
104. Person references PERSON pdForename varchar 32 pdSurname varchar 32 pdGender integer PersonRole integer constraint badpdPersonRole foreign key PersonRole references PERSONROLE CurrentSpecialty integer constraint BadpdCurrentSpecialty foreign key CurrentSpecialty references CURRENTSPECIALTY CurrentLocation integer constraint BadpdCurrentLocation foreign key CurrentLocation references CURRENTLOCATION Ethnicity integer constraint badPersEthnicity FOREIGN KEY Ethnicity REFERENCES ETHNICITY PhysicalAddress varchar 128 Email varchar 128 Telephone varchar 32 i We toss in pdGender for reasons of common sense and we ve added a pd Created field to allow us to determine when a particular entry was made Gender codes are for female and 2 for male CurrentSpecialty is coded as below and refers to their main anaesthetic in terest CurrentLocation is where the person mainly practises Here are the relevant tables CREATE TABLE CURRENTSPECIALTY currentspecialty integer constraint badCurrentSpecialty primary key currentspecialty SpecialText varchar 32 INSERT INTO CURRENTSPECIALTY currentspecialty SpecialText VALUES 0 nil 1 General 2 Cardiothoracics 3 Obstetrics 4 other 7 DATABASE DEFINITION 121 We might wish to augm
105. SUSERSTATUS eZHeaderGreet success SMINUSERSTATUS SMAXUSERSTATUS Details updated 0 print lt lt lt HTMLO lt DOCTYPE HTML PUBLIC N3C DTD HTML 4 01 Transitional EN gt lt html lang en gt lt head gt lt title gt Details updated lt title gt LINK href css eZstyle css type text css rel stylesheet gt lt head gt lt body gt SMYHEADER 9 WORKING PHP CODE 177 HTMLO SOTHERLOGONID POST editperson SNEWROLE POST newrole SNEWLOCATION POST nevlocation SNEWSPECIALTY POST newspecialty SNEWSURNAME POST newsurname SNEWFORENAME POST newforename SQUALYEAR POST qualyear we might check and forbid a new role of superuser CheckCode OTHERLOGONID Bad logon id 4 or fail CheckCode NEWROLE Bad role code CheckCodeNull QUALYEAR if SQUALYEAR NULL STHISYEAR WhatYearIsIt if SQUALYEAR lt 1950 SQUALYEAR gt STHISYEAR SQUALYEAR NULL 1 y Sanitise NENSURNAME Sanitise NENFORENAME if strlen SNEWSPECIALTY lt 1 SNEWSPECIALTY SNEWSPECIALTY NULL else CheckCode SNEWSPECIALTY Bad specialty
106. Sh Dim bHR GuiCtrlCreateButton HR Sx S Spitch 5h Dim bSpO2 GuiCtrlCreateButton SpO2 x 4 Spitch Sw h Dim SbETCO2 GuiCtrlCreateButton ETCO2 x 5 Spitch Sw h Dim mCSV GuiCtrlCreateButton Parse to CSV 1 6 Shskip 3 Spitch Sbigw Sh Dim mDAT GuiCtrlCreateButton CSV to DAT 4 Shskip 3 pitch Sbigw h Dim mSS GuiCtrlCreateButton Add to SS list 5 hskip 3 Spitch Sbigw h Dim sGE GuiCtrlCreateButton Get from SS x 7 Spitch Sbigw h Dim sXML GuiCtrlCreateButton Convert to XML 2 Shskip 7 Spitch Sbigw h Dim sCSV GuiCtrlCreateButton XML to CSV 3 Shskip 7 Spitch Sbigw h Dim sDAT GuiCtrlCreateButton CSV to DAT 4 Shskip 7 Spitch Sbigw h Dim 5555 GuiCtrlCreateButton Add to SS list 5 hskip 7 pitch Sbigw h Dim REPL GuiCtrlCreateButton Replay via SS 6 Shskip 5 Spitch Sbigw Sh Dim bQuit GuiCtrlCreateButton Quit 6 hskip 8 5 Spitch Sw Sh GUICtrlSetBkColor bQuit xFF0000 red button Dim bNev GuiCtrlCreateButton Nev case x 8 5 Spitch Sw h GUICtrlSetBkColor bNev OXFFFFOO 77 yellow button tick boxes Dim xSBP GUICtrlCreateCheckbox 1 Shskip 1 pitch Dim SxDBP GUICtrlCreateCheckbox 1 Shskip 2 pitch 2 EZ CAPTURE MANUAL DATA CAPTURE 40 Dim xHR GUICtrlCreateChec
107. SpO2 myDisable xETCO2 then check if raw data exist if so tick boxes SFIVEITEMS CheckRav xSBP xDBP xHR xSpO2 xETCO2 FILENAME myDisable vSBP myDisable vDBP myDisable vHR s myDisable vSpO2 myDisable vETCO2 7 Secondly Parse to CSV is only enabled when all 5 inputs are in If SFIVEITEMS lt gt 31 Then if bits 0 4 are not set myDisable SmCSV EndIf CSV to DAT is enabled when all processing was valid myDisable mDAT TestmDAT mDAT EZPATH FILENAME m FIX THIS gt TestFile INNNNNNNNNNNOOOOOOOOOO Must check on status of Perl submission FIX M Gl 63 Add SS list manual is valid when CSV to DAT succeeded myDisable SmSS TestFile mSS EZPATH amp dat FILENAME m dat 7 Replay via SS is only valid when both ADD buttons succeeded Hmm myDisable SREPL If SISLISTED 3 Then if both flags set myEnable REPL ndlf or make this a rtn 2 7 Convert to XML is only valid once get from 55 succeeded myDisable sXML 2 EZ CAPTURE MANUAL DATA CAPTURE 42 TestFile sXML EZPATH amp iar FILENAME iar XML to cSV is valid once convert is ok myDisable sCSV TestFile sCSV SEZPATH amp xml FILENAME xml ss CSV to D
108. State SW_RESTORE EndFunc rr Similar but filename specific is ViewNotepad Func ViewNotepad EZPATH EZDIR FNAME fnam SEZPATH amp SEZDIR FNAME If Not FileExists fnam amp SUFFIX MsgBox ONTOP Oops Return EndIf Then GuiSetState 8SW MINIMIZI STARGET SFNAME SisXL 0 E If SSUFFIX csv Then File not found s lastfile SEZPATH amp log SSUFFIX amp 51 SW_MAXIMIZI Lu fnam 8 SUFFIX EXCEL RegRead HKEY_CLASSES_ROOT mht OpenWithList Microsoft Office HKEY_CLASSES_ROOT Applications XLpath XLpath RegRead if StringLen XLpath gt 5 Then isXL 1 STARGET Microsoft Excel EndIf EndIf If SisXL 1 Then Run SXLPATH amp amp Sfnam amp SUFFIX Else Run Notepad exe amp Sfnam amp SSUFFIX EndIf Sleep 1000 WinWaitClose STARGET GuiSetState SW_RESTORE EndFunc 2 4 2 Queue entries for replay by SAFERsleep AddToSSList open the file SSLIST TXT and rr rr mv if the entry exists rr search for an entry FILENAMESSUFFIX DAT suffix is return the index of the entry EZPATH SEZDIR EZPATH amp SEZDIR SW_MAXIMIZI SW_MAXIMIZI s or m E gt EXE shell edit comme
109. TEE HH HH HHH HH HH WARNING Similar names exist in the database LIST OF SIMILAR NAMES insert list of forename surname etc Are you sure you wish to add this person Do NOT add person YES Add person T THERE HH HH EEEE E EEE EEE EEEE HE TEE HH E TEE HH RE header Cache control no cache require once ValidFx php f our login validation script SMINUSERSTATUS eZ ADMINISTRATOR MIN SMAXUSERSTATUS EVERYONE success validate login SHOW USER list SMYHEADER SUSERSTATUS eZHeaderGreet success SMINUSERSTATUS SMAXUSERSTATUS Adding new person print lt lt lt HTMLO lt DOCTYPE HTML PUBLIC N3C DTD HTML 4 01 Transitional EN gt lt html lang en gt lt head gt lt title gt Administration Adding new person lt title gt LINK href css eZstyle css type text css rel stylesheet gt script type text javascript o function CheckInput return gt tr lt script gt O ue stub 9 WORKING PHP CODE 159 lt head gt lt body gt SMYHEADER HTMLO SFORENAME _POST forename SSURNAME _POST surname 1 SSTARTYEAR POST startyear SGENDER POST gender SPERSONROLE POST personrole SCONFIRM POST confirmation SCURRENTSPECIALTY POST currentspecialty SCURRENTLOCATION POST currentlocation Sanitise
110. TYPE HTML PUBLIC N3C DTD HTML 4 01 Transitional EN gt lt html lang en gt lt head gt lt title gt Edit log in lt title gt LINK href css eZstyle css type text css rel stylesheet gt lt head gt lt body gt SMYHEADER lt p gt lt a href mainpage php Return to main page lt a gt or lt h3 gt Select a user sorted by surname lt h3 gt lt p gt lt div align center gt lt table width 90 border 2 lt tr gt lt td gt lt i gt Forename lt i gt lt td gt lt td gt lt i gt Surname lt i gt lt td gt 9 WORKING PHP CODE 180 lt td gt lt i gt Role lt i gt lt td gt lt td gt lt i gt Started lt i gt lt td gt lt td gt lt i gt Click here lt i gt lt td gt lt tr gt HTMLO Sactiveusers array Sqry SELECT distinct Person FROM PERSDATA WHERE PersonRole gt 0 Sactiveusers SQLManySQL handDB qry get active users Sactiveusers Flatten Sactiveusers Susers GetLinkedUserDetails handDB activeusers lt a href eZ_do_editlogon php edit logon USERID gt Go lt a gt MyDoubleSort Susers 1 0 sort by surname then forename PrintDetailTable Susers 5 print table with 5 columns print lt lt lt HTML3 lt table gt lt div gt lt p gt lt a href mainpage php Return to main page lt a gt body html HTML3 9 WORKING PHP CODE Backup data User Superuser Back up
111. Z SHW AN INTERACTIVE WEB BASED APPLICATION 106 var i 0 while i lt 12 MYCLOCK i new Image 48 48 var cname images clk i png alert Debug Clock image is myname MYCLOCK i src cname dc function Tick4 don t SetClock TICKER 4 if TICKER gt 11 TICKER 0 y document images clock src MYCLOCK TICK Gl R src function Tick5 TICKER if TICKER gt 11 TICKER 0 ICKTIME 5000 revert y document images clock src MYCLOCK TICKER src SetClock TICKTIME function StopClock clearTimeout CLOCKTICK function SetClock t CLOCKTICK setTimeout Tick5 t function SpeedTime TICKTIME QUICKTIME clearTimeout CLOCKTICK in case SetClock TICKTIME function ZeroClock need document images clock src MYCLOCK 01 src 6 EZ SHW AN INTERACTIVE WEB BASED APPLICATION 107 buffered image loading sequential function DOnext if BUFFERING MODIM Tick4 BUFFERING TOTALIMAGES if loadNextImage else ZeroClock document getElementBylId loadingLabel style visibility hidden document images mainimage src MYIMAGES 01 src NextOn y function loadNext Image MYIMAGES BUFFERING new Image 824
112. a problem with logging on message follows gt Here s the second part oops2 htm lt p gt Click lt a href login htm gt here lt a gt to try again lt body gt 8 1 3 Javascript file md5 js Here s a Javascript file that mediates md5 encoding stored locally in ez ez shw php js and on the server in ez js Thanks to Paul Johnston for this md5 Javascript code x A JavaScript implementation of the RSA Data Security Inc MD5 Message Digest Algorithm as defined in RFC 1321 Version 2 1 Copyright C Paul Johnston 1999 2002 Other contributors Greg Holt Andrew Kepert Ydnar Lostinet Distributed under the BSD License See http pajhome org uk crypt md5 for more info x Configurable variables You may need to tweak these to be compatible with the server side but the defaults work in most cases x var hexcase 0 hex output format 0 lowercase 1 uppercase var b dpad base 64 pad character for strict RFC compliance y var chrsz 8 bits per input character 8 ASCII 16 Unicode 8 PHP ACCESS CODING These are the functions you ll usually want to call 141 They take string arguments and return either hex or base 64 encoded strings xA function hex md5 s return binl2hex core md5 str2binl s s length chrsz function b64 md5 s return binl2b64 core md5 str2binl s s length chrsz function str md5 s return binl2s
113. ace NNNN thisline split up the line at each comma Sitemarray explode thisline if count itemarray cols Sc count Sitemarray print lt br gt lt b gt Error lt b gt Mismatch between column count cols and line thisline c print_r Sitemarray return 1 fail i if DEBUGGING print cbro line data print_r Sitemarray left right i while i lt Scols list Scol val FormatOneltem headarrayl il Sitemarray i Sleft Scol right Sval i im remove final commas Sleft rtrim left Sright rtrim Sright Sqry INSERT INTO STABLENAME Sleft VALUES Sright if SDEBUGGING print br QUERY qry r if mysql_query Sqry handDB print lt br gt SQL ERROR mysql error return 1 fail STOTALLINESREAD bump count of successful inserts return 0 4 success A subsidiary routine FormatOneltem formats a single data item function FormatOneItem Scol Sitm Sretval return array of 2 elements Sretval 0 Scol default 10 ANCILLARY CODE Sitm preg replace X Sitm restore commas itm preg_replace n Mn itm fix carriage returns itm preg replace Sitm duplicate single
114. aint badForensicKey primary key forensic Person integer constraint badForensicPerson foreign key Person references PERSON flp varchar 15 fTime TIMESTAMP fCode integer fText varchar 128 The above table is not yet in use and we don t yet have a separate table for the fCode field 7 7 UIDS In this final table we create seeds for generating unique IDs for all of the other tables The SQL standard doesn t directly provide automatic key generation and although dialects do provide thinks like auto incrementing fields or permit user defined functions to fill the gap we will not use these facilities as they vary be tween databases We will rather take keys as we need them from the UIDS table Each new primary key for a new table entry will be fetched from the UIDS ta ble We don t have key seed fields for tables that will not ordinarily acquire new rows The process of updating auto incrementing these source fields is rather tricky and database features designed to prevent errors may get in our way Problems only really arise where several users are concurrently accessing the same field in UIDS but we must account for this eventuality The accessory fields be ginning with aux are used to accommodate this necessity they must start off with values identical to the corresponding key fields CREATE TABLE UIDS uids integer constraint badUids primary key uids
115. associated subroutines The log is written to the ez log directory sub OpenLog my islog LOCALFILE Sislog S LOCALFILE 8 if islog return if not logging my STODAY amp GetLocalTime my logfile ez log LOCALFILE x2c TODAY LOG open LOGFILE gt Slogfile or die CRASH Could not open LOG logfile n De sub GetLocalTime my sec min hour Smday mon year Swday yday isdst sec min hour Smday mon year 4 FORMAT TRANSLATION EZ XLATE 83 Swday yday isdst CORE localtime time Syear 1900 Hfix y2k sec amp DoubleDigit sec Smin amp DoubleDigit min Shour amp DoubleDigit Shour Smday amp DoubleDigit mday Smon amp DoubleDigit mon Smon january is zero return year mon mday hour min sec sub DoubleDigit i 51 8 if length i gt 1 return i y return 0 i concatenate my sub CloseLog my islog Sislog if islog close LOGFILE im _ se A death routine for fatal errors sub Die my Se Se _ my 1 SLINECOUNT 1 amp Print n n DIED Data line 1 n Message Se 0 SEXITCODE 128 exit SEXITCODE die n Fatal 4 1 2 A DOS batch file xml2csv Here s the batch file xml2csv bat used to invoke the XML translation from the DOS command l
116. atal exit SEXITCODE caution S die n Fatal T Reading console values sub ReadConsole my dattype DURATION Sdattype DURATION _ first check duration while SDURATION d E http perldoc perl org functions exit html 69 print An Oops Duration of lt SDURATION gt doesn t seem valid print n n Pleas nter the DURATION in minutes SDURATION lt STDIN gt y DURATION 5 int SDURATION 4 5 round up 2 EZ CAPTURE MANUAL DATA CAPTURE my my Sc print my tot 1 SDURATION 5 St n n ENTER DATA Use the letter n for NA Use to skip back x for no more n for NA Pomp t 0 Sforced 0 while bus r Sbadinp forced count time c tot 6 Sforced print in Enter dattype value for time t here will validate spo2 etco2 Sinp lt STDIN gt chomp inp remove cr lf my Sv amp ValidParam Sinp dattype if v Ts SKIP BACK if c gt 0 SG else print n Can t go back At start y elsif Sv 2 NA sStore c 1 1 signals datum NA e du elsif v 3 forced Sforced 1 elsif v 0 print An Oops Invalid parameter inp An else sStore c inp store value Sc else IS FORCED amp Store c 1
117. bel value triplet Look up the time in ALLTIMES obtain an index and store the value at that index in the array for this label Warn if duplicate values are encountered for a particular time 5 Repeat the preceding step for all labels 6 Write the header 7 For each time obtain values for all label arrays in turn writing NA if no value exists and write the time and values in CSV format Note that pressure values are compound and should be split up into three components So for example NBP lt data gt lt time gt 2008 03 31T10 24 13 lt time gt lt label gt NBP lt label gt lt value gt 119 000000 57 000000 77 000000 lt value gt lt data gt should be turned into three NBP sys NBP dia and NBP mean in the fi nal translation one value becomes three columns We must code for this and potentially for other similar pressure readings When we translate from CSV to DAT we will need to identify such values and re translate accordingly Perl program to translate anaesthetic monitor data from XML to CSV format usr local bin perl w my SEZPATH ez my SOUTPATH SEZPATH csv my SLOCALPATH SEZPATH xml my SEXITCODE 0 code on exiting Perl my SDEBUG 3 0 debug off l overview 2 detail 3 nitpicking my LOGPRINT 1 print to log my SWARNINGS 0 see usage the following are global my SLOCALFILE SARGV 0 get fi
118. ble id labele gt Heart Rate lt span gt lt br gt input class invisible type checkbox name spo2 id checkb4 or lt span class invisible id labelf SpO lt sub gt 2 lt sub gt lt span gt lt br gt lt input class invisible type checkbox name etco2 ide checkb5 c lt span class invisible id labelg EtCO lt sub gt 2 lt sub gt lt span gt lt td gt lt td vidthe 706 align center gt lt br gt lt span class invisible id labelh Optional comment lt span gt lt br gt lt input class invisible type text size 50 id textb name vai lt p gt lt input class invisible type button onClick StoreAndThanks ic lt p gt lt span class invisible id thanks1 td tr lt table gt lt td gt lt tr gt lt table gt lt end main table gt lt FORM gt lt body gt lt html gt Thank you lt span gt 6 EZ SHW AN INTERACTIVE WEB BASED APPLICATION 6 1 2 Cascading style sheet Here s eZstyle css eZstyle css my tiny style sheet 1 Broad brush strokes body margin left 0 margin right 0px color 00008B font family Garamond serif text align left div margin top lem hi h2 h3 h4 h5 h color 000040 font family sans serif margin bottom 0 margin top 0 3em hr border lpx AAAAAA border style dashed
119. cess SMINUSERSTATUS SMAXUSERSTATUS Edit details 0 print lt lt lt HTMLO lt DOCTYPE HTML PUBLIC N3C DTD HTML 4 01 Transitional EN gt lt html lang en gt lt head gt lt title gt Edit lt title gt LINK href css eZstyle css type text css rel stylesheet script type text javascript lt function CheckInputSurname myform valu myform newsurname value if valu length lt 2 alert Minimum surname length is 2 characters might perform other checks return false y return true function CheckInputForename myform valu myform newforename value if valu length lt 1 alert Minimum forename length is 1 character might perform other checks return false y return true function CheckAllInputs myform we will not check the poplists if CheckInputForename myform CheckInputSurname myform clumsy return false H return true y gt lt script gt lt head gt lt body gt SMYHEADER HTMLO 9 WORKING PHP CODE check user ID or fail SOTHERSURNAME FetchSurname Sha SOTHERFORENAME FetchForename Sqry SELECT pLogi nName FRO list SOTHERLOGIN Get SQL the
120. check validity of casenumber befor red button Fil file amp SFA ENUMB EZ_CAS ER S SFA ENUMB ta SmyDATE SFAT S EZ CASE DATE ta SmyTIME SFAT S EZ CASE TIME ta SmyEND SFAT SEZ_CAS ta SmyS URGERY ta SmyDESC SFAT SEZ _ RIP ISLIS SFAT SEZ S EEND URGE EZ CAS ER 1355 1 RY ION SFAT ED SbQuit Then S buttonI D Then SFA EZ CAS ENU BER SFA EZ CAS EDAT E SFA EZ CASE II E FAT EZ CASE EN FAT EZ S URG D FAT Sduration FF EZ_D ESC ValidateAllInputs FA RI MsgBox ONTOP If duration 5 0 Then GUIDelete mygui SFAT rro 1 5 SFAT SEZ_VALI PTION GUICtrlRead EZ_MAXLINES DFLAGS was Done DATI END URGI E E RY EZ_D button pressed GUICtrlRead caselD GUICtrlRead my GUICtrlRead myTI GUICtrlRead my ERY GUICtrlRead myS ESCRIPTION my DI ESCRIP1 ION ENUMB EZ_CAS ER SFATIS EZ_CASE DA El SFATIS EZ_CASE SFATIS EZ_CASE Debug Duration is SFA
121. d the current is less than the stored value we first add 1 million to this number but otherwise we simply find the difference If the difference is over the cutoff say 2 seconds i e 2000 microseconds then timeout has occurred and we act accordingly We have accordingly modified the SQL for creation of the UIDS table in previous versions all of the aux columns in UIDS were varchar 32 but now they are simple integers See Section 7 7 Now we can set about fetching a key We assume the existence of the constants MAXKEY for example set at 1 billion MAXFETCHTRIES perhaps 1000 and the FETCHTIMEOUT set at say 2000 milliseconds function FetchKey ShandDB Sky Snow MAXKEY ModTimeNow MAXKEY prevents collision ff print lt p gt Debug time modification is now Scount 0 Sok 0 while Sok amp amp Scount lt MAXFETCHTRIES Scount Sq UPDATE UIDS SET auxSky Snow 2311 the database used doesn t support integer values up to 9 digits then the code might need to be modified ever so slightly 10 ANCILLARY CODE 207 WHERE auxSky uSky Sok TryDoSQL ShandDB q lock generator Tir print lt p gt Debug attempt vas amp lt q amp gt giving Sok f problem is succeed if no rows updated thus if Sok if apparent success q SELECT u ky FROM UIDS WHERE auxSky Snow list j GetSQL handDB 54 get new key Ti
122. dated for SOTHERFORENAME SOTHERSURNAME lt p gt Name is now SNEWFORENAME SNEWSURNAME role specialty and location are SROLETXT SPECTXT LOCTXT lt p gt lt a href eZ_do_edit php editperson SOTHERLOGONID gt Back to previous page lt a gt lt p gt lt a href mainpage php Return to main page lt a gt lt bo HTML dy html 3 9 WORKING PHP CODE 2 Edit somebody s log in User Superuser Return to main page or Select a user sorted by surname Forename Surname Role Started Darran Lowes superuser 2000 Mr Superuser superuser 179 Return to main page Figure 11 Editing a user log on 9 6 Editing log on details The following page presents a table of users who are permitted to have log on priv ileges Clickable links are created which submit a GET to the page eZ_do_editlogon The user ID submitted to that page is associated with the name editlogon eZ_edit_logon php header Cache control no cache STHISP AGE eZ edit logon php require once ValidFx php our login validatio n script SMINUSERSTATUS eZ ADMINISTRATOR MIN SMAXUSERSTATUS EVERYONE Ssuccess validate login SHOW USER list SMYHEADER SUSERSTATUS eZHeaderGreet success SMINUSERSTATUS SMAXUSERSTATUS Edit somebody s log in 0 print lt lt lt HTMLO lt DOC
123. der lin my COLNAMES split get names my Scc 0 clumsy count my cn my SCOLLOOKUP foreach cn COLNAMES SCOLLOOKUP cn cc See TT hi now given name can get position of column f HERE WILL PROCESS datrules txt into RULES array my RULES my SRCOUNT 0 my dr foreach dr DATRUL Gl S if dr Nw N if comment SOUTPATH Sdouttfot 2 1Nn 4 FORMAT TRANSLATION EZ XLATE amp Print Please consu y print An Fin n NOTE There was were SWARNINGS lt the log 0 ished Nn 1 ignore elsif length Sdr lt 4 ignore short lines else SRULES SRCOUNT sPrepareRule dr COLLOOKUP the above can DIE if bad line SRCOUNT y my SILEN S INDATA do NOT add 1 my LASTTIME redundant my STHISTIME while SLINECOUNT lt SILEN SLINECOUNT skip first line 5 SINDATA SLINECOUNT my D split D amp TruncArray D convert to 6 decimals here might check for dud lines not at present here fill in dummy values for IDAS SLASTTIME STHISTIME THISTIME D 0 if length LASTTIME gt 0 amp InterpolateTime STHISTIME SL
124. ds We therefore automate the process again using AutoIt and Perl Here s the code that coordinates the translation from IAR to XML Func Iar2Xml SEZPATH SIARFILENAME 7 NB at present we assume th xistence of all of the paths listed below SEZPATH ez SXPATH EZPATH amp ez xlateN SIARPATH EZPATH amp iar SXMLPATH EZPATH amp xml SERRORLOG SEZPATH log IARFILENAME amp xml LOG 2 EZ CAPTURE MANUAL DATA CAPTURE 57 ClipPut Clear clipboard activate SAFERsleep viewer NB batch file must be defined Run XPATH amp xlat bat amp SIARPATH 6 SIARFILENAME IAR XPATH ugh WinWaitActive SAFERsleep IAR Viewer WinActivate SAFERsleep IAR Viewer HERE MUST CHECK FOR Error box and if appears i simply close down don t capture log the error If WinExists Error Then Sdudtext ControlGetText Error CLASS Static INSTANCE 1 get FileWrite SERRORLOG Error in file amp SIARFILENAME 6 text amp dudtext MsgBox SONTOP Parse Error IAR viewer forced error logged 5 WinActivate Error Send ENTERJ 7 acknowledge Sleep 100 Return 1 1 failure EndIf Sleep 100 ControlClick SAFERsleep IAR Viewer CLASS TcxCustomInne
125. dtd gt lt html lang en gt lt head gt lt title gt Main Page display anaesthetic record lt title gt lt link type text css rel stylesheet href css eZstyle css gt lt script type text javascript gt xc LOAD IMAGES 6 EZ SHW AN INTERACTIVE WEB BASED APPLICATION 105 TOTALIMAGES 75 datuml MYIMAGES new Array TOTALIMAGES PATIENTID S0012 s datum2 THISIMAGE 0 PreloadImages here might check cookie for start image NOW 0 TIMESTAMP 0 ONEMINUTE 15000 debug every 15s ONEMINUTE 60000 ONESECOND 1000 MINUTETIMER vitally important GLOBAL AAGH likewise T MYCLOCK new Array 12 TICKER 0 TICKTIME ONEMINUTE 12 QUICKTIME ONESECOND 12 CLOCKTICK LoadClock BUFFERINC 0 MYIMAGES 0 new Image 824 446 later taller MYIMAGES 0 src png START png MODIM parseInt TOTALIMAGES 12 addLoadEvent PreloadImages set up preloading event loader function addLoadEvent func var oldonload window onload if typeof vindov onload function window onload func else window onload function if oldonload oldonload func clock stuff function LoadClock 6 E
126. e more The po tential errors are numerous as even more than one process might interfere 3 Proprietary solutions exist which should allow the user to conjoin multiple queries into a single atomic statement but we wish for a more generic solution 10 ANCILLARY CODE 203 10 7 2 An initial solution How about the following schema In all of the following we assume we have a key generator table called UIDS that contains a single row filled with key generating columns 1 First lock the key generator We assume that we have two keys in the UIDS generator table uValue and uValueLock and that for now both are integers Scount 0 Sok 0 while Sok amp amp count lt 1000 i Seount Sok TryDoSQL ShandDB UPDATE UIDS SET uValueLock uValue l WHERE uValueLock uValue lock generator field h 2 Next either fail 1f repeated attempts all failed or fetch the new generated value if Sok j GetSQL handDB SELECT uValueLock FROM UIDS get new key else return 0 fail y 3 Finally allow others to get the next value DoSQL handDB UPDATE UIDS SET uValueLock ee release lock 10 ANCILLARY CODE 204 10 7 3 A refined solution The preceding approach seems fairly robust but there is a major problem if a process locks a key generator and then dies the generator is locked forever We therefor
127. e need a robust timeout If all processes are accessing the same source of a timestamp here is one solution 1 Lock the generator as above assuming the initial value in uValueLockTxt is the same as uValue but write a timestamp provided as now to uVal ueLock This will cause subsequent attempts to fail nastily But anyone failing can now see when the value was set Scount 0 Sok 0 while Sok amp amp count lt 1000 Seount Sok TryDoSQL handDB UPDATE UIDS SET uValueLock Snow WHERE uValue cast uValueLock AS INTEGER lock generator Here s the catch Within the same loop if we fail check that the previous person who grabbed control hasn t died disgracefully If this isn t the case no time out then we delay and try again but if the person has timed out we still grant them the increment by doing it ourself but reset uValueLock to again make it accessible if 1 ok timeout GetSQL handDB SELECT uValueLock FROM UIDS get lock time delta Julian now Julian Stimeout if delta gt SMAXTIMEOUT DoSQL ShandDB UPDATE UIDS uValue uValuetl WHERE uValueLock Stimeout restore function else here we might insert a random delay 2We assume that now is an accurate timestamp with a millisecond value and preferably a microsecond value SET uVal
128. eZ database connect php Note that there is a potentially fatal flaw in CPANEL it s possible to delete an entire database with one click and no confirmation We ve already uploaded database_create php so all we need to do is upload the following 1 eZ_database_connect php which we place in the relevant directory above the HTML public directory 2 eZ GLOBALS php which goes into the ez directory These are described in the next section Install Ocelot permitting ODBC connectivity and in Windows go Start Control Panel Administrative Tools Data Sources Under User DSN click on the Add button se lect Ocelot from the list and click Finish In the data source name type in the letters eZ and you re done Bin the Ocelot example within a DOS box from the ocelot directory type in demo32 and press Enter Paste the SQL in sequentially after typing in disconnect default and then connect to eZ Remember to COMMIT at the end 7 DATABASE DEFINITION 127 7 10 PHP Creating the SQL database Before we create our database we have several prerequisites The first is a script that actually connects to the database eZ database connect php Here s the script It requires the existence of the global variable DEBUGGING which we ll consider in a moment function eZ_database_connect GLOBAL DEBUGGING ShandDB mysql_pconnect localhost name_sysadmin PASSWORDHERE or die Cannot connect to database
129. eadLine Sf j next time s StringSplit v If s 1 time Then Sarr SEZ_CASETIME s 2 and time Else SWARNINGS SWARNINGS 1 EndIf cf perl 2 EZ CAPTURE MANUAL DATA CAPTURE 63 Sv FileReadLine f validity flags s StringSplit v If Ss 1 valid Then Sarr EZ_VALIDFLAGS 55121 Else SWARNINGS SWARNINGS 1 EndIf Sv FileReadLine f listed flags 7 might here check for success 55 StringSplit v If s 1 listed Then Sarr EZ_ISLISTED s 2 Else SWARNINGS SWARNINGS 1 EndIf parameters added in v 0 37 Sv FileReadLine Sf end time s StringSplit v If Ss 1 end Then Sarr SEZ_CASEEND s 2 Else SWARNINGS SWARNINGS 1 EndIf Sv FileReadLine f description s StringSplit v If s 1 surgery Then Sarr SEZ SURGERY 55121 Else SWARNINGS SWARNINGS 1 EndIf Sv FileReadLin S ji Surgery s StringSplit v If s 1 description Then Sarr S EZ DESCRIPTION s 2 Else SWARNINGS SWARNINGS 1 EndIf v FileReadLin 52 duration derived s StringSplit v If s 1 duration Then Sarr S EZ DURATION s 2 Else 2 EZ CAPTURE MANUAL DATA CAPTURE 64 SWARNINGS
130. ection 2 4 uu l x li 1111111111 T r r r T T T T T T T L a 20 00 OS BROS EENE ANI AN ee eR 11111111111 X xis me call IDE oral 1A A A TUL LI LA 40 1 111111 4 1 1 4 4 4 2 LLLLLLI 0 l Tili AE T 1 A A 1 TA KS c 11 RA AAR SEER ON ES CR LL D UL LL 1 Mia E WE E A UE Figure 1 Constant values The process of data entry uses certain short cuts to signal detailed structure of the record calibration and zeroing and check measurements Note the following values e ZERO is a value in the range of 0 05 to 0 05 mm e MAXVAL signals a value in one of three ranges 59 61 mm 56 3 58 3 mm and 83 9 85 9 mm all being offsets from the baseline with a centre value that is the average of the lower and upper limits Each of these ranges refers to a different type of record but each is equivalent to an actual value of 220 mmHg or a heart rate of 220 min 1 MAXVAL is used as a calibration 2 EZ CAPTURE MANUAL DATA CAPTURE 10 signal We will refer to the three types of records corresponding to the three ranges used above as type A type B and type C records respectively e MINVAL signals a measured value in the range of MAXVAL 10 MINVAL corresponds to a measurement extending from the baseline at 20 mmHg or a heart rate of 20 min to the line signalling a value of 40 mmHg or min e The x calib
131. ed they would have intervened EXPLAIN BETTER The SQL database is loosely based on the one we created for the STrICT study We kick off with a table of tables which lists all of the tables within the database in the order in which they were created This allows us to re import backed up data without relational problems The name of the table is METATABLE and we clearly have to make it before the other tables CREATE TABLE METATABLE metatable integer constraint badMetatable primary key metatable TableName varchar 32 Now that we ve sorted that out here s PERSON 7 1 PERSON CREATE TABLE PERSON person integer constraint badPerson primary key person pExpiration integer pLoginName varchar 16 pPassword varchar 32 pSID varchar 32 pValue varchar 255 FirstQualified integer pMade timestamp We ve moved the Forename Surname and PersonRole fields from the PER SON table to the PERSDATA table below We ve also moved FirstQualified from the PERSDATA table to here as it can only ever have one value and belongs here The additional fields required by our PHP program are 7 DATABASE DEFINITION 119 pExpiration is a UNIX timestamp used to handle time out if a user overstays their welcome at present we time out after a fixed maximum period of 1 hour rather than monitoring for inactivity pLoginName is the log in name of a user if appropriate pPassword w
132. ent the above table somewhat CREATE TABLE CURRENTLOCATION currentlocation integer constraint badCurrentLocation primary key currentlocation LocationText varchar 32 INSERT INTO CURRENTLOCATION CurrentLocation LocationText VALUES 1 Mainly public 2 Mainly private 3 Similar public private 7 3 ANRECORD ANRECORD refers to an anesthetic record captured either manually or automat ically We will create an anonymised PERSON entry that refers to a given patient to facilitate data analysis CREATE TABLE ANRECORD anrecord integer constraint badAnrecord primary key anrecord anual integer PngFilename varchar 32 Person integer constraint badAnrecPerson foreign key Person references PERSON Manual is 1 for manually recorded scenario 0 for machine recorded PngFile name is the name without 001 nnn suffix of PNG files 7 4 ONESESSION CREATE TABLE ONESESSION onesession integer constraint BadOnesession primary key onesession osStart TIMESTAMP osEnd TIMESTAMP Assessor integer constraint BadosAssessor foreign key Assessor references PERSON Anrecord integer constraint badOsAnrecord foreign key Anrecord references ANRECORD I 7 DATABASE DEFINITION 122 7 5 RATING First let s create a small table which contains the text describing each rating item We l
133. est c2d demo csv to dat echo test csv2dat demo captured csv to dat echo test captur demo rav csv processing cho 11 HARDWARE SOFTWARE USEFUL FILES amp CHANGE LOG 212 11 1 Change Log Changes for versions 0 35 0 36 1 Fixed Y calibration in ez captur pl Previously because we cycled the times we overvvrote Y calibration values 1 Push values to a stack rather than writing to array Fixes the problem with overwriting at same time ie push YCALS to store each value and for GetYCal sum the values dividing by their length 2 Amendments to the capture of raw data a Modified the Autolt program so that it expects three sets of data rather than one b Start as usual with zero and cal but at end of first series systolic blood pressures terminate before repeat zero and cal i e enter Excel c Autolt saves this series as eg X0001 sbp csv d Likewise for X0001 dbp csv and X0001 hr csv but with the final se ries terminate with a zero cal and x measurement time e Then only do we submit the name and timestamp to Perl What Perl does is tries to open X0001 csv If this fails then it looks for the components concatenates them and does its magic Perl uses an exit code to report failure bits 0 1 or 2 of the exit code are set depending on which sequence failed sbp dbp or hr f Autolt reads the Perl exit code and offers the user the opportunity to repeat the offending series overwriting the
134. etchRole ShandDB p list det1 3 GetSQL ShandDB SELECT FirstQualified FROM PERSON WHERE person p year of lst qualification Sdet1 4 link use str_replace rather than regex Sdet1 4 str replace USERID Sp det1 4 might check for success Sopt i Sdetl i 1 y return Sopt 10 4 3 FetchSurname Given a person s ID obtain their surname function FetchSurname ShandDB id Sqry SELECT MAX persdata FROM PERSDATA WHERE Person id AND pdSurname IS NOT NULL list Spd GetSQL ShandDB qry fetch key for surname Sqry SELECT pdSurname FROM PERSDATA WHERE persdata pd list surname GetSQL ShandDB qry fetch surname return surname 10 4 4 FetchForename In a similar fasion to FetchSurname obtain a person s forename function FetchForename ShandDB id Sqry SELECT MAX persdata FROM PERSDATA WHERE Person Sid AND pdForename IS NOT NULL 10 ANCILLARY CODE 197 list Spd GetSQL ShandDB qry fetch key for forename Sqry SELECT pdForename FROM PERSDATA WHERE persdata Spd list forename GetSQL ShandDB Sqry fetch forename return Sforename FetchRole The following can be made far simpler if we accept that in this database a pe
135. f then we overwrite table row I with the current timestamp and the value J J We then 6 Submit the value J in the login form that the user sees 7 The user responds with md5 J md5 pwd login and the user J value J which should be identical to J where represents concatenation of the two strings 8 On receiving the user response with Ju we examine the SALT table item at index I mod K If J is not equal to J or the time has expired we say invalid timeout and they can retry after a 30s wait If both are ok we 9 Calculate md5 J md5 pwd for the given user and if not equal to the sup plied value say invalid timeout otherwise 10 Store md5 J md5 pwd as the session ID against that user name both in the database and as a cookie at the user end and proceed In order to implement the above we need a SALT table with say 100 entries If we were concerned about repeated frequent logging attempts messing around with access by other users we might log the IP address of each unsuccessful attempt and check subsequent attempts e g institute delay lock out for repeat offenders 81 2 processLogon The following routine must be invoked before anything is written as HTML It either exits on failure or returns the user key function processLogon Susername Spswd ShandDB salt
136. ffsets We can also check the duration at various points We can also use the duration to calculate alpha Our reference time interval is always 5 min If just 10 minutely values are charted then NAs must always be inserted in between by the capturer Note that if an anaesthetic starts at a time not divisible by e g 5 min or the relevant number of minutes corresponding to alpha then we should start recording at the first integral time before the actual start time and record the first datum as zero zero missing Conversely if the anaesthetic doesn t end on a mark non integral time with respect to alpha then we must record the final value but not put in a missing value at the end In measuring the x duration we should measure from the point at which we start recording even if this is before the actual start of the anaesthetic i e on an integral boundary and end at the last mark even if the anaesthetic ends several minutes after this Our rationale is that our x measurement is a calibration value and if we measure between manually constructed marks on the chart this is less reliable that if we measure between pre printed lines on the chart In addition if we either skip or include both the start and the end there is too much variability a nominal 9 minutes or 2a for us to check things accurately 12 STILL TO DO 214 5 10 12 10 Based on the preceding points a Acquire end time and duratio
137. foreach d 0 ALLDATA SKBCOUNT Print print OUTFILE close OUTFILI n n E E Count Val ue Extracting nSKBCOUNT d lt Sd gt 2 E csv 12 3 RETRIEVE FILES FROM SAFERSLEEP USING PERL 73 3 Retrieve files from SAFERsleep using Perl Here s the Perl script getcrypt pl placed in the ez ez xlate directory First we connect to SAFERsleep then we obtain a binary image of the encrypted LAR file and write it to the ez iar directory usr local bin perl w use strict use Win32 0DBC my SDEBUG 3 0 to turn off debugging 1 overviev 2 detail 3 nitpicking my SLOGPRINT 1 print to log my EZDIR ez my SEXITCODE 0 code on exiting Perl global my CASENUM SARGV 0 e g S0029 my CONFILENAME SARGV 1 connection string file my SPARAMS SARGV 2 eg debug 3 logprint 0 if SPARAMS debug d command line control SDEBUG 1 if PARAMS logprint d SLOGPRINT 1 sOpenLog LOGPRINT EZDIR SCASENUM for debugging sPrint An Arguments are CASENUM CONFILENAME if CASENUM S d 4 i sDie An Bad number lt SCASENUM gt PARAMS 3 my REALNUM SOOS1 my CONSTRING amp GetConnectionString EZDIR C
138. g what motivated their decision to intervene 6 The user can identify artifacts 7 All user annotations are stored as long lived cookies 8 At the end the cookie data are written in a mock fashion to the server 9 The user is then thanked for participating Note that the user can pause the assessment at any time but they cannot go back in time We should store the images in a separate png directory that is not the same as the usual images directory We might even have relevant subdirecto ries within the png directory CONSIDER THE m vs s suffix also the merit of having the PNG images served up as BLOBS 9 2 2 Actual assessments The actual user assessment is as above but note that a block of ten anaesthetics will be randomised and this order will be preserved There are several other wrinkles 9 WORKING PHP CODE 152 e If the assessment is halted and the user exits on return the current state will be retrieved This suggests that we should make some indication of points of assessment and even permit the user to mouseover these with a popup or overlay of details e For the same anaesthetic we will not allow the manual view to follow the automatic immediately or vice versa Otherwise any order is permissible e At the end the assessing anaesthetist is asked whether they thought this was a manual or an automated anaesthetic record We must consider in some detail the implications of multiple
139. ge php Assess an anaesthetic oo eRe eke d 9 2 1 Demonstration page 257 dion assessed o co rre EMBED d q o o lt socs eo ee ROH esc eH Oe REG ROS Editing log on details 24694624 eed ee bed ee es a Editing someone s details css esae REX x eee HS Editing log on details isis Back p aaa as DAA A RS 10 Ancillary code 10 1 10 2 10 3 10 4 10 5 10 6 10 7 General purpose functions 10 1 1 A header function oa er xb da pub 10 1 5 Sanili36 ou a xd Redon a ES a iss 10 1 4 WhatYearlsIt Handling StS TO a e a e ok s q 1102 PHOBPODBSU 2522 rr 10 2 2 TextPoplistSeleeied oue oo vege baw S KREG KES 10 2 3 PrintActiveUserlist Tables arrays and sorting oos 9 ala x eS 10 3 1 MyDoubleSort ss s ss s ros s ly oy sd RR 10 3 2 ConcatenateAray gan Sow Ge Soa SE aee go 10 3 3 Flaten a thew doe d oe 446 dua ee a 1034 PrintDetailTable uus os RR User information 6 l o m ee 10 4 1 PullOutUserInfo 10 4 2 GetLinkedUserDetails 10 4 3 FetchSurname 1044 FetchForename 64 4446 204 so 64 X 3 CSV processing Lo NS oS ES Ab d ek SEES SQL related functions 22 Ke EE Re RG a RA 10 6 9 GEISOL a o 77 7 1002 DO ULU luum um RR bes ESO RR
140. gfile 2 EZ CAPTURE MANUAL DATA CAPTURE Here are the subsidiary routines sub GetLocalTime my sec min hour Smday mon year Swday yday isdst sec min hour Smday mon year Swday yday isdst CORE localtime time year 1900 fix y2k Ssec amp DoubleDigit sec Smin amp DoubleDigit min Shour amp DoubleDigit Shour Smday amp DoubleDigit mday Smon amp DoubleDigit mon Smon january is zero return year mon mday hour min sec sub DoubleDigit my i i if length i gt 1 return i y return 0 i concatenate 36 2 EZ CAPTURE MANUAL DATA CAPTURE 2 4 A comprehensive GUI 37 We here describe an AutoIt GUI that allows the user to perform all the necessary capture and format translation both from SAFERsleep automated records and from manual caliper data Here s the initialisation code include lt GUIConstants au3 gt include lt WindowsConstants au3 gt Suserdll DllOpen user32 dll for frequent use of dll FAKEDCMS suppresses activation of DCMS gives time to open Excel and paste data into Excel nasty SFAKEDCMS 0 use numeric seconds for ll Excel pause for Excel pause SFAKEDCMS 30 if use numeric seconds Lu useful constants Const SONTOP 0x40000 Co
141. gg b c d a xliz len 16 Poy 7680876936 2 389564586 7 606105819 22 1044525330 7 176418897 2 1200080426 7 1473231341 22 45705983 7 1770035416 2 1958414417 7 42063 22 1990404162 125 1804603682 2 40341101 7 1502002290 225 1236535329 Bou 1657965100 9 1069501632 14 643717713 20 5313897302 900150983cd24fb0d6963 7d28e17 72 and a bit length PHP ACCESS CODING a mads ogla b d x d md5_gg d a b c x md5_gg c d a b x b md5_gg b dy a x a md5_gg a c d x md5_gg d a b C x md5_gg c d a b x b md5_gg b c d a x a md5_ggla c d x d md5_gg d a b c x md5_gg c d a b x b md5_gg b d a x a md5 hh a b c d x d md5_hh d a b c x md5 hh c d a b x b md5 hh b c d a x a md5 hh a b c d x d md5_hh d a b c x c md5 hh c d a b x b md5 hh b c d a x a md5 hh a b c d x d md5_hh d a b c x c md5 hh c d a b x b md5 hh b c d a x a md5 hh a b c d x d md5_hh d a b c x md5 hh c d a b x b md5 hh b c d a x a md5_ii a b c d x d md5_ii d a b c x md5_ii c d a b x b md5_ii b d a x a md5_ii a c d x d md5_ii d a b c x md5_ii c d a b x b md5_ii b d a x a md5 ii a b c d x d md5_
142. ght work along the following lines 1 Connect the Digital Calipers to the USB interface module and insert the USB interface module into the USB port of the PC running Windows 2 Press the on button on the Calipers 3 Run the driving software DETAILS ensuring that the COM port etc are correctly set up 4 Capture data acquired using the calipers 5 Save the record to Excel don t try other methods as this may crash the PC 6 Save the Excel spreadsheet as a CSV file with a unique sequential number 7 Invoke a Perl script to a Convert all digital caliper recorded values to mmHg rates b Request input for SpO2 and EtCO2 c Write a unified time based record of all data as a CSV file 8 Repeat record capture as required 9 Exit turn off calipers shut down PC and remove USB interface module and calipers We have partially automated the above process This automation involves ac quiring and saving basic information about the record before initiating capture capturing separate caliper data for the systolic blood pressure diastolic blood pressure and heart rate and entering SpO and ETCO data from the keyboard 2We used XP and cannot guarantee that this will work under Vista 2 EZ CAPTURE MANUAL DATA CAPTURE 9 prior to invoking a Perl script to integrate the raw data into a final CSV file Au tomation is achieved using the Windows program Autolt for which we ve written scripts described in S
143. gt Debug user status is SUSERSTATUS SOLD 4 might try eg Welcome hmm if Sprevious if strlen SOLDPAG SOLD previously at lt a href OLDPAGE gt SOLDPAGE lt a gt Lu gt 3 y Stxt 0 lt p gt lt div align center gt lt table width 95 gt lt tr gt lt td width 150 align center gt lt a href GPL htm gt lt img border 0 title Click here alt eZ logo src images tinyezlogo png gt lt a gt lt td gt lt td width 4 gt lt img alt vidthe 4 height 64 src images vbar png gt lt td gt lt td gt lt h2 gt title lt h2 gt lt span class info User USER SOLD lt span gt lt td gt lt tr gt lt table gt lt hr gt lt div gt 10 ANCILLARY CODE 190 Stxt 1 SUSERSTATUS return Stxt 10 1 2 CheckCode Check that item is numeric function CheckCode amp code msg if preg match s d s S code vals print lt br gt Bad data item amp lt S code amp gt lt p gt msg readfile badcode htm exit Scode vals 1 trim whitespace just in case y Similar to CheckCode is CheckCodeNull which however doesn t exit merely returning NULL if the match fails function CheckCodeNull amp S code if 1 preg match Ns Nd Ns S code vals code NULL 1 Scode vals 1 trim whitespace 10 1 3 Sanitise Clean up
144. h amp 6 year amp _ amp DoubleDigit gh amp amp DoubleDigit gmi amp _ amp DoubleDigit gs EndFunc 7 trivial function to turn 1 digit into two Func DoubleDigit d If StringLen d lt 2 Then Sd O amp d EndIf Return d EndFunc 2 5 1 DOS invocation of ez GUI We simply type in run from within the ez directory echo off cls Vezlez capturlez gui au3 Invoking the anaesthetic viewer We do so using a DOS batch file xlat bat stored in the ez ez xlate directory echo off cls AnaestheticViewer 1 This assumes that the AnaestheticViewer exe is in the DOS path see invoca tion 2 EZ CAPTURE MANUAL DATA CAPTURE 67 2 6 Perl keyboard input A simple Perl program to acquire either ETCO2 or SpO2 values from the console and write them to a file in the format S0001 spo2 in the ez rawdata directory We submit command line parameters the first being the serial number the second the type of datum spo2 or etco2 and the third the duration of the anaesthetic in minutes An optional fourth parameter consists of command line controls The program is called ez keyboard pl The exit code reflects success zero or failure nonzero usr loca l bin perl w my SDEBUG 3 0 to turn off debugging 1 overviev 2 detail 3 nitpicking my SLOGPRINT 1 print to log my SWARNINGS 0 see u
145. have occurred and we can proceed so there is no need to test for success Note that the casts and multiple accesses in the above will tend to slow things a fair bit so if we really require vast numbers of keys generated quickly this solution is probably unwise 10 ANCILLARY CODE 206 10 7 4 Working code Let s flesh out the above ideas First we will generate a number which reflects a timestamp without being a full timestamp We will use the microtime timer to obtain a microseconds stamp which we modify as follows function ModTimeNow list usec sec explode microtime Ssec 1000000 4 modulo 1 million seconds Sstamp int 1000 float usec float sec return stamp Let s assume that we want a granularity of 1 millisecond in our counting We wish to time out if a key locks for more than say a few seconds say 2 seconds We ll use a large safety factor so that even if a process fails in the middle of key retrieval several days must elapse before the process briefly appears not to have failed again The number we store is thus the current UNIX timestamp modulo 1 000 000 seconds We add the microseconds multiply this modified number by 1000 to get millisecond chunks and thus create an integer value between 0 and 1 billion A subsequent program which is locked out calculates the current timestamp modulo million seconds as above If the value has wrappe
146. hich accommodates an md5 encoded password pSID is a session ID and pValue is used to store stuff The most recent page visited by this user We ve also added pMade a timestamp for the creation of a person entry as a bookkeeping entry Here s the PERSONROLE table used below CREATE TABLE PERSONROL personrole integer constraint badPersonRole primary key personrole rText varchar 32 Lu INSERT INTO PERSONROLE personrole rText VALUES 0 anonymous 2 anaesthetist 192 superuser We add the role of superuser for the database administrator to use and we have a special value of nobody just in case Next we have the ETHNICITY table CREATE TABLE ETHNICITY ethnicity integer constraint badEthnicity primary key ethnicity EthnicName varchar 32 INSERT INTO E VALUES HNICITY ethnicity EthnicName 2 aori NZ European Asian Pacific Islander z Other j O15 9 bb H 101 might be argued that a separate table is needed relating an individual and multiple ethnic origins but we won t go into this level of detail 7 DATABASE DEFINITION 120 7 2 PERSDATA CREATE TABLE PERSDATA persdata integer constraint badPersdata primary key persdata pdCreated timestamp Person integer constraint badpdPerson foreign key
147. hp our login validation script if invoked by InitialLogon php then IT defined success and set SLOGGED_IN otherwise if SLOGGED_IN success validate login SHOW USER returns SUSERKEY ShandDB for our use if Ssuccess exit im SMINUSERSTATUS NOBODY SMAXUSERSTATUS EVERYONE THISPAGE mainpage php list SMYHEADER SUSERSTATUS eZHeaderGreet success SMINUSERSTATUS MAXUSERSTATUS Assess amp nbsp Anaesthetics amp nbsp Online 1 I print HTML1 lt DOCTYPE HTML PUBLIC W3C DTD HTML 4 01 Transitional 1 html lang en head 149 9 WORKING PHP CODE 150 lt title gt eZ Main Page lt title gt lt LINK href css eZstyle css type text css rel stylesh lt head gt lt body gt s table vidthe 1005 height 98 lt tr gt lt td classe middling align center OUTER TBL still no good CSS equivalent gt lt table class heavybox gt lt tr gt lt td gt TBL gt lt middle SMYHEADER HTML1 if SUSERSTATUS lt eZ_ASSESSOR_MAX print lt p gt lt a href eZ assess php Assess another anaesthetic lt a gt else print lt lt lt HTML2b lt p gt Please choose one of the following options EMONSTRATION lt t lt table width 806 5c1
148. hp Return to main page lt a gt body html HTML3 Edit details User Superuser Return to main page Alter details for Johan van Schalkwyk Login name is johanvs By default all values are left at their current settings a Alter surname van Schalkwyk b Alter forename onn c Change role superuser d Change location Mainly pubic only for nurse registrar e Change specialty 4 registrar only e Year of qualification 1994 Gol Back to list of people Return to main page Figure 9 Editing a person s details eZ_do_edit php The following PHP script is deceptively short because it uses GET and then sim ply invokes a much more complex script header Cache control no cache require_once ValidFx php our login validation script success validate login SHOW USER here GET user ID SOTHERLOGONID GET editperson CheckCode OTHERLOGONID Bad log on ID 4 or fail require subedit php subedit php Here s the much more complicated subedit php The reason for the above shenani gans is to allow us to POST data from within eZ do edit php to the POST version which can then invoke itself Why not simply use POST always It s easier in some circumstances to submit the user ID using GET 9 WORKING PHP CODE 173 SMINUSERSTATUS eZ ADMINISTRATOR MIN SMAXUSERSTATUS EVERYONE list SMYHEADER SUSERSTATUS eZHeaderGreet suc
149. i gt Role lt i gt lt td gt lt td gt lt i gt Started lt i gt lt td gt lt td gt lt i gt Click here lt i gt lt td gt lt tr gt HTMLpau Sactiveusers array Sqry SELECT distinct Person FROM PERSDATA WHERE PersonRole gt 0 Sactiveusers SQLManySQL handDB qry get active users Sactiveusers Flatten activeusers Susers GetLinkedUserDetails handDB activeusers link MyDoubleSort Susers 1 0 fsort by surname then forename PrintDetailTable users 5 f print table vith 5 columns 10 ANCILLARY CODE 193 10 3 Tables arrays and sorting 10 3 1 MyDoubleSort Given 2 D array of rows sort first by the first column then by the second if first column entries ar qual Similar to MySort function MyDoubleSort amp S arry coll col2 GLOBAL CLUMSY INDEX SCLUMSY INDEX coll G OBAL SCLUMSY_INDEX2 CLUMSY INDEX2 col2 usort arry my dblsort function my dblsort first second GLOBAL CLUMSY INDEX GLOBAL SCLUMSY_INDEX2 strcmp first I CLUMSY INDEX second CLUMSY_INDEX i Fh h r if nonzero not the same return Sr im two items are equal so compare sub items return strcmp first SCLUMSY_INDEX2 second CLUMSY_INDEX2 10 3 2 ConcatenateArray Join all array elements into a single string
150. id password username exit y create expiry time and SID Sexpiry time eZ_TIMEOUT SSID Spswd ugh Sqry UPDATE PERSON SET pSID SID pExpiration Sexpiry WHERE person Suk DoSQL ShandDB qry set db SID expirn and store SID in a cookie setcookie eZ SID SSID Sexpiry COOKIE_EXTRA_WAIT Sdqry SELECT pSID FROM PERSON WHERE person Suk list SSID GetSQL handDB dqry debug get sid print lt p gt Debug cookie set to SSID timeout expiry return Suk return user key Force Html InitialLogon All the following does is read an HTML warning file See section 6 1 and enclose the supplied message It would be possible to fancy things up a bit function Force Html InitialLogon msg fancy dressing up might go here print p DEBUG Message is msg readfile oopsl htm 8 PHP ACCESS CODING 140 print msg readfile oops2 htm HTML files oops1 htm and oops2 htm The following files might conveniently be combined into one file with a string to be substituted for the message in the centre Oh well here s oops1 htm lt head gt lt title gt Oops lt title gt lt LINK href css strictstyle css type text css rel stylesheet gt lt head gt lt body gt lt h2 gt Oops lt h2 gt There was
151. if SRULEFILE N txt i invalid rule file SRULEFILE datrules txt H We might later consider submitting the file name as a separate parameter to Perl 4 FORMAT TRANSLATION EZ XLATE 87 my SPARAMS SARGV 2 eg debug 3 logprint 0 if PARAMS debug d command line control SDEBUG 1 y if SPARAMS logprint d SLOGPRINT 1 sOpenLog LOGPRINT EZPATH SLOCALFILE start writing to error debug log my SFILENAME SLOCALFILE csv e g E S0013 m csv here from LOCALPATH load file containing translation rules my datrules LOCALPATH SRULEFILE open DATRULES datrules or amp Die Unable to open datrules my DATRULE close DATRULI FILENAME SLOCALPATH FILENAME S lt DATRULES gt f load all lines open FILE FILENAME or amp Die Unable to open source file lt SFILENAME gt sPrint Debugging file FILENAME 1 my INDATA lt FILE gt close FILE my doutf SOUTPATHSLOCALFILE dat sPrint An Source file lt FILENAME gt n Output path n Local file SLOCALFILE An Output file open DOUTFILE gt doutf or amp Die CRASH Could not open output DAT FILE obtain headers from input file SINDATA 0 get hea
152. ii d a b c x md5 ii c d a b x b md5_ii b d a x a md5 ii a c d x d md5_ii d a b c x c md5_ii c d a b x b md5_ii b d a x a safe add a olda b safe add b oldb c safe add c oldc d safe add d oldd return Array a b c d These functions implement the four basic operations the algorithm uses 7 function md5_cmn q a b X e i 10 1415 i 4 qe 9 1 14 183 IR 1413 i 2 i 7 i 12 i 5 iB i411 1 14 i 1 i 4 i 7 i 10 1413 i 0 i 3 i 6 14 9 i 12 1415 i 2 is 0 i 7 1 14 i 5 i 12 1 i 10 i 1 it 8 1415 i 6 1413 i 4 1411 i 2 1429 SE 5 95 20 5 9 20 5 9 20 Y 6 23 4 6 23 4 o E 23 4 Y 93 Y 23 6 0 5 21 6 0 5 21 6 0 5 21 6 0 5 N 701558691 38016083 660478335 405537848 568446438 1019803690 187363961 1163531501 1444681467 51403784 1735328473 1926607734 378558 2022574463 1839030562 35309556 1530992060 1272893353 155497632 1094730640 681279174 358537222 122521979 76029189 640364487 421815835 530742520 995338651 198630844 1126891415 1416354905 57434055 1700485571 1894986606 1051523 2054922799 1873313359
153. ileClose file Return 0 not found EndFunc 2 EZ CAPTURE MANUAL DATA CAPTURE 2 4 3 Advanced Datum acquisition 54 Similar to our basic schema we here obtain just one data set for one of SBP DBP or HR We initialise data fetch and wait for Excel When invoked after a sufficient wait we save the file in the format X0001 sbp csv where X0001 represents the case number and the suffix is one of sbp dbp or hr We start each set with a zero and Y calibration Note that with the final HR acquisition alone we must perform a terminal zero calibrate and x determination Func GetSequence Sseqname SFILENAME SDATETIME SFAKEDCMS SEZPATH ez SPATHNAME EZPATH amp ravdataN SFILENAME FILENAME amp seqname amp csv 77 e g S0001 sbp csv OpenDCMS FAKEDCMS WinActivate DCMS Data entry here Excel WinWaitActive Microsoft Excel WinActivate Microsoft Excel if target file exists detect and delete it heh SWHOLEFILE SPATHNAME amp FILENAME If FileExists WHOL FileDelete SWHOLEFI EndIf EFILE E If SFAKEDCMS lt gt 0 Then Then MsgBox ONTOP Fake Excel input You have WinActivate Microsoft Excel EndIf Sleep 3000 7 good long wait for import Send f
154. ils for this user Click lt a href eZ do editlogon php editlogon N ARTYI This person first qualified in STARTY EAR SSURNAME SPERSONROLE 3 here lt a gt to do so HTML2X print lt lt lt HTML2E E AR 160 has been added to the database EWID gt lt p gt lt a href eZ_add_person php gt Add lt i gt another lt i gt person lt a gt lt p gt lt a href mainpage php Return to main page lt a gt HTML2E else ARE simi print lt lt lt HTML2B lar cases lt FORM name eZ_assess ACTION eZ_admin_personadded php myself METHOD POST onSubmit return CheckInput this gt lt input type hidden name forename value SFORENAME gt lt input type hidden name surname value SSURNAME gt lt input type hidden name startyear value SSTARTYEAR gt lt input type hidden name gender value SGENDER gt lt input type hidden name personrole value SPERSONROLE gt lt input type hidden name currentspecialty value SCURRENTSPECIALTY gt lt input type hidden name currentlocation value SCURRENTLOCATION gt lt input type hidden name confirmation value 1 gt lt h2 gt Please confirm lt h2 gt The following users have you wish to add that you wish to add t CONFIRM button below exists in the databa
155. incorporate a set of OTPs known only to the administrator and the database and use these for the XOR 9 WORKING PHP CODE 164 lt DOCTYPE HTML PUBLIC W3C DTD HTML 4 01 Transitional EN gt lt html lang en gt lt head gt lt title gt Edit person s details lt title gt LINK href css eZstyle css type text css rel stylesheet gt lt script src js md5 js type text javascript gt lt script gt lt script type text javascript cha function ConfirmClear if confirm Are you sure you want to clear the form Click OK to clear it return true return false function CheckInput myform errorcount 0 errmsg mypwd myform mypswd value ulogon myform userlogon value pwdl myform newpasswordl value pwd2 myform newpassword2 value if NastyString mypwd errmsg errmsg You password does NOT contain characters errorcount if NastyString pwdl errmsg errmsg Password CANNOT contain characters errorcount y if ulogon length 4 errmsg errmsg Please supply user name 4 characters or more errorcount y if mypwd length lt 6 errmsg errmsg Your password IS 6 or more characters long errorcount y if pwdl length lt 6 errmsg errmsg New user password minimum length must be 6 characters errorcount y if pwd2 length lt
156. ine 4 FORMAT TRANSLATION EZ XLATE 84 echo off cls rem Translate XML to CSV perl ez xlateVez xml2csv pl 1 ECHO Error level ECHO SERRORLEVELS It should be placed in the ez directory The sole argument is to the source XML file An example is in this test file test x2c bat echo off cls echo Translate XML to CSV test only perl ez xlatelez xml2csv pl test xml debug 2 logprint 0 ECHO Error level ECHO SERRORLEVELS oo 4 FORMAT TRANSLATION EZ XLATE 85 4 2 Translate from CSV to DAT Given CSV files we next need to translate the columns of CSV data into a for mat recognised by SAFERsleep We write a custom Perl program to make this translation from CSV to a SAFERsleep DAT file Note that the first line of the CSV file to be converted must contain timestamps in the format 2008 03 31T10 09 42 There s another potential catch if a mean pressure is absent it s tempting to calculate this here We do not do so The NBP m value must have been worked out and inserted into the source CSV file There are four major wrinkles here 1 We wish to be selective in the columns we export from the CSV file 2 Pressures are compound in the IDAS DAT file so we need to amalgamate three columns to create a DAT pressure column 3 In their manual records most anaesthetists do not differentiate between intra arterial blood pressures and
157. is substituted with a real value 2 Scanning it for NA if this is present we return a null string 3 Replacing all pipes with double quotes in the string q sub ExtractDAT my r 8D Sr D _ my q 4 FORMAT TRANSLATION EZ XLATE 92 sPrint An Debug applying lt r gt to D 3 eval Sr valuate string put result in q if 580 if failed amp Print n Warning Missing variable or other eval failure G SWARNINGS SEXITCODE 0x08 warning code eval failure return HMM vhat if SD x doesn t exist if q NA return y Sq s g replace all pipes with quotes return q A clumsy truncation routine coercing all numbers to floats with six digits sub TruncArray brutal my D D _ my 8 my i 0 my Sf Str amp Print n Trunc 3 foreach f D Str amp Trunc f Print Sf S tr 3 SX i Str Si bump index y return X sub Trunc my f Sf if f dt d 6 if 6 digits or more Sf SEPSILON prevent massive truncation error if f dt d 6 in case return 1 y if f d Nd 4 FORMAT TRANSLATION EZ XLATE 93 my pre 1 my post 2 while length Spost lt 6 Spost 0 return
158. k RunWait GComSpec amp c perl amp SEZPATH amp ez xlatelez csv2dat pl s FILENAME s amp datrules txt SEZPATH If perlok 0 Then MsgBox SONTOP Note Conversion was successful TestFile sSS EZPATH amp dat FILENAME s dat se MsgBox ONTOP Problem See log Return code was perlok EndIf Case msg 5595 If AddToSSList EZPATH FILENAME s SDURATION gt 0 Then if success SISLISTED BitOR SISLISTED 2 bit 1 set ss file StoreParam SEZPATH SFILENAME EZ ISLISTED SISLISTED Store listed sgBox ONTOP Success Added to play list 6 FILENAME 6 s DAT If SISLISTED 3 Then 7 if both flags set myEnable REPL EndIf or make this a rtn Else SgBox SONTOP Oops Failed to add amp SFILENAME s to playlist EndIf Case msg SREPL Sdoit MsgBox SONTOP 1 Confirm Do you want to replay the files If Sdoit 1 Then OK button pressed 2 cancel GuiSetState SW_MINIMIZE Sperlok RunWait ComSpec amp c amp _ SEZPATH 6 ez replay ez replay au3 SEZPATH E GuiSetState SW_RESTORE Else MsgBox SONTOP Cancelled Nothing done EndIf uu sas IMAGE CLICKS Case msg imCSV LogNotepad EZPATH FILE
159. kbox 1 Shskip 3 pitch Dim xSpO2 GUICtrlCreateCheckbox 1 Shskip 4 pitch Dim xETCO2 GUICtrlCreateCheckbox 1 Shskip 5 pitch Dim vSBP GUICtrlCreateCheckbox 2 7 Shskip 1 pitch Dim vDBP GUICtrlCreateCheckbox 2 7 Shskip 2 pitch Dim SvHR GUICtrlCreateCheckbox 2 7 Shskip 3 pitch Dim vSpO2 GUICtrlCreateCheckbox 2 7 Shskip 4 pitch Dim vETCO2 2 GUICtrlCreateCheckbox 2 7 Shskip 5 pitch and set the Valid flags SetGoodItems SGOODITEMS SvSBP vDBP vHR S vSpO2 SvETCO2 graphics arrow from parse valid to CSV2DAT GUICtrlCreatePic ez images arrow gif 3 3 Shskip 3 pitch 80 40 arrow from get from SS to IAR2XML GUICtrlCreatePic ez images arrow gif 1 2 Shskip 7 Spitch 80 40 down arrow from add to replay GUICtrlCreatePic ez images arrowdn gif 6 Shskip 3 pitch 90 110 up arrow from add to replay GUICtrlCreatePic ez images arrowup gif 6 Shskip 5 8 Spitch 90 110 gin Dim vwXML GUICtrlCreatePic ez images seexml gif 2 Shskip 7 8 pitch 60 CSV Dim vwCSV GUICtrlCreatePic ez images seecsv gif 1 62 hskip 3 8 Spitch Dim vwCSV2 GUICtrlCreatePic ez images seecsv gif 3 Shskip 7 8 Spitch 60 dat Dim vwDAT GUICtrlCreatePic ez images seedat gif 4 Shskip 3 8 pitch 60 Dim vwDAT2 GUICtrlCreatePic ez images seedat gif 4 Shskip 7 8 Spitch 60 sslist txt Dim
160. l call it RATING CREATE TABLE RATING rating integer constraint BadRating primary key rating Onesession integer constraint badRatingSession foreign key Onesession references ONESESSION raText varchar 255 raSBP integer raDBP integer raHR integer raSPO2 integer raETCO2 integer raTime integer The five references to measured parameters are set to 1 only if these were documented as having influenced the anaesthetist s decision to intervene The raText field contains the description of the decision to intervene The raTime field contains the frame at which this particular intervention occurred the count starts at 1 for the first frame 7 6 Frills The SALT table is used for logging on using md5 encoded passwords CREATE TABLE SALT salt integer constraint badSaltkey primary key salt sTime integer sValue integer The sTime is a UNIX integer time 32 bits used to see whether a particular salt value has expired and the sValue entry is a pseudorandom number We won t here initialise the hundred entries in the SALT table reserving that for the first time we try to check a password We also create a transaction log which details user their IP address a times tamp for the transaction a code for what was done and an optional description field Here we go 7 DATABASE DEFINITION 123 CREATE TABLE FORENSIC forensic integer constr
161. le The next fetch will retrieve this incremented value and so on Here s a variant of DoSQL which returns 1 on success O on failure without an error message function TryDoSQL ShandDB qry Smessage return mysql_query Sqry handDB 11 HARDWARE SOFTWARE USEFUL FILES amp CHANGE LOG 209 11 Hardware software useful files amp Change Log Hardware Describe Notes on languages and programs At present SAFERsleep runs under Microsoft Windows and therefore all of our code has been developed in this environment The code might however be mod ified for similar purposes on dissimilar operating systems Autolt is a scripting language designed to compensate for the inadequacies of Windows but Perl is cross platform We assume that the user can interact in a basic fashion with the DOS console under Windows The code runs well under Windows 2000 and Win dows XP This code has not been tested under Windows Vista and it is likely owing to the somewhat paranoid behaviour of this incarnation of Windows that problems will be encountered with this platform At present all files used in this suite of programs can be generated from a single source the file ez XXX tex where XXX is the version number e g 035 for version 0 35 The documentation this document is generated from the same source using IFEX To generate the various files use our application Dogwagger version 2 1 or greater In summary our code requi
162. le row mysql fetch array handQ MYSQL NUM mykey Srow 0 Smyvalue ConcatenateArray array_slice Srow 1 concatenate remaining elements print lt option value mykey gt Smyvalue lt option gt n Scount 1 y print select return count 10 2 2 TextPoplistSelected This function is similar to PrintPoplist It accepts the key of the selected item which is then flagged as selected function TextPoplistSelected handDB listname query k Sopt 10 ANCILLARY CODE 192 s if k lt 1 s selected im Sopt opt sprintf lt select name S listname gt lt option s value 0 gt lt option gt n ShandQ mysql_query query ShandDB Scount 0 while row mysql fetch array handQ MYSQL NUM mykey Srow 0 Smyvalue ConcatenateArray array_slice Srow 1 concatenate remaining elements 5 if k mykey s selected y Sopt Sopt sprintf lt option s value d gt s lt option gt n mykey myvalue Scount 1 y Sopt Sopt sprintf lt select gt return Sopt 10 2 3 PrintActiveUserlist function PrintActiveUserlist handDB link print lt lt lt HTMLpau lt p gt lt div align center lt table width 90 border 2 lt tr gt lt td gt lt i gt Forename lt i gt lt td gt lt td gt lt i gt Surname lt i gt lt td gt lt td gt lt
163. le The format of the 2 EZ CAPTURE MANUAL DATA CAPTURE 18 output file is shown in Table 2 In order to output numeric values and what about precision we need to make the appropriate conversions using the calibration values Time NBP s NBP d HR SpO2 ETCO2 NBP m rawSBP rawDBP rawHR 2008 12 14T10 23 00 120 70 72 99 NA 88 a b c 2008 12 14T10 28 00 123 66 72 NA 33 86 a b c Table 2 Output table format also CSV Note that in Table 2 we have renamed the systolic blood pressure NBP s and so forth This is for subsequent compatibility see code below routine WriteAllData caly GetYCalValue YCALS for each value and time in ALLDATA WarnAndExcludeDuplicates value rsbp rdbp rhr spoz etcoz ExtractData value sbp rsbp caly dbp rdbo caly hr rhr caly WriteCsvDatum time sbp dbp hr spo2 etco2 rsbp end for end routine WriteAllData rdbp rhr 2 EZ CAPTURE MANUAL DATA CAPTURE 19 2 3 Perl code raw data to CSV This code is somewhat more complex than the simple schema just outlined In Perl it s probably wise to declare globals in the main routine so we don t have a separate Initialisation section 2 3 1 Main routine We start with the usual Perl shebang and a whole lot of nasty global variables not calculated to win friends Note that we do NOT at present create or check for the existence of the log rawdata a
164. leExists NHOLEPATH 6 FILENAME amp SSUFFIX Then myEnable btn EndIf EndFunc Store a parameter to the INF file Func StoreParam EZPATH FILENAME Sparmno value Sfnam EZPATH 6 ez info FILENAME amp inf If Not FileExists fnam Then MsgBox ONTOP Error INF File doesn t exist fnam return EndIf SARR Slurp fnam SARR Sparmno value Vomit fnam SARR 5 REWRITE EndFunc 2 4 1 Invoke Notepad Here we look for all relevant log files and work through them until we get the last file which we display by opening up NotePad We minimise the GUI until the log file closes Func LogNotepad SEZPATH SFILENAME SSUFFIX Sfnam SEZPATH amp log s SFILENAME 6 SUFFIX 6 LOG Sh FileFindFirstFile fnam If h 1 Then MsgBox ONTOP Oops LOG File not found 6 fnam Return EndIf Stot 0 DIM FA tot 1 77 just playing for now later select from list file While 1 Slastfile file file FileFindNextFile h If error Then ExitLoop SFA Stot file Stot Stot 1 ReDim FA tot 1 WEnd FileClose h 2 EZ CAPTURE MANUAL DATA CAPTURE run notepad GuiSetState SW_MINIMIZE Run Notepad exe Sleep 1000 WinWaitClose SFILENAME amp SUFFIX GuiSet
165. lename e g S0012 WITHOUT suffix my SPARAMS SARGV 1 eg debug 3 logprint 0 if PARAMS debug d command line control SDEBUG 1 if SPARAMS logprint d SLOGPRINT 1 y 4 FORMAT TRANSLATION EZ XLATE 80 sOpenLog L if SLOCALF OGPRINT LOCALFI E start writing to error debug log ILE 1 S d 4 i amp Die y Bad file name my FILENAME E SLOCALFILI my SLINECOU SFILENA E NT 0 OCALFILE gt xml e g S0012 xml SLOCALPATH SFI open FILE ENAME SFILENAME or amp Die Unable to open file lt SFILENAME gt amp Print De my INDATA close FILE my Scoutf Print Mn open COUTF CRAS bugging file SFI lt FILE gt ENAME 1 SOUTPATHSLOCALFILE s csv note s suffix for sAFERsleepl Source file F ILE 2Scou tf o H Could not open ILENAME gt n Output path lt SOUTPATH gt An Local file 51 r amp Die output CSV FILE coutf n now establish associative array of times my TIMECO my SALLTIM my 3 my SLABELS oe Ur oe foreach j UNT 0 ES 0 0 and ar INDATA SLINECO if j my my my if my T if 51 amp P 1
166. licking next Simply hides thanks moves function DoNext if THISIMAGE document getElementByld elapsedLabel style visibility visible Arton IntOn HideThanks ShowNext Image SpeedTime advance clock quickly BrieflyDisableNext 6 EZ SHW AN INTERACTIVE WEB BASED APPLICATION 110 function Nextoff clearTimeout AAGH in case next re enabling is pending document getElementBylId nextbutton disabled true function NextOn document getElementById nextbutton disabled false function Intoff document getElementById intbutton disabled true function IntOn document getElementById intbutton disabled false function Artoff document getElementById artbutton disabled true function ArtOn document getElementById artbutton disabled false function BrieflyDisableNext NextOff AAGH setTimeout ReEnableNext ONESECOND function ReEnableNext ClearMinTimer in order to set it in a moment NextOn SetMinTimer ONEMINUTE ONESECOND ShowNextImage simply display next image after incrementing count function ShouvNextlmage THISIMAGE if THISIMAGE TOTALIMAGI ClearMinTimer ArtOff IntOff disable alert Replay completed Thank you Fl ca 6 EZ SHW A
167. login validation script Ssuccess validate login SHOW USER gt SUSERKEY handDB SMINUSERSTATUS NOBODY SMAXUSERSTATUS EVERYONE list SMYHEADER SUSERSTATUS eZHeaderGreet success SMINUSERSTATUS SMAXUSERSTATUS Logging out 0 now SUSERKEY ShandDB set so clean up DB log out setcookie eZ SID time 100 clear cookie qry UPDATE PERSON SET pSID NULL pExpiration 0 WHERE person SUSERKEY handleQ mysql_query S qry handDB if ShandleQ hmm debugging only print lt br gt Logout error user key was amp 1t SUSERKEY gt mysql_error im mysql close handDB print lt lt lt HTML1 lt DOCTYPE HTML PUBLIC W3C DTD HTML 4 01 Transitional EN gt lt html lang en gt lt head gt lt title gt Log out from eZ lt title gt LINK href css eZstyle css type text css rel stylesheet gt lt head gt SMYHEADER lt p gt Logged out Thanks for using eZ lt p gt lt a href login php gt Click here lt a gt to log in again HTML1 9 WORKING PHP CODE eZ Z Assess Anaesthetics Online User johanvs Please choose one of the following options 1 Add a person DEMONSTRATION 2 Edit a person 3 Edit log on 4 View delete data 5 Back up and restore data Log out Documentation Figure 4 The main page 9 Working PHP code 9 1 The main page mainpage php header Cache control no cache require once ValidFx p
168. lows MainInterface make a comprehensive GUI Func MainInterface userdll FILENAME SDATETIME _ SGOODITEMS SISLISTED DURATION Shskip 115 Spitch 60 Sh 40 Sw 70 Sbigw 100 Slabw 200 Sx 30 EZPATH ez Ur 7 the following are flags that allow enabling of various buttons SFIVEITEMS bits set data ARE in contrast with SmISCSV SmISDAT SmISSS is manual name in SAFERsleep submission list 0 0 2 EZ CAPTURE MANUAL DATA CAPTURE 39 SsISIAR 0 does IAR exist SsISXML 0 SsISCSV 0 SsISDAT 0 SsISSS 0 is automatic name in SS submission list make the GUI Dim Smygui GuiCreate EZ Data Manipulation Case No amp FILENAME amp amp SDATETIME 800 600 30 10 SWS_CAPTION SWS_EX_TOPMOST FONT Sfont Comic Sans MS GUISetFont 8 400 1 font Size 8 font labels GuiCtrlCreateLabel MANUAL RECORD Acquire using calipers keyboard 10 12 2 Slabw Sh GuiCtrlCreateLabel SAFERSLEEP RECORD Obtain from database 10 6 3 pitch 2 Slabw Sh GuiCtrlCreateLabel Valid 2 6 Shskip 0 7 Spitch labw h buttons Dim SbSBP GuiCtrlCreateButton SBP Sx 1 Spitch Sw Sh Dim SbDBP GuiCtrlCreateButton DBP 2 5pitch
169. makedirectories bat to create this structure if not already made echo off cls m Q 33333333333 a Q ez ez ez captur ez captur images ez xlate ez s ez s ez s ez s ez s ez s ez s ez s hw hwNhtml hw html css hw html images hw php hw php images hw php js hw php css 25Note that DogWagger is a Perl program written for Perl version 5 6 It uses the Perl Tk interface For mysterious reasons Tk has been excised not only from more recent versions of ActivePerl eg 5 8 and 5 10 but even from current version 5 6 even though previously available versions included Tk This is frustrating and irritating You will either need to run a more recent version of Perl installing Tk and perhaps modifying the code slightly or use an older version Drop me a line 11 HARDWARE SOFTWARE USEFUL FILES amp CHANGE LOG 211 md ez shwYsql md ez replay md ez replay capture md rawdata md iar md xml md csv md log md dat md images md ez info A help file Here s help bat that simply reminds the user of what we can do from the com mand line echo off cls cho echo HELP WITH EZ cho echo captur capture from calipers process echo iar2xml list is in lezlez xlateliarlist txt echo xml2csv test xml xml to csv echo csv2dat test csv csv to IDAS format echo replay replay list via IDAS cho echo test x2c demo xml to csv echo t
170. mit NAME submit VALUE CONFIRM Add this person gt lt td gt lt tr gt lt table gt lt div gt HTML2C function InsertPerson myODBC FORENAME SSURNAM y Li SSTARTYEAR Sgender role SCURRENTSPECIALTY SCURRENTLOCATION if strlen STARTYEAR lt 4 bad data default to 1900 ugh SSTARTYEAR 1900 y Snow date Y m d h i s SNEWID FetchKey myODBC Person f nev key for PERSON Sqry INSERT INTO PERSON person pMade FirstQualified m VALUES SNEWID TIMESTAMP now DATE SSTARTYEAR 01 01 DoSQL myODBC Sqry insert new person SiPERSDATA FetchKey myODBC Persdata Sqry INSERT INTO PERSDATA persdata Person PersonRole CurrentSpecialty CurrentLocation pdCreated pdSurname pdForename pdGender VALUES SiPERSDATA SNEWID role CURRENTSPECIALTY CURRENTLOCATION TIMESTAMP Snow SSURNAME SFORENAME gender DoSQL myODBC qry insert person data 9 WORKING PHP CODE return SNEWID hmm function GetUserDetails handDB similarnames Ssimilarnames is array of IDs key of PERSON table this fx is cumbersome and slow surname role date of 1st qualifn as year 01 01 Sopt array i foreach similarnames as Sp
171. my TODAY amp GetLocalTime my Slogfile ez log RANFILENAME DATTYPE TODAY LOG open LOGFILE gt Slogfile or die CRASH Could not open LOG logfile print n Writing to log file logfile sub CloseLog my islog Sislog if Sislog close LOGFIL im QL Gl Here are the subsidiary routines sub GetLocalTime my sec min hour Smday mon year Swday yday isdst Ssec min hour mday mon year Swday yday isdst CORE localtime time year 1900 fix y2k Ssec amp DoubleDigit sec Smin amp DoubleDigit min Shour amp DoubleDigit Shour Smday amp DoubleDigit mday Smon amp DoubleDigit mon Smon january is zero return year mon mday hour min sec sub DoubleDigit 68 SiWn 2 EZ CAPTURE MANUAL DATA CAPTURE Si i if length i gt 1 return i return 0 i concatenate my sub Print my Sp level level is debugging level O none l overview 2 detail 3 picky Sp level _ if SDEBUG gt level f if level is 0 always print if SLOGPRINT print LOGFILE p return print p console print sub Die my Se Se _ my 1 SLINECOUNT 1 Print n n DIED Data line 1 N Index was SIDX n Message Se 0 SEXITCODE 128 f
172. n within ez gui au3 check that these match and pass duration as a parameter to ez captur pl b In ez captur pl accept duration as a parameter and check this against the measured duration failing 1f the two don t match The only role of the time passed to this program is in calculation validation of alpha c Similarly pass duration to the keyboard capture routine ez keyboard pl Also added a Operation name and b Brief description of the patient Added ability to view CSV XML DAT files from GUI QUIT button added to entry screen for GUI Confirm OVERWRITE if file exists for raw data Also back up prior file WEB PHP CREATION TO UPDATE Still to Do Make GPL htm page Still need to move PNG related code to server and upgrade it Still must write menu for viewing all anaesthetists input We need sensible values for EtCO2 i e if in kPa translate to mmHg 760 000 mmHg 101 325 kPa For first timer and subsequently permit alteration of details Rejig HTML to permit capture of times etc and restart using cookies Note that in the HTML we must hide whether images originate from m or s Randomly alter names to a and b FIX UP demo test batch files with the new formats etc Perhaps later provide ability to view raw source csv files 12 STILL TO DO 215 11 We should fix up minor warnings in ez captur pl related to data counts etc These have been temporarily suppre
173. nd csv sub directories Creation MUST be done manually We also assume that the working directory is not the directory in which this program ez captur pl is located but the main ez directory containing the destination csv sub directory usr local bin perl w use POSIX qv floor for date calculations my SDEBUG 2 0 to turn off debugging 1 overviev 2 detail 3 nitpicking my STORECOUNT 1 also used for debugging my SLOGPRINT 1 print to log my SWARNINGS 0 see usage my SEZDIR ez my SEXITCODE 0 code on exiting Perl exit code reports defects 0 ok 1 sbp 2 dbp 4 hr 8 spo2 my SBASELINE 20 20mmHg or bpm my VARIABLES sbp dbp hr spo2 etco2 note the order my SIDX 0 my SMAXIDX 3 my STIME 0 my SLINECOUNT 1 f will skip first line my SSERIESCOUNT 1 doubled for each new series my SRAWFILENAME SARGV 0 source filename from command line NO suffix NO path my STIMESTAMP SARGV 1 timestamp DD MM YYYY HH MM my TRUEDURATN ARGVI21 ADDED in v 0 37 my SPARAMS SARGV 3 eg debug 3 logprint 0 This is clumsy and a bit nasty Consider submitting the path to the destination directory as an extra command line parameter to the Perl program 16 etco2 2 EZ CAPTURE MANUAL DATA CAPTURE
174. nd quick The person doing the measuring can simply measure offsets from baseline where they encounter a measurement between normal time intervals they simply measure the offset and then record the measurement as usual 3 Although what probably happened was the user forgot to signal a low value under 40 and simply measured the record We will issue a warning here 2 EZ CAPTURE MANUAL DATA CAPTURE 13 4 There is a system for recording unusually low values under 40 mmHg or under 40 min This is robust in the sense that simply measuring this value will signal an error unless the value is exceptionally low in the range of alpha where an interpolated value will incorrectly be recorded ultimately resulting in an error in the apparent duration of the record 5 Measurements above the calibration range will be recorded as outside the range rather than extrapolated values 2 2 Algorithm pseudocode We here develop some sketchy pseudocode that interprets data read in as a CSV file Even if you are very adept at Perl you might still wish to glace through this simple pseudocode before you move to the Perl code in the next section as this code is very simply written Each CSV file has an initial header line that can be ignored followed by any number of lines until end of file As this is DOS each line ends in CR LF hex adecimal OD 0A Each line is numbered sequentially followed by a comma and a single numeric value
175. non invasive blood pressures We should accordingly render all pressures as NBP in the DAT file EXPLORE THIS 4 IDAS doesn t respect the timestamp in the DAT file simply taking data for each sample as needed Regardless of other settings in demonstration mode IDAS seems to take a sample as originating every 30 s unless sample timestamps are identical in which case the samples are taken as originating at the same time Display in demonstration mode is every minute so if we wish to skip samples we must a Provide dummy samples every 30 s using a modality that isn t com monly displayed b Provide our actual samples as required Although ironically enough the original XML is close enough to make direct translation from XML to DAT attractive 7A subsidiary problem we must explore is the case where either the diastolic or systolic is missing We will determine the mean according to the usual physiological formula where we add a third of the pulse pressure to the diastolic SFor example ST3 or disable display of the chosen item from within IDAS 4 FORMAT TRANSLATION EZ XLATE 86 We address the need to be selective in our export by having in the CSV source directory a file datrules txt that provides rules for column selection The rules are formatted as follows 6 Conversion rules for CSV to DAT D101 SpO2 Sp02 SD 0 HR HR D 0 ETCO2 ETCO2 SD
176. nserted function ReadBigCsv ShandDB SBIGNAME first check for people with an ID of 1000 or more If so fail Sqry SELECT COUNT person FROM PERSON WHERE person gt 999 list SPERSCOUNT GetSQL handDB qry get new people if SPERSCOUNT gt 0 print lt p gt There are already PERSCOUNT new people in the database so I won t restore anything return 1 qry DELETE FROM UIDS WHERE uids 1 DoSQL ShandDB qry delete UIDS allow new insertion into UIDS Serrcount 0 SCSVFILE csv BIGNAME csv if stat SCSVFILE if not exists print lt br gt File not found CSVFILE return 1 signal 1 error y 9 WORKING PHP CODE SBIGLINES SNEWCSV Sheadarray Scsvname SL if file CSVFILE 0 rro m r 1 4 r SBIGLINES 0 preg_match print return im foreach lt p gt Woops 1 big bad CSV SBIGLINES as L SsDatabaseBackupName eZ 185 get all lines L print lt br gt Debug parsing amp lt S L amp gt if L preg match Tab Scsvname Sfx l print P Table preg match if elsif preg match note the gr Scolcount Sheadarray dy match Sfx 1 explode leName pull out name csvname
177. nst SEZ CASENUMBER 1 Const SEZ_CASEDATE 2 Const EZ CASETIME 3 Const SEZ VALIDFLAGS 4 Const SEZ_ISLISTED 5 Const SEZ_CASEEND 6 Const EZ SURGERY 7 Const EZ DESCRIPTION 8 Const SEZ DURATION 9 Const EZ MAXLINES 9 counts the above constants here request patient ID Smore 1 While more 1 Snad XGetFileAndTimestamp SFILENAME Snad SEZ_CASENUMBER SFILENAME StringUpper SFILENAME SDATETIME Snad SEZ_CASEDATE 6 6 Snad SEZ_CASETIME SVALIDITY nad EZ_VALIDFLAGS ISLISTED nad EZ_ISLISTED SDURATION nad EZ_DURATION Smore Mainlnterface userdll FILENAME SVALIDITY SISLISTED Wend DllClose S userdll 7 tidy up Ext T SDATETIME SDURATION 2 EZ CAPTURE MANUAL DATA CAPTURE 38 EZ Data Manipulation Case No 0012 21 12 2008 21 05 MANUAL RECORD Acquire using calipers keyboard Valid m pp V d H Parse tocSv F CSVtoDAT Add fo SS list spoz F LOG ETco2 M Replay via SS SAFERSLEEP RECORD Obtain from database Get from SS Convert to xa XML to CSV CSV to DAT a uu a i E k Add to SS list a i LOG Lr Figure 2 Ez Graphical user interface A sample screenshot of the main page is shown in Fig 2 and the Autolt code that creates it is as fol
178. nth amp DoubleDigit int day amp DoubleDigit gh amp DoubleDigit gmi amp DoubleDigit int gs i sub DoubleDigit my i i 84 if length i gt 1 return i return 0 i concatenate Here s the rule processing routine A rule is in the format q D 0 1 Spo2 D x I 90 4 FORMAT TRANSLATION EZ XLATE 91 where z is an integer greater than zero Even the following is possible ISD 0 I NBP D 1 D 2 D 3 Given a string along the lines of DI01 SpO2 SpO2 We turn it into a rule by identifying all items in curly braces and replacing each by the relevant D x reference If a column reference isn t found we Die sub PrepareRule my dr COLLOOKUP Sdr COLLOOKUP my Sismore 1 my Spre Sv Spost while ismore if N 42 N 7 pre v post 1 2 3 if exists COLLOOKUP v amp Print Fatal Column v not found 0 amp Die Column v not foudn y Sv COLLOOKUP v Sv is numeric 5 pre SD v 1 post else Sismore 0 1 _ y Sar s N g replace all quotes with pipes my Sr wr Sdr 2 sPrint An Debug prepared rule is lt r gt 3 return Sr And next the template filling routine that uses a rule We handle a rule by 1 Evaluating it so that each D x value
179. ny 1 plusminus value for range alphaAlo 2 15 alphaAhi lt 2 35 alphaBlo 4 43 4 3 alphaBhi 4 63 alphaclo lt alphaths lt 3 31 minlo tiny t 10 minhi lt tiny t710 2 EZ CAPTURE MANUAL DATA CAPTURE case value in CALA gt return c tiny cttiny alphaAlo alphaAhi minle minha value in CALB gt return c tiny e tiny alphaBlo alphaBhi ALO minni value in CALC gt return c tiny cttiny alphaClo alphaBhi minl minni default fail Bad calibration value end routine TestYCal routine TesttCal t c StoretCal it 16 if t 5 or t gt 1000 gt fail Bad time base 4 arbitrary Nos end routine TesttCal Main data processing Here s the main data processing and storing routine routine ProcessDatum t y if y in ZERO gt y2 lt ReadLine if y2 in ZERO gt 0 0 signals datum NA Store t NA return t 5 if y2 in MAXVAL gt 0 MAXVAL end of run recalibrate Recalibrate idx idx 1 if global signal new variable return 0 back to start time if y2 gt MAXVAL gt meaningless fail Bad Y calibration value if y2 lt MINVAL gt special signal to store LOW values Store t y2 default gt fail Bad special datum value if y in ALPHA gt y2 lt ReadLine ALPHAm ALPHAh ALPHA1 2 toff lt ro
180. p our login validation script SMINUSERSTATUS eZ ADMINISTRATOR MIN 9 WORKING PHP CODE SMAXUS Ssuccess E list RSTATUS EVERYONE validate login 154 SHOW USER YHEADER SUSERSTATUS eZHeaderGreet success STHISYEAR WhatYearIsIt SMINUSERSTATUS SMAXUSERSTATUS Add a new person 0 ancillary php INSERTED BELOW E print lt lt lt HTMLO lt DOCTYPE HTML PUBLIC W3C DTD HTML 4 01 Transitional EN gt lt html lang en gt lt head gt lt title gt Administration Enter details of a person lt title gt LINK href css eZstyle css type text css rel stylesheet script type text javascript em The following is clumsy and must be adjusted functio err if if if r if Tr Please Oops if nev fields are added n CheckInput myform orcount 0 ValidForename myform forename 0 errorcount A y ValidSurname myform surname 0 errorcount y myform gender selectedIndex 1 errorcount y myform personrole selectedIndex lt 1 errorcount y myform personrole selectedIndex lt 2 if ValidStartYear myform startyear 0 errorcount y if myform currentlocation selectedIndex 1 errorcount y erro
181. p SUCCESS eZ database created print lt p gt lt a href login php GO THERE lt a gt 7 DATABASE DEFINITION 131 here should commit mysql_query COMMIT ShandDB but mySQL auto commits by default ugh else print lt p gt ERROR Failed to create eZ database else print lt p gt eZ database already exists Duh y mysql close handDB removed keep database open The above should be largely self explanatory If the database_create php script succeeded then A link will be created at the bottom of the page pointing to the script login php We ll consider this next 8 PHP ACCESS CODING 132 8 PHP access coding Web pages described in the HTML Section Section 6 1 above are served up using scripts written in PHP version 5 Data obtained from the HTML pages are written to the SQL database using PHP 8 1 Logging in login php Here s the main log in script which generates a log in page by writing HTML code together with a salt number The user types in their username and password which the page encrypts and then POSTs to InitialLogon php See Section 8 1 1 Note that apart from requiring the script eZ GLOBALS php which we ve al ready defined it contains SCONNECTIONPATH this script also needs ancil lary php which is described later Section 10 In addition because the HTML uses some javascri
182. particular record To make things even more complex some anaesthetists choose to re scale the x axis so we check for this by asking the user to enter start and end times MAXVAL red MINVAL blue alpha and the x and y calibration mea surements are shown in Fig 1 together with the baseline in black from which all y measurements are made In addition this chart shows an initial delay treaa between the point at which x axis measurement started a pre printed vertical line and the first user mark Next look at the end of the anaesthetic Although it ini tially seems that the anaesthetic actually ends after a pre printed vertical line this 2 EZ CAPTURE MANUAL DATA CAPTURE 11 is only if you look at the charting of diastolic blood pressure If anything the systolic mark is before the time line Here we have chosen to use common sense making the interpretation that the anaesthetist signalled a recording on the time line so the tiag can be disregarded However note that even if we had accepted this lag time the x axis calibration value would have extended to the same vertical pre printed line as per our rules above We signal data capture as follows SEE USER MANUAL FOR MORE DE TAIL 1 An initial ZERO must always be present indicating that the Calipers have been zeroed close the calipers so that they read zero or very close to zero e g 0 01 but do not press the ZERO button The initial ZERO is always followed by
183. php This page is clumsy We print data for all SQL tables to a single CSV file hoping that we never have to use these data We constrain our export to rows where the key is gt 1000 Initially we used the mySQL SHOW TABLES functionality but from version 0 64 we keep a list of tables as we create them in the METATABLES table and here we simply keep the same order in writing the tables This approach allows us to re create the tables without inserting items which depend on others PHP to generate a CSV file for download header Content type application octet stream header Content Disposition attachment filename eZ FULLBACKUP csv header Cache control no cache STHISPAGE backup all php require_once ValidFx php our login validation script SMINUSERSTATUS eZ_ADMINISTRATOR_MIN SMAXUSERSTATUS EVERYONE Ssuccess validate login SHOW USER 4 provides ShandDB Sdate date F j Y 9 WORKING PHP CODE 187 print S DatabaseBackupName eZ DatePerformed Sdate print An If you wish to restore the database you must print An upload this file to the csv subdirectory print An re create a fresh database and Restore get list of tables
184. pswd CheckCode salt bad SALT value Worrying ShandDB eZ_database_connect SUSERKEY processLogon username psud handDB salt Prepare to load main page SLOGGED_IN 1 Sqry SELECT PersonRole pValue ROM PERSON PERSDATA WHERE PERSON person PERSDATA Person Hj But it might be accessed directly in this case the POST variable username will not be set in which case we simply direct the user to the login htm file Section 8 1 8 PHP ACCESS CODING 137 AND PERSON person SUSERKEY list Suserstatus SOLDPAGE GetSQL ShandDB qry get status old Ssuccess USER Susername STATUS Suserstatus OLDPAGE SOLDPAGE clumsy duplication of validate_login ValidFx php require mainpage php The above duplication of success is clumsy but if we repeat the log in at tempt at mainpage php we encounter a problem the altered cookie is only seen at the next browser page load so login fails If everything worked according to plan we load the main page Section 9 1 Here s that processLogon function where we confirm the md5 encrypted user password using the schema described below It is very desirable to use Javascript md5 encoding of all passwords prior to submission We encrypt the password provided by the user in the first page and check the submitted value in
185. pt we must create the Js subdirectory of eZ on anaesthetist com and place the md5 js script there Ulti mately we may wish to insert one or more pretty images that we ll then need to upload into the eZ images directory so we might as well make this directory now Note that if the javascript include isn t found you failed to upload it then the script will silently fail to perform correctly header Cache control no cache require once eZ GLOBALS php require once SCONNECTIONPATH require ancillary php GLOBAL ShandDB ShandDB eZ database connect if ShandDB mysql close handDB print An Failed to connect to database ugh readfil rescue htm return 0 seed pseudorandom number generator Smt microtime if preg match 0 mt matches Smt time ugh else Smt Smatches 1 srand mt 8 PHP ACCESS CODING 133 find a free row to use SK SALTSIZE number of salt rows global STIMEOUT SALTTIMEOUT global constant Squiet 20 attempts while Squiet gt 0 J rand 4 hmm SI U SK index into salt table Snow time UNIX time Sqry SELECT sTime sValue FROM SALT WHERE salt I list SSTIME SSVAL GetSQL handDB qry get salt if strlen STIME gt 1 if row exists
186. qry get encr pwd f print lt p gt Debug my md5 pwd is SMD5PWD if strlen SMD5PWD lt 30 hack for startup SMD5PWD md5 SMD5PWD print lt p gt Debug Hack bare password now SMD5PWD im if SMYPSWD md5 MD5PWD if double md51 Sd md5 MD5PWD DEBUG print lt p gt Debug this md5 is d readfile badpassvord htm exit y print lt p gt Debug doublemd5 is SMYPSWD xor of new password md5 is SNEWPWD1 user is SUSERLOGON with id SOTHERLOGONID db md5 pwd is SMD5PWD extract new password using xor SNEWPWD1 XorString MD5PUD S NEWPWDI1 print lt p gt Debug xor extract gave SNEWPWD1 if strlen NEWPWD1 31 readfile badpassvord htm exit y check that new user name doesn t exist for somebody else don t use UNIQUE constraint as can be null Sqry SELECT COUNT person FROM PERSON WHERE pLoginName SUSERLOGON AND person lt gt SOTHERLOGONID Fl list Sdups GetSQL ShandDB Sqry get dup logon if Sdups 0 readfile duplicate htm exit write the new password qry UPDATE PERSON SET pLoginName SUSERLOGON pPassword SNEWPWD1 WHERE person OTHERLOGONID DoSQL handDB qry update user id password fetch eye candy SOTHERSURN
187. quotes Smtch if preg match s s S itm Smtch ncasing quotes Sitm mtch 1 get 1 else Sitm rtrim itm Sitm ltrim itm if strlen itm 1 Sitm NULL E Sretval 1 Sitm default return value next pull out column name NOTE column name must NOT contain double quotes if preg match Ns Nw NsS s col mtch check the above line in view of the double quotes if no match must be integer simply return defaults return retval 11 CT nature mtchlll 4 1 can be null retvall01 Smtch 2 column name is 2 if retval 1 NULL return Sretval im Sretval 1 Snature S itm an example is DATE 2006 01 03 simpler than complex switch case stmt return Sretval return both values 199 10 ANCILLARY CODE 200 10 6 SQL related functions 10 6 1 GetSQL Obtain a single row from the database as an array function GetSQL ShandDB qry message if DEBUGGING print lt br gt DEBUGGING Query was amp lt Sqry gt amp gt ShandQ mysql_query qry ShandDB if is resource handQ print lt br gt SQL error amp lt qry amp gt br message mysql_error exit this is serious FAIL r problem SELECT MAX mysession sTrainee FROM MYSESSION WHERE sAssesso
188. r 3 GROUP BY sTrainee IF there are no entries in MYSESSION this will not fail but also will not return a valid handle in handQ Thus if is resource handQ is a resourcel 1 mysql num rows ShandQ return 4 NULL i row mysql fetch array handQ MYSQL_NUM if DEBUGGING E print amp gt print r row DEBUGGING return Srow return array 10 6 2 DoSQL function DoSQL handDB qry message Sok mysql_query qry handDB if 1 ok print lt p gt Query error amp lt qry amp gt Se mysql error print lt p gt Error message Se if DEBUGGING print lt br gt DEBUGGING Stmt to execute vas amp lt qry amp gt 10 ANCILLARY CODE simply return 10 6 3 SQLManySQL Obtain array of arrays all data function SQLManySQL handDB qry msg handQ mysql query qry handDB if is resource handQ f debug print lt br gt SQL QUERY error msg mysql error exit serious failure y SoutAry array if is resource handQ print lt br gt SQL QUERY error msg mysql error return outAry y i while Srow mysql fetch array handQ MYSQL NUM SoutAry S i row array of arrays Si return outAry 201
189. rMemo INSTANCE Sleep 100 Send a Sleep 100 Send c Sleep 1000 this delay seems important get data from clipboard SXMLDATA ClipGet get xml from clipboard If StringLen XMLDATA lt 1000 Then FileWrite SERRORLOG Warning tiny XML file 6 SIARFILENAME log warn EndIf 77 Simply write to xml file Soutn StringSplit IARFILENAME get rid of suffix SOUTNAME outn 1 amp xml might check for error SfHandle FileOpen SXMLPATH amp SOUTNAME 2 7 Write erase prior contents If error lt gt 0 Then if faa Led sgBox ONTOP FATAL Error Failed to open file for writing amp filename Exit EndIf FileNrite fHandle XMLDATA j 777777777777777272277 need to do so repeated FileClose fHandle WinClose SAFERsleep IAR Viewer WinWaitClose SAFERsleep IAR Viewer Sleep 500 Walt just in case FileWrite SERRORLOG Apparently successful translation 6 SIARFILENAME 7 Return 0 1 success 2 EZ CAPTURE MANUAL DATA CAPTURE 58 EndFunc Enter Case Number Appendectomy Fit young male ras Figure 3 Initial screen for record information 2 5 Obtain basic record information XGetFileAndTimestamp pops up a GUI and obtains a file name as well as a date and time and certain other information The date is in NZ format
190. ration match Print n nExit code 32 0 Qh y 2 3 4 Main data processing Here s the main data processing and storing routine sub ProcessDatum my St Sy St Sy _ my 5 2 y3 if amp ISIN Sy ZERO y2 amp ReadLine if amp ISIN y2 ZERO amp Print n Storing NA value 2 sStore t SNA return 5645 elsif amp ISIN y2 MAXVAL amp Print n Moving to next series 2 amp NextSeries St Sy y2 SSERIESCOUNT 2 double return 0 elsif y2 gt MAXVALhi amp Die n Bad calibration value y2 elsif y2 lt MINVALlO amp Print n Special low value 2 amp Store St y2 4 special low value 2 EZ CAPTURE MANUAL DATA CAPTURE 27 return t 5 else amp Die An Bad special datum value y2 y elsif amp ISIN Sy ALPHA amp Print An Special offset y 2 my Stoff int 5 y ALPHAm FOR NOW TRUNCATE SHOULD PROBABLY ROUND FIX M Sy2 amp ReadLine amp Store t toff 5 y2 store offset value 5 as is past PRIOR time return t do NOT advance El elsif y lt MINVALLlo amp Die n Bad y data value Sy elsif Sy gt SMAXVALhi amp Print n Value above upper cal range 2 amp Store t SMAXVALm signal above upper cal return t 5 else amp Store t Sy return 5645
191. ration value This is a measurement of duration from the start of the anaesthetic to the end of the anaesthetic but with two caveats 1 Measurement must start from a pre printed vertical line on the chart not a user defined mark that is one of the vertical lines used to mark the time This is normally a 5 minute mark unless the user has chosen a different time base Use the smallest printed interval If the first datum recorded is not on a pre printed vertical line then choose the line before the first user mark NOT afterwards When recording data as described below signal the first recording as a missing value then measure the offset also described below 2 Measurement of the x axis calibration must likewise end ar a vertical pre printed line but 1f the last user marking is between two such lines only measure to the vertical pre printed line just before this line If the last user marking coincides with a pre printed vertical line measure to this line e The value a is the distance between two minor vertical time lines Unfor tunately this too varies depending on the type of record For Types A C the values in mm are 2 15 2 35 4 43 2 4 63 2 and 3 11 3 31 Note that in the type B record the value of 4 53 usually refers to a ten minute interval but we always mandate a five minute measuring interval When we deter mine x axis time offsets we will use measured values to determine more precise values for alpha for a
192. rcount gt 0 if errorcount 1 alert complete relevant fields You left out one else alert Please complete relevant fields There were errorcount errors r return false 9 WORKING PHP CODE 155 return true ValidStartYear startyear chirp check if valid year If not return false If chirp is nonzero then also give ALERT function ValidStartYear startyear chirp thisyear STHISYEAR if startyear value length 4 startyear value lt 1950 startyear value gt thisyear what if insert alphas if chirp alert Please enter valid 4 digit year e g 2003 startyear select startyear focus return false y return true function ValidSurname surname chirp if surname value length 2 can add more to the above if chirp alert Please enter valid surname y surname select surname focus return false y return true function ValidForename forename chirp if forename value length lt 2 can add more to the above if chirp alert Please enter valid forename im forename select forename focus return false y return true 9 WORKING PHP CODE 156 function ConfirmClear if confirm Are you sure you want to clear the form Click OK to clear it return true im return false gt lt
193. rentspecial TextPopl Sqry 90 GIN lt 1 OCATION RLOGONID ERLOGONID ENTLOCATION SpecialText FROM CURR ECIALTY listSelected SOTHI ERLOGIN ERFOR 9 WORKING PHP CODE 175 lt div align center gt lt FORM name eZ_update ACTION eZ_update php METHOD POST onSubmit return CheckAllInputs this gt lt input type hidden name editperson value SOTHERLOGONID gt lt table width 808675 lt tr gt lt td width 30 gt a Alter surname lt td gt lt td width 70675 lt input type text name newsurname Size 16 value OTHERSURNAME gt lt td gt lt tr gt lt tr gt lt td width 30 gt b Alter forename lt td gt lt td width 70 gt lt input type text name newforename Size 16 value OTHERFORENAME gt lt td gt lt tr gt lt tr gt lt td width 30 gt c Change role lt td gt lt td width 70675 SROLEPOPLIST lt td gt lt tr gt lt tr gt lt td width 30 gt d Change location lt td gt lt td width 70675 SLOCATIONPOPLIST lt td gt lt CLS lt tr gt lt td width 30 gt e Change specialty lt td gt lt td width 70675 SPECIALTYPOPLIST lt td gt lt tr gt lt tr gt lt td width 306 5e Year of qualification lt td gt lt td width 70 gt lt input type text size
194. res the following software for development All that is needed to interact with the final product is a recent web browser with Javascript and cookies enabled 1 Driving software for the digital calipers STATE DETAILS 2 SaferSleep state version number with server access ODBC i e SQL CLI connectivity 3 Perl version 5 6 See notes above we used ActivePerl version 5 6 1 binary build 635 2003 02 04 4 Autolt version 3 2 10 0 1999 2007 Jonathan Bennett amp AutoIt Team 5 Javascript ECMAscript within a fairly recent Web browser e g FireFox version 2 0 or greater or Internet Explorer 5 or greater 24 At present owing to the removal of the Tk toolkit from later versions of Perl Dogwagger version 2 1 which requires Tk will choke on higher versions of Perl 1 1 HARDWARE SOFTWARE USEFUL FILES CHANGE LOG 210 6 A web based version of mySQL and a server running PHP version 3 or greater Optionally an SQL 3 compliant database other than mySQL might be used to test the code 7 BTEX for generation of documentation We used MikTex but any IATEX2E compliant engine will work 8 My small Dogwagger program version 2 1 to extract files from the TEX source Make extract code from BTFX file Update this and manually run Dog Wagger if update IATEX file name echo off 615 rem makefile perl dogwagger21 pl ez 037 tex Creating the directory structure Here s a little DOS batch file
195. rmation Then 77 MsgBox ONTOP Dx Info box 2 detected Send ENTER Hit enter at Login screen Else MsgBox ONTOP dX Info box 2 NOT detected Click OK Send ENTER Hit enter at Login screen EndIf Sleep 3000 If WinExists Main Menu Then MsgBox SONTOP Dx Main menu detected Send ENTER new case default Else sgBox ONTOP Ooops No main menu Exit EndIf 3 BIG OUTER LOOP FOR SINGLE ANAESTHETICS SISMORE 1 While SISMORE HERE WE OVERWRITE THE DEMO DAT FILE Scurrentpath EZPATH dat amp CURRENTFILE amp dat If FileExists Scurrentpath 0 Then sgBox ONTOP Error Source DAT file not found amp currentpath Ia s EndIf Sdestpath C Program Files Safer Sleep IDAS Client devicedata DEMO DAT If FileExists destpath 0 Then sgBox ONTOP Error DEMO DAT not found amp destpath Exit EndIf 5 EZ REPLAY REPLAYING DATA VIA SAFERSLEEP 99 FileCopy currentpath destpath 1 overwrite 77 might check for success START NEW ANAESTHETIC MsgBox SONTOP Debug New Anaesthetic waiting Sleep 1000 If WinExists Start New Anaesthetic 0 Then Send ENTER MsgBox SONTOP HMM Try again Click OK to start new anaesthetic Else MsgBox 5 EndIf WinWaitAc Send SFAKENHI Sleep 500 Send ENTER
196. rson will only ever have one role function FetchRole ShandDB id SELECT MAX persdata FROM PERSDATA qry p WHERE Person id AND PersonRole IS NOT NULL list Spd GetSQL ShandDB qry fetch key for role Sqry SELECT PERSONROLE rText FROM PERSDATA PERSONROLE WHERE PERSDATA PersonRole PERSONROLE personrole AND PERSDATA persdata Spd list SPersonRole GetSQL handDB Sqry fetch role return PersonRole 10 5 CSV processing The variable STOTALLINESREAD is declared as global in SaveCsvLine and in cremented there for each successful line inserted Note that the header array is exploded willy nilly so you re likely to get duff SQL code if the format of this line isn t exactly correct Another good reason not to allow users to submit such CSV files Here s the meaty routine to parse lines and insert them as database rows function SaveCsvLine TABLENAME Sheadarray thisline handDB GLOBAL SDEBUGGING GLOBAL STOTALLINESREAD Scols count headarray if cols 1 print lt br gt Column has no length for table TABLENAME return 1 fail y first fix up format of thisline convert to a temporary backtick 10 ANCILLARY CODE 198 We will convert this back to comma later FormatOneItem Sthisline preg repl
197. rzck DEMS Mp L CLASS ThunderRT6CommandButton INSTANCE 1 Sleep 300 EndFunc E OY M E EJ p Func CloseDCMS FAKEDCMS If FAKEDCMS lt gt 0 Then return do nothing EndIf 2 EZ CAPTURE MANUAL DATA CAPTURE 56 Shutdown and exit WinActivate DCMS 7 Close port ContralcCliick DEMS Wm CLASS ThunderRT6CommandButton INSTANCE 11 Exit DCMS Controlelick DCMS Npr CLASS ThunderRT6CommandButton INSTANCE 10 EndFunc 2 4 4 Keyboard input Func GetKbSequence Sseqname SFILENAME SDATETIME SDURATION SEZPATH ez prog ComSpec c amp perl 6 SEZPATH ez capturNez keyboard pl Sperlok RunWait prog FILENAME amp amp seqname amp SDURATION SEZPATH SW_MAXIMIZE run the Perl program in DOS with relevant arguments 7 last Run parameter specifies working directory If Sperlok 0 Then Return 1 EndIf sgBox ONTOP OOPS Error in keyboard input ndFunc ri 2 4 5 Decrypt SAFERsleep IAR file to XML It is also possible to retrieve automatically captured records from SAFERsleep but these are encrypted A decryption tool is provided with XML output but it is inconvenient to use this tool manually on multiple recor
198. s document getElementBylId texta style visibility visible document getElementBylId oka style visibility visible document getElementById cancela style visibility visible document getElementById labela style visibility visible function RevealBottomInputs document getElementById checkbl style visibility visible document getElementById checkb2 style visibility visible document getElementById checkb3 style visibility visible 6 EZ SHW AN INTERACTIVE WEB BASED APPLICATION 114 document getElementBylId checkb4 style visibilitye visible document getElementById checkb5 style visibility visible document getElementById textb style visibility visible document getElementById okb style visibility visible document getElementById labelb style visibility visible document getElementById labelc style visibility visible document getElementById labeld style visibility visible document getElementById labele style visibility visible document getElementById labelf style visibility visible document getElementById labelg style visibility visible document getElementById labelh style visibility visible gt lt script gt lt head gt
199. s The IAR to XML translation has already been described above Section 2 4 5 4 1 Translate from XML to CSV From within the XML data we clip out and separate data tags in the following format lt data gt lt time gt 2008 03 31T10 09 42 lt time gt lt label gt ETCO2 lt label gt lt value gt 0 000000 lt value gt lt data gt The single line has been broken into two for the sake of legibility One approach is to identify all distinct times and create an ordered array of these times We then identify all labels make an array for each label and then enter values at each time where the label exists 4 1 1 Perl code translate to CSV The following perl program accepts a source file name The program opens the source XML file and using the same name but with a CSV rather than an XML suffix writes the file to the destination directory If the destination file exists it is simply overwritten The plan is 1 Get file name from the command line 2 Read in whole XML file 3 Identify all distinct times and store the times in order in an array called ALLTIMES It may be best to use a counter and associative array assuming that a later time contained in the file is always later in time than any earlier one and associating a monotonically increasing count with each new time 4 FORMAT TRANSLATION EZ XLATE 79 4 Identify the first label create an array for it and work through the entire XML file snipping out each time la
200. sage my EZDIR ez my SRAWPATH SEZDIR rawdata my SEXITCODE 0 code on exiting Perl my ALLDATA used to store data values GLOBAL my STORECOUNT 1 also used for debugging my SRAWFILENAME SARGV 0 4 serial number eg S0001 NO suffix my DATTYPE SARGV 1 etco2 or spo2 my SDURATION SARGV 2 duration in minutes my SPARAMS SARGV 3 f eg debug 3 logprint 0 if PARAMS debug d command line control SDEBUG 1 if SPARAMS logprint d SLOGPR E INT 1 sOpenLog LOGPRINT SRAWFILENAME SDATTYPE start writing to error debug log amp Print n SARGV 0 amp ReadConsole SDATTYP amp Print Mn Command line arguments are SRAWFILENAME SDATTYPE SDURATION SPARAMS ia avoid lt stdin gt bug in Perl Gl SDURATION END of data acquisition n n 1 HERE WRIT E DATA TO RAW FILE amp WriteKbData SRAWPATH SRAWFILENAME DATTYPE if SWARNINGS gt 0 print n NOTE There was were SWARNINGS warning s 2 EZ CAPTURE MANUAL DATA CAPTURE Please consult the log y print An Finished n CloseLog LOGPRINT exit SEXITCODE Here s the logging routine sub OpenLog my islog SRAWFILENAME DATTYPE Sislog SRAWFILENAME DATTYPE _ if Sislog return if not logging
201. se g Created an Autolt interface with three buttons Press a button to ac quire each series and a final one to validate the combination If a component is invalid this is renamed to for example X0001 dbp timestamp inv for invalid If the user presses a button where an unchecked component exists he she is asked whether they wish to overwrite and if so that component is invalidated 3 Have the ability to bypass actual capture faking the Excel submission etc for debugging purposes 4 Version 0 36 Get IDAS database interrogation working 26 As initially conceived 11 9 10 11 1 1 HARDWARE SOFTWARE USEFUL FILES amp CHANGE LOG 213 We also need the ability to review the playlist log played items and remove them Use MWSnap rather than Paintshop but see next version Introduced another flag in the au3 interface have we saved to playlist Also store the following DURATION and ALPHA INTERVAL 2 5 5 or 10min WRITE TO PLAYLIST See GetFileList etc 1 Changes for version 0 37 Finalised replay through IDAS Complex Enabled invocation of replay in main GUI Insert non displayed entries to be read by IDAS every 30s as DEMO DAT always plays values every 30s regardless of time Enter the end time as accurately as possible Now we store the duration as a parameter and pass it around using the duration and start time to display SpOz requests etc with actual times rather than o
202. se align center gt lt table width 65 align center lt p gt lt div lt tr gt lt td names Similar SSURNAME his user by clic SFOR E E NAME Abort and don colspan 5 to the one Please lt i gt confirm lt i gt king on the ot confirm border 2 lt b gt Users with similar names lt b gt lt td gt lt tr gt lt tr gt lt td gt lt i gt Forename lt i gt lt td gt lt td gt lt i gt Surname lt i gt lt td gt Obviously if the person already gt 9 WORKING PHP CODE 161 lt td gt lt i gt Current role lt i gt lt td gt lt td gt lt i gt Year started lt i gt lt td gt lt td gt lt i gt Database ID No lt i gt lt td gt lt tr gt HTML2B NOTE that because similarnames was generated by SQLManySQL it is actually an array of arrays each sub array having one element This is nasty So we flatten the array to 1 dimension Ssimilarnames Flatten Ssimilarnames Susers GetUserDetails ShandDB similarnames get forename surname role year started print lt br gt Debugging print r Susers debug PrintDetailTable Susers 5 print table with 5 columns print lt lt lt HTML2C lt tr gt lt td colspan 2 gt lt a href mainpage php gt Abort Do NOT add user FORENAME SSURNAME lt a gt lt td gt lt td colspan 3 gt lt INPUT TYPE sub
203. separating elements with blanks There is a terminal blank function ConcatenateArray Sary Sopt foreach ary as itm Sopt itm return Sopt y 10 3 3 Flatten Given an array of many dimensions flatten to a unidimensional array which is returned as a new array The problem with the following is the deprecated Call time pass by reference 10 ANCILLARY CODE 194 function Flatten Smyarray don t use me Ssimflat array array valk myarray flatten array amp S simflat see flatten array fx below return 5s2mtlat function flatten array value key amp S array if is_array value array push array value else array_walk value flatten array amp Sarray y S0 instead we use function Flatten S myarray SAout array foreach Smyarray as Sa if is array a SJ Flatten a foreach J as i array_push SAout i y else array push Aout a Y return Aout 10 3 4 PrintDetailTable function PrintDetailTable Sdata cols cols is number of colums Sdata array of data foreach data as d print br Deeper debug print r d print tr i while Si cols print td if strlen d Si lt 1 10 ANCILLARY CODE 195 print should work if NULL else print d i y print td Si 1 y print lt tr gt
204. ssed We might react more emphati cally to errors in DURATION in this program 12 Give some leeway with a warning if a value between alpha and MINVAL is read in directly not simply an error assume low reading and only die if subsequent problems but issue a warning 13 With 5 min changes we have a vast amount of redundant information in the PNG files Might compare these A simple strategy is to change nothing 1f they are the same omitted file leave the same and an advanced one might be to subtract the old from the new and only store the new changes as an overlay transparent background but this latter change will require sophisticated programming
205. t This is a security measure lt td gt lt tr gt lt tr gt lt td colspan 2 gt amp nbsp lt td gt lt tr gt lt tr gt lt td gt lt b gt 2 Enter user log on password for lt b gt lt td gt lt td gt lt b gt SOTHERFORENAME SOTHERSURNAME lt b gt lt td gt lt tr gt lt tr gt lt td gt a User log on name lt td gt lt td gt lt input type text name userlogon size 16 value SOTHERLOGIN gt lt br gt If exists can be left the same lt td gt lt tr gt lt tr gt lt td rowspan 2 b New password lt td gt lt td gt lt input type password name newpasswordl size 16 gt lt br gt Enter new password lt td gt tr tr td input type password name newpassword2 size 16 br Re type lt i gt new lt i gt password lt td gt lt tr gt lt tr gt lt td gt lt INPUT TYPE submit NAME submit VALUE Go gt lt td gt lt td gt lt INPUT TYPE reset VALUE Clear Form onClick return ConfirmClear gt lt td gt lt tr gt lt table gt lt form gt body html HTML2 9 WORKING PHP CODE 168 Edit person s details User Superuser Log on password have been updated for user Johan van Schalkwyk Log on name is johanvs Return to main page Edit another logon Figure 7 Editing id password eZ_do_editlogon2 php The page which takes the new log on data and writes
206. t Bad CSV name Nothing done Gl SDEBUGGING 0 print lt lt lt HTML3 lt p gt lt a href mainpage php Return to main page lt a gt body html HTML3 A large CSV reader This continues from the preceding PHP script We permit a single CSV file to contain multiple data tables in order To be able to do this we establish the con ventions that e The file must contain within its first line the text 9 WORKING PHP CODE 184 SsDatabaseBackupName eZ e Any line which starts with SSTableName forces termination of the previous table and the start of the newly speci fied one e After the tablename line there must be a columndata line along the lines of SsColumnData 4 rating int Patient int Assessor int raText string The line must start with a double percent sign followed by the word Colum nData with the number of columns in parenthesis and an equals sign After this we have the names of the columns each followed by its data type in parenthesis and a comma Let s implement this functionality within csv_read php supplying the database handle and the name of the CSV file without a directory path and suffix In order to completely restore a database this file should be uploaded to the csv subdirectory of the eZ directory after the main database has been created this creation may involve reading of other CSV files and before new data have been i
207. tabase for subsequent analysis The database is fully described as is the PHP code that links the web page and interacting anaesthetist to the database The suite is thus divided into the following sections Programs to capture data from a pair of digital calipers Section 2 Translation utilities Section 4 that translate from IAR to XML XML to CSV and CSV to DAT formats Programs to replay data through IDAS and screen grab the resulting display Section 5 Web display and database routines Sections 6 8 including SQL code and PHP code 1 INTRODUCTION 1 1 A note on the directory structure This has become somewhat complex so in Table 1 we show the relationships be tween noteworthy directories and sub directories In select subdirectories we ve also listed important files in parenthesis ez gui au3 css gt cascading style sheet images to display rav csv files exported from Excel IAR files from IDAS ated form XML ated from CSV to by ez TEX 2 ez captur gt ez captur pl ez xlat ez xml2csv pl ez csv2dat pl AnaestheticViewer exe ez shw html mainpage htm images php gt php scripts sql gt sql script ez replay gt ez replay au3 capture gt captured PNG images ez info gt basic case info rawdata gt iar gt grab encrypted xml gt files e
208. th the entire specification for that datum seamlessly excised Note that for the routine to work reliably the string should end with a comma sub PullDatum my t Sorig St is t t Sorig _ Sorig my dat modif dat modif 2 keep Perl happy if orig t modif 1 3 Sdat 2 else modif Sorig Sdat 1 im return dat modif to search for search IN arget string etc original string to 2 EZ CAPTURE MANUAL DATA CAPTURE 33 To obtain the Y calibration value we take all the values in YCALS and simply average them HMM CHECK ME The Y calibration value in mm represents 200 units so to get a conversion factor divide 200 by the average value sub GetYCal my d Stot n Stot 0 0 n 0 foreach d YCALS if length d gt 0 should always succeed Stot d n y y if n lt 1 most strange amp Die Odd No Y calibration values can this occur y Print An Y calibration total tot counte n 1 return 200 0 tot n We also need time manipulation routines Julian returns a Julian day float given year month day etc Gregorian does the reverse Note that IDAS doesn t seem to address issues of daylight saving 1 e the hour that is lost and the groundhog hour sub KiwiAddMinutes input format is DD MM YYYY HH MM aagh output
209. the destination page To encrypt the password we set the password value to the md5 string provided by Paul Johnston s Javascript routine hex_md5 See Section Next we implement a similar but more complex encryption of user pass words Now if we simply encrypt the password then anyone intercepting this md5 encrypted password can always use it to log on So we must provide some thing salt from the server side so that every new session is distinct Salt values must also expire and be used once only We proceed as follows 1 We already have a way of determining whether a user is logged on or not we store a session ID and clear it at log out Sessions expire 2 When someone requests a log on we provide a salt value in the log on page The server also increments the SALT table index once the salt value has been provided 3 We generate the salt value as a pseudorandom integer J and take I J mod ulo K where K is the number of items in the SALT table using I as an index into SALT 4 If that SALT table entry hasn t expired we try again max of 20 times at which time we say busy encourage wait of 30s and then allow re submission Note that this approach has not been formally cryptographically tested 8There s also the matter of rainbow tables This approach cannot protect against Man in the middle attacks 8 PHP ACCESS CODING 138 5 If SALT entry is expired 5 min is the cutof
210. tr core md5 str2binl s s length chrsz function hex hmac md5 key data return binl2hex core hmac md5 key data function b64 hmac md5 key data return binl2b64 core hmac md5 key data function str hmac md5 key data return binl2str core hmac md5 key data x Perform a simple self test to see if the VM is working wf function md5_vm_test return hex_md5 abc Calculate the MD5 of an array of little endian words function core md5 x len append padding xllen gt gt 5 0x80 lt lt len 32 x len 64 gt gt gt 9 lt lt 4 14 var a 1732584193 var b 271733879 var c 1732584194 var d 271733878 for var i 0 i x length i var olda a var oldb b var oldc c var oldd d a md5 ff a b c d x i 0 wdg5 ff d a b c 114 11 md5 ff c d a b x i 2 b cx mdb ff b d a x Tit 31 a md5 ff a b c d x i 4 d md5 ff d a b c x i 5 md5 ff c d a b x i l b md5 ff b c d a x i 7 a md5 ff a b c d x i 8 d md5 ff d a b c x i 9 md5 ff c d a b x i 10 b md5 ff b c d a x i 11 a md5 ff a b c d x 1 12 d md5 ff d a b c x 1 13 c md5 ff c d a b x it14 b md5 ff b c d a x i 15 a md5 gg a b c d x i 1 d md5 gg d a b c x it l c md5 gg c d a b x i 11 b md5_
211. ueLock cast uValue 1l as varchar 32 10 ANCILLARY CODE 205 he F Here Julian calculates a Julian date from a standard timestamp which is a floating point value Alternatively we might use modified unix timestamps without the Julian fussing One good modification would be to use a mi crotime value combined with a UNIX timestamp modulo an appropriate interval It would then be wise to determine the maximum key value ever and always add this to the modified timestamp to prevent that odd failure See below 2 There is a residual catch How do we obtain our value if 1 Sok return 0 fail 3 GetSQL handDB SELECT uValue FROM UIDS WHERE uValueLock now get new key j The above ensures that if a reset has already occurred the key fetch will fail It is true that if this occurs then there will be a gap in the record but this gap signals a process defect which must be identified The important consideration is that if the timeout detecting process now kicks in the number will still be updated If it doesn t then the following will succeed and the two are mutually exclusive 3 Finally allow others to get the next value DoSQL handDB UPDATE UIDS SET uValueLock SET uValue j WHERE uValueLock now release lock This will fail if somebody has already performed the reset but even then the increment will
212. um lt lt cnt num gt gt gt 32 cnt x Convert a string to an array of little endian words If chrsz is ASCII characters 5255 have their hi byte silently ignored s 143 8 PHP ACCESS CODING 144 function str2binl str var bin Array var mask 1 lt lt chrsz 1 for var i 0 i lt str length chrsz i chrsz bin i gt gt 5 str charCodeat i chrsz mask lt lt 1532 return bin x Convert an array of little endian words to a string af function binl2str bin var str var mask 1 lt lt chrsz 1 for var i 0 i lt bin length 32 i chrsz str String fromCharCode bin i gt gt 5 gt gt gt i 5 32 mask return str x Convert an array of little endian words to a hex string function binl2hex binarray var hex_tab hexcase 0123456789ABCDEF 0123456789abcdef var str for var i 0 i binarray length 4 i str hex_tab charAt binarray i gt gt 2 gt gt 154 844 6 OxF hex_tab charAt binarray i gt gt 2 gt gt i 4 8 amp OxF return str x Convert an array of little endian words to a base 64 string il function binl2b64 binarray var tab ABCDEFGHIJKLMNOPORSTUVWXYZabcdefghijklmnopgrstuvwxyz0123456789 var str for var i 0 i binarray length 4 i 3 var triplet binarray i 2 2 gt gt 8 1 4 OxFF lt lt 16
213. und 5 y2 ALPHAm Store t toff y2 return t do NOT advance 2 EZ CAPTURE MANUAL DATA CAPTURE 17 if y lt MINVAL gt fail Bad data value if y gt MAXVAL gt MAXVALm lt MAXVALh MAXVAL1 2 Store t MAXVALm return t 5 default gt Store t y return t 5 FiO EtCO After determining the number of values to acquire which is simply the DURA TION measurement divided by alpha check me and identical to the maximum time value noting that if the last time value is not on a 5 minute mark the user must enter a 0 0 we acquire first FiO2 and then EtCO2 values if present allow ing the user to enter NA values where appropriate What about oopses routine ReadFiO2andEtCO2 here determine maximum index of ALLDATA validate vs DURATION int DURATION 4 5 t lt 0 while t lt c sp lt acquire allow NA or integer 0 100 Store Es Sp t lt t 5 end while dox 0 while t c et acquire as above Store t et t lt t 5 end while end routine ReadFiO2andEtCO2 Write data All data should now have been stored in the single dimensional array ALLDATA indexed by time in minutes The first time is zero signalling the start of data recording There may be missing data for a particular time and there is the possibility that two closely recorded values are registered under the same time We will next simply write all time data in order as a CSV fi
214. ure 6 Editing log on details 9 4 Editing log on details Here s the page eZ_do_editlogon php that accepts new log on details for the se lected user Once the administrator has entered the new details we must still POST the values to eZ do editlogon2 php We md5 encode the administrator password twice to prevent it being revealed Because the md5 encoded password being supplied for the user could be used to log on as that user if somebody listened in to a password changing session we xor the password with the singly md5 encoded administrator password before submit ting this Then the server side script can securely pull out the new password header Cache control no cache 4 STHISPAGE eZ do editlogon php require once ValidFx php our login validation script SMINUSERSTATUS eZ ADMINISTRATOR MIN SMAXUSERSTATUS EVERYONE success validate login SHOW USER list SMYHEADER SUSERSTATUS eZHeaderGreet success SMINUSERSTATUS SMAXUSERSTATUS Edit person s details 0 print lt lt lt HTMLO 2INoting that if the session were recorded and the user password subsequently was disclosed this would compromise the current administrator password so it s a good idea for the administrator to change their password often However if this session too had been captured the new password would also be compromised For better security it would be wise to
215. value but try for honesty Sjdthen delta Syy mm dd hr mi se amp Gregorian jdthen print DOUTFILE yy mm dd T hr mi se T3 0 000000 An y Here s a copy of our Julian Gregorian subroutines stolen from our data cap ture Perl script in Section 2 3 sub Julian i my Sfm 554 Sfh Simi Sis SEE fy Sim fd Sfh fmi fs Sff s8 my Sf f 367 Sfy int 7 fytint fm 9 12 4 int 3 int Sfy fm 9 7 100 1 4 int 275 Sfm 9 fd 1721028 5 Sfh Simi 5254 0 S 60 60 24 return f sub Gregorian my 3d jd _ 4 FORMAT TRANSLATION EZ XLATE my SEPSILON 0 000001 jd SEPSILON my Z SR G A SB C my Syear month day Z floor jd 1721118 5 SR 3d 1721118 5 Z G 2 0 25 SA floor G 36524 25 SB A floor A 4 year floor B G 365 25 SC B Z floor 365 25 year Smonth int 5 C 456 153 day C int 153 month 457 5 SR if month gt 12 Syear year 1 month month 12 y my gd 0 5 jd int 3d if gd gt 1 Julian starts at midday gd 1 y my gh gmi gs Sgh gd clumsy gh 24 Sgmi Sgh gh int gh Sgmi gh Sgmi 60 gs gmi gmi int gmi gs gmi gs 60 return year amp DoubleDigit mo
216. value in OTHERLOGIN may f in the folloving ve assume only Sqry SELECT PersonRole FRO list SOTHERROLE GetSQL Shand Sqry SELECT CurrentSpecial list SOTHERSPECIALTY GetSQL Sqry SELECT CurrentLocation F list SOTHERLOCATION GetSQ1 Sqry SELECT FirstQualified FRO list QUALYEAR GetSQL handDB Sqry SEL WH SROLEPOPLIST newrole ERE pe qry Sqry SE ECT current WHERE cu SLOCATIONPOP EIST newlocation Sqry SE SSPECIALTYPOPLIST SLGIN newspecialty if strlen OTHERLO SLGIN else SLGIN Login name is y print lt lt lt HTML3 lt p gt lt a href mainpage php Return to main page lt a gt lt h3 gt Alter details for SOTH div class narrow SLGIN By default all values are left at their current settings div ERLOGONID ri one valid DATA entry ECT personrole rsonrole 5 O TextPoplistSelected RSDATA WH E get role ERSDATA W I ERLOGONID get user login ERLOGONID ERLOGONID RSDATA WH get qual yr rText FRO Gl SOTHERROLE tionText FROM CURRI ocatio rrentlocatio TextPoplistSelected Sqry 50 ECT currentspecialty WHERE cur
217. vwSS GUICtrlCreatePic ez images sslist gif 5 4 Shskip 5 1 Spitch 60 right brace for SBP etc GUICtrlCreatePic ez images rbrace gif 1 2 hskip 1 3 Spitch 40 4 pitch right brace for valid GUICtrlCreatePic ez images rbrace gif 2 9 Shskip 1 3 Spitch 40 4 pitch Special graphics view Log clickable Dim imCSV GUICtrlCreatePic ez images Ilog gif 2 2 Shskip 3 8 pitch 30 Dim imDAT GUICtrlCreatePic ez images Ilog gif 4 58 Shskip 3 8 Spitch 30 Dim imADD GUICtrlCreatePic ez images Ilog gif 5 58 Shskip 3 8 Spitch 30 Dim isGET GUICtrlCreatePic ez images Ilog gif 0 88 Shskip 7 8 Spitch 30 Dim isXML GUICtrlCreatePic ez images Ilog gif 2 58 Shskip 7 8 Spitch 30 Dim isCSV GUICtrlCreatePic ez images Ilog gif 3 58 Shskip 7 8 Spitch 30 Dim isDAT GUICtrlCreatePic ez images Ilog gif 4 58 Shskip 7 8 Spitch 30 Dim isADD GUICtrlCreatePic ez images Ilog gif 5 58 Shskip 7 8 Spitch 30 2 EZ CAPTURE MANUAL DATA CAPTURE 41 check for defects otherwise will behave VERY oddly If vuXML 0 OR vwCSV 0 OR vvDAT 0 OR SvwSS 0 OR SimCSV 0 Then sgBox SONTOP Error Missing images in ez images Fix me Bye l Exit EndIf here set control states at start ugh first tick boxes are always greyed myDisable 5 5 myDisable 5 myDisable xHR myDisable x
218. ws that incoming data is raw The possibility exists that similar people might al ready exist in the database The latter script checks for this and requires confirma tion then forcing resubmission of data to itself but with the confirmation variable set to 1 If confirmation is 1 then no further checking takes place 9 WORKING PHP CODE eZ_admin_personadded php 158 We process the POST data from the preceding page In addition we provide the option to add a user name and password Screen layout THEE HH HH HEHE HH HH lt Message about added person gt Add user name password for reviewers superusers Back to main page T HEHE HEH TEE HH HH TEE HH HH alternatively if confirmation is required we get HEHEHE HA EEEE E E EE EEE EEEE HE
219. xported from IAR to XML CSV gt CSV files trans dat gt DAT files trans log gt error logging images images referred Table 1 Directory structure of EZ The directories ez captur ez xlate ez shw and ez replay contain the relevant Perl and or AutoIt executables that perform capture and formatting of raw data obtained from the digital calipers translation between various formats display as HTML pages and replay of DAT files through SAFERsleep 1 INTRODUCTION 7 1 2 DOS execution We have created a comprehensive Graphical User Interface GUI that is described in Section 2 4 However we also have created a number of useful DOS batch files used to run components of our program suite The main advantages of this console execution are simplicity and clarity especially when it comes to debugging The batch files include Raw data capture and processing e captur bat Capture data from digital calipers Section using an Autolt script Translation between formats Conversion of IAR to XML format is now accomplished within the main GUI program written in AutoIt we simply invoke the IDAS viewer and write the resulting output to an XML file Other translations are e xml2csv bat Invokes a Perl program to translate the source XML file first argument in ez xml to a CSV file stored in the csv subdirectory of ez The batch file test x2c bat performs this transformation on a test file Section 4 1
220. ysql close S handDB ForceLogin Welcome to eZ exit 2a debug only Sdqry SELECT pSID FROM PERSON WHERE person 1 list i GetSQL handDB dqry debug get su sid print lt p gt Superuser SID is currently i 3 Check for failure Sqry SELECT person pExpiration pLoginName pValue FROM PERSON WHERE pSID SID ShandQ mysql_query qry handDB if is resource handQ debug print br DEBUG SQL error at login mysql error y if mysql num rovs handQ force cookie to evaporate mysql_close ShandDB setcookie eZ SID time 100 ForceLogin No match for cookie exit y 4 if cookie stale present login row mysql fetch assoc ShandQ Sexptime row pExpiration 4 Srow is associative array Snow time if Sexptime lt Snow here force cookie to evaporate mysql close ShandDB setcookie eZ SID time 100 print lt br gt Debug exp time amp lt S exptime amp gt TIME is Snow ForceLogin Session has expired 8 PHP ACCESS CODING 147 exit H 5 Retrieve previous page SOLDPAGE row pValue most recent page SUSERKEY S row person Sexpiry time eZ TIMEOUT if strlen THISPAGE lt 2 if invalid STHISPA

Download Pdf Manuals

image

Related Search

EzCapture ezcapture ez capture software ez capture topcon ez capture software download ez capture driver ecapture github ecapturedtech ecapture android ecapture windows

Related Contents

powerful - Farnell  Internet Email for Meta5  DeLOCK Adapter Displayport to HDMI  Samsung SyncMaster  KV-29FQ85E Colour Television  LASSI-HS User`s Manual  OM, 445, 445 e, 450 e, 2010-01  Philips SPF1027/93, User's Manual  Zハンドルバーキット(BAT ミドルタイプ)取扱説明書  1 Premete  

Copyright © All rights reserved.
Failed to retrieve file