text
stringlengths
14
6.51M
{ Private include file for system-dependent routines in STRING library. * * This version is for any system where the command line arguments can * be accessed by the standard ARGN and ARGP arguments to the C function MAIN. } %include 'sys_sys2.ins.pas'; type cmline_argp_t = {array of pointers to command line arguments} array[0..0] of ^string; {each entry points to null-terminated string} cmline_argp_p_t = {points to list of argument pointers} ^cmline_argp_t; var (string_sys) cmline_n_args: sys_int_machine_t; {number of command line arguments} cmline_argp_p: cmline_argp_p_t; {points to cmline args pointers array}
unit TextEditor.SkipRegions; interface uses System.Classes, System.SysUtils, TextEditor.Consts; type TTextEditorSkipRegionItemType = (ritUnspecified, ritMultiLineString, ritSingleLineString, ritMultiLineComment, ritSingleLineComment); TTextEditorSkipRegionItem = class(TCollectionItem) strict private FCloseToken: string; FOpenToken: string; FRegionType: TTextEditorSkipRegionItemType; FSkipEmptyChars: Boolean; FSkipIfNextCharIsNot: Char; public property OpenToken: string read FOpenToken write FOpenToken; property CloseToken: string read FCloseToken write FCloseToken; property RegionType: TTextEditorSkipRegionItemType read FRegionType write FRegionType; property SkipEmptyChars: Boolean read FSkipEmptyChars write FSkipEmptyChars; property SkipIfNextCharIsNot: Char read FSkipIfNextCharIsNot write FSkipIfNextCharIsNot default TEXT_EDITOR_NONE_CHAR; end; TTextEditorSkipRegions = class(TCollection) strict private function GetSkipRegionItem(const AIndex: Integer): TTextEditorSkipRegionItem; public function Add(const AOpenToken, ACloseToken: string): TTextEditorSkipRegionItem; function Contains(const AOpenToken, ACloseToken: string): Boolean; property SkipRegionItems[const AIndex: Integer]: TTextEditorSkipRegionItem read GetSkipRegionItem; default; end; implementation uses Winapi.Windows; { TTextEditorSkipRegions } function TTextEditorSkipRegions.Add(const AOpenToken, ACloseToken: string): TTextEditorSkipRegionItem; begin Result := TTextEditorSkipRegionItem(inherited Add); with Result do begin OpenToken := AOpenToken; CloseToken := ACloseToken; end; end; function TTextEditorSkipRegions.Contains(const AOpenToken, ACloseToken: string): Boolean; var LIndex: Integer; LSkipRegion: TTextEditorSkipRegionItem; begin Result := False; for LIndex := 0 to Count - 1 do begin LSkipRegion := SkipRegionItems[LIndex]; if (LSkipRegion.OpenToken = AOpenToken) and (LSkipRegion.CloseToken = ACloseToken) then Exit(True); end; end; function TTextEditorSkipRegions.GetSkipRegionItem(const AIndex: Integer): TTextEditorSkipRegionItem; begin Result := TTextEditorSkipRegionItem(inherited Items[AIndex]); end; end.
Unit AdvClassHashes; { Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } Interface Uses AdvObjects, AdvHashes, AdvStringHashes, AdvIterators; Type TAdvObjectClassHashEntry = Class(TAdvStringHashEntry) Private FData : TClass; Public Procedure Assign(oSource : TAdvObject); Override; Property Data : TClass Read FData Write FData; // no set data as hashed classname may be different to FData.ClassName. End; TAdvObjectClassHashTable = Class(TAdvStringHashTable) Protected Function ItemClass : TAdvHashEntryClass; Override; Public Function Iterator : TAdvIterator; Override; End; TAdvObjectClassHashTableIterator = Class(TAdvObjectClassIterator) Private FInternal : TAdvStringHashTableIterator; Function GetHashTable: TAdvObjectClassHashTable; Procedure SetHashTable(Const Value: TAdvObjectClassHashTable); Public Constructor Create; Override; Destructor Destroy; Override; Procedure First; Override; Procedure Last; Override; Procedure Next; Override; Procedure Back; Override; Function More : Boolean; Override; Function Current : TClass; Override; Property HashTable : TAdvObjectClassHashTable Read GetHashTable Write SetHashTable; End; Implementation Procedure TAdvObjectClassHashEntry.Assign(oSource: TAdvObject); Begin Inherited; FData := TAdvObjectClassHashEntry(oSource).Data; End; Constructor TAdvObjectClassHashTableIterator.Create; Begin Inherited; FInternal := TAdvStringHashTableIterator.Create; End; Destructor TAdvObjectClassHashTableIterator.Destroy; Begin FInternal.Free; Inherited; End; Function TAdvObjectClassHashTable.ItemClass : TAdvHashEntryClass; Begin Result := TAdvObjectClassHashEntry; End; Function TAdvObjectClassHashTable.Iterator : TAdvIterator; Begin Result := TAdvObjectClassHashTableIterator.Create; TAdvObjectClassHashTableIterator(Result).HashTable := TAdvObjectClassHashTable(Self.Link); End; Function TAdvObjectClassHashTableIterator.Current : TClass; Begin Result := TAdvObjectClassHashEntry(FInternal.Current).Data; End; Procedure TAdvObjectClassHashTableIterator.First; Begin Inherited; FInternal.First; End; Procedure TAdvObjectClassHashTableIterator.Last; Begin Inherited; FInternal.Last; End; Procedure TAdvObjectClassHashTableIterator.Next; Begin Inherited; FInternal.Next; End; Procedure TAdvObjectClassHashTableIterator.Back; Begin Inherited; FInternal.Back; End; Function TAdvObjectClassHashTableIterator.More : Boolean; Begin Result := FInternal.More; End; Function TAdvObjectClassHashTableIterator.GetHashTable : TAdvObjectClassHashTable; Begin Result := TAdvObjectClassHashTable(FInternal.HashTable); End; Procedure TAdvObjectClassHashTableIterator.SetHashTable(Const Value: TAdvObjectClassHashTable); Begin FInternal.HashTable := Value; End; End. // AdvClassHashes //
unit MahExcel; interface uses Windows, Variants, ComObj, SysUtils, DB, Math, Dialogs; // ============================================================================= // TDataSet to Excel without OLE or Excel required // Mike Heydon Dec 2002 // ============================================================================= type // TDataSetToExcel TDataSetToExcel = class(TObject) protected procedure WriteToken(AToken: word; ALength: word); procedure WriteFont(const AFontName: string; AFontHeight, AAttribute: word); procedure WriteFormat(const AFormatStr: string); private FRow: word; FDataFile: file; FFileName: string; FDataSet: TDataSet; public constructor Create(ADataSet: TDataSet; const AFileName: string); function WriteFile: boolean; end; TExcelWriter = class private FWorkSheetName, FFIle: String; FExcelApp, FExcelWorkBook, FExcelWorkSheet: OleVariant; procedure setWorkSheetName(value: string); public constructor Create(AFile: String); procedure VarWriteCell(AColumn, ARows: Integer; value: variant); overload; procedure WriteCell(AColumn, ARows: Integer; Field: TFIeld); overload; procedure WriteCell(AColumn, ARows: Integer; value: string); overload; procedure WriteCell(AColumn, ARows: Integer; value: integer); overload; procedure WriteCell(AColumn, ARows: Integer; value: double); overload; function ReadCell(AColumn, ARows: Integer): variant; destructor Destroy; override; property WorkSheetName: String read FWorkSheetName write setWorkSheetName; end; // ----------------------------------------------------------------------------- implementation const // XL Tokens XL_DIM = $00; XL_BOF = $09; XL_EOF = $0A; XL_DOCUMENT = $10; XL_FORMAT = $1E; XL_COLWIDTH = $24; XL_FONT = $31; // XL Cell Types XL_INTEGER = $02; XL_DOUBLE = $03; XL_STRING = $04; // XL Cell Formats XL_INTFORMAT = $81; XL_DBLFORMAT = $82; XL_XDTFORMAT = $83; XL_DTEFORMAT = $84; XL_TMEFORMAT = $85; XL_HEADBOLD = $40; XL_HEADSHADE = $F8; // ======================== // Create the class // ======================== constructor TDataSetToExcel.Create(ADataSet: TDataSet; const AFileName: string); begin FDataSet := ADataSet; FFileName := ChangeFileExt(AFilename, '.xls'); end; // ==================================== // Write a Token Descripton Header // ==================================== procedure TDataSetToExcel.WriteToken(AToken: word; ALength: word); var aTOKBuffer: array[0..1] of word; begin aTOKBuffer[0] := AToken; aTOKBuffer[1] := ALength; Blockwrite(FDataFile, aTOKBuffer, SizeOf(aTOKBuffer)); end; // ==================================== // Write the font information // ==================================== procedure TDataSetToExcel.WriteFont(const AFontName: string; AFontHeight, AAttribute: word); var iLen: byte; begin AFontHeight := AFontHeight * 20; WriteToken(XL_FONT, 5 + length(AFontName)); BlockWrite(FDataFile, AFontHeight, 2); BlockWrite(FDataFile, AAttribute, 2); iLen := length(AFontName); BlockWrite(FDataFile, iLen, 1); BlockWrite(FDataFile, AFontName[1], iLen); end; // ==================================== // Write the format information // ==================================== procedure TDataSetToExcel.WriteFormat(const AFormatStr: string); var iLen: byte; begin WriteToken(XL_FORMAT, 1 + length(AFormatStr)); iLen := length(AFormatStr); BlockWrite(FDataFile, iLen, 1); BlockWrite(FDataFile, AFormatStr[1], iLen); end; // ==================================== // Write the XL file from data set // ==================================== function TDataSetToExcel.WriteFile: boolean; var bRetvar: boolean; aDOCBuffer: array[0..1] of word; aDIMBuffer: array[0..3] of word; aAttributes: array[0..2] of byte; i: integer; iColNum, iDataLen: byte; sStrData: string; fDblData: double; wWidth: word; begin bRetvar := true; FRow := 0; FillChar(aAttributes, SizeOf(aAttributes), 0); AssignFile(FDataFile, FFileName); try Rewrite(FDataFile, 1); // Beginning of File WriteToken(XL_BOF, 4); aDOCBuffer[0] := 0; aDOCBuffer[1] := XL_DOCUMENT; Blockwrite(FDataFile, aDOCBuffer, SizeOf(aDOCBuffer)); // Font Table WriteFont('Arial', 10, 0); WriteFont('Arial', 10, 1); WriteFont('Courier New', 11, 0); // Column widths ShowMessage('FC: '+IntToStr(FDataSet.FieldCount) +', FDC: '+IntToStr(FDataSet.FieldDefs.Count)); for i := 0 to FDataSet.FieldCount - 1 do begin wWidth := (FDataSet.Fields[i].DisplayWidth + 1) * 256; // if FDataSet.FieldDefs[i].DataType = ftDateTime then if FDataSet.Fields[i].DataType = ftDateTime then inc(wWidth, 2000); // if FDataSet.FieldDefs[i].DataType = ftDate then if FDataSet.Fields[i].DataType = ftDate then inc(wWidth, 1050); // if FDataSet.FieldDefs[i].DataType = ftTime then if FDataSet.Fields[i].DataType = ftTime then inc(wWidth, 100); WriteToken(XL_COLWIDTH, 4); iColNum := i; BlockWrite(FDataFile, iColNum, 1); BlockWrite(FDataFile, iColNum, 1); BlockWrite(FDataFile, wWidth, 2); end; // Column Formats WriteFormat('General'); WriteFormat('0'); WriteFormat('###,###,##0.00'); WriteFormat('dd-mmm-yyyy hh:mm:ss'); WriteFormat('dd-mmm-yyyy'); WriteFormat('hh:mm:ss'); // Dimensions WriteToken(XL_DIM, 8); aDIMBuffer[0] := 0; aDIMBuffer[1] := Min(FDataSet.RecordCount, $FFFF); aDIMBuffer[2] := 0; aDIMBuffer[3] := Min(FDataSet.FieldCount - 1, $FFFF); Blockwrite(FDataFile, aDIMBuffer, SizeOf(aDIMBuffer)); // Column Headers ShowMessage('Headers:'+IntToStr(FDataSet.FieldCount)); for i := 0 to FDataSet.FieldCount - 1 do begin sStrData := FDataSet.Fields[i].DisplayName; iDataLen := length(sStrData); WriteToken(XL_STRING, iDataLen + 8); WriteToken(FRow, i); aAttributes[1] := XL_HEADBOLD; aAttributes[2] := XL_HEADSHADE; BlockWrite(FDataFile, aAttributes, SizeOf(aAttributes)); BlockWrite(FDataFile, iDataLen, SizeOf(iDataLen)); if iDataLen > 0 then BlockWrite(FDataFile, sStrData[1], iDataLen); aAttributes[2] := 0; end; // Data Rows while not FDataSet.Eof do begin inc(FRow); for i := 0 to FDataSet.FieldCount - 1 do begin // case FDataSet.FieldDefs[i].DataType of case FDataSet.Fields[i].DataType of ftBoolean, ftWideString, ftFixedChar, ftString: begin sStrData := FDataSet.Fields[i].AsString; iDataLen := length(sStrData); WriteToken(XL_STRING, iDataLen + 8); WriteToken(FRow, i); aAttributes[1] := 0; BlockWrite(FDataFile, aAttributes, SizeOf(aAttributes)); BlockWrite(FDataFile, iDataLen, SizeOf(iDataLen)); if iDataLen > 0 then BlockWrite(FDataFile, sStrData[1], iDataLen); end; ftAutoInc, ftSmallInt, ftInteger, ftWord, ftLargeInt: begin fDblData := FDataSet.Fields[i].AsFloat; iDataLen := SizeOf(fDblData); WriteToken(XL_DOUBLE, 15); WriteToken(FRow, i); aAttributes[1] := XL_INTFORMAT; BlockWrite(FDataFile, aAttributes, SizeOf(aAttributes)); BlockWrite(FDataFile, fDblData, iDatalen); end; ftFloat, ftCurrency, ftBcd: begin fDblData := FDataSet.Fields[i].AsFloat; iDataLen := SizeOf(fDblData); WriteToken(XL_DOUBLE, 15); WriteToken(FRow, i); aAttributes[1] := XL_DBLFORMAT; BlockWrite(FDataFile, aAttributes, SizeOf(aAttributes)); BlockWrite(FDataFile, fDblData, iDatalen); end; ftDateTime: begin fDblData := FDataSet.Fields[i].AsFloat; iDataLen := SizeOf(fDblData); WriteToken(XL_DOUBLE, 15); WriteToken(FRow, i); aAttributes[1] := XL_XDTFORMAT; BlockWrite(FDataFile, aAttributes, SizeOf(aAttributes)); BlockWrite(FDataFile, fDblData, iDatalen); end; ftDate: begin fDblData := FDataSet.Fields[i].AsFloat; iDataLen := SizeOf(fDblData); WriteToken(XL_DOUBLE, 15); WriteToken(FRow, i); aAttributes[1] := XL_DTEFORMAT; BlockWrite(FDataFile, aAttributes, SizeOf(aAttributes)); BlockWrite(FDataFile, fDblData, iDatalen); end; ftTime: begin fDblData := FDataSet.Fields[i].AsFloat; iDataLen := SizeOf(fDblData); WriteToken(XL_DOUBLE, 15); WriteToken(FRow, i); aAttributes[1] := XL_TMEFORMAT; BlockWrite(FDataFile, aAttributes, SizeOf(aAttributes)); BlockWrite(FDataFile, fDblData, iDatalen); end; end; end; FDataSet.Next; end; // End of File WriteToken(XL_EOF, 0); CloseFile(FDataFile); except bRetvar := false; end; Result := bRetvar; end; { TExcelWriter } constructor TExcelWriter.Create(AFile: String); begin FFile:= AFile; FWorkSheetName := ''; try FExcelApp := CreateOleObject('Excel.Application'); Except MessageDlg('Error. Apakah Excel terinstall?',mtError,[mbOK], 0); end; if not VarIsNull(FExcelApp) then begin if FileExists(FFIle) then begin FExcelApp.Workbooks.open(AFile); FExcelWorkBook := FExcelApp.ActiveWorkbook; if FExcelWorkBook.worksheets.count = 0 then begin FExcelWorkBook.WorkSheets.add; end; FExcelWorkSheet := FExcelWorkBook.WorkSheets[1]; end else begin FFile := ChangeFileExt(AFile, '.xls'); FExcelWorkBook := FExcelApp.workBooks.add; FExcelWorkSheet := FExcelWorkBook.WorkSheets[1]; end; end; end; destructor TExcelWriter.Destroy; begin if FileExists(FFIle) then FExcelWorkBook.close(true) else begin FExcelWorkBook.saveAs(FFIle); FExcelWorkBook.close; end; FExcelApp:= Unassigned; FExcelWorkBook := Unassigned; FExcelWorkSheet := Unassigned; inherited; end; function TExcelWriter.ReadCell(AColumn, ARows: Integer): variant; begin Result := FExcelWorkSheet.cells[Arows+1, AColumn+1].value; end; procedure TExcelWriter.setWorkSheetName(value: string); begin if value = FExcelWorkSheet.name then exit; FWorkSheetName := value; FExcelWorkSheet.name := FWorkSheetName; end; procedure TExcelWriter.WriteCell(AColumn, ARows: Integer; value: string); begin // VarWriteCell(Arows, AColumn, value); FExcelWorkSheet.cells[Arows, AColumn] := value; end; procedure TExcelWriter.WriteCell(AColumn, ARows, value: integer); begin // VarWriteCell(Arows, AColumn, value); FExcelWorkSheet.cells[Arows, AColumn] := value; end; procedure TExcelWriter.WriteCell(AColumn, ARows: Integer; value: double); begin // VarWriteCell(Arows, AColumn, value); FExcelWorkSheet.cells[Arows, AColumn] := value; end; procedure TExcelWriter.VarWriteCell(AColumn, ARows: Integer; value: variant); begin assert (False, 'Jangan pake funsgi ini!'); FExcelWorkSheet.cells[Arows, AColumn] := value; end; procedure TExcelWriter.WriteCell(AColumn, ARows: Integer; Field: TFIeld); begin VarWriteCell(Arows, AColumn, Field.Value); end; end.
unit GifMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Net.URLClient, System.Net.HttpClient, FMX.GifUtils, System.Net.HttpClientComponent, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, FMX.Objects, FMX.Ani, FMX.WebBrowser; type TForm13 = class(TForm) Edit1: TEdit; Button1: TButton; NetHTTPRequest1: TNetHTTPRequest; NetHTTPClient1: TNetHTTPClient; Image1: TImage; BitmapAnimation1: TBitmapAnimation; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } gifPlayer: TGifPlayer; public { Public declarations } end; var Form13: TForm13; implementation {$R *.fmx} procedure TForm13.FormDestroy(Sender: TObject); begin gifPlayer.Destroy; end; procedure TForm13.FormCreate(Sender: TObject); begin gifPlayer := TGifPlayer.Create(nil); gifPlayer.Image := Image1; end; procedure TForm13.Button1Click(Sender: TObject); var gifStrm: TMemoryStream; begin gifStrm := TMemoryStream.Create; try NetHTTPRequest1.Get(Edit1.Text, gifStrm); gifStrm.Seek(0,soBeginning); image1.Bitmap.LoadFromStream(gifStrm); gifStrm.Seek(0,soBeginning); gifPlayer.LoadFromStream(gifStrm); gifPlayer.Play; finally gifStrm.Free; end; end; end.
{ File: TVDESK.PAS Version: 1.0 Note: Allows a full Turbo Vision desktop with a specific character pattern.} uses App, Objects, Menus; type TTutorApp = object(TApplication) procedure InitStatusLine; virtual; procedure InitMenuBar; virtual; procedure InitDesktop; virtual; end; procedure TTutorApp.InitStatusLine; { draw nothing, allow ALT-X quit } var R: TRect; begin GetExtent(R); R.A.Y := R.B.Y - 1; { below screen bottom } New(StatusLine, Init(R, NewStatusDef(0, $EFFF, StdStatusKeys(nil), nil))); end; procedure TTutorApp.InitMenuBar; { do nothing } begin end; procedure TTutorApp.InitDesktop; var R: TRect; begin GetExtent(R); { get application rectangle } { Adjust R.A.Y and R.B.Y here! } New(Desktop, Init(R)); { construct custom desktop } Desktop^.Background^.Pattern := '°'; { change pattern character } end; Var TutorApp : TTutorApp; { declare an instance of yours } begin TutorApp.Init; TutorApp.Run; TutorApp.Done; end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ***************************************************************** The following delphi code is based on Emule (0.46.2.26) Kad's implementation http://emule.sourceforge.net and KadC library http://kadc.sourceforge.net/ ***************************************************************** } { Description: DHT hashlists used by dhtthread to store published files } unit dhthashlist; interface uses dhttypes,hashlist,classes,sysutils,helper_datetime; const DB_DHTHASH_ITEMS = 1031; DB_DHTKEYFILES_ITEMS = 1031; DB_DHT_KEYWORD_ITEMS = 1031; DB_DHTHASHPARTIALSOURCES_ITEMS = 1031; DHT_EXPIRE_FILETIME = 21600;// 6 hours (seconds) DHT_EXPIRE_PARTIALSOURCES = 3600; // 1 hour procedure DHT_CheckExpireHashFileList(hslst:THashList; TimeInterval:Cardinal); procedure DHT_FreeHashFileList(Firsthash:precord_dht_hash; hslt:THashList); procedure DHT_FreeHashFile(hash:precord_dht_hash; hlst:thashList); function DHT_findhashFileSource(hash:precord_dht_hash; ip:cardinal):precord_dht_source; function DHT_FindHashFile(hslt:THashList):precord_DHT_hash; procedure DHT_CheckExpireHashFile(hash:precord_dht_hash; nowt:cardinal; timeInterval:cardinal; hlst:thashlist); procedure DHT_FreeSource(source:precord_dht_source; hash:precord_dht_hash); procedure DHT_FreeLastSource(hash:precord_dht_hash); function DHT_FindKeywordFile:precord_dht_storedfile; procedure DHT_FreeKeyWordFile(pfile:precord_dht_storedfile); procedure DHT_FreeKeywordFileList(FirstKeywordFile:precord_dht_storedfile); procedure DHT_FreeFile_Keyword(keyword: PDHTKeyword; item: PDHTKeywordItem; share:precord_dht_storedfile); procedure DHT_CheckExpireKeywordFileList; function DHT_KWList_Findkey(keyword:pchar; lenkey:byte; crc:word): PDHTKeyword; function DHT_KWList_Addkey(keyword:pchar; lenkey:byte; crc:word): PDHTKeyword; function DHT_KWList_AddShare(keyword:PDHTKeyword; share:precord_dht_storedfile): PDHTKeywordItem; var db_DHT_hashFile:ThashList; db_DHT_hashPartialSources:THashList; db_DHT_keywordFile:THashList; db_DHT_keywords:THashlist; DHT_SharedFilesCount:integer; DHT_SharedHashCount:integer; DHT_SharedPartialSourcesCount:integer; implementation uses thread_dht,windows; /////////////////////////////////////////// hash file sources ///////////////////////// procedure DHT_CheckExpireHashFileList(hslst:THashList; TimeInterval:Cardinal); var i:integer; FirstHash,nextHash:precord_dht_hash; nowt:cardinal; begin nowt:=time_now; for i:=0 to high(hslst.bkt) do begin if hslst.bkt[i]=nil then continue; FirstHash:=hslst.bkt[i]; while (FirstHash<>nil) do begin nextHash:=FirstHash^.next; DHT_CheckExpireHashFile(firstHash, nowt, TimeInterval, hslst); FirstHash:=nextHash; end; end; end; procedure DHT_CheckExpireHashFile(hash:precord_dht_hash; nowt:cardinal; timeInterval:cardinal; hlst:thashlist); var source,nextsource:precord_dht_source; begin if nowt-hash^.lastSeen>timeInterval then begin DHT_FreeHashFile(hash,hlst); exit; end; source:=Hash^.firstSource; while (source<>nil) do begin nextSource:=Source^.next; if nowt-source^.lastSeen>timeInterval then DHT_FreeSource(source,hash); source:=nextSource; end; if hash^.firstSource=nil then DHT_FreeHashFile(hash,hlst); //hash^.count=0 end; procedure DHT_FreeLastSource(hash:precord_dht_hash); var source:precord_dht_source; begin source:=Hash^.firstSource; while (source<>nil) do begin if source^.next=nil then begin DHT_FreeSource(source,hash); break; end; Source:=Source^.next; end; end; procedure DHT_FreeSource(source:precord_dht_source; hash:precord_dht_hash); begin source^.raw:=''; if source^.prev=nil then hash^.firstSource:=source^.next else source^.prev^.next:=source^.next; if source^.next<>nil then source^.next^.prev:=source^.prev; FreeMem(source,sizeof(record_dht_source)); dec(hash^.count); end; procedure DHT_FreeHashFile(hash:precord_dht_hash; hlst:ThashList); var source,nextsource:precord_dht_source; begin source:=Hash^.firstSource; while (source<>nil) do begin nextSource:=Source^.next; DHT_FreeSource(source,hash); source:=nextSource; end; if hash^.prev=nil then hlst.bkt[hash^.crc mod DB_DHTHASH_ITEMS]:=hash^.next else hash^.prev^.next:=hash^.next; if hash^.next<>nil then hash^.next^.prev:=hash^.prev; FreeMem(Hash,sizeof(recorD_dht_hash)); if hlst=db_DHT_hashFile then begin if DHT_SharedHashCount>0 then dec(DHT_SharedHashCount); end else begin if DHT_SharedPartialSourcesCount>0 then dec(DHT_SharedPartialSourcesCount); end; end; procedure DHT_FreeHashFileList(Firsthash:precord_dht_hash; hslt:THashList); var nextHash:precord_dht_hash; begin if firstHash=nil then exit; while (FirstHash<>nil) do begin nextHash:=FirstHash^.next; DHT_FreeHashFile(firstHash,hslt); FirstHash:=nextHash; end; end; function DHT_FindHashFile(hslt:THashList):precord_DHT_hash; begin if hslt.bkt[DHT_crcsha1_global mod DB_DHTHASH_ITEMS]=nil then begin result:=nil; exit; end; result:=hslt.bkt[(DHT_crcsha1_global mod DB_DHTHASH_ITEMS)]; while (result<>nil) do begin if result^.crc=DHT_crcsha1_global then if comparemem(@result^.hashValue[0],@DHT_hash_sha1_global[0],20) then exit; result:=result^.next; end; end; function DHT_findhashFileSource(hash:precord_dht_hash; ip:cardinal):precord_dht_source; begin result:=hash^.firstSource; while (result<>nil) do begin if result^.ip=ip then exit; result:=result^.next; end; end; //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////// keyword file db ////////////////////////////////////////// function DHT_FindKeywordFile:precord_dht_storedfile; begin if db_DHT_keywordFile.bkt[(DHT_crcsha1_global mod DB_DHTKEYFILES_ITEMS)]=nil then begin result:=nil; exit; end; result:=db_DHT_keywordFile.bkt[(DHT_crcsha1_global mod DB_DHTKEYFILES_ITEMS)]; while (result<>nil) do begin if result^.crc=DHT_crcsha1_global then if comparemem(@result^.hashValue[0],@DHT_hash_sha1_global[0],20) then exit; result:=result^.next; end; end; procedure DHT_FreeKeywordFileList(FirstKeywordFile:precord_dht_storedfile); var nextKeywordFile:precord_dht_storedfile; begin if firstKeyWordFile=nil then exit; while (firstKeyWordFile<>nil) do begin nextKeywordFile:=firstKeyWordFile^.next; DHT_FreeKeyWordFile(firstKeyWordFile); firstKeyWordFile:=nextKeywordFile; end; end; procedure DHT_FreeFile_Keyword(keyword: PDHTKeyword; item: PDHTKeywordItem; share:precord_dht_storedfile); procedure DHT_FreeKeyWord(keyword: PDHTKeyword); begin if db_DHT_keywords.bkt[keyword^.crc mod DB_DHT_KEYWORD_ITEMS]=nil then exit; if keyword^.prev=nil then db_DHT_keywords.bkt[keyword^.crc mod DB_DHT_KEYWORD_ITEMS]:=keyword^.next else keyword^.prev^.next:=keyword^.next; if keyword^.next<>nil then keyword^.next^.prev:=keyword^.prev; setlength(keyword^.keyword,0); FreeMem(keyword,sizeof(TDHTKeyword)); end; begin if item=nil then exit;// already cleared keyword for this item, this happens with files having duplicated keywords if item^.prev=nil then keyword^.firstitem:=item^.next else item^.prev^.next:=item^.next; if item^.next<>nil then item^.next^.prev:=item^.prev; FreeMem(item,sizeof(TDHTKeywordItem)); dec(keyword^.count); if keyword^.firstitem=nil then DHT_FreeKeyWord(keyword); end; procedure DHT_FreeKeyWordFile(pfile:precord_dht_storedfile); var i:integer; begin pfile^.info:=''; // remove file keyword items, and whole keyword if needed for i:=0 to pfile^.numkeywords-1 do DHT_FreeFile_Keyword(pfile^.keywords[i*3],pfile^.keywords[(i*3)+1],pfile); FreeMem(pfile^.keywords, pfile^.numkeywords * 3 * SizeOf(Pointer)); // detach file from list if pfile^.prev=nil then db_DHT_keywordFile.bkt[(pfile^.crc mod DB_DHTKEYFILES_ITEMS)]:=pfile^.next else pfile^.prev^.next:=pfile^.next; if pfile^.next<>nil then pfile^.next^.prev:=pfile^.prev; FreeMem(pfile,sizeof(record_dht_storedfile)); if DHT_SharedFilesCount>0 then dec(DHT_SharedFilesCount); end; procedure DHT_CheckExpireKeywordFileList; // once every 60 minutes var i:integer; FirstKeywordFile,nextKeywordFile:precord_dht_storedfile; nowt:cardinal; begin nowt:=time_now; for i:=0 to high(db_DHT_keywordFile.bkt) do begin if db_DHT_keywordFile.bkt[i]=nil then continue; FirstKeywordFile:=db_DHT_keywordFile.bkt[i]; while (FirstKeywordFile<>nil) do begin nextKeywordFile:=FirstKeywordFile^.next; if nowt-FirstKeywordFile^.lastSeen>DHT_EXPIRE_FILETIME then DHT_FreeKeyWordFile(FirstKeywordFile) else begin if FirstKeywordFile^.count>30 then FirstKeywordFile^.count:=30; end; FirstKeywordFile:=nextKeywordFile; end; end; end; /////////////////////////////////////////////////////////////////////////////7 /////////////////////////7 KEYWORDS ///////////////////////////////////////// function DHT_KWList_Findkey(keyword:pchar; lenkey:byte; crc:word): PDHTKeyword; begin if db_DHT_keywords.bkt[(crc mod DB_DHT_KEYWORD_ITEMS)]=nil then begin result:=nil; exit; end; result:=db_DHT_keywords.bkt[(crc mod DB_DHT_KEYWORD_ITEMS)]; while (result<>nil) do begin if length(result^.keyword)=lenkey then if comparemem(@result^.keyword[0],keyword,lenkey) then exit; result:=result^.next; end; end; function writestringfrombuffer(buff:pointer; len:integer):string; begin setlength(result,len); move(buff^,result[1],len); end; function DHT_KWList_Addkey(keyword:pchar; lenkey:byte; crc:word): PDHTKeyword; var first:PDHTKeyword; begin result:=AllocMem(sizeof(TDHTKeyword)); setlength(result^.keyword,lenkey); move(keyword^,result^.keyword[0],lenkey); result^.firstitem:=nil; result^.count:=0; result^.crc:=crc; first:=db_DHT_keywords.bkt[(crc mod DB_DHT_KEYWORD_ITEMS)]; result^.next:=first; if first<>nil then first^.prev:=result; result^.prev:=nil; db_DHT_keywords.bkt[(crc mod DB_DHT_KEYWORD_ITEMS)]:=result; end; function DHT_KWList_AddShare(keyword:PDHTKeyword; share:precord_dht_storedfile): PDHTKeywordItem; function DHT_KWList_ShareExists(keyword:PDHTKeyword; share:precord_DHT_storedfile):boolean; begin if keyword^.firstitem=nil then begin result:=false; exit; end; result:=(keyword^.firstItem^.share=share); // can be only the first item end; begin //we seen already this keyword for this file, eg keyword contained in both title and artist field, //the first keyword instance gets a valid 'item' pointer, the second one a nil pointer... if DHT_KWList_ShareExists(keyword,share) then begin result:=nil; exit; end; result:=AllocMem(sizeof(TDHTKeywordItem)); result^.next:=keyword^.firstitem; if keyword^.firstitem<>nil then keyword^.firstitem^.prev:=result; result^.prev:=nil; keyword^.firstitem:=result; result^.share:=share; inc(keyword^.count); end; end.
unit UServiceDelphi; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs; type TsrvPrincipal = class(TService) procedure ServiceAfterInstall(Sender: TService); procedure ServiceAfterUninstall(Sender: TService); procedure ServiceBeforeInstall(Sender: TService); procedure ServiceBeforeUninstall(Sender: TService); procedure ServiceContinue(Sender: TService; var Continued: Boolean); procedure ServiceCreate(Sender: TObject); procedure ServiceDestroy(Sender: TObject); procedure ServiceExecute(Sender: TService); procedure ServicePause(Sender: TService; var Paused: Boolean); procedure ServiceShutdown(Sender: TService); procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); private public function GetServiceController: TServiceController; override; end; var srvPrincipal: TsrvPrincipal; implementation {$R *.DFM} procedure doSaveLog(Msg: String); var loLista: Tstringlist; begin try loLista := Tstringlist.create; try if FileExists('c:\log.log') then loLista.LoadFromFile('c:\log.log'); loLista.add(TimeToStr(now) + ': ' + Msg); except on E: Exception do loLista.add(TimeToStr(now) + ': erro ' + E.Message); end; finally loLista.SaveToFile('c:\log.log'); loLista.free; end; end; procedure ServiceController(CtrlCode: DWord); stdcall; begin srvPrincipal.Controller(CtrlCode); end; function TsrvPrincipal.GetServiceController: TServiceController; begin Result := ServiceController; end; procedure TsrvPrincipal.ServiceAfterInstall(Sender: TService); begin doSaveLog('ServiceAfterInstall'); end; procedure TsrvPrincipal.ServiceAfterUninstall(Sender: TService); begin doSaveLog('ServiceAfterUninstall'); end; procedure TsrvPrincipal.ServiceBeforeInstall(Sender: TService); begin doSaveLog('ServiceBeforeInstall'); end; procedure TsrvPrincipal.ServiceBeforeUninstall(Sender: TService); begin doSaveLog('ServiceBeforeUninstall'); end; procedure TsrvPrincipal.ServiceContinue(Sender: TService; var Continued: Boolean); begin doSaveLog('ServiceContinue'); end; procedure TsrvPrincipal.ServiceCreate(Sender: TObject); begin doSaveLog('ServiceCreate'); end; procedure TsrvPrincipal.ServiceDestroy(Sender: TObject); begin doSaveLog('ServiceDestroy'); end; procedure TsrvPrincipal.ServiceExecute(Sender: TService); begin doSaveLog('ServiceExecute'); while not self.Terminated do ServiceThread.ProcessRequests(true); end; procedure TsrvPrincipal.ServicePause(Sender: TService; var Paused: Boolean); begin doSaveLog('ServicePause'); end; procedure TsrvPrincipal.ServiceShutdown(Sender: TService); begin doSaveLog('ServiceShutdown'); end; procedure TsrvPrincipal.ServiceStart(Sender: TService; var Started: Boolean); begin doSaveLog('ServiceStart'); end; procedure TsrvPrincipal.ServiceStop(Sender: TService; var Stopped: Boolean); begin doSaveLog('ServiceStop'); end; // Leia mais em: Criando um Windows Service http://www.devmedia.com.br/criando-um-windows-service/7867#ixzz1wyo1XkDh end.
{ Add XESP (parent enable) element to the references of specific base object. Apply to references (or cell(s)/worldspace(s) they are in). } unit AddXESP; const sBaseObject = 'CommonChair01FL "Chair" [FURN:0006E7A6]'; // base object for references to add parent sParent = '000E52E4'; // parent object sRefSignatures = 'REFR,ACHR,PGRE,PMIS,PHZD,PARW,PBAR,PBEA,PCON,PFLA'; function Process(e: IInterface): integer; begin if Pos(Signature(e), sRefSignatures) = 0 then Exit; if GetIsDeleted(e) then Exit; if not SameText(GetElementEditValues(e, 'NAME'), sBaseObject) then Exit; if ElementExists(e, 'XESP') then AddMessage('Parent already exists on ' + Name(e)) else begin Add(e, 'XESP', True); SetElementEditValues(e, 'XESP\Reference', sParent); end; end; end.
procedure CreateFrmWait(var frmWait : TForm); Var lblWait : Tlabel; begin frmWait := TForm.Create(nil); frmWait.Width := 300; frmWait.Height := 200; frmWait.Position := poDesktopCenter; frmWait.Caption := 'Загрузка данных'; lblWait := TLabel.Create(frmWait); lblWait.Parent := frmWait; lblWait.Name := 'lblWait'; lblWait.WordWrap := true; lblWait.Autosize := false; lblWait.top := 15; lblWait.Left := 15; lblWait.Width := frmWait.Width - 30; lblWait.Height := frmWait.Height - 100; lblWait.Visible := true; frmWait.Show; end; procedure FreeFrmWait(frmWait : TForm); begin frmWait.lblWait.Free; frmWait.Free; end; procedure UpdateFrmWaitStatus(frmWait : TForm; sStatus : String); begin frmWait.lblWait.Caption := sStatus; Application.ProcessMessages; end; function ParusLoad(nLoad : Integer, sFile : String); begin StoredProc.StoredProcName := 'PP_SBER_LOADACC'; StoredProc.Prepare; StoredProc.ParamByName('NLOAD').Value := nLoad; StoredProc.ParamByName('SFILE').Value := sFile; StoredProc.ExecProc; Result := StoredProc.ParamByName('SOUT').AsString; end; procedure LoadFromExcel; Const xlCellTypeLastCell = 11; ofAllowMultiSelect = 64; ofFileMustExist = 512; Var OD : TOpenDialog; xl, xlsheet : Variant; iRows, iCols, i, j, iFile : Integer; sSQL : String; si : String; frmWait : TForm; v : String; begin OD := TOpenDialog.Create(nil); OD.Filter := 'Файлы Excel (*.xls)|*.xls'; OD.Options := ofAllowMultiSelect + ofFileMustExist; if (not(OD.Execute)) then begin OD.Free; exit; end; CreateFrmWait(frmWait); xl := CreateOleObject('Excel.Application'); Query.SQL.Text := 'delete from t_s_excel where authid = user'; Query.Execute; Query.SQL.Clear; for iFile := 0 to OD.Files.Count - 1 do begin UpdateFrmWaitStatus(frmWait, 'Открываю файл: ' + OD.Files.Strings[iFile]); xl.Workbooks.Add(OD.Files.Strings[iFile]); iRows := xl.Selection.SpecialCells(xlCellTypeLastCell).Row; iCols := xl.Selection.SpecialCells(xlCellTypeLastCell).Column; UpdateFrmWaitStatus(frmWait, 'Открываю файл: ' + OD.Files.Strings[iFile] + #13#10 + 'Найдено: ' + IntToStr(iRows) + ' строк и ' + IntToStr(iCols) + ' столбцов'); for j := 1 to iRows do begin sSQL := 'insert into t_s_excel(authid, n, sfile'; for i := 1 to iCols do begin sSQL := sSQL + ', d' + trim(IntToStr(i)); end; sSQL := sSQL + ') values(user, ' + IntToStr(j) + ', ''' + OD.Files.Strings[iFile] + ''''; for i := 1 to iCols do begin v := VarToStr(xl.Cells(j,i).Value); if v <> '' then sSQL := sSQL + ', ''' + v + '''' else sSQL := sSQL + ', null'; end; sSQL := sSQL + ')'; Query.SQL.Text := sSQL; try Query.Execute; except ShowMessage('ОШИБКА: ' + #13#10 + sSQL); raise; exit; end; if j mod 25 = 0 then begin UpdateFrmWaitStatus(frmWait, 'Загружаю: ' + OD.Files.Strings[iFile] + #13#10 + 'Загружено: ' + IntToStr(j / iRows * 100) + '%'); end; xl.Cells(j,8).Value := ParusLoad(j, OD.Files.Strings[iFile]); if j = 1 then xl.Columns('H:H').ColumnWidth := 50; end; end; // iFile OD.Free; xl.Visible := true; FreeFrmWait(frmWait); ShowMessage('Результаты загрузки в Excel - файле'); end;
{ ID: a_zaky01 PROG: milk LANG: PASCAL } var total,n,i,money:longint; price,milk:array[1..5000] of longint; fin,fout:text; procedure sort(l,r:longint); var i,j,x,temp:longint; begin i:=l; j:=r; x:=price[(l+r) div 2]; repeat while price[i]<x do inc(i); while price[j]>x do dec(j); if not(i>j) then begin temp:=price[i]; price[i]:=price[j]; price[j]:=temp; temp:=milk[i]; milk[i]:=milk[j]; milk[j]:=temp; inc(i); dec(j); end; until i>j; if l<j then sort(l,j); if i<r then sort(i,r); end; begin assign(fin,'milk.in'); assign(fout,'milk.out'); reset(fin); rewrite(fout); readln(fin,total,n); for i:=1 to n do readln(fin,price[i],milk[i]); sort(1,n); i:=1; money:=0; while total>0 do begin if total>=milk[i] then begin total:=total-milk[i]; money:=money+(milk[i]*price[i]); end else begin money:=money+(total*price[i]); total:=0; end; inc(i); end; writeln(fout,money); close(fin); close(fout); end.
{$J+} {Writable constants} unit Extbl10u; interface uses WinProcs, WinTypes, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OvcTCEdt, OvcTCmmn, OvcTCell, OvcTCStr, OvcTCHdr, OvcBase, OvcTable, Buttons, StdCtrls; const BITMAP_1 = 10001; BITMAP_2 = 10002; type MyArrayRecord = record S1 : string[10]; S2 : string[10]; end; TForm1 = class(TForm) OvcTable1: TOvcTable; OvcController1: TOvcController; OvcTCColHead1: TOvcTCColHead; OvcTCString1: TOvcTCString; OvcTCString2: TOvcTCString; procedure FormCreate(Sender: TObject); procedure OvcTable1GetCellData(Sender: TObject; RowNum: Longint; ColNum: Integer; var Data: Pointer; Purpose: TOvcCellDataPurpose); procedure OvcTCColHead1OwnerDraw(Sender: TObject; TableCanvas: TCanvas; const CellRect: TRect; RowNum: Longint; ColNum: Integer; const CellAttr: TOvcCellAttributes; Data: Pointer; var DoneIt: Boolean); procedure OvcTable1LockedCellClick(Sender: TObject; RowNum: Longint; ColNum: Integer); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OvcTable1ActiveCellMoving(Sender: TObject; Command: Word; var RowNum: Longint; var ColNum: Integer); procedure OvcTable1ActiveCellChanged(Sender: TObject; RowNum: Longint; ColNum: Integer); private { Private declarations } public { Public declarations } MyArray : array[1..9] of MyArrayRecord; Col1Down, Col2Down : Boolean; SortCol : TColNum; InactiveBMP, ActiveBMP : TBitmap; procedure SortRecords(Col : Integer); end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); var I, J : integer; begin Randomize; for I := 1 to 9 do begin MyArray[I].S1[0] := Chr(10); MyArray[I].S2[0] := Chr(10); for J := 1 to 10 do begin MyArray[I].S1[J] := Chr(Ord('A') + Random(26)); MyArray[I].S2[J] := Chr(Ord('A') + Random(26)); end; end; Col1Down := False; Col2Down := False; InactiveBMP := TBitmap.Create; ActiveBMP := TBitmap.Create; {$IFDEF WIN32} InactiveBMP.LoadFromResourceID(HInstance, BITMAP_1); ActiveBMP.LoadFromResourceID(HInstance, BITMAP_2); {$ELSE} InactiveBMP.Handle := LoadBitmap(HInstance, MAKEINTRESOURCE(BITMAP_1)); ActiveBMP.Handle := LoadBitmap(HInstance, MAKEINTRESOURCE(BITMAP_2)); {$ENDIF} end; procedure TForm1.OvcTable1GetCellData(Sender: TObject; RowNum: Longint; ColNum: Integer; var Data: Pointer; Purpose: TOvcCellDataPurpose); begin Data := nil; if (RowNum > 0) and (RowNum <= High(MyArray)) then begin case ColNum of 1 : Data := @MyArray[RowNum].S1; 2 : Data := @MyArray[RowNum].S2; end; end; end; procedure TForm1.OvcTCColHead1OwnerDraw(Sender: TObject; TableCanvas: TCanvas; const CellRect: TRect; RowNum: Longint; ColNum: Integer; const CellAttr: TOvcCellAttributes; Data: Pointer; var DoneIt: Boolean); var DRect : TRect; SRect : TRect; begin if RowNum = 0 then begin TableCanvas.Font.Color := clBlack; DRect := Rect(CellRect.Right-24, CellRect.Top+4, CellRect.Right-8, CellRect.Top+20); SRect := Rect(0,0,16,16); case ColNum of 0 : DrawButtonFace(TableCanvas, CellRect, 2, bsAutoDetect, False, False, False); 1 : begin DrawButtonFace(TableCanvas, CellRect, 2, bsAutoDetect, False, Col1Down, False); if Col1Down then begin TableCanvas.TextOut(CellRect.Left+10, CellRect.Top+10, 'Active'); TableCanvas.BrushCopy(DRect, ActiveBMP, SRect, clSilver); end else begin TableCanvas.TextOut(CellRect.Left+10, CellRect.Top+10, 'Inactive'); TableCanvas.BrushCopy(DRect, InactiveBMP, SRect, clSilver); end; end; 2 : begin DrawButtonFace(TableCanvas, CellRect, 2, bsAutoDetect, False, Col2Down, False); if Col2Down then begin TableCanvas.TextOut(CellRect.Left+10, CellRect.Top+10, 'Active'); TableCanvas.BrushCopy(DRect, ActiveBMP, SRect, clSilver); end else begin TableCanvas.TextOut(CellRect.Left+10, CellRect.Top+10, 'Inactive'); TableCanvas.BrushCopy(DRect, InactiveBMP, SRect, clSilver); end; end; end; DoneIt := True; end; end; procedure TForm1.OvcTable1LockedCellClick(Sender: TObject; RowNum: Longint; ColNum: Integer); begin if (RowNum <> 0) then Exit; Col1Down := ColNum = 1; Col2Down := ColNum = 2; with OvcTable1 do begin AllowRedraw := False; if Col1Down then SortRecords(1) else SortRecords(2); if Col1Down then TOvcTCString(Columns[1].DefaultCell).Color := clRed else TOvcTCString(Columns[1].DefaultCell).Color := clSilver; if Col2Down then TOvcTCString(Columns[2].DefaultCell).Color := clRed else TOvcTCString(Columns[2].DefaultCell).Color := clSilver; InvalidateTable; AllowRedraw := True; end; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(InactiveBMP) then InactiveBMP.Free; if Assigned(ActiveBMP) then ActiveBMP.Free; end; procedure TForm1.SortRecords(Col : Integer); var I, J : Integer; TR : MyArrayRecord; begin for I := 1 to High(MyArray)-1 do begin for J := I+1 to High(MyArray) do begin if (Col = 1) then begin if CompareText(MyArray[J].S1, MyArray[I].S1) < 0 then begin TR := MyArray[I]; MyArray[I] := MyArray[J]; MyArray[J] := TR; end; end else begin if CompareText(MyArray[J].S2, MyArray[I].S2) < 0 then begin TR := MyArray[I]; MyArray[I] := MyArray[J]; MyArray[J] := TR; end; end; end; end; end; procedure TForm1.OvcTable1ActiveCellMoving(Sender: TObject; Command: Word; var RowNum: Longint; var ColNum: Integer); begin SortCol := OvcTable1.ActiveCol; end; procedure TForm1.OvcTable1ActiveCellChanged(Sender: TObject; RowNum: Longint; ColNum: Integer); begin with OvcTable1 do begin AllowRedraw := False; try SortRecords(SortCol); InvalidateTable; finally AllowRedraw := True; end; end; end; end.
UNIT DateIO1; INTERFACE TYPE Month = (NoMonth, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC); PROCEDURE WriteMonth(VAR FOut: TEXT; VAR Mo: Month); IMPLEMENTATION PROCEDURE WriteMonth(VAR FOut: TEXT; VAR Mo: Month); BEGIN {WriteMonth} IF Mo = JAN THEN WRITE(FOut, 'JAN') ELSE IF Mo = FEB THEN WRITE(FOut, 'FEB') ELSE IF Mo = MAR THEN WRITE(FOut, 'MAR') ELSE IF Mo = APR THEN WRITE(FOut, 'APR') ELSE IF Mo = MAY THEN WRITE(FOut, 'MAY') ELSE IF Mo = JUN THEN WRITE(FOut, 'JUN') ELSE IF Mo = JUL THEN WRITE(FOut, 'JUL') ELSE IF Mo = AUG THEN WRITE(FOut, 'AUG') ELSE IF Mo = SEP THEN WRITE(FOut, 'SEP') ELSE IF Mo = OCT THEN WRITE(FOut, 'OCT') ELSE IF Mo = NOV THEN WRITE(FOut, 'NOV') ELSE IF Mo = DEC THEN WRITE(FOut, 'DEC') ELSE WRITE(FOut, 'NoMonth') END;{WriteMonth} BEGIN END.
(************************************* Ext2D Engine *************************************) (* Модуль : E2DPhysic.pas *) (* Автор : Есин Владимир *) (* Создан : 27.08.06 *) (* Информация : Модуль содежит функции для орпеделения столкновений. *) (* Изменения : нет изменений. *) (****************************************************************************************) unit E2DPhysic; interface uses E2DTypes, Windows; { Функция для определения столкновения. Параметры : Image1ID, Image2ID : идентификаторы изображений, для обьектов которых необходимо определить столкновение; Place1, Place2 : место расположения изображения на экране; Collision : переменная для сохранения результата столкновения. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_GetCollision(Image1ID, Image2ID : E2D_TImageID; ImageRect1, ImageRect2 : PRect; Place1, Place2 : PPoint; var Collision : Boolean) : E2D_Result; stdcall; export; implementation uses E2DConsts, { Для констант ошибок и экрана } E2DVars; { Для изображений } function E2D_GetCollision; var ir : TRect; { Прямоугольник пересечения на экране } sr1, sr2 : TRect; { Прямоугольники на экране } ir1, ir2 : TRect; { Прямоугольники пересечения } cv1, cv2 : E2D_TColor; { Цвета пикселов } i, j : Longword; { Счетчики цикла } ofs1, ofs2 : Longword; { Смещения адресов } label OnOK; { Завершение функции } begin { E2D_GetCollision } // Устанавливаем столкновение. Collision := False; // Проверяем идентификаторы изображений. if (Image1ID >= NumImages) or (Image2ID >= NumImages) then begin { if } // Если не получилось помещаем код ошибки в результат Result := E2DERR_SYSTEM_INVALIDID; // и выходим из функции. Exit; end; { if } try // Пытаемся вычислить прямоугольники на экране для первого SetRect(sr1, Place1^.X, Place1^.Y, Place1^.X + ImageRect1^.Right - ImageRect1^.Left, Place1^.Y + ImageRect1^.Bottom - ImageRect1^.Top); // и второго изображений SetRect(sr2, Place2^.X, Place2^.Y, Place2^.X + ImageRect2^.Right - ImageRect2^.Left, Place2^.Y + ImageRect2^.Bottom - ImageRect2^.Top); // и пересечь прямоугольники на экране. IntersectRect(ir, sr1, sr2); except // Если не получилось помещаем код ошибки в результат Result := E2DERR_SYSTEM_INVPOINTER; // и выходим из функции. Exit; end; { try } // Проверяем пересечение. if (ir.Left = 0) and (ir.Right = 0) and (ir.Top = 0) and (ir.Bottom = 0) then // Если пересечения нет завершаем функцию. goto OnOK; // Запоминаем прямоугольники пересечения для первого ir1 := ir; // и второго обьекта. ir2 := ir; // Сдвигаем прямоугольники для первого OffsetRect(ir1, -Place1^.X, -Place1^.Y); // и второго обьекта. OffsetRect(ir2, -Place2^.X, -Place2^.Y); {$WARNINGS OFF} // Вычисляем базовые смещения для первого ofs1 := Longword(Images[Image1ID].Data) + (ImageRect1^.Top + ir1.Top) * E2D_SCREEN_BYTESPP * Images[Image1ID].Info.Width; // и второго обьектов. ofs2 := Longword(Images[Image2ID].Data) + (ImageRect2^.Top + ir2.Top) * E2D_SCREEN_BYTESPP * Images[Image2ID].Info.Width; // Пытаемся проверить значения пикселов в прямоугольнике. for j := 0 to ir.Bottom - ir.Top - 1 do begin { for } // Вычисляем новые смещения для первого ofs1 := ofs1 + (ImageRect1^.Left + ir1.Left) * E2D_SCREEN_BYTESPP; // и второго обьектов. ofs2 := ofs2 + (ImageRect2^.Left + ir2.Left) * E2D_SCREEN_BYTESPP; // Проверяем значения пикселов в прямоугольнике. for i := 0 to ir.Right - ir.Left - 1 do begin { for } // Получаем пикселы для первого cv1 := E2D_PColor(ofs1)^; // и второго обьектов. cv2 := E2D_PColor(ofs2)^; // Сравниваем значения пикселов. if (cv1 <> E2D_SCREEN_COLORKEY) and (cv2 <> E2D_SCREEN_COLORKEY) then begin { if } // Если они оба отличны от цвета фона устанавливаем столкновение Collision := True; // и выходим из цикла. goto OnOK; end; { if } // Увеличиваем смещения порвого ofs1 := ofs1 + E2D_SCREEN_BYTESPP; // и второго обьектов. ofs2 := ofs2 + E2D_SCREEN_BYTESPP; end; { for } // Вычисляем новые смещения для первого ofs1 := ofs1 + (ImageRect1^.Right - ir1.Right + Images[Image1ID].Info.Width - ImageRect1^.Right) * E2D_SCREEN_BYTESPP; // и второго обьектов. ofs2 := ofs2 + (ImageRect2^.Right - ir2.Right + Images[Image2ID].Info.Width - ImageRect2^.Right) * E2D_SCREEN_BYTESPP; {$WARNINGS ON} end; { for } OnOK : // Делаем результат успешным. Result := E2DERR_OK; end; { E2D_GetCollision } end.
(*======================================================================* | cmpFakeCombobox | | | | Fake a combobox, providing additional capabilities. | | | | Version Date By Description | | ------- ---------- ---- ------------------------------------------| | 1.0 31/05/2001 CPWW Original | *======================================================================*) unit cmpFakeCombobox; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; const WM_HIDELIST = WM_USER + $201; type TFakeCombobox = class(TCustomControl) private fButtonPressed: Boolean; fOnKeyDown: TKeyEvent; fSpecialButton: Boolean; fOnSpecialButtonClick: TNotifyEvent; function GetDropdownButtonWidth: Integer; function GetButtonRect: TRect; procedure SetButtonPressed(const Value: Boolean); function GetOnDblClick: TNotifyEvent; procedure SetOnDblClick(const Value : TNotifyEvent); procedure StringListOnChange (Sender : TObject); procedure SetSpecialButton(const Value: Boolean); private fEdit : TEdit; fItems : TStrings; fListBox : TListBox; function GetAutoSelect: Boolean; procedure SetAutoSelect(const Value: Boolean); function GetCharCase: TEditCharCase; procedure SetCharCase(const Value: TEditCharCase); function GetCursor: TCursor; procedure SetCursor(const Value: TCursor); function GetHideSelection: Boolean; procedure SetHideSelection(const Value: Boolean); function GetMaxLength: Integer; function GetOEMConvert: boolean; procedure SetMaxLength(const Value: Integer); procedure SetOEMConvert(const Value: boolean); function GetPAsswordChar: char; procedure SetPasswordChar(const Value: char); function GetText: string; procedure SetText(const Value: string); function GetReadOnly: Boolean; procedure SetReadOnly(const Value: Boolean); procedure SetItems(const Value: TStrings); procedure DoOnListboxMouseDown (Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DoOnListboxKeyDown (Sender : TObject; var Key: Word; Shift: TShiftState); procedure DoOnEditKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState); procedure DoOnListBoxExit (Sender : TObject); procedure ShowList (show, update : Boolean); procedure WmHideList (var Msg : TMessage); message WM_HIDELIST; property DropdownButtonWidth : Integer read GetDropdownButtonWidth; property ButtonRect : TRect read GetButtonRect; property ButtonPressed : Boolean read fButtonPressed write SetButtonPressed; { Private declarations } protected procedure Paint; override; procedure Resize; override; procedure Loaded; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState;X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; { Protected declarations } public constructor Create (AOwner : TComponent); override; destructor Destroy; override; procedure SetFocus; override; function Focused : Boolean; override; { Public declarations } published property Anchors; property AutoSelect : Boolean read GetAutoSelect write SetAutoSelect; property BiDiMode; property CharCase : TEditCharCase read GetCharCase write SetCharCase; property Color default clWhite; property Constraints; property Cursor : TCursor read GetCursor write SetCursor; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HelpContext; property HideSelection : Boolean read GetHideSelection write SetHideSelection; property Items : TStrings read fItems write SetItems; property MaxLength : Integer read GetMaxLength write SetMaxLength; property OEMConvert : boolean read GetOEMConvert write SetOEMConvert; property PasswordChar : char read GetPAsswordChar write SetPasswordChar; property PopupMenu; property ReadOnly : Boolean read GetReadOnly write SetReadOnly; property ShowHint; property SpecialButton : Boolean read fSpecialButton write SetSpecialButton; property TabOrder; property TabStop default True; property Text : string read GetText write SetText; property Visible; property OnEnter; property OnExit; property OnDblClick : TNotifyEvent read GetOnDblClick write SetOnDblClick; property OnKeyDown : TKeyEvent read fOnKeyDown write fOnKeyDown; property OnSpecialButtonClick : TNotifyEvent read fOnSpecialButtonClick write fOnSpecialButtonClick; { Published declarations } end; implementation { TFakeCombobox } constructor TFakeCombobox.Create(AOwner: TComponent); begin inherited; Width := 145; Height := 21; Color := clWhite; ControlStyle := [csFramed, csOpaque]; TabStop := True; fItems := TStringList.Create; TStringList (fItems).OnChange := StringListOnChange; fEdit := TEdit.Create (self); fEdit.Parent := Self; fEdit.Ctl3D := False; fEdit.BorderStyle := bsNone; fEdit.Left := 2; fEdit.Top := 2; fEdit.ParentBiDiMode := True; fEdit.ParentColor := True; fEdit.ParentFont := True; fEdit.ParentShowHint := True; fEdit.OnKeyDown := DoOnEditKeyDown; end; destructor TFakeCombobox.Destroy; begin fItems.Free; inherited end; procedure TFakeCombobox.DoOnListBoxExit(Sender: TObject); begin ShowList (False, False); end; procedure TFakeCombobox.DoOnListboxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin PostMessage (Handle, WM_HIDELIST, 1, 0); end; procedure TFakeCombobox.DoOnListBoxKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_RETURN then PostMessage (Handle, WM_HIDELIST, 1, 0) else if (Key = VK_ESCAPE) or (Key = VK_PRIOR) then PostMessage (Handle, WM_HIDELIST, 0, 0) end; function TFakeCombobox.Focused: Boolean; begin Result := fEdit.Focused end; function TFakeCombobox.GetAutoSelect: Boolean; begin Result := fEdit.AutoSelect; end; function TFakeCombobox.GetButtonRect: TRect; begin result := ClientRect; Dec (result.Right); result.Top := result.Top + 1; result.Bottom := result.Bottom - 1; result.Left := result.Right - DropdownButtonWidth; end; function TFakeCombobox.GetCharCase: TEditCharCase; begin Result := fEdit.CharCase; end; function TFakeCombobox.GetCursor: TCursor; begin Result := fEdit.Cursor end; function TFakeCombobox.GetDropdownButtonWidth: Integer; begin if SpecialButton then Result := 17 else if Items.Count > 0 then Result := 13 else Result := 0 end; function TFakeCombobox.GetHideSelection: Boolean; begin Result := fEdit.HideSelection end; function TFakeCombobox.GetMaxLength: Integer; begin Result := fEdit.MaxLength end; function TFakeCombobox.GetOEMConvert: boolean; begin Result := fEdit.OEMConvert end; function TFakeCombobox.GetOnDblClick: TNotifyEvent; begin Result := fEdit.OnDblClick end; function TFakeCombobox.GetPasswordChar: char; begin Result := fEdit.PasswordChar end; function TFakeCombobox.GetReadOnly: Boolean; begin Result := fEdit.ReadOnly end; function TFakeCombobox.GetText: string; begin Result := fEdit.Text end; procedure TFakeCombobox.Loaded; begin inherited; Resize end; procedure TFakeCombobox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; SetFocus; if ((Items.Count > 0) or SpecialButton) then if PtInRect (ButtonRect, Point (X, Y)) then begin ButtonPressed := True; if not SpecialButton then ShowList (True, False) else if Assigned (OnSpecialButtonClick) then OnSpecialButtonClick (Self); end end; procedure TFakeCombobox.MouseMove(Shift: TShiftState; X, Y: Integer); begin if not PtInRect (ButtonRect, Point (X, Y)) then ButtonPressed := False else if ssLeft in Shift then ButtonPressed := True end; procedure TFakeCombobox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ButtonPressed := False end; procedure TFakeCombobox.Paint; var r : TRect; Style : Integer; oldMode : Integer; begin inherited; r := ClientRect; Frame3d (Canvas, r, clBlack, clBtnFace, 1); Frame3d (Canvas, r, clWhite, clWhite, 1); if SpecialButton then begin r := ButtonRect; Style := DFCS_BUTTONPUSH; if ButtonPressed then Style := Style or DFCS_PUSHED; DrawFrameControl (Canvas.Handle, r, DFC_BUTTON, Style); oldMode := SetBkMode (Canvas.Handle, TRANSPARENT); OffsetRect (r, 0, -4); DrawText (Canvas.Handle, '...', 3, r, DT_CENTER or DT_VCENTER or DT_SINGLELINE); SetBkMode (Canvas.Handle, oldMode); end else if Items.Count > 0 then begin r := ButtonRect; Style := DFCS_SCROLLCOMBOBOX; if ButtonPressed then Style := Style or DFCS_PUSHED; DrawFrameControl (Canvas.Handle, r, DFC_SCROLL, Style); end end; procedure TFakeCombobox.Resize; begin inherited; fEdit.Height := ClientHeight - 4; fEdit.Width := ClientWidth - 4 - DropdownButtonWidth end; procedure TFakeCombobox.SetAutoSelect(const Value: Boolean); begin fEdit.AutoSelect := Value end; procedure TFakeCombobox.SetButtonPressed(const Value: Boolean); begin if fButtonPressed <> Value then begin if Value then SetCapture (Handle) else ReleaseCapture; fButtonPressed := Value; Invalidate end end; procedure TFakeCombobox.SetCharCase(const Value: TEditCharCase); begin fEdit.CharCase := value end; procedure TFakeCombobox.SetCursor(const Value: TCursor); begin fEdit.Cursor := Value end; procedure TFakeCombobox.SetFocus; begin fEdit.SetFocus end; procedure TFakeCombobox.SetHideSelection(const Value: Boolean); begin fEdit.HideSelection := Value end; procedure TFakeCombobox.SetItems(const Value: TStrings); var oldCount : Integer; begin oldCount := Items.Count; fItems.Assign (Value); if (oldCount = 0) <> (fItems.Count = 0) then begin Resize; Invalidate end end; procedure TFakeCombobox.SetMaxLength(const Value: Integer); begin fEdit.MaxLength := Value end; procedure TFakeCombobox.SetOEMConvert(const Value: boolean); begin fEdit.OEMConvert := value end; procedure TFakeCombobox.SetOnDblClick(const Value : TNotifyEvent); begin fEdit.OnDblClick := Value end; procedure TFakeCombobox.SetPasswordChar(const Value: char); begin fEdit.PasswordChar := Value end; procedure TFakeCombobox.SetReadOnly(const Value: Boolean); begin fEdit.ReadOnly := Value end; procedure TFakeCombobox.SetText(const Value: string); begin fEdit.Text := value end; procedure TFakeCombobox.ShowList(show, update: Boolean); var i : Integer; begin if Show then begin if not Assigned (fListBox) then begin fListBox := TListBox.Create (Self); fListBox.Parent := Parent; fListBox.Top := Top + ClientHeight - 2; fListBox.Left := Left - 1; fListBox.Width := ClientWidth + 1; fListBox.OnExit := DoOnListboxExit; fListBox.OnKeyDown := DoOnListBoxKeyDown; fListBox.OnMouseDown := DoOnListboxMouseDown; end else fListBox.Clear; if fItems.Count > 6 then i := 6 else i := fItems.Count; fListBox.ItemHeight := ClientHeight; fListBox.Height := ClientHeight * i; fListBox.Items.AddStrings (fItems); fListBox.ItemIndex := fItems.IndexOf (fEdit.Text); Application.ProcessMessages; fListBox.SetFocus end else begin if (fListBox.ItemIndex >= 0) and (fListBox.ItemIndex < fItems.Count) and Update then fEdit.Text := fListBox.Items [fListBox.ItemIndex]; FreeAndNil (fListBox); if Assigned (OnExit) and Update then OnExit (Self); SetFocus end end; procedure TFakeCombobox.StringListOnChange(Sender: TObject); begin if Items.Count in [0..1] then Resize end; procedure TFakeCombobox.WmHideList(var Msg: TMessage); begin ShowList (False, Boolean (Msg.wParam)); end; procedure TFakeCombobox.DoOnEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = VK_NEXT then begin if Items.Count > 0 then ShowList (True, False) else if SpecialButton and Assigned (OnSpecialButtonClick) then OnSpecialButtonClick (Self); end else if Assigned (fOnKeyDown) then fOnKeyDown (Self, key, shift); end; procedure TFakeCombobox.SetSpecialButton(const Value: Boolean); begin if Value <> fSpecialButton then begin fSpecialButton := Value; Resize; invalidate end end; end.
(* * Copyright (c) 2008-2009, Ciobanu Alexandru * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$I ../Library/src/DeHL.Defines.inc} unit Tests.Tree; interface uses SysUtils, Tests.Utils, TestFramework, DeHL.Types, DeHL.Exceptions, DeHL.Collections.Tree, DeHL.Collections.Base, DeHL.Collections.List, DeHL.Arrays; type TTestTree = class(TDeHLTestCase) published procedure Test_Create_Value; procedure Test_Create_Tree; procedure Test_Create_Type_Value; procedure Test_Create_Type_Tree; procedure Test_Add; procedure Test_Clear; procedure Test_Remove; procedure Test_Contains; procedure Test_Find; procedure Test_Count; procedure Test_Root; procedure Test_CopyTo; procedure Test_Empty; procedure Test_Enumerator; end; implementation { TTestTree } procedure TTestTree.Test_Add; var LTree, LTree2: TTree<Integer>; begin LTree := TTree<Integer>.Create(0); LTree2 := TTree<Integer>.Create(0); LTree.Add(LTree.Root, 1); LTree.Add(LTree.Root, 2); LTree.Add(LTree.Root.Children.First, 3); CheckEquals(1, LTree.Root.Children.First.Value); CheckEquals(2, LTree.Root.Children.Last.Value); CheckEquals(3, LTree.Root.Children.First.Children.First.Value); CheckException(Exception, procedure() begin LTree.Add(nil, 4); end, 'Exception not thrown in AddLeft (1)!' ); CheckException(Exception, procedure() var LNode: TTreeNode<Integer>; begin LNode := TTreeNode<Integer>.Create(12, LTree2); try LTree.Add(LNode, 4); finally LNode.Free; end; end, 'Exception not thrown in AddLeft (2)!' ); CheckException(Exception, procedure() var LNode: TTreeNode<Integer>; begin LNode := TTreeNode<Integer>.Create(12, LTree); try LTree.Add(LNode, 4); finally LNode.Free; end; end, 'Exception not thrown in AddLeft (3)!' ); LTree.Free; LTree2.Free; end; procedure TTestTree.Test_Clear; var LTree: TTree<Integer>; begin LTree := TTree<Integer>.Create(100); LTree.Clear; CheckTrue(LTree.Root = nil); //TODO: implement me + implement proper root setting LTree.Free; end; procedure TTestTree.Test_Contains; var LTree: TTree<Integer>; begin LTree := TTree<Integer>.Create(100); LTree.Add(LTree.Root, 99); end; procedure TTestTree.Test_CopyTo; begin end; procedure TTestTree.Test_Count; begin end; procedure TTestTree.Test_Create_Tree; begin end; procedure TTestTree.Test_Create_Type_Tree; begin end; procedure TTestTree.Test_Create_Type_Value; begin end; procedure TTestTree.Test_Create_Value; begin end; procedure TTestTree.Test_Empty; begin end; procedure TTestTree.Test_Enumerator; begin end; procedure TTestTree.Test_Find; begin end; procedure TTestTree.Test_Remove; begin end; procedure TTestTree.Test_Root; begin end; initialization TestFramework.RegisterTest(TTestTree.Suite); end.
unit DAO.DistribuidorVA; interface uses DAO.Base, Model.DistribuidorVA, Generics.Collections, System.Classes; type TDistribuidorVADAO = class(TDAO) public function Insert(aDistribuidor: TDistribuidorVA): Boolean; function Update(aDistribuidor: TDistribuidorVA): Boolean; function Delete(iID: Integer): Boolean; function FindByID(iID: Integer): TObjectList<TDistribuidorVA>; function FindByCodigo(iCodigo: Integer): TObjectList<TDistribuidorVA>; end; const TABLENAME = 'va_distribuidor'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TDistribuidorVADAO.Insert(aDistribuidor: TDistribuidorVA): Boolean; var sSQL: String; begin Result := False; aDistribuidor.ID := GetKeyValue(TABLENAME,'ID_DISTRIBUIDOR'); sSQL := 'INSERT INTO ' + TABLENAME + '(' + 'ID_DISTRIBUIDOR, COD_DISTRIBUIDOR, NOM_DISTRIBUIDOR, DES_LOG) ' + 'VALUE (' + ':pID_DISTRIBUIDOR, :pCOD_DISTRIBUIDOR, :pNOM_DISTRIBUIDOR, :pDES_LOG); '; Connection.ExecSQL(sSQL, [aDistribuidor.ID, aDistribuidor.Codigo, aDistribuidor.Nome, aDistribuidor.Log], [ftInteger, ftInteger, ftString, ftString]); Result := True; end; function TDistribuidorVADAO.Update(aDistribuidor: TDistribuidorVA): Boolean; var sSQL: String; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' SET ' + 'COD_DISTRIBUIDOR = :pCOD_DISTRIBUIDOR, NOM_DISTRIBUIDOR = :pNOM_DISTRIBUIDOR, DES_LOG = :pDES_LOG ' + 'WHERE ' + 'ID_DISTRIBUIDOR = :pID_DISTRIBUIDOR, ; '; Connection.ExecSQL(sSQL, [aDistribuidor.Codigo, aDistribuidor.Nome, aDistribuidor.Log, aDistribuidor.ID], [ftInteger, ftString, ftString, ftInteger]); Result := True; end; function TDistribuidorVADAO.Delete(iID: Integer): Boolean; var sSQL: String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' WHERE ID_DISTRIBUIDOR = :pID_DISTRIBUIDOR;'; Connection.ExecSQL(sSQL,[iID],[ftInteger]); Result := True; end; function TDistribuidorVADAO.FindByID(iID: Integer): TObjectList<TDistribuidorVA>; var FDQuery: TFDQuery; produtos: TObjectList<TDistribuidorVA>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); if iID >= 0 then begin FDQuery.SQL.Add('WHERE ID_DISTRIBUIDOR = :pID_DISTRIBUIDOR'); FDQuery.ParamByName('pID_DISTRIBUIDOR').AsInteger := iID; end; FDQuery.Open(); produtos := TObjectList<TDistribuidorVA>.Create(); while not FDQuery.Eof do begin produtos.Add(TDistribuidorVA.Create(FDQuery.FieldByName('ID_DISTRIBUIDOR').AsInteger, FDQuery.FieldByName('COD_DISTRIBUIDOR').AsInteger, FDQuery.FieldByName('NOM_DISTRIBUIDOR').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := produtos; end; function TDistribuidorVADAO.FindByCodigo(iCodigo: Integer): TObjectList<TDistribuidorVA>; var FDQuery: TFDQuery; produtos: TObjectList<TDistribuidorVA>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE COD_DISTRIBUIDOR = :pCOD_DISTRIBUIDOR'); FDQuery.ParamByName('pCOD_DISTRIBUIDOR').AsInteger := iCodigo; FDQuery.Open(); produtos := TObjectList<TDistribuidorVA>.Create(); while not FDQuery.Eof do begin produtos.Add(TDistribuidorVA.Create(FDQuery.FieldByName('ID_DISTRIBUIDOR').AsInteger, FDQuery.FieldByName('COD_DISTRIBUIDOR').AsInteger, FDQuery.FieldByName('NOM_DISTRIBUIDOR').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := produtos; end; end.
unit StringUtils; interface uses Classes, SysUtils, Variants; function IsInStringList(const iStringList: TStringList; const iString: String):Boolean; function StringConv(const v:Variant):String; function SplitString(const Delimiter: Char; Input: string): TStringList; function SearchAndReplace(sSrc, sLookFor, sReplaceWith: string): string; implementation // From http://www.chami.com/tips/delphi/010197D.html function SearchAndReplace; var nPos, nLenLookFor : integer; begin nPos := Pos( sLookFor, sSrc ); nLenLookFor := Length( sLookFor ); while(nPos > 0)do begin Delete( sSrc, nPos, nLenLookFor ); Insert( sReplaceWith, sSrc, nPos ); nPos := Pos( sLookFor, sSrc ); end; Result := sSrc; end; function SplitString(const Delimiter: Char; Input: string): TStringList; var i: Integer; c: Char; currentString: String; begin result := TStringList.Create(); currentString := ''; for i := 1 to Length(Input) do begin c := Input[i]; if c = delimiter then begin result.Add(currentString); currentString := ''; end else begin currentString := currentString + c; end; end; if currentString <> '' then result.Add(currentString); end; function IsInStringList(const iStringList: TStringList; const iString: String):Boolean; var i: LongWord; begin result := false; for i := 0 to iStringList.Count - 1 do begin if iStringList[i] = iString then begin result := true; break; end; end; end; function StringConv(const v:Variant):String; var t: Word; begin t := VarType(v); if (t = varNull) or (t = varEmpty) then begin result := 'nil'; Exit; end; if t = varBoolean then begin if Boolean(v) then result := 'true' else result := 'false'; Exit; end; if t = varInteger then begin result := IntToStr(Integer(v)); Exit; end; if t = varWord then begin result := IntToStr(Word(v)); Exit; end; if t = varSingle then begin result := IntToStr(Integer(v)); Exit; end; if t = varByte then begin result := IntToStr(Byte(v)); Exit; end; if t = varString then begin result := String(v); Exit; end; result := '<unknown type>'; end; end.
unit Changeoffsetunit; {$MODE Delphi} interface uses LCLIntf, Messages, SysUtils, classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, LResources, ExtCtrls,symbolhandler, math, betterControls; type { TChangeOffset } TChangeOffset = class(TForm) Cancel: TButton; Change: TButton; TabControl1: TTabControl; cbHexadecimal: TCheckBox; Edit1: TEdit; procedure ChangeClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure TabControl1Changing(Sender: TObject; var AllowChange: Boolean); procedure TabControl1Change(Sender: TObject); procedure cbHexadecimalClick(Sender: TObject); private { Private declarations } public { Public declarations } offset: Int64; FromAddress: ptrUint; toAddress: ptrUint; error: integer; end; var ChangeOffset: TChangeOffset; implementation resourcestring rsThisIsNotAnValidValue = 'This is not an valid value'; procedure TChangeOffset.ChangeClick(Sender: TObject); var temp: ptruint; s: string; begin if tabcontrol1.TabIndex=0 then begin if cbHexadecimal.checked then begin s:=trim(edit1.text); if length(s)>1 then begin if s[1]='-' then begin val('-$'+copy(s,2,length(s)),offset,error); end else val('$'+s,offset,error); end else val('$'+s,offset,error); end else val(edit1.Text,offset,error); end else begin try temp:=symhandler.getAddressFromName(edit1.text); offset:=temp-fromaddress; except error:=1; end; end; end; procedure TChangeOffset.FormCreate(Sender: TObject); begin //tabcontrol1.AutoSize:=true; end; procedure TChangeOffset.FormShow(Sender: TObject); var r: trect; begin if tabcontrol1.TabIndex=0 then begin if cbHexadecimal.Checked then edit1.Text:=IntToHex(toaddress-fromaddress,8) else edit1.Text:=IntToStr(integer(toaddress-fromaddress)); end else begin edit1.Text:=IntToHex(toaddress,8); end; change.autosize:=false; cancel.autosize:=false; change.width:=max(change.width, cancel.width); cancel.width:=max(change.width, cancel.width); clientheight:=cancel.top+cancel.Height+tabcontrol1.TabHeight+5; ClientWidth:=(cancel.left+cancel.width)*2; end; procedure TChangeOffset.TabControl1Changing(Sender: TObject; var AllowChange: Boolean); var controle: integer; begin if tabcontrol1.TabIndex=0 then begin if cbHexadecimal.checked then val('$'+edit1.Text,offset,controle) else val(edit1.text,offset,controle); end else begin val('$'+edit1.text,toaddress,controle); end; if controle=0 then allowchange:=true else begin allowchange:=false; raise exception.Create(rsThisIsNotAnValidValue); end; end; procedure TChangeOffset.TabControl1Change(Sender: TObject); begin if tabcontrol1.TabIndex=0 then begin cbHexadecimal.Visible:=true; if cbHexadecimal.Checked then edit1.Text:=IntToHex(toaddress-fromaddress,8) else edit1.Text:=IntToStr(integer(toaddress-fromaddress)); end else begin cbHexadecimal.visible:=false; edit1.Text:=IntToHex(toaddress,8); end; end; procedure TChangeOffset.cbHexadecimalClick(Sender: TObject); begin if tabcontrol1.TabIndex=0 then begin if cbHexadecimal.Checked then edit1.Text:=IntToHex(toaddress-fromaddress,8) else edit1.Text:=IntToStr(integer(toaddress-fromaddress)); end; end; initialization {$i Changeoffsetunit.lrs} end.
{******************************************************************************* * * * PentireFMX * * * * https://github.com/gmurt/PentireFMX * * * * Copyright 2020 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License forthe specific language governing permissions and * * limitations under the License. * * * *******************************************************************************} unit ksAppEvents; interface uses FMX.Objects, FMX.Platform; type IksEventForm = interface ['{2A2C3294-795B-4CC3-85FE-99F9A29DEAA9}'] procedure DoAppEvent(AAppEvent: TApplicationEvent); end; implementation uses System.SysUtils, System.Classes, FMX.Forms, fmx.dialogservice; type TksAppEvents = class private public constructor Create; virtual; function DoAppEvent(AAppEvent: TApplicationEvent; AContext: TObject) : Boolean; end; var AAppEvents: TksAppEvents; { TksAppEvents } function TksAppEvents.DoAppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; var ICount: integer; AIntf: IksEventForm; begin if aappevent <> TApplicationEvent.BecameActive then exit; for ICount := 0 to Screen.FormCount-1 do begin if Supports(Screen.Forms[ICount], IksEventForm, AIntf) then begin tthread.Synchronize(nil, procedure begin AIntf.DoAppEvent(AAppEvent); end ); end; end; Result := True; end; constructor TksAppEvents.Create; var AppEventSvc: IFMXApplicationEventService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService, IInterface(AppEventSvc)) then AppEventSvc.SetApplicationEventHandler(DoAppEvent); end; initialization AAppEvents := TksAppEvents.Create; finalization AAppEvents.Free; end.
unit unClientUpdateService; { In order for CodeSite to be able to send messages, the service must be configured as an interactive service after it is installed. Otherwise, Codesite will not log any messages to any destination. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs ,unUpdateClientThread ; resourcestring SRESException = 'Client Update Service reported %1. Please Check the ClientUpdateService.csl log file for details.'; type TClientUpdater = class(TService) procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); procedure ServiceAfterInstall(Sender: TService); private FClientUpdateThread :TUpdateClientThread; procedure RegisterMessages(Sender:TService); procedure RegisterDescription(Sender:TService); procedure ThreadTerminate(Sender: TObject); public function GetServiceController: TServiceController; override; end; var ClientUpdater: TClientUpdater; implementation {$R *.DFM} {$R ClientUpdateServiceEventLogMessages.RES} uses {$IFDEF hcCodeSite} hcCodesiteHelper, {$ENDIF} unPath ,Registry ; procedure ServiceController(CtrlCode: DWord); stdcall; begin ClientUpdater.Controller(CtrlCode); end; function TClientUpdater.GetServiceController: TServiceController; begin Result := ServiceController; end; procedure TClientUpdater.ServiceStart(Sender: TService; var Started: Boolean); begin {$IFDEF hcCodeSite} hcCodeSite.DestinationDetails:= 'File[Path='+ExtractFilePath(AppFileName)+'ClientUpdateService.csl] '; hcCodeSite.SendMsg('Service is starting'); {$ENDIF} AllowPause := False; //don't allow the service to be paused. Start and Stop only. Interactive := True; try FClientUpdateThread := TUpdateClientThread.Create(True); with FClientUpdateThread do begin Service := Self; FreeOnTerminate := True; OnTerminate := ThreadTerminate; Start; end; Started := True; if True then LogMessage('Client Update Service Started',EVENTLOG_INFORMATION_TYPE,0,0); {$IFDEF hcCodeSite} hcCodeSite.SendMsg('Service has been started'); {$ENDIF} except on e: Exception do begin {$IFDEF hcCodeSite} hcCodeSite.SendException(E); {$ENDIF} LogMessage(E.Message,EVENTLOG_ERROR_TYPE,0,103); Started := False; end; end; end; procedure TClientUpdater.ServiceStop(Sender: TService; var Stopped: Boolean); begin try {$IFDEF hcCodeSite} hcCodeSite.SendMsg('Service is stopping'); {$ENDIF} Stopped := True; LogMessage('Client Update Service Stopped',EVENTLOG_INFORMATION_TYPE,0,0); except on e: Exception do begin {$IFDEF hcCodeSite} hcCodeSite.SendException(E); {$ENDIF} LogMessage(Format('Exception Occurred: %s',[E.Message])); Stopped := False; end; end; end; procedure TClientUpdater.ThreadTerminate(Sender: TObject); begin //restart the worker thread if the service is supposed to be running if self.Status = csRunning then begin {$IFDEF hcCodeSite} hcCodeSite.SendMsg('Starting New Thread'); {$ENDIF} FClientUpdateThread := TUpdateClientThread.Create(True); with FClientUpdateThread do begin Service := Self; FreeOnTerminate := True; OnTerminate := ThreadTerminate; Start; end; end; end; procedure TClientUpdater.ServiceAfterInstall(Sender: TService); begin RegisterDescription(Sender); RegisterMessages(Sender); end; procedure TClientUpdater.RegisterMessages(Sender :TService); { Register the message table compiled into this EXE with the EventLog so it can properly display any of our error messages. } begin with TRegistry.Create(KEY_READ or KEY_WRITE) do try RootKey := HKEY_LOCAL_MACHINE; if OpenKey('SYSTEM\CurrentControlSet\Services\EventLog\Application\' + Name, True) then begin WriteString('EventMessageFile', ParamStr(0)); end finally Free; end; end; procedure TClientUpdater.RegisterDescription(Sender :TService); { Register description displayed in the Service Manager. } begin with TRegistry.Create(KEY_READ or KEY_WRITE) do try RootKey := HKEY_LOCAL_MACHINE; if OpenKey('SYSTEM\CurrentControlSet\Services\' + Name, True) then begin WriteString('Description', 'A service to update application components.'); end finally Free; end; end; end.
unit chatbotsubsystem; {$mode objfpc}{$H+} interface uses Classes, SysUtils, vkcmobserver, MainModel, ChatModel, entities; type { TChatBotSystemWorker } TChatBotSystemWorker = class(TThread) private FChanged: boolean; FChatModel: IChatModel; FMainModel: IMainModel; procedure SetChanged(AValue: boolean); procedure SetChatModel(AValue: IChatModel); procedure SetMainModel(AValue: IMainModel); protected procedure Execute; override; public property Changed: boolean read FChanged write SetChanged; property MainModel: IMainModel read FMainModel write SetMainModel; property ChatModel: IChatModel read FChatModel write SetChatModel; end; { TChatBotSubSystem } TChatBotSubSystem = class private FObserver: TVKCMObserver; FWorker: TChatBotSystemWorker; procedure SetObserver(AValue: TVKCMObserver); procedure OnNotification; public constructor Create(AMainModel: IMainModel; AChatModel: IChatModel); property Observer: TVKCMObserver read FObserver write SetObserver; destructor Destroy; override; end; var LChatBotSubSystem: TChatBotSubSystem; implementation { TChatBotSystemWorker } procedure TChatBotSystemWorker.SetChanged(AValue: boolean); begin if FChanged = AValue then Exit; FChanged := AValue; end; procedure TChatBotSystemWorker.SetChatModel(AValue: IChatModel); begin if FChatModel = AValue then Exit; FChatModel := AValue; end; procedure TChatBotSystemWorker.SetMainModel(AValue: IMainModel); begin if FMainModel = AValue then Exit; FMainModel := AValue; end; procedure TChatBotSystemWorker.Execute; var CommunityList: TCommunityList; Community: TCommunity; Dialogs: TDialogsList; Dialog: TDialog; Command: TChatBotCommand; i, j, k: integer; NewMessage: TMessage; RecievedMessage: string; begin while not Terminated do if Changed then begin CommunityList := MainModel.GetCommunities; for i := 0 to CommunityList.Count - 1 do begin Community := CommunityList[i]; Dialogs := ChatModel.GetLastDialogs(Community); for j := 0 to Dialogs.Count - 1 do begin Dialog := Dialogs[j]; if Dialog.Messages[Dialog.Messages.Count - 1].Out = otRecieved then begin RecievedMessage := Dialog.Messages[Dialog.Messages.Count - 1].Message; for k := 0 to Community.Chatbot.Commands.Count - 1 do begin Command := Community.Chatbot.Commands[k]; if SameText(RecievedMessage, Command.Command) then begin NewMessage := TMessage.Create; NewMessage.Message := Command.Response; NewMessage.Date := Now(); NewMessage.Deleted := False; NewMessage.Emoji := False; NewMessage.FromId := Community.Id; NewMessage.UserId := Dialog.Person.Id; NewMessage.Out := otSent; ChatModel.SendMessage(Community, NewMessage); end; end; end; end; end; Changed := false; end; end; { TChatBotSubSystem } procedure TChatBotSubSystem.SetObserver(AValue: TVKCMObserver); begin if FObserver = AValue then Exit; FObserver := AValue; end; procedure TChatBotSubSystem.OnNotification; begin FWorker.Changed := True; end; constructor TChatBotSubSystem.Create(AMainModel: IMainModel; AChatModel: IChatModel); begin FWorker := TChatBotSystemWorker.Create(True); FWorker.MainModel := AMainModel; FWorker.ChatModel := AChatModel; FWorker.FreeOnTerminate := True; FWorker.Changed := False; FWorker.Start; FObserver := TVKCMObserver.Create; FObserver.Notify := @OnNotification; end; destructor TChatBotSubSystem.Destroy; begin FWorker.Terminate; FWorker.WaitFor; FreeAndNil(FObserver); inherited Destroy; end; end.
unit HTMLEditorPlugin; interface uses PluginManagerIntf, PluginIntf, HTMLEditorIntf, DHTMLFrm, Classes; type THTMLEditorPlugin = class (TPlugin, IPlugin, IHTMLEditor) private Form: TDHTMLForm; FLocalPath: String; FRemotePath: String; FFilesList: TStringList; function GetLocalPath: String; function GetRemotePath: String; procedure SetLocalPath(const Value: String); procedure SetRemotePath(const Value: String); function GetFilesList: TStringList; procedure SetFilesList(const Value: TStringList); public function GetName: string; function Load: Boolean; function UnLoad: Boolean; { IHTMLEditor } function Execute(var Text: String): Boolean; property LocalPath: String read GetLocalPath write SetLocalPath; property RemotePath: String read GetRemotePath write SetRemotePath; property FilesList: TStringList read GetFilesList write SetFilesList; end; function RegisterPlugin(Module: HMODULE; PluginManager: IPluginManager): Boolean; exports RegisterPlugin; implementation uses Windows; function RegisterPlugin(Module: HMODULE; PluginManager: IPluginManager): Boolean; var Plugin: IInterface; begin Plugin := THTMLEditorPlugin.Create(Module, PluginManager); Result := PluginManager.RegisterPlugin(Plugin); end; { THTMLEditorPlugin } function THTMLEditorPlugin.Execute(var Text: String): Boolean; begin if not Assigned(Form) then Form := TDHTMLForm.Create(nil); Form.LocalPath := FLocalPath; Form.RemotePath := FRemotePath; Form.FilesList := FFilesList; Form.Text := Text; Form.ReplacePath; Form.PluginManager := FPluginManager; Result := Form.ShowModal = idOK; if Result then begin Form.ReplaceAndSaveImages; Text := Form.Text; end; end; function THTMLEditorPlugin.GetFilesList: TStringList; begin Result := FFilesList; end; function THTMLEditorPlugin.GetLocalPath: String; begin Result := FLocalPath; end; function THTMLEditorPlugin.GetName: string; begin Result := 'HTMLEditorPlugin'; end; function THTMLEditorPlugin.GetRemotePath: String; begin Result := FRemotePath; end; function THTMLEditorPlugin.Load: Boolean; begin Result := True; Form := TDHTMLForm.Create(nil); end; procedure THTMLEditorPlugin.SetFilesList(const Value: TStringList); begin FFilesList := Value; end; procedure THTMLEditorPlugin.SetLocalPath(const Value: String); begin FLocalPath := Value; end; procedure THTMLEditorPlugin.SetRemotePath(const Value: String); begin FRemotePath := Value; end; function THTMLEditorPlugin.UnLoad: Boolean; begin Result := True; if Assigned(Form) then Form.Free; end; end.
unit VisibleDSA.AlgoVisualizer; interface uses System.Classes, System.SysUtils, System.Types, System.Math, FMX.Graphics, FMX.Forms, VisibleDSA.AlgoVisHelper, VisibleDSA.FractalData; type TAlgoVisualizer = class(TObject) private _data: TFractalData; _times: integer; _isForward: boolean; procedure __setData; procedure __desktopCenter(form: TForm); procedure __formShow(Sender: TObject); public constructor Create(form: TForm); destructor Destroy; override; procedure Paint(canvas: TCanvas); procedure Run; end; implementation uses VisibleDSA.AlgoForm; { TAlgoVisualizer } constructor TAlgoVisualizer.Create(form: TForm); var depth, w, h: integer; begin _isForward := true; depth := 6; _times := 1; w := Trunc(Power(3, depth)); h := Trunc(Power(3, depth)); form.ClientWidth := w; form.ClientHeight := h; form.Caption := 'Fractal Visualizer --- ' + Format('W: %d, H: %d', [w, h]); form.OnShow := __formShow; __desktopCenter(form); _data := TFractalData.Create(depth); end; destructor TAlgoVisualizer.Destroy; begin FreeAndNil(_data); inherited Destroy; end; procedure TAlgoVisualizer.Paint(canvas: TCanvas); var Count: integer; procedure __drawFractal__(Ax, Ay, side, depth: integer); var Bx, By, h, Cx, Cy: integer; AB_centerX, AB_centerY, AC_centerX, AC_centerY: integer; begin Count := Count + 1; if side <= 1 then begin TAlgoVisHelper.SetFill(CL_INDIGO); TAlgoVisHelper.FillRectangle(canvas, Ax, Ay, 1, 1); Exit; end; Bx := Ax + side; By := Ay; h := Round(sin(60 * Pi / 180) * side); Cx := Ax + side div 2; Cy := Ay - h; if depth = _data.Depth then begin TAlgoVisHelper.SetFill(CL_INDIGO); TAlgoVisHelper.FillTriangle(canvas, Point(Ax, Ay), Point(Bx, By), Point(Cx, Cy)); Exit; end; AB_centerX := (Ax + Bx) div 2; AB_centerY := (Ay + By) div 2; AC_centerX := (Ax + Cx) div 2; AC_centerY := (Ay + Cy) div 2; __drawFractal__(Ax, Ay, side div 2, depth + 1); __drawFractal__(AC_centerx, AC_centery, side div 2, depth + 1); __drawFractal__(AB_centerX, AB_centerY, side div 2, depth + 1); end; begin Count := 0; __drawFractal__(0, canvas.Height, canvas.Width, 0); AlgoForm.Caption := Format(' Count: %d', [Count]); //TAlgoVisHelper.SetFill(CL_INDIGO); //TAlgoVisHelper.FillTriangle(canvas, Point(0, canvas.Height), // Point(canvas.Width, canvas.Height), Point(canvas.Width div 2, 0)); end; procedure TAlgoVisualizer.Run; begin while true do begin _data.Depth := _times; __setData; if _isForward then begin _times := _times + 1; if _times >= 9 then _isForward := not _isForward; end else begin _times := _times - 1; if _times < 1 then _isForward := not _isForward; end; end; end; procedure TAlgoVisualizer.__desktopCenter(form: TForm); var top, left: Double; begin top := (Screen.Height div 2) - (form.ClientHeight div 2); left := (Screen.Width div 2) - (form.ClientWidth div 2); form.top := Trunc(top); form.left := Trunc(left); end; procedure TAlgoVisualizer.__formShow(Sender: TObject); var thread: TThread; begin thread := TThread.CreateAnonymousThread(Run); thread.FreeOnTerminate := true; thread.Start; end; procedure TAlgoVisualizer.__setData; begin TAlgoVisHelper.Pause(100); AlgoForm.PaintBox.Repaint; end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Xml, Sugar.TestFramework; type NodeTest = public class (Testcase) private Doc: XmlDocument; Data: XmlNode; public method Setup; override; method Name; method Value; method LocalName; method Document; method Parent; method NextSibling; method PreviousSibling; method FirstChild; method LastChild; method Item; method ChildCount; method ChildNodes; end; implementation method NodeTest.Setup; begin Doc := XmlDocument.FromString(XmlTestData.RssXml); Assert.IsNotNull(Doc); Data := Doc.FirstChild; Assert.IsNotNull(Data); end; method NodeTest.Name; begin Assert.CheckString("rss", Data.Name); var lValue := Data.FirstChild.FirstChild.NextSibling; Assert.IsNotNull(lValue); Assert.CheckString("{http://www.w3.org/2005/Atom}link", lValue.Name); lValue := lValue.NextSibling.FirstChild; Assert.IsNotNull(lValue); Assert.CheckString("#text", lValue.Name); end; method NodeTest.Value; begin var lValue := Data.FirstChild.ChildNodes[2]; Assert.IsNotNull(lValue); Assert.CheckString("http://blogs.remobjects.com", lValue.Value); lValue.Value := "http://test.com"; Assert.CheckString("http://test.com", lValue.Value); lValue := Data.FirstChild.ChildNodes[10]; Assert.IsNotNull(lValue); Assert.CheckInt(13, lValue.ChildCount); lValue.Value := "Test"; //replaces all content with text node Assert.CheckInt(1, lValue.ChildCount); Assert.CheckString("Test", lValue.Value); lValue.Value := ""; Assert.CheckInt(0, lValue.ChildCount); Assert.CheckString("", lValue.Value); Assert.IsException(->begin lValue.Value := nil; end); end; method NodeTest.LocalName; begin Assert.CheckString("rss", Data.LocalName); var lValue := Data.FirstChild.FirstChild.NextSibling; Assert.IsNotNull(lValue); Assert.CheckString("link", lValue.LocalName); lValue := lValue.NextSibling.FirstChild; Assert.IsNotNull(lValue); Assert.CheckString("#text", lValue.LocalName); end; method NodeTest.Document; begin Assert.IsNotNull(Data.Document); Assert.IsNotNull(Data.FirstChild.Document); Assert.CheckBool(true, Data.Document.Equals(Doc)); end; method NodeTest.Parent; begin Assert.IsNull(Data.Parent); Assert.IsNotNull(Data.FirstChild.Parent); Assert.CheckBool(true, Data.FirstChild.Parent.Equals(Data)); end; method NodeTest.NextSibling; begin Assert.IsNull(Data.NextSibling); var lValue := Data.FirstChild.FirstChild; Assert.CheckBool(true, lValue.Equals(Data.FirstChild.ChildNodes[0])); Assert.IsNotNull(lValue.NextSibling); Assert.CheckBool(true, lValue.NextSibling.Equals(Data.FirstChild.ChildNodes[1])); end; method NodeTest.PreviousSibling; begin Assert.IsNull(Data.PreviousSibling); var lValue := Data.FirstChild.LastChild; Assert.CheckBool(true, lValue.Equals(Data.FirstChild.ChildNodes[10])); Assert.IsNotNull(lValue.PreviousSibling); Assert.CheckBool(true, lValue.PreviousSibling.Equals(Data.FirstChild.ChildNodes[9])); end; method NodeTest.FirstChild; begin Assert.IsNotNull(Data.FirstChild); Assert.CheckString("channel", Data.FirstChild.LocalName); var lValue := Data.FirstChild.FirstChild; Assert.IsNotNull(lValue); Assert.CheckString("title", lValue.LocalName); end; method NodeTest.LastChild; begin var lValue := Data.FirstChild.LastChild; Assert.IsNotNull(lValue); Assert.CheckString("item", lValue.LocalName); end; method NodeTest.Item; begin Assert.IsNotNull(Data.Item[0]); Assert.CheckString("channel", Data.Item[0].LocalName); Assert.IsNotNull(Data[0]); Assert.CheckString("channel", Data[0].LocalName); Assert.CheckBool(true, Data[0].Equals(Data.FirstChild)); Assert.IsException(->Data.Item[-1]); Assert.IsException(->Data.Item[555]); end; method NodeTest.ChildCount; begin Assert.CheckInt(1, Data.ChildCount); Assert.CheckInt(11, Data.FirstChild.ChildCount); end; method NodeTest.ChildNodes; begin var Expected: array of String := ["title", "link", "link", "description", "lastBuildDate", "#comment", "language", "updatePeriod", "updateFrequency", "generator", "item"]; var Actual := Data.FirstChild.ChildNodes; Assert.CheckInt(11, length(Actual)); for i: Integer := 0 to length(Actual) - 1 do Assert.CheckString(Expected[i], Actual[i].LocalName); end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [NFE_NUMERO] The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 1.0 *******************************************************************************} unit NfeNumeroController; interface uses Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos, NfeNumeroVO, Generics.Collections; type TNfeNumeroController = class(TController) private class var FDataSet: TClientDataSet; public class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False); overload; class function ConsultaObjeto(pFiltro: String): TNfeNumeroVO; class function GetDataSet: TClientDataSet; override; class procedure SetDataSet(pDataSet: TClientDataSet); override; end; implementation uses UDataModule, T2TiORM; class procedure TNfeNumeroController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean); var Retorno: TObjectList<TNfeNumeroVO>; begin try Retorno := TT2TiORM.Consultar<TNfeNumeroVO>(pFiltro, pPagina, pConsultaCompleta); TratarRetorno<TNfeNumeroVO>(Retorno); finally end; end; class function TNfeNumeroController.ConsultaObjeto(pFiltro: String): TNfeNumeroVO; var UltimoID: Integer; begin try if TT2TiORM.SelectMax('NFE_NUMERO', pFiltro) = -1 then begin Result := TNfeNumeroVO.Create; Result.Serie := '001'; Result.Numero := 1; Result.IdEmpresa := 1; UltimoID := TT2TiORM.Inserir(Result); Result := TT2TiORM.ConsultarUmObjeto<TNfeNumeroVO>('ID=' + IntToStr(UltimoID), False); end else begin TT2TiORM.ComandoSQL('update NFE_NUMERO set NUMERO = NUMERO + 1'); Result := TT2TiORM.ConsultarUmObjeto<TNfeNumeroVO>('', False); end; finally end; end; class function TNfeNumeroController.GetDataSet: TClientDataSet; begin Result := FDataSet; end; class procedure TNfeNumeroController.SetDataSet(pDataSet: TClientDataSet); begin FDataSet := pDataSet; end; initialization Classes.RegisterClass(TNfeNumeroController); finalization Classes.UnRegisterClass(TNfeNumeroController); end.
unit Expedicao.Services.uSeguradora; interface uses FireDAC.Comp.Client, Expedicao.Models.uSeguradora; type TSeguradoraService = class private public function ObterSeguradoraPeloOID(pSeguradoraOID: Integer): TSeguradora; function ObterSeguradoraDaQuery(pQry: TFDQuery): TSeguradora; end; implementation uses uDataModule; { TSvcSeguradora } function TSeguradoraService.ObterSeguradoraDaQuery(pQry: TFDQuery): TSeguradora; begin Result := TSeguradora.Create; with Result do begin SeguradoraOID := pQry.FieldByName('SeguradoraOID').AsInteger; Descricao := pQry.FieldByName('Descricao').AsString; CNPJ := pQry.FieldByName('CNPJ').AsString; Telefone := pQry.FieldByName('Telefone').AsString; Corretor := pQry.FieldByName('Corretor').AsString; end; end; function TSeguradoraService.ObterSeguradoraPeloOID( pSeguradoraOID: Integer): TSeguradora; var lQry: TFDQuery; begin Result := nil; lQry := DataModule1.ObterQuery; try lQry.Open('SELECT * FROM Seguradora WHERE SeguradoraOID = :SeguradoraOID', [pSeguradoraOID]); if lQry.IsEmpty then Exit; Result := ObterSeguradoraDaQuery(lQry); finally DataModule1.DestruirQuery(lQry); end; end; end.
program cinco; type celular = record codigo : integer; nombre : String; descripcion : String; marca : String; precio : real; stockMinimo : integer; stockDisponible : integer; end; archivoCelulares = file of celular; procedure cargarArchivoBinario (var archivo : archivoCelulares; var celulares : Text); var unCelular : celular; begin reset(celulares); rewrite(archivo); writeln; while (not eof(celulares)) do begin readln(celulares, unCelular.codigo, unCelular.precio, unCelular.marca, unCelular.nombre); readln(celulares, unCelular.stockDisponible, unCelular.stockMinimo, unCelular.descripcion); write(archivo, unCelular); end; writeln('Archivo cargado'); close(archivo); close(celulares); end; procedure listarCelularesStockMenorAlMinimo (var archivo : archivoCelulares); var unCelular : celular; begin reset(archivo); while (not eof(archivo)) do begin read(archivo,unCelular); if (unCelular.stockDisponible < unCelular.stockMinimo) then with unCelular do writeln('Codigo: ',codigo,' Precio: ',precio:4:2,'$ Marca: ',marca,' Nombre: ',nombre,' stock disponible: ',stockDisponible,' stock minimo: ',stockMinimo,' descrpicion: ',descripcion); end; close(archivo); end; procedure listarCelularesConDescripcion (var archivo : archivoCelulares; unaDescripcion : String); var unCelular : celular; begin reset(archivo); while (not eof(archivo)) do begin read(archivo,unCelular); if (unCelular.descripcion = unaDescripcion) then with unCelular do writeln('Codigo: ',codigo,' Precio: ',precio:4:2,'$ Marca: ',marca,' Nombre: ',nombre,' stock disponible: ',stockDisponible,' stock minimo: ',stockMinimo,' descrpicion: ',descripcion); end; close(archivo); end; procedure exportarDatos (var archivo : archivoCelulares; var celularFinal : Text); var unCelular : celular; begin reset(archivo); rewrite(celularFinal); while (not eof(archivo)) do begin read(archivo,unCelular); with unCelular do begin writeln('Codigo: ',codigo,' Precio: ',precio:4:2,'$ Marca: ',marca,' Nombre: ',nombre,' stock disponible: ',stockDisponible,' stock minimo: ',stockMinimo,' descrpicion: ',descripcion); writeln(celularFinal,' ',codigo,' ',precio:4:2,'$ ',marca,' ',nombre,' ',stockDisponible,' ',stockMinimo,' ',descripcion); end; end; close(archivo); close(celularFinal); end; //Programa Principal var celulares : Text; //archivo con datos celularFinal : Text; //archivo a cargar archivo : archivoCelulares; op : char; archivoFisico, unaDescripcion : String; begin writeln('Ingrese nombre del archivo binario'); readln(archivoFisico); assign(archivo,archivoFisico); assign(celulares,'celulares.txt'); assign(celularFinal,'celular.txt'); repeat writeln('******************************************************************************************'); writeln('Menu de opciones'); writeln(' a.- Crear un archivo a partir de un archivo de texto'); writeln(' b.- Listar celulares con un stock menor al minimo'); writeln(' c.- Listar celulares cuya descripcion se corresponde con una ingresada'); writeln(' d.- Exportar todos los datos del archivo a uno de texto'); writeln(' e.- Salir'); writeln('******************************************************************************************'); readln(op); case op of 'a': cargarArchivoBinario(archivo,celulares); 'b': listarCelularesStockMenorAlMinimo(archivo); 'c': begin writeln('Ingrese una descripcion: '); readln(unaDescripcion); listarCelularesConDescripcion(archivo,unaDescripcion); end; 'd': exportarDatos(archivo,celularFinal); else writeln('Saliendo. . .'); end; until (op = 'e'); end.
UNIT figs; INTERFACE uses project,windows,extctrls,graphics; const MaxCells = 3; CubeSize = 500; DefaultCells = 3; Colors:array[1..6]of TColor=(clRed,clGreen,clBlue,clMaroon,clLime,clAqua); RotAngle = 10; MoveStep = 25; type TRubic = class private fCells:integer; procedure setCells(c:integer); public planes:array[1..6,1..MaxCells,1..MaxCells]of integer; coords:array[1..6,0..MaxCells,0..MaxCells]of T3Point; points:array[1..6,0..MaxCells,0..MaxCells]of T2Point; constructor create; destructor destroy;override; procedure draw(pb:TPaintBox); procedure project; property cells:integer read fCells write setCells; end; IMPLEMENTATION constructor TRubic.create; var p,x,y:integer; begin inherited create; for p:=1 to 6 do for x:=1 to MaxCells do for y:=1 to MaxCells do planes[p,x,y]:=p; fCells:=0; cells:=DefaultCells; end; destructor TRubic.destroy; begin inherited destroy; end; procedure TRubic.setCells(c:integer); var matr:array[0..MaxCells,0..MaxCells,0..MaxCells]of T3Point; a,x,y,z,cs:integer; begin if(c=cells)then exit; fCells:=c; cs:=2*CubeSize div cells; ap(matr[0,0,0],-CubeSize,-CubeSize,-CubeSize); {base lines} for a:=1 to cells do begin ap(matr[a,0,0],matr[a-1,0,0].x+cs,matr[a-1,0,0].y ,matr[a-1,0,0].z ); ap(matr[0,a,0],matr[0,a-1,0].x ,matr[0,a-1,0].y+cs,matr[0,a-1,0].z ); ap(matr[0,0,a],matr[0,0,a-1].x ,matr[0,0,a-1].y ,matr[0,0,a-1].z+cs); end; {base planes} for x:=1 to cells do for y:=1 to cells do begin ap(matr[0,x,y],matr[0,x-1,y-1].x ,matr[0,x-1,y-1].y+cs,matr[0,x-1,y-1].z+cs); ap(matr[x,0,y],matr[x-1,0,y-1].x+cs,matr[x-1,0,y-1].y ,matr[x-1,0,y-1].z+cs); ap(matr[x,y,0],matr[x-1,y-1,0].x+cs,matr[x-1,y-1,0].y+cs,matr[x-1,y-1,0].z ); end; {other points} for x:=1 to cells do for y:=1 to cells do for z:=1 to cells do ap(matr[x,y,z],matr[x-1,y-1,z-1].x+cs,matr[x-1,y-1,z-1].y+cs,matr[x-1,y-1,z-1].z+cs); {and the target planes} for x:=0 to cells do for y:=0 to cells do begin coords[1,x,y]:=matr[cells,x,y]; coords[2,x,y]:=matr[x,cells,y]; coords[3,x,y]:=matr[x,y,cells]; coords[4,x,y]:=matr[0,x,y]; coords[5,x,y]:=matr[x,0,y]; coords[6,x,y]:=matr[x,y,0]; end; end; procedure TRubic.draw(pb:TPaintBox); var vis:array[1..6]of boolean; p,x,y:integer; r:array[1..4]of TPoint; begin C.x:=pb.width div 2; C.y:=pb.height div 2; project; vis[1]:=U.x>CubeSize; vis[1+3]:=U.x<-CubeSize; vis[2]:=U.y>CubeSize; vis[2+3]:=U.y<-CubeSize; vis[3]:=U.z>CubeSize; vis[3+3]:=U.z<-CubeSize; for p:=1 to 6 do if(vis[p])then for x:=1 to cells do for y:=1 to cells do begin pb.canvas.brush.color:=Colors[planes[p,x,y]]; r[1].x:=points[p,x-1,y-1].x; r[1].y:=points[p,x-1,y-1].y; r[2].x:=points[p,x ,y-1].x; r[2].y:=points[p,x ,y-1].y; r[3].x:=points[p,x ,y ].x; r[3].y:=points[p,x ,y ].y; r[4].x:=points[p,x-1,y ].x; r[4].y:=points[p,x-1,y ].y; pb.canvas.polygon(r); end; end; procedure TRubic.project; var p,x,y:integer; begin for p:=1 to 6 do for x:=0 to cells do for y:=0 to cells do pp(coords[p,x,y],points[p,x,y]); end; END.
unit ShellUtils_Globals; interface uses SCARFunctions, ShellUtils_Main, SysUtils, Dialogs; type TExportFunc = record Ptr: Pointer; Name: AnsiString; end; const ExportFunctions: array[0..2] of TExportFunc = ((Ptr: @MyRun; Name: 'procedure Run(const Path: AnsiString);'), (Ptr: @MyRunEx; Name: 'procedure RunEx(const Path, Params: AnsiString);'), (Ptr: @MyDeleteFile; Name: 'function DeleteFile(const Path: AnsiString): Boolean;')); function GetFunctionCount: Integer; stdcall; function GetFunctionInfo(x: Integer; var ProcAddr: Pointer; var ProcDef: PAnsiChar): Integer; stdcall; implementation function GetFunctionCount: Integer; stdcall; begin Result := High(ExportFunctions) + 1; end; function GetFunctionInfo(x: Integer; var ProcAddr: Pointer; var ProcDef: PAnsiChar): Integer; stdcall; begin WriteLn(IntToStr(GetSCARVersion)); Result := -1; if (x >= Low(ExportFunctions)) and (x <= High(ExportFunctions)) then begin ProcAddr := ExportFunctions[x].Ptr; StrPCopy(ProcDef, ExportFunctions[x].Name); Result := x; end; end; end.
unit Moment4D.DateTime; interface uses Moment4D.Main; type TMomentDateTime = class (TInterfacedObject, IDateTime) FDelphiDT: TDateTime; function add: IWithDuration; procedure delphiDT (dt: TDateTime); function asDelphiDT: TDateTime; function clone: IDateTime; constructor CreateFromDelphi(dt: TDateTime); end; implementation { TMomentDateTime } uses Moment4D.WithDuration; function TMomentDateTime.add: IWithDuration; begin Result := TOperationWithDuration.Create(self); end; function TMomentDateTime.asDelphiDT: TDateTime; begin Result := FDelphiDT; end; function TMomentDateTime.clone: IDateTime; var dt2: TMomentDateTime; begin dt2 := TMomentDateTime.Create(); dt2.FDelphiDT := FDelphiDT; Result := dt2; end; constructor TMomentDateTime.CreateFromDelphi(dt: TDateTime); begin FDelphiDT := dt; end; procedure TMomentDateTime.delphiDT(dt: TDateTime); begin FDelphiDT := dt; end; end.
unit soutils; { ----------------------------------------------------------------------- # This file is part of WAPT # Copyright (C) 2013 Tranquil IT Systems http://www.tranquil.it # WAPT aims to help Windows systems administrators to deploy # setup and update applications on users PC. # # Part of this file is based on JEDI JCL library # # WAPT is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # WAPT is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with WAPT. If not, see <http://www.gnu.org/licenses/>. # # ----------------------------------------------------------------------- } {$mode objfpc}{$H+} interface uses Classes, SysUtils,SuperObject; function StringList2SOArray(St:TStringList):ISuperObject; function StringArray2SOArray(A:TStringArray):ISuperObject; function DynArr2SOArray(const items: Array of String):ISuperObject; function SOArray2StringArray(items: ISuperObject):TStringArray; // aggregate Rows by identical KeyName value. // If AggFieldName is not empty, returns a list of single extracted value from rows // else return a list of rows objects function SOAggregate(Rows: ISuperObject; KeyName: String; AggFieldName: String=''): ISuperObject; function MergeSOArrays(A,B:ISuperObject):ISuperObject; function SplitLines(const St:String):ISuperObject; function Split(const St: String; Sep: String): ISuperObject; function Join(const Sep: String; Arr:ISuperObject):String; function StrIn(const St: String; List:ISuperObject): Boolean; function StrToken(var S: string; Separator: String): string; // create a new array with a field function ExtractField(SOList:ISuperObject;const fieldname:String;NilIfNil:Boolean=True):ISuperObject; // create a new array with a subset of the fields function ExtractFields(SOList:ISuperObject;const keys: Array of String):ISuperObject; function RemoveDuplicates(SOArray: ISuperObject): ISuperObject; // expand an array of array to an array of dict. All items must have same count of cell // fieldnames of cell is in ColumnNames function SOArrayArrayExpand(SOArray:ISuperobject;ColumnNames: TStringArray): ISuperObject; function SOArrayArrayExpand(SOArray: ISuperobject; ColumnName: String ): ISuperObject; function csv2SO(csv:String;Sep:Char=#0):ISuperObject; // Compare 2 values given their PropertyName type TSOCompareByPropertyName=function (const PropertyName:String;const d1,d2:ISuperObject):TSuperCompareResult; type TSOCompare=function (const SO1,SO2:ISuperObject):integer; // Default function to QuickSort an arrays of SuperObject. function DefaultSOCompareFunc(const SO1,SO2:ISuperObject):integer; procedure Sort(SOArray: ISuperObject;CompareFunc: TSOCompare;Reversed:Boolean=False); // procedure SOArrayExtend(const TargetArray,NewElements:ISuperObject); // Sort the Array SOArray using the composite key described by keys array procedure SortByFields(SOArray: ISuperObject;Fields:array of string;reversed:Boolean=False); // return an object with only keys attributes. If keys is empty, return SO itself. function SOExtractFields(SO:ISuperObject; const keys: Array of String):ISuperObject; // return an object without the ExcludedKeys attributes. If ExcludedKeys is empty, return SO itself. function SOFilterFields(SO:ISuperObject; const ExcludedKeys: Array of String):ISuperObject; // extract one string property as an array of string function SOExtractStringField(SOList:ISuperObject;const fieldname:String):TStringArray; //Compare 2 SO objects given a list of keys function SOCompareByKeys(SO1, SO2: ISuperObject; const keys: array of String;const CompareFunc:TSOCompareByPropertyName=Nil;DirectProperties:Boolean=False): TSuperCompareResult; // Return the first occurence of AnObject in the List of objects, using the composite key described by keys array function SOArrayFindFirst(AnObject, List: ISuperObject; const keys: array of String): ISuperobject; function SOArrayIndexOf(AnObject, List: ISuperObject): Integer; function SOArrayIndexOf(const S:String; List: ISuperObject): Integer; // string splitted by comma. function SOEnsureList(StringOrArray: ISuperObject): ISuperObject; function CompareInt(i1,i2: Int64):Integer; function GetIntCompResult(const i: int64): TSuperCompareResult; function SOArrayIntersect(const a1,a2:ISuperObject):ISuperObject; function StringArrayIntersect(const a1,a2:TStringArray):TStringArray; implementation uses StrUtils; operator in(const a:string;const b:Array Of String):Boolean;inline; var i:integer; begin //result := pos(a,b)>=0; Result := False; for i :=Low(b) to High(b) do if a = b[i] then begin Result := True; Break; end; end; function CompareInt(i1,i2: Int64):Integer; begin if i1<i2 then Result := -1 else if i1>i2 then Result := 1 else Result := 0; end; function GetIntCompResult(const i: int64): TSuperCompareResult; begin if i < 0 then result := cpLess else if i = 0 then result := cpEqu else Result := cpGreat; end; function SOArray2StringArray(items: ISuperObject): TStringArray; var s:ISuperObject; i:integer; begin if (items<>Nil) and (items.AsArray<>Nil) then begin SetLength(result,items.AsArray.Length); i:= 0; for s in items do begin result[i] := Utf8Encode(s.AsString); inc(i); end; end else SetLength(result,0); end; function StrToken(var S: string; Separator: String): string; var I: SizeInt; begin I := Pos(Separator, S); if I <> 0 then begin Result := Copy(S, 1, I - 1); Delete(S, 1, I+Length(Separator)-1); end else begin Result := S; S := ''; end; end; function DynArr2SOArray(const items: array of String): ISuperObject; var i:integer; begin Result := TSuperObject.Create(stArray); for i:=low(items) to High(items) do Result.AsArray.Add(items[i]); end; function StringList2SOArray(St: TStringList): ISuperObject; var i:integer; begin Result := TSuperObject.Create(stArray); for i:=0 to st.Count-1 do Result.AsArray.Add(st[i]); end; function SplitLines(const St: String): ISuperObject; var tok : String; St2:String; begin Result := TSuperObject.Create(stArray); St2 := StrUtils.StringsReplace(St,[#13#10,#13,#10],[#13,#13,#13],[rfReplaceAll]); while St2<>'' do begin tok := StrToken(St2,#13); Result.AsArray.Add(UTF8Decode(tok)); end; end; function Split(const St: String; Sep: String): ISuperObject; var tok : String; St2:String; begin Result := TSuperObject.Create(stArray); St2 := St; while St2<>'' do begin tok := StrToken(St2,Sep); Result.AsArray.Add(tok); end; end; function ExtractField(SOList:ISuperObject;const fieldname:String;NilIfNil:Boolean=True):ISuperObject; var item:ISuperObject; begin if (SOList<>Nil) and (SOList.AsArray<>Nil) then begin Result := TSuperObject.Create(stArray); for item in SOList do begin if Item.DataType = stObject then Result.AsArray.Add(item[fieldname]) else if Item.DataType = stArray then Result.AsArray.Add(item.AsArray[StrToInt(fieldname)]); end; end else if NilIfNil then Result := Nil else Result := SA([]); end; function SOFilterFields(SO: ISuperObject; const ExcludedKeys: array of String ): ISuperObject; var key: ISuperObject; begin if length(ExcludedKeys) = 0 then Result := SO else begin result := TSuperObject.Create(stObject); for key in SO.AsObject.GetNames do if not (key.AsString in ExcludedKeys) then Result[key.AsString] := SO[key.AsString]; end; end; function SOExtractStringField(SOList:ISuperObject;const fieldname:String):TStringArray; var item:ISuperObject; i: integer; begin if (SOList<>Nil) and (SOList.AsArray<>Nil) then begin SetLength(Result,SOList.AsArray.Length); i := 0; for item in SOList do begin if Item.DataType = stObject then Result[i] := item.S[fieldname] else if Item.DataType = stArray then Result[i] := item.AsArray.S[StrToInt(fieldname)]; inc(i); end; end else Result := Nil; end; function ExtractFields(SOList: ISuperObject; const keys: array of String ): ISuperObject; var item:ISuperObject; begin if(SOList<>Nil) then begin if (SOList.DataType <> stArray) then Raise Exception.Create('Need a TSuperObject Array'); Result := TSuperObject.Create(stArray); for item in SOList do Result.AsArray.Add(SOExtractFields(item,keys)) end else Result := Nil; end; function Join(const Sep: String; Arr: ISuperObject): String; var item:ISuperObject; begin result := ''; if Arr<>Nil then begin if Arr.DataType=stArray then for item in Arr do begin if Result<>'' then Result:=Result+Sep; Result:=Result+UTF8Encode(item.AsString); end else Result := UTF8Encode(Arr.AsString); end; end; // return True if St is in the List list of string function StrIn(const St: String; List: ISuperObject): Boolean; var it:ISuperObject; begin if List <>Nil then for it in List do begin if (it.DataType=stString) and (it.AsString=St) then begin result := True; Exit; end; end; result := False; end; function RemoveDuplicates(SOArray: ISuperObject): ISuperObject; var Done: Array of UnicodeString; item: ISuperObject; s: UnicodeString; begin Result := TSuperObject.Create(stArray); for item in SOArray do begin s := item.AsString; if not (s in Done) then begin SetLength(Done,Length(Done)+1); Done[Length(Done)-1] := s; Result.AsArray.Add(item); end; end; end; function SOArrayArrayExpand(SOArray: ISuperobject; ColumnNames: TStringArray ): ISuperObject; var item,row: ISUperObject; i: integer; begin Result := TSuperObject.Create(stArray); for item in SOArray do begin row := SO(); for i:=0 to length(ColumnNames)-1 do row[ColumnNames[i]] := item.AsArray[i]; Result.AsArray.Add(row); end; end; function SOArrayArrayExpand(SOArray: ISuperobject; ColumnName: String ): ISuperObject; var item: ISUperObject; begin Result := TSuperObject.Create(stArray); if Assigned(SOArray) then for item in SOArray do // single item Result.AsArray.Add(SO([ColumnName, item])); end; function csv2SO(csv: String;Sep:Char=#0): ISuperObject; var r,col,maxcol:integer; row : String; Lines,header,values,newrec:ISuperObject; begin lines := SplitLines(csv); row := UTF8Encode(lines.AsArray.S[0]); if Sep=#0 then begin if pos(#9,row)>0 then Sep := #9 else if pos(';',row)>0 then Sep := ';' else if pos(',',row)>0 then Sep := ','; end; header := Split(row,Sep); result := TSuperObject.Create(stArray); if Lines.AsArray.Length>1 then for r:=1 to lines.AsArray.Length-1 do begin row := Utf8Encode(lines.AsArray.S[r]); values :=Split(row,sep); Newrec := TSuperObject.Create; result.AsArray.Add(newrec); maxcol := values.AsArray.Length; if maxcol > header.AsArray.Length then maxcol := header.AsArray.Length; for col := 0 to maxcol-1 do newrec.S[header.AsArray.S[col]] := values.AsArray.S[col]; end else begin Newrec := TSuperObject.Create; result.AsArray.Add(newrec); for col := 0 to header.AsArray.Length-1 do newrec.S[header.AsArray.S[col]] := ''; end; end; function DefaultSOCompareFunc(const SO1,SO2:ISuperObject):integer; var compresult : TSuperCompareResult; begin compresult := SO1.Compare(SO2); case compresult of cpLess : Result := -1; cpEqu : Result := 0; cpGreat : Result := 1; cpError : Result := CompareStr(Utf8Encode(SO1.AsString),Utf8Encode(SO2.AsString)); end; end; procedure Sort(SOArray: ISuperObject;CompareFunc: TSOCompare;Reversed:Boolean=False); var IReversed:Integer; procedure QuickSort(L, R: integer;CompareFunc: TSOCompare;IReversed:Integer=1); var I, J : Integer; pivot, temp:ISuperObject; begin I := L; J := R; pivot := SOArray.AsArray[(L + R) div 2]; repeat while (IReversed*CompareFunc(SOArray.AsArray[I], pivot) < 0) do Inc(I); while (IReversed*CompareFunc(SOArray.AsArray[J], pivot) > 0) do Dec(J); if I <= J then begin //exchange items temp := SOArray.AsArray[I]; SOArray.AsArray[I] := SOArray.AsArray[J]; SOArray.AsArray[J] := temp; Inc(I); Dec(J); end; until I > J; if J > L then QuickSort(L, J, CompareFunc,IReversed); if I < R then QuickSort(I, R, CompareFunc,IReversed); end; begin if Reversed then IReversed:=-1 else IReversed:=1; If CompareFunc=Nil then CompareFunc := @DefaultSOCompareFunc; if (SOArray.AsArray<>Nil) and (SOArray.AsArray.Length>1) then QuickSort(0,SOArray.AsArray.Length-1,CompareFunc,IReversed); end; procedure SOArrayExtend(const TargetArray, NewElements: ISuperObject); var Elem: ISuperObject; begin For Elem in NewElements do TargetArray.AsArray.Add(Elem); end; procedure SortByFields(SOArray: ISuperObject;Fields:array of string;reversed:Boolean=False); function SOCompareFields(SOArray:ISuperObject;idx1,idx2:integer):integer; var compresult : TSuperCompareResult; SO1,SO2,F1,F2:ISuperObject; i:integer; begin SO1 := SOArray.AsArray[idx1]; SO2 := SOArray.AsArray[idx2]; for i:=low(Fields) to high(fields) do begin F1 := SO1[Fields[i]]; F2 := SO2[Fields[i]]; compresult := SO1.Compare(SO2); case compresult of cpLess : Result := -1; cpEqu : Result := 0; cpGreat : Result := 1; cpError : Result := CompareStr(Utf8Encode(F1.AsString),Utf8Encode(F2.AsString)); end; if Reversed then Result := -Result; if Result<>0 then Break; end; end; procedure QuickSort(L, R: integer); var I, J, P: Integer; item1,item2:ISuperObject; begin repeat I := L; J := R; P := (L + R) shr 1; repeat while SOCompareFields(SOArray, I, P) < 0 do Inc(I); while SOCompareFields(SOArray,J, P) > 0 do Dec(J); if I <= J then begin //exchange items item1 := SOArray.AsArray[I]; item2 := SOArray.AsArray[J]; SOArray.AsArray[I] := item2; SOArray.AsArray[J] := item1; if P = I then P := J else if P = J then P := I; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(L, J); L := I; until I >= R; end; begin if (SOArray.AsArray<>Nil) and (SOArray.AsArray.Length>1) then QuickSort(0,SOArray.AsArray.Length-1); end; function SOExtractFields(SO: ISuperObject; const keys: array of String): ISuperObject; var key: String; begin if length(keys) = 0 then Result := SO else begin result := TSuperObject.Create(stObject); for key in keys do Result[key] := SO[key]; end; end; function SOArrayIntersect(const a1,a2:ISuperObject):ISuperObject; var i,j:integer; begin Result := TSuperObject.Create(stArray); if assigned(a1) and assigned(a2) then for i:=0 to a1.AsArray.Length -1 do begin for j := 0 to a2.AsArray.Length-1 do begin if a1.AsArray[i].Compare(a2.AsArray[j]) = cpEqu then Result.AsArray.Add(a1.AsArray[i]); end; end; end; function StringArrayIntersect(const a1,a2:TStringArray):TStringArray; var i,j:integer; begin SetLength(Result,0); for i:=0 to Length(a1)-1 do begin for j := 0 to Length(a2)-1 do begin if a1[i] = a2[j] then begin SetLength(result,Length(Result)+1); result[Length(result)-1] := a1[i]; end; end; end; end; // Compare 2 objects SO1 and SO2 by comparing each key value in turn. If CompareFunc is supplied, comparison function can be based on the key name function SOCompareByKeys(SO1, SO2: ISuperObject; const keys: array of String;const CompareFunc:TSOCompareByPropertyName=Nil;DirectProperties:Boolean=False): TSuperCompareResult; var i: integer; key: String; reckeys: Array of String; PropValue1,PropValue2: ISuperObject; begin // Nil is Less than something.. if (SO1=Nil) and (SO2<>Nil) then begin Result := cpLess; exit; end else if (SO1<>Nil) and (SO2=Nil) then begin Result := cpGreat; exit; end else // can not compare nothing if (SO1=Nil) and (SO2=Nil) then begin Result := cpError; exit; end else // can not compare objects which have no keys... if (SO1.AsObject=Nil) or (SO2.AsObject=Nil) then begin Result := cpError; exit; end; // If no key property names, take all common attributes names to make comparison. if length(keys) = 0 then reckeys := StringArrayIntersect(SOArray2StringArray(SO1.AsObject.GetNames()),SOArray2StringArray(SO2.AsObject.GetNames())) else begin // copy list of keys passed as parameter SetLength(reckeys,length(keys)); for i := 0 to length(keys)-1 do reckeys[i] := keys[i]; end; // If no key -> error if (length(reckeys) = 0) then result := cpError else for key in reckeys do begin if (key<>'') then begin if DirectProperties then begin PropValue1 := SO1.AsObject[key]; PropValue2 := SO2.AsObject[key]; end else begin PropValue1 := SO1[key]; PropValue2 := SO2[key]; end; if (PropValue1 = Nil) and (PropValue2 = Nil) or (ObjectIsNull(PropValue1) and ObjectIsNull(PropValue2)) then // both objects have no value with this key. Result := cpEqu else if ((PropValue1 = Nil) or ObjectIsNull(PropValue1)) and ((PropValue2 <> Nil) and not ObjectIsNull(PropValue2)) then // Nil first Result := cpLess else if ((PropValue1 <> Nil) and not ObjectIsNull(PropValue1)) and ((PropValue2 = Nil) or ObjectIsNull(PropValue2)) then // Nil first Result := cpGreat else // TODO: problem when comparison returns cpError if not Assigned(CompareFunc) then begin if PropValue1 <> Nil then Result := PropValue1.Compare(PropValue2) else Result := cpEqu; end else Result := CompareFunc(key,PropValue1,PropValue2); end else Result := cpEqu; if (Result <> cpEqu) then break; end; end; function SOArrayFindFirst(AnObject, List: ISuperObject; const keys: array of String ): ISuperobject; var item: ISuperObject; key:String; begin Result := Nil; for item in List do begin if length(keys) = 0 then begin if (item = AnObject) or (item.Compare(AnObject) = cpEqu) then begin Result := item; exit; end; end else begin for key in keys do begin if (item[key]<>Nil) and (item[key].Compare(AnObject[key]) <> cpEqu) then break; end; if (item[key]<>Nil) and (item[key].Compare(AnObject[key]) = cpEqu) then begin Result := item; exit; end; end; end; end; function SOArrayIndexOf(AnObject, List: ISuperObject): Integer; var item: ISuperObject; begin if Assigned(List) and (List.DataType=stArray) then for result := 0 to List.AsArray.Length-1 do if (List.AsArray[Result] = AnObject) or (List.AsArray[Result].Compare(AnObject) = cpEqu) then exit; Result := -1; end; function SOArrayIndexOf(const S: String; List: ISuperObject): Integer; begin if Assigned(List) and (List.DataType=stArray) then for result := 0 to List.AsArray.Length-1 do if List.AsArray.S[Result] = S then exit; Result := -1; end; // string splitted by comma. function SOEnsureList(StringOrArray: ISuperObject): ISuperObject; begin if not Assigned(StringOrArray) then Result := TSuperObject.Create(stArray) else if StringOrArray.DataType=stArray then Result := StringOrArray else Result := SOUtils.Split(StringOrArray.AsString,','); end; function StringArray2SOArray(A:TStringArray):ISuperObject; var s:String; begin Result := TSuperObject.Create(stArray); for s in A do Result.AsArray.Add(s); end; function MergeSOArrays(A,B:ISuperObject):ISuperObject; var item,itemA:ISuperObject; DoAppend: Boolean; begin result := A.Clone; for item in B do begin DoAppend := True; for itemA in result do if itemA.Compare(item) = cpEqu then begin DoAppend := False; break; end; if DoAppend then result.AsArray.Add(item); end; end; function SOAggregate(Rows: ISuperObject; KeyName: String; AggFieldName: String=''): ISuperObject; var Key: UnicodeString; Row,Data: ISuperObject; begin Result := SO(); for Row in Rows do begin Key := Row.S[KeyName]; if (AggFieldName<>'') then Data := Row[AggFieldName] else Data := Row; if Result.AsObject.Exists(Key) then Result.A[Key].Add(Data) else Result[Key] := SA([Data]); end; end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Scene3D.Renderer.CameraPreset; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface uses SysUtils, Classes, Math, Vulkan, PasVulkan.Types, PasVulkan.Math, PasVulkan.Framework, PasVulkan.Application, PasVulkan.VirtualReality, PasVulkan.VirtualFileSystem; type { TpvScene3DRendererCameraPreset } TpvScene3DRendererCameraPreset=class public type TShaderData=packed record SensorSize:TpvVector2; FocalLength:TpvFloat; FlangeFocalDistance:TpvFloat; FocalPlaneDistance:TpvFloat; FNumber:TpvFloat; FNumberMin:TpvFloat; FNumberMax:TpvFloat; Ngon:TpvFloat; HighlightThreshold:TpvFloat; HighlightGain:TpvFloat; BokehChromaticAberration:TpvFloat; end; PShaderData=^TShaderData; private fSensorSize:TpvVector2; fSensorSizeProperty:TpvVector2Property; fFocalLength:TpvFloat; fFlangeFocalDistance:TpvFloat; fFocalPlaneDistance:TpvFloat; fFNumber:TpvFloat; fFNumberMin:TpvFloat; fFNumberMax:TpvFloat; fBlurKernelSize:TpvInt32; fNgon:TpvFloat; fMaxCoC:TpvFloat; fHighlightThreshold:TpvFloat; fHighlightGain:TpvFloat; fBokehChromaticAberration:TpvFloat; fAutoFocus:boolean; function GetFieldOfViewAngleRadians:TpvFloat; function GetAspectRatio:TpvFloat; public constructor Create; reintroduce; destructor Destroy; override; procedure Assign(const aFrom:TpvScene3DRendererCameraPreset); published // Sensor size at digital cameras in mm (or film size at analog cameras) property SensorSize:TpvVector2Property read fSensorSizeProperty; // Focal length in mm property FocalLength:TpvFloat read fFocalLength write fFocalLength; // Flange focal distance in mm (distance from lens to sensor) property FlangeFocalDistance:TpvFloat read fFlangeFocalDistance write fFlangeFocalDistance; // Focal plane distance in mm (distance from lens to focused plane world point) property FocalPlaneDistance:TpvFloat read fFocalPlaneDistance write fFocalPlaneDistance; // f-number (f/n) property FNumber:TpvFloat read fFNumber write fFNumber; // minimum f-number property FNumberMin:TpvFloat read fFNumberMin write fFNumberMin; // maximum f-number property FNumberMax:TpvFloat read fFNumberMax write fFNumberMax; // ngon property Ngon:TpvFloat read fNgon write fNgon; // Blur kernel size property BlurKernelSize:TpvInt32 read fBlurKernelSize write fBlurKernelSize; // maximum CoC radius property MaxCoC:TpvFloat read fMaxCoC write fMaxCoC; // Highlight threshold property HighlightThreshold:TpvFloat read fHighlightThreshold write fHighlightThreshold; // Highlight gain property HighlightGain:TpvFloat read fHighlightGain write fHighlightGain; // Bokeh chromatic aberration/fringing property BokehChromaticAberration:TpvFloat read fBokehChromaticAberration write fBokehChromaticAberration; // Angle of field of view in radians property FieldOfViewAngleRadians:TpvFloat read GetFieldOfViewAngleRadians; // Aspect ratio property AspectRatio:TpvFloat read GetAspectRatio; // AutoFocus property AutoFocus:boolean read fAutoFocus write fAutoFocus; end; implementation { TpvScene3DRendererCameraPreset } constructor TpvScene3DRendererCameraPreset.Create; begin inherited Create; fSensorSize:=TpvVector2.Create(36.0,24.0); // 36 x 24 mm fSensorSizeProperty:=TpvVector2Property.Create(@fSensorSize); fFocalLength:=50.0; fFlangeFocalDistance:=100.0; fFocalPlaneDistance:=4000.0; fFNumber:=16.0; fFNumberMin:=1.0; fFNumberMax:=16.0; fNgon:=6; fBlurKernelSize:=8; fMaxCoC:=0.05; fHighlightThreshold:=0.25; fHighlightGain:=1.0; fBokehChromaticAberration:=0.7; fAutoFocus:=true; end; destructor TpvScene3DRendererCameraPreset.Destroy; begin FreeAndNil(fSensorSizeProperty); inherited Destroy; end; procedure TpvScene3DRendererCameraPreset.Assign(const aFrom:TpvScene3DRendererCameraPreset); begin fSensorSize:=aFrom.fSensorSize; fFocalLength:=aFrom.fFocalLength; fFlangeFocalDistance:=aFrom.fFlangeFocalDistance; fFocalPlaneDistance:=aFrom.fFocalPlaneDistance; fFNumber:=aFrom.fFNumber; fFNumberMin:=aFrom.fFNumberMin; fFNumberMax:=aFrom.fFNumberMax; fBlurKernelSize:=aFrom.fBlurKernelSize; fNgon:=aFrom.fNgon; fMaxCoC:=aFrom.fMaxCoC; fHighlightThreshold:=aFrom.fHighlightThreshold; fHighlightGain:=aFrom.fHighlightGain; fBokehChromaticAberration:=aFrom.fBokehChromaticAberration; fAutoFocus:=aFrom.fAutoFocus; end; function TpvScene3DRendererCameraPreset.GetFieldOfViewAngleRadians:TpvFloat; begin result:=2.0*ArcTan((fSensorSize.x*(fFocalPlaneDistance-fFocalLength))/(2.0*fFocalPlaneDistance*fFocalLength)); end; function TpvScene3DRendererCameraPreset.GetAspectRatio:TpvFloat; begin result:=fSensorSize.x/fSensorSize.y; end; initialization finalization end.
program testconst02(output); {tests constants in procedures, including constants with different values in different scopes} const maxthis = 80; minthis = -4.28; somestring = 'my string'; procedure testconsts(a:integer; b:real); const localone = 1; minthis = -5.96; {redefined name} begin writeln ('here, minthis should be -5.96: ', minthis); writeln (a + maxthis + localone); {references a local and global constant} writeln(b * (11.92 / minthis)); end; begin writeln('here, minthis should be -4.28: ', minthis); writeln('next two results should be 88 and 4.0'); testconsts(7, 2.0); end.
unit TestGnSet; interface uses SysUtils, TestFramework, uGnSet, uGnTestUtils, uGnGenerics; type Test_GnSet = class(TTestCase) strict private FSet: TGnSet_Cardinal.IGnSetSpec; public procedure SetUp; override; published procedure Append1; procedure Append2; procedure Delete1; procedure Contains1; procedure Enum1; procedure Union1; procedure InSect1; procedure IsEmpty1; end; implementation procedure Test_GnSet.SetUp; begin FSet := TGnSet_Cardinal.Create; end; procedure Test_GnSet.Append2; begin FSet.Append([0, 2, 3]); CheckEnumTrue(FSet.GetEnumerator, [0, 2, 3]); FSet.Append([2, 3, 4, 5]); CheckEnumTrue(FSet.GetEnumerator, [0, 2, 3, 4, 5]); end; procedure Test_GnSet.Contains1; begin CheckFalse(FSet.Contains(0)); FSet.Append(0); CheckTrue(FSet.Contains(0)); FSet.Delete(0); CheckFalse(FSet.Contains(0)); FSet.Append(0); FSet.Append(123); FSet.Append(5555555); CheckTrue(FSet.Contains(0)); CheckTrue(FSet.Contains(123)); CheckTrue(FSet.Contains(5555555)); end; procedure Test_GnSet.Delete1; begin FSet.Append(0); FSet.Append(123); FSet.Append(5555555); CheckEquals(FSet.Count, 3); FSet.Delete(22); CheckEquals(FSet.Count, 3); FSet.Delete(123); CheckEquals(FSet.Count, 2); FSet.Delete(123); CheckEquals(FSet.Count, 2); CheckEquals(FSet[0], 0); CheckEquals(FSet[1], 5555555); FSet.Delete(0); FSet.Delete(5555555); CheckEquals(FSet.Count, 0); FSet.Delete(0); FSet.Delete(5555555); CheckEquals(FSet.Count, 0); end; procedure Test_GnSet.Enum1; begin CheckEnumTrue(FSet.GetEnumerator, []); FSet.Append(1); FSet.Append(2); FSet.Append(3); CheckEnumTrue(FSet.GetEnumerator, [1, 2, 3]); FSet.Append(4); FSet.Append(5); CheckEnumTrue(FSet.GetEnumerator, [1, 2, 3, 4, 5]); end; procedure Test_GnSet.InSect1; var Set2: TGnSet_Cardinal.IGnSetSpec; begin Set2 := TGnSet_Cardinal.Create; CheckFalse(FSet.IsSect(Set2)); Set2.Append(1); Set2.Append(2); CheckFalse(FSet.IsSect(Set2)); FSet.Append(3); FSet.Append(4); CheckFalse(FSet.IsSect(Set2)); Set2.Append(3); CheckTrue(FSet.IsSect(Set2)); end; procedure Test_GnSet.Append1; begin CheckEquals(FSet.Count, 0); FSet.Append(0); CheckEquals(FSet.Count, 1); FSet.Append(123); CheckEquals(FSet.Count, 2); FSet.Append(5555555); CheckEquals(FSet.Count, 3); FSet.Append(123); CheckEquals(FSet.Count, 3); FSet.Append(123); CheckEquals(FSet.Count, 3); CheckEquals(FSet[0], 0); CheckEquals(FSet[1], 123); CheckEquals(FSet[2], 5555555); end; procedure Test_GnSet.IsEmpty1; begin CheckTrue(FSet.IsEmpty); FSet.Append(5); CheckFalse(FSet.IsEmpty); FSet.Append(6); CheckFalse(FSet.IsEmpty); FSet.Delete(6); CheckFalse(FSet.IsEmpty); FSet.Delete(5); CheckTrue(FSet.IsEmpty); end; procedure Test_GnSet.Union1; var Set2: TGnSet_Cardinal.IGnSetSpec; begin Set2 := TGnSet_Cardinal.Create; FSet.UnionFrom(Set2); CheckEquals(FSet.Count, 0); CheckEquals(Set2.Count, 0); Set2.Append([1, 2]); FSet.UnionFrom(Set2); CheckEnumTrue(FSet.GetEnumerator, [1, 2]); CheckEnumTrue(Set2.GetEnumerator, [1, 2]); FSet.Append([5, 6]); FSet.UnionFrom(Set2); CheckEnumTrue(FSet.GetEnumerator, [1, 2, 5, 6]); CheckEnumTrue(Set2.GetEnumerator, [1, 2]); Set2.Append([3, 4]); FSet.UnionFrom(Set2); CheckEnumTrue(FSet.GetEnumerator, [1, 2, 3, 4, 5, 6]); CheckEnumTrue(Set2.GetEnumerator, [1, 2, 3, 4]); end; initialization RegisterTest(Test_GnSet.Suite); end.
unit ReflectModelIntf; interface uses InfraValueTypeIntf; type IAddress = interface; IPerson = interface ['{52768039-C8B4-4E31-BA9B-E765951454A8}'] procedure SetAddress(const Value: IAddress); procedure SetBirthday(const Value: IInfraDate); procedure SetEmail(const Value: IInfraString); procedure SetName(const Value: IInfraString); function GetAddress: IAddress; function GetBirthday: IInfraDate; function GetAge: IInfraInteger; function GetEmail: IInfraString; function GetName: IInfraString; property Address: IAddress read GetAddress write SetAddress; property Name: IInfraString read GetName write SetName; property Email: IInfraString read GetEmail write SetEmail; property Birthday: IInfraDate read GetBirthday write SetBirthday; end; IStudent = interface(IPerson) ['{996D9565-F487-4766-B2F9-F37BEB74AE2F}'] function GetSchoolNumber: IInfraString; procedure SetSchoolNumber(const Value: IInfraString); property SchoolNumber: IInfraString read GetSchoolNumber write SetSchoolNumber; end; IAddress = interface ['{844C021B-8D73-4CC9-867A-9553BAA0F0A2}'] function GetCity: IInfraString; function GetNumber: IInfraInteger; function GetQuarter: IInfraString; function GetStreet: IInfraString; procedure SetCity(const Value: IInfraString); procedure SetNumber(const Value: IInfraInteger); procedure SetQuarter(const Value: IInfraString); procedure SetStreet(const Value: IInfraString); property Street: IInfraString read GetStreet write SetStreet; property City: IInfraString read GetCity write SetCity; property Quarter: IInfraString read GetQuarter write SetQuarter; property Number: IInfraInteger read GetNumber write SetNumber; end; IMyMethodsClass = Interface ['{32E1DD21-2537-4A27-A3DE-481E85A8E246}'] function GetMessage: IInfraString; function MethodFunc0: IInfraString; function MethodFunc1(const p1: IInfraString): IInfraString; function MethodFunc2(const p1: IInfraString; const p2:IInfraInteger): IInfraInteger; function MethodFunc3(const p1: IInfraString; const p2:IInfraInteger; const p3: IInfraDateTime): IInfraDateTime; function MethodFunc4(const p1: IInfraString; const p2:IInfraInteger; const p3: IInfraDateTime; const p4: IInfraBoolean): IInfraBoolean; function MethodFunc5(const p1: IInfraString; const p2:IInfraInteger; const p3: IInfraDateTime; const p4: IInfraBoolean; const p5: IInfraDouble): IInfraDouble; procedure MethodProc0; procedure MethodProc1(const p1: IInfraString); procedure MethodProc2(const p1: IInfraString; const p2:IInfraInteger); procedure MethodProc3(const p1: IInfraString; const p2:IInfraInteger; const p3: IInfraDateTime); procedure MethodProc4(const p1: IInfraString; const p2:IInfraInteger; const p3: IInfraDateTime; const p4: IInfraBoolean); procedure MethodProc5(const p1: IInfraString; const p2:IInfraInteger; const p3: IInfraDateTime; const p4: IInfraBoolean; const p5: IInfraDouble); property Message: IInfraString read GetMessage; end; implementation end.
unit tpShell; (* Permission is hereby granted, on 3-Aug-2005, free of charge, to any person obtaining a copy of this file (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Author of original version of this file: Michael Ax *) interface { // TtpProcess: Base class used by the dos/windows/dll shell components // TWindowsShell: Component-based WinExec call. // TDLLShell: Provides assistance with calling procs in a DLL. } {$I hrefdefines.inc} { Master copy of hrefdefines.inc is versioned on Source Forge in the ZaphodsMap project: https://sourceforge.net/p/zaphodsmap/code/HEAD/tree/trunk/ZaphodsMap/Source/hrefdefines.inc } uses {$IFDEF MSWINDOWS} Windows, Forms, Controls, Messages, {$ENDIF} {$IFDEF LINUX} // Kylix QForms, QControls, {$ENDIF} Classes, SysUtils, updateOK, tpAction, ucWinSecurityObj, ucString; Const DefaultProcessor = 'COMMAND.COM'; Const ShowCommands:array[TWindowState] of word = (SW_SHOWNORMAL,SW_SHOWMINIMIZED,SW_SHOWMAXIMIZED); Type TShellOptions = (shlWaitTillIdle,shlWaitTillDone,shlUseShell,shlMsgTillReady,shlMsgTillDone); TShellFlags = set of TShellOptions; TTpProcess = class(TtpAction) private fFlags : TShellFlags; fShellResult : DWORD; fOnShelled : TNotifyEvent; fOnWait : TNotifyEvent; // fWorking : TWorkingMsg; {See Note 1 at end of file} protected fCommand : String; fCommandLine : String; function DoShell: DWORD; Virtual; procedure DoOnShell; Virtual; procedure SetCommand(const Value:String); virtual; procedure SetCommandLine(const Value:String); public constructor Create(AOwner: TComponent); override; // procedure Notification(AComponent: TComponent; Operation: TOperation); Override; {Note 1} procedure DoExecute; override; procedure Run(const aCmd,aParam:String); property Command : String read fCommand write SetCommand; property Parameters : String read fCommandLine write SetCommandLine; published // property Working : TWorkingMsg read fWorking write fWorking; {Note 1} property Flags : TShellFlags read fFlags write fFlags; property ShellResult : DWORD read fShellResult write fShellResult stored false; property OnShelled : TNotifyEvent read fOnShelled write fOnShelled; property OnWait : TnotifyEvent read fOnWait write fOnWait; end; TDLLShell = class(TTpProcess) protected function DoShell: DWORD; Override; public constructor Create(AOwner: TComponent); override; published property Module : String read fCommand write SetCommand; property Proc : String read fCommandLine write SetCommandLine; end; TWindowsShell = class(TTpProcess) {Note that from here on ShellResult equals the Handle returned by the shell. You can use ShellResult to see if the window is still there like the code associated with shlWaitTillDone even if that flag is not actually set.} private fWindowStyle: TWindowState; fShowWindow: word; // fOnPreShell : TNotifyEvent; // fOnPostShell : TNotifyEvent; // fOnWait : TNotifyEvent; procedure SetWindowStyle(Value:TWindowState); protected function DoShell: DWORD; Override; procedure SetCommand(const Value:String); override; function GetTest:Boolean; Override; function GetComSpec: String; {returns default if blank} function GetExecStr: String; procedure SetExecStr(const Value:String); procedure SetNoString(const Value:String); public StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; constructor Create(AOwner: TComponent); override; constructor CreateWait(AOwner: TComponent;const aCommand,aParameter:String); published property Command; property Parameters; property ShowWindow: word read fShowWindow write fShowWindow stored false; property ComSpec: String read GetComSpec write SetNoString stored false; property ExecString : String read GetExecStr write SetExecStr stored false; // property WindowStyle : TWindowState read fWindowStyle write SetWindowStyle; end; function GetEnvVar(const Value:String):String; //procedure Register; implementation uses ucShell; {------------------------------------------------------------------------------} function GetEnvVar(const Value:String):String; const cLength=80; var i:integer; begin Result:=''; SetLength(Result,cLength); i:=GetEnvironmentVariable(pchar(Value),pchar(Result),cLength); Result:=copy(Result,1,i); end; {-------------------------------------------------------------------------} constructor TTpProcess.Create(AOwner: TComponent); begin inherited Create(AOwner); end; (* See Note 1 procedure TTpProcess.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (csUpdating in ComponentState) then exit; if Operation = opRemove then begin cx.NilIfSet(fWorking,AComponent); end; end; *) procedure TTpProcess.Run(const aCmd,aParam:String); begin Command:=aCmd; Parameters:=aParam; Execute; end; Procedure TTpProcess.DoExecute; begin { See Note 1 if (fFlags*[shlMsgTillReady,shlMsgTillDone])<>[] then begin cx.MakeIfNil(fWorking,TWorkingMsg); fWorking.BusyOn; end; } inherited DoExecute; fShellResult:=DoShell; { See Note 1 if fWorking<>nil then begin fWorking.BusyOff; fWorking:=nil; end; } end; function TTpProcess.DoShell:DWORD; {someone overrides this method shells than calls inherited to manage the message} begin Result:=0; DoOnShell; { See Note 1 if (shlMsgTillReady in fFlags) and (fWorking<>nil) then begin fWorking.BusyOff; fWorking:=nil; end; } end; procedure TTpProcess.DoOnShell; begin if Assigned(fOnShelled) then fOnShelled(Self); end; {} procedure TTpProcess.SetCommand(const Value:String); begin fCommand:=Value; end; {} procedure TTpProcess.SetCommandLine(const Value:String); begin fCommandLine:=Value; end; {-----------------------------------------------------------------------------------------} { TDLLShell } {-----------------------------------------------------------------------------------------} constructor TDLLShell.Create(AOwner: TComponent); begin inherited Create(AOwner); end; function TDLLShell.DoShell:DWORD; var DllName, ProcName: PChar; LinkedProc: Procedure; Handle: THandle; begin Result:=0; { if not FileExists(Module) then raise Exception.Create(classname+': Module '+Module+' does not exist!');} if ExtractFileExt(Module)='' then DllName:=PChar(ChangeFileExt(Module,'.DLL')) else DllName:=PChar(Module); try Handle:=LoadLibrary(DllName); if Handle<ErrorThreshold then raise Exception.Create(classname+': Handle for Module '+Module+' is '+inttostr(longint(Handle))); ProcName:=PChar(Proc); try TFarProc(@LinkedProc):= GetProcAddress(Handle, ProcName); if TFarProc(@LinkedProc)=nil then raise Exception.Create(classname+': Module '+Module+' has no procedure '+Proc); inherited DoShell; {can turn off message} LinkedProc; finally FreeLibrary(Handle); end; finally end; end; {-----------------------------------------------------------------------------------------} { TWindowsShell } {-----------------------------------------------------------------------------------------} constructor TWindowsShell.Create(AOwner: TComponent); begin inherited Create(AOwner); fFlags:=[shlWaitTillIdle]; WindowStyle:=wsNormal; end; constructor TWindowsShell.CreateWait(AOwner: TComponent;const aCommand,aParameter:String); begin inherited Create(AOwner); if aCommand='' then begin Flags:= Flags+[shlUseShell]; ExecString:= aParameter; end else begin Command:=aCommand; Parameters:=aParameter; end; Flags:=Flags+[shlWaitTillIdle,shlWaitTillDone,shlMsgTillReady,shlMsgTillDone]; end; {} procedure TWindowsShell.SetWindowStyle(Value:TWindowState); begin fWindowStyle:=Value; fShowWindow:=ShowCommands[fWindowStyle]; end; function TWindowsShell.DoShell:DWORD; var a1,a2: string; begin Result:=0; a1:= Command; a2:= Parameters; FillChar(StartupInfo, SizeOf(TStartupInfo), 0); //windows with StartupInfo do begin cb := SizeOf(TStartupInfo); dwFlags := STARTF_USESHOWWINDOW or STARTF_FORCEONFEEDBACK; wShowWindow:= fShowWindow; end; if CreateProcess(nil, PChar(a1+' '+a2), @gsa, @gsa, False, NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo) then with ProcessInfo do begin if (fFlags*[shlWaitTillIdle])<>[] then begin WaitForInputIdle(hProcess, INFINITE); end; inherited DoShell; if (fFlags*[shlMsgTillDone,shlWaitTillDone])<>[] then begin WaitForSingleObject(hProcess, INFINITE); end; CloseHandle(hThread); if not GetExitCodeProcess(hProcess,Result) then Result:=DWORD(-1); CloseHandle(hProcess); //windows end else Result:=DWORD(-1); end; function TWindowsShell.GetTest:Boolean; begin Result:= (fShellResult=0) or (fShellResult>=32); end; procedure TWindowsShell.SetNoString(const Value:String); begin end; {-----------------------------------------------------------------------------------------} function TWindowsShell.GetExecStr:String; begin Result:=Command+' '+Parameters; end; procedure TWindowsShell.SetExecStr(const Value:String); var a1,a2:string; begin if shlUseShell in fFlags then a1:=ComSpec+' /C '+a1 else a1:=Value; splitString(a1,' ',a1,a2); Command:=a1; Parameters:=a2; end; function TWindowsShell.GetComSpec: String; begin Result:=GetEnvVar('COMSPEC'); if Result='' then Result:=DefaultProcessor; end; procedure TWindowsShell.SetCommand(const Value:String); begin fCommand:=Value; if pos('.',fCommand)=0 then fCommand:=fCommand+'.exe'; end; //---------------------------------------------------------------------- //procedure Register; //begin // RegisterComponents('TPACK', [TTpProcess,TDLLShell,TWindowsShell]); //end; //---------------------------------------------------------------------- { Note 1: The source to working.pas was posted at www.href.com/pub/source on 24-Mar-2003. } end.
unit YUVImage; interface type //#ifndef _YUVIMAGE_DEF //#define _YUVIMAGE_DEF {$ifndef _YUVIMAGE_DEF} {$define _YUVIMAGE_DEF} // YUV图像格式定义 YUV_IMAGE_FORMAT = ( YIF_444, YIF_422, YIF_YV12 // 420 ); // YUV图像数据结构定义 _YUVImage = record format :YUV_IMAGE_FORMAT; y :pByte; // Y数据指针 u :pByte; // U数据指针 v :pByte; // V数据指针 a :pByte; // Alpha 通道(不透明度) width :integer; // 图像宽度 height :integer; // 图像高度 y_pitch :integer; // Y数据每行所占字节数 u_pitch :integer; // U数据每行所占字节数 v_pitch :integer; // V数据每行所占字节数 end; PYUVImage = ^_YUVImage; {$endif} implementation end.
unit UGitHub; interface procedure CheckGitHubUpdate(const Repository, CurrentVersion: string); implementation uses System.Net.HttpClient, System.JSON, Vcl.Dialogs, Vcl.Graphics, System.SysUtils, System.UITypes, System.Classes, Vcl.ExtActns, System.IOUtils, System.Zip, Winapi.ShellAPI, Winapi.Windows, UFrm, UCommon, Vcl.Forms; const URL_GITHUB = 'https://api.github.com/repos/%s/releases/latest'; type TThCheck = class(TThread) protected procedure Execute; override; private Repository: string; CurrentVersion: string; procedure Check; procedure Download(const URL: string); procedure Log(const A: string; bBold: Boolean = True; Color: TColor = clBlack); end; procedure TThCheck.Execute; begin try Check; except on E: Exception do Log('ERROR: '+E.Message, True, clRed); end; Synchronize( procedure begin Frm.SetButtons(True); end); end; procedure TThCheck.Log(const A: string; bBold: Boolean = True; Color: TColor = clBlack); begin Synchronize( procedure begin Frm.Log(A, bBold, Color); end); end; procedure TThCheck.Check; var H: THTTPClient; Res, tag_url, tag_version, tag_zip: string; data: TJSONObject; Confirm: Boolean; begin Log('Checking for component update...'); H := THTTPClient.Create; try Res := H.Get(Format(URL_GITHUB, [Repository])).ContentAsString; finally H.Free; end; data := TJSONObject.ParseJSONValue(Res) as TJSONObject; try if data.GetValue('id')=nil then raise Exception.Create('No releases found on GitHub'); tag_version := data.GetValue('tag_name').Value; tag_url := data.GetValue('html_url').Value; tag_zip := data.GetValue('zipball_url').Value; finally data.Free; end; if tag_version.StartsWith('v', True) then Delete(tag_version, 1, 1); if CurrentVersion<>tag_version then begin Log(Format('New version "%s" available.', [tag_version]), True, clPurple); Synchronize( procedure begin Confirm := MessageDlg(Format( 'There is a new version "%s" of the component available at GitHub.'+ ' Do you want to update it automatically?'+#13#13+ 'The contents of the component''s current folder will be kept'+ ' in a new folder with the current date and time suffix.', [tag_version]), mtInformation, mbYesNo, 0) = mrYes; end); if Confirm then Download(tag_zip); end else Log('Your version is already updated.', True, clGreen); end; procedure TThCheck.Download(const URL: string); var Dw: TDownLoadURL; TmpPath, TmpFile: string; Z: TZipFile; ZInternalFile: string; ZInternalFileFound: Boolean; begin Log('Downloading new version...'); TmpPath := ChangeFileExt(TPath.GetTempFileName, string.Empty); if not CreateDir(TmpPath) then raise Exception.Create('Could not create temporary folder'); TmpFile := TPath.Combine(TmpPath, 'data.zip'); Dw := TDownLoadURL.Create(nil); try Dw.URL := URL; Dw.Filename := TmpFile; Dw.ExecuteTarget(nil); finally Dw.Free; end; Log('Extracting new Component Install app...'); Z := TZipFile.Create; try Z.Open(TmpFile, zmRead); ZInternalFileFound := False; for ZInternalFile in Z.FileNames do if SameText(NormalizeAndRemoveFirstDir(ZInternalFile), COMPINST_EXE) then begin ZInternalFileFound := True; Z.Extract(ZInternalFile, TmpPath, False); Break; end; if not ZInternalFileFound then raise Exception.Create('Component Installer not found in zip file'); finally Z.Free; end; //***FOR TEST ONLY if FileExists(TPath.Combine(AppDir, 'NO_UPD_CI_APP.TXT')) then begin TFile.Copy(Application.ExeName, TPath.Combine(TmpPath, COMPINST_EXE), True); end; //*** Log('Running new app...'); SetEnvironmentVariable('UPD_PATH', PChar(AppDir)); ShellExecute(0, '', PChar(TPath.Combine(TmpPath, COMPINST_EXE)), '/upd', '', SW_SHOWNORMAL); Synchronize(Application.Terminate); end; procedure CheckGitHubUpdate(const Repository, CurrentVersion: string); var C: TThCheck; begin if Repository.IsEmpty then Exit; Frm.SetButtons(False); C := TThCheck.Create(True); C.Repository := Repository; C.CurrentVersion := CurrentVersion; C.Start; end; end.
unit CurveFitter; // ----------------------- // Non-linear curve fitter // ----------------------- // (c) J. Dempster, University of Strathclyde, 2003 // 8-6-03 // 14.08.06 interface uses SysUtils, Classes, COmCtrls, SHDocVw ; const ChannelLimit = 7 ; LastParameter = 11 ; MaxBuf = 32768 ; MaxWork = 9999999 ; type TWorkArray = Array[0..MaxWork] of Single ; TDataArray = Array[0..MaxBuf] of Single ; TCFEqnType = ( None, Lorentzian, Lorentzian2, LorAndOneOverF, Linear, Parabola, Exponential, Exponential2, Exponential3, MEPCNoise, EPC, HHK, HHNa, Gaussian, Gaussian2, Gaussian3, PDFExp, PDFExp2, PDFExp3, PDFExp4, PDFExp5, Quadratic, Cubic, DecayingExp, DecayingExp2, DecayingExp3, Boltzmann, PowerFunc ) ; TPars = record Value : Array[0..LastParameter+1] of Single ; SD : Array[0..LastParameter+1] of Single ; Map : Array[0..LastParameter+1] of Integer ; end ; TCurveFitter = class(TComponent) private { Private declarations } FXUnits : string ; // X data units FYUnits : string ; // Y data units FEqnType : TCFEqnType ; // Type of equation to be fitted // Equation parameters Pars : Array[0..LastParameter] of single ; // Parameter values ParSDs : Array[0..LastParameter] of single ; // Parameters st. devs AbsPars : Array[0..LastParameter] of boolean ; // Positive only flags LogPars : Array[0..LastParameter] of boolean ; // Log. transform flags FixedPars : Array[0..LastParameter] of boolean ; // Fixed parameter flags ParameterScaleFactors : Array[0..LastParameter] of single ; ParsSet : Boolean ; { Initial parameters set for fit } // Data points of curve to be fitted nPoints : Integer ; // No. of data points XData : Array[0..MaxBuf] of Single ; // X values YData : Array[0..MaxBuf] of Single ; // Y values BinWidth : Array[0..MaxBuf] of Single ; // Binwidth (if histogram) Normalised : boolean ; // Data normalised { Curve fitting } ResidualSDScaleFactor : single ; UseBinWidthsFlag : Boolean ; { Use histogram bin widths in fit } ResidualSDValue : single ; { Residual standard deviation } RValue : single ; { Hamilton's R } DegreesOfFreedomValue : Integer ; { Statistical deg's of freedom } IterationsValue : Integer ; // No. of iterations to achieve fit GoodFitFlag : Boolean ; // Fit has been successful flag Procedure SetupNormalisation( xScale : single ; yScale : single ) ; function NormaliseParameter( Index : Integer ; Value : single ) : single ; function DenormaliseParameter( Index : Integer ; Value : single ) : single ; procedure SetParameter( Index : Integer ; Value : single ) ; function GetParameter( Index : Integer) : single ; function GetParameterSD( Index : Integer ) : single ; function GetLogParameter( Index : Integer ) : boolean ; function GetFixed( Index : Integer ) : boolean ; procedure SetFixed( Index : Integer ; Fixed : Boolean ) ; function GetParName( Index : Integer ) : string ; function GetParUnits( Index : Integer ) : string ; function GetNumParameters : Integer ; function GetName : String ; function PDFExpFunc( Pars : Array of single ; nExp : Integer ; X : Single ) : Single ; procedure PDFExpScaling( var AbsPars : Array of Boolean ; var LogPars : Array of Boolean ; var ParameterScaleFactors : Array of Single ; yScale : Single ; nExp : Integer ) ; procedure PDFExpNames( var ParNames : Array of String ; nExp : Integer ) ; procedure PDFExpUnits( var ParUnits : Array of String ; FXUnits : String ; nExp : Integer ) ; function GaussianFunc( Pars : Array of single ; nGaus : Integer ; X : Single ) : Single ; procedure ScaleData ; procedure UnScaleParameters ; procedure SsqMin ( var Pars : TPars ; nPoints,nPars,ItMax,NumSig,NSiqSq : LongInt ; Delta : Single ; var W,SLTJJ : Array of Single ; var ICONV,ITER : LongInt ; var SSQ : Single ; var F : Array of Single ) ; procedure FitFunc( Const FitPars :TPars ; nPoints : Integer ; nPars : Integer ; Var Residuals : Array of Single ; iStart : Integer ) ; function SSQCAL( const Pars : TPars ; nPoints : Integer ; nPars : Integer ; var Residuals : Array of Single ; iStart : Integer ; const W : Array of Single ) : Single ; procedure STAT( nPoints : Integer ; { no. of residuals (observations) } nPars : Integer ; { no. of fitted parameters } var F : Array of Single ; { final values of the residuals (IN) } var Y : Array of Single ; { Y Data (IN) } var W : Array of Single ; { Y Data weights (IN) } var SLT : Array of Single ; { lower super triangle of J(TRANS)*J from SLTJJ in SSQMIN (IN) } var SSQ : Single; { Final sum of squares of residuals (IN) Returned containing parameter corr. coeffs. as CX(1,1),CX(2,1),CX(2,2),CX(3,1)....CX(N,N)} var SDPars : Array of Single ; { OUT standard deviations of each parameter X } var SDMIN : Single ; { OUT Minimised standard deviation } var R : Single ; { OUT Hamilton's R } var XPAR : Array of Single { IN Fitted parameter array } ) ; procedure MINV( var A : Array of Single ; N : LongInt ; var D : Single ; var L,M : Array of LongInt ) ; FUNCTION SQRT1 ( R : single ) : single ; function IntLimitTo( Value, LowerLimit, UpperLimit : Integer ) : Integer ; function erf(x : Single ) : Single ; function FPower( x,y : Single ) : Single ; function SafeExp( x : single ) : single ; function MinInt( const Buf : array of LongInt ) : LongInt ; function MinFlt( const Buf : array of Single ) : Single ; function MaxInt( const Buf : array of LongInt ) : LongInt ; function MaxFlt( const Buf : array of Single ) : Single ; function GetFitResults : String ; protected { Protected declarations } public { Public declarations } constructor Create(AOwner : TComponent) ; override ; destructor Destroy ; override ; property XUnits : String Read FXUnits Write FXUnits ; property YUnits : String Read FYUnits Write FYUnits ; property Parameters[i : Integer] : single read GetParameter write SetParameter ; property ParameterSDs[i : Integer] : single read GetParameterSD ; property IsLogParameters[i : Integer] : boolean read GetLogParameter ; property FixedParameters[i : Integer] : boolean read GetFixed write SetFixed ; property ParNames[i : Integer] : string read GetParName ; property ParUnits[i : Integer] : string read GetParUnits ; procedure AddPoint( XValue : Single ; YValue : Single ) ; procedure ClearPoints ; function InitialGuess( Index : Integer ) : single ; function EquationValue( X : Single ) : Single ; { Return f(X) } procedure FitCurve ; procedure CopyResultsToWebBrowser( WebBrowser : TWebBrowser ) ; published { Published declarations } property Equation : TCFEqnType Read FEqnType Write FEqnType ; Property NumParameters : Integer Read GetNumParameters ; Property NumPoints : Integer Read nPoints ; Property ParametersSet : Boolean read ParsSet write ParsSet ; property GoodFit : Boolean read GoodFitFlag ; property DegreesOfFreedom : Integer read DegreesOfFreedomValue ; property R : single read RValue; property Iterations : Integer read IterationsValue ; property ResidualSD : single read ResidualSDValue ; property UseBinWidths : Boolean read UseBinWidthsFlag write UseBinWidthsFlag ; property EqnName : string read GetName ; property FitResults : String read GetFitResults ; end; procedure Register; implementation const MaxSingle = 1E38 ; procedure Register; begin RegisterComponents('Samples', [TCurveFitter]); end; constructor TCurveFitter.Create(AOwner : TComponent) ; { -------------------------------------------------- Initialise component's internal objects and fields -------------------------------------------------- } begin inherited Create(AOwner) ; FXUnits := '' ; FYUnits := '' ; nPoints := 0 ; end ; destructor TCurveFitter.Destroy ; { ------------------------------------ Tidy up when component is destroyed ----------------------------------- } begin { Call inherited destructor } inherited Destroy ; end ; procedure TCurveFitter.AddPoint( XValue : Single ; YValue : Single ) ; // -------------------------------------------- // Add new point to X,Y data array to be fitted // -------------------------------------------- begin if nPoints < High(XData) then begin XData[nPoints] := XValue ; YData[nPoints] := YValue ; Inc(nPoints) ; end ; end ; procedure TCurveFitter.ClearPoints ; // -------------------- // Clear X,Y data array // -------------------- begin nPoints := 0 ; end ; function TCurveFitter.GetName : String ; { ------------------------------- Get the formula of the equation -------------------------------} var Name : string ; begin Case FEqnType of Lorentzian : begin Name := ' y(f) = S<sub>0</sub>/(1 + (f/f<sub>c</sub>)<sup>2</sub>)' ; end ; Lorentzian2 : Name := ' y(f) = S<sub>1</sub>/(1 + (f/f<sub>c1</sub>)<sup>2</sup>' + ' + S<sub>2</sub>/(1 + (f/f<sub>c2</sub>)<sup>2</sup>)' ; LorAndOneOverF : Name := ' y(f) = S<sub>1</sub>/(1 + (f/F<sub>c1</sub>)<sup>2</sup>' + 'S<sub>2</sub>/f<sup>2</sup> )' ; Linear : Name := ' y(x) = Mx + C' ; Parabola : Name := ' y(x) = V<sub>b</sub> + I<sub>ux</sub> - x<sup>2</sup>/N<sub>c</sub> ' ; Exponential : Name := ' y(t) = Aexp(-t/<Font face=symbol>t</Font>) + Ss ' ; Exponential2 : Name := ' y(t) = A<sub>1</sub>exp(-t/<Font face=symbol>t</Font><sub>1</sub>1)' + 'A<sub>2</sub>exp(-t/<Font face=symbol>t</Font><sub>2</sub>) + Ss ' ; Exponential3 : Name := 'y(t) = A<sub>1</sub>exp(-t/<Font face=symbol>t</Font><sub>1</sub>1)' + '+ A<sub>2</sub>exp(-t/<Font face=symbol>t</Font><sub>2</sub>)' + '+ A<sub>3</sub>exp(-t/<Font face=symbol>t</Font><sub>3</sub>)+ Ss ' ; EPC : Name := ' y(t) = A0.5(1+erf(x-x<sub>0</sub>)/<Font face=symbol>t</Font><sub>R</sub>)' + 'exp(-(x-x<sub>0</sub>)/<Font face=symbol>t</Font><sub>D</sub>))' ; MEPCNoise : Name := ' y(f) = A/[1+(f<sup>2</sup>(1/F<sub>r</sub><sup>2</sup> ' + '+ 1/F<sub>d</sub><sup>2</sup>))' + '+f<sup>4</sup>/(F<sub>r</sub><sup>2</sup>F<sub>d</sub><sup>2</sup>)]' ; HHK : Name := ' y(t) = A(1 - exp(-t/<Font face=symbol>t</Font><sub>M</sub>)<sup>P</sup>' ; HHNa : Name := ' y(t) = A[(1 - exp(-t/<Font face=symbol>t</Font><sub>M</sub>)<sup>P</sup>]' + '[H<sub>inf</sub> - (H<sub>inf</sub>-1)exp(-t/<Font face=symbol>t</Font><sub>H</sub>)]' ; Gaussian : Name := ' y(x) = Peak exp(-(x-<Font face=symbol>m</Font>)<sup>2</sup>/' + '(2<Font face=symbol>s</Font><sup>2</sup>) )' ; Gaussian2 : Name := ' y(x) = <Font face=symbol>S</Font><sub>i=1..2</sub>' + 'Pk<sub>i</sub>exp(-(x-<Font face=symbol>m</Font><sub>i</sub>)<sup>2</sup>' + '/(2<Font face=symbol>s</Font><sub>i</sub><sup>2</sup>) )' ; Gaussian3 : Name := ' y(x) = <Font face=symbol>S</Font><sub>i=1..3</sub>' + 'Pk<sub>i</sub>exp(-(x-<Font face=symbol>m</Font><sub>i</sub>)<sup>2</sup>' + '/(2<Font face=symbol>s</Font><sub>i</sub><sup>2</sup>) )' ; PDFExp : Name := ' y(t) = (A/<Font face=symbol>t</Font>)exp(-t/<Font face=symbol>t</Font>)' ; PDFExp2 : Name := ' p(t) = <Font face=symbol>S</Font><sub>i=1..2</sub>' + '(A<sub>i</sub>/<Font face=symbol>t</Font><sub>i</sub>)' + 'exp(-t/<Font face=symbol>t</Font><sub>i</sub>)' ; PDFExp3 : Name := ' p(t) = <Font face=symbol>S</Font><sub>i=1..3</sub>' + '(A<sub>i</sub>/<Font face=symbol>t</Font><sub>i</sub>)' + 'exp(-t/<Font face=symbol>t</Font><sub>i</sub>)' ; PDFExp4 : Name := ' p(t) = <Font face=symbol>S</Font><sub>i=1..4</sub>' + '(A<sub>i</sub>/<Font face=symbol>t</Font><sub>i</sub>)' + 'exp(-t/<Font face=symbol>t</Font><sub>i</sub>)' ; PDFExp5 : Name := ' p(t) = <Font face=symbol>S</Font><sub>i=1..5</sub>' + '(A<sub>i</sub>/<Font face=symbol>t</Font><sub>i</sub>)' + 'exp(-t/<Font face=symbol>t</Font><sub>i</sub>)' ; Quadratic : Name := ' y(x) = Ax<sup>2</sup> + Bx + C' ; Cubic : Name := 'y (x) = Ax<sup>3</sup> + Bx<sup>2</sup> + Cx + D' ; DecayingExp : Name := ' y(t) = Aexp(-t/<Font face=symbol>t</Font>)' ; DecayingExp2 : Name := ' y(t) = A<sub>1</sub>exp(-t/<Font face=symbol>t</Font><sub>1</sub>)' + ' + A<sub>2</sub>exp(-t/<Font face=symbol>t</Font><sub>2</sub>)' ; DecayingExp3 : Name := ' y(t) = A<sub>1</sub>exp(-t/<Font face=symbol>t</Font><sub>1</sub>)' + ' + A<sub>2</sub>exp(-t/<Font face=symbol>t</Font><sub>2</sub>)' + ' + A<sub>3</sub>exp(-t/<Font face=symbol>t</Font><sub>3</sub>)' ; Boltzmann : Name := 'y(x) = y<sub>max</sub> / (1 + exp( -(x-x<sub>1/2</sub>)' + '/x<sub>slp</sub>)) + y<sub>min</sub>' ; PowerFunc : Name := 'y(x) = Ax<sup>B</sup>' ; else Name := 'None' ; end ; Result := Name ; end ; procedure TCurveFitter.CopyResultsToWebBrowser( WebBrowser : TWebBrowser ) ; // ------------------------------------- // Copy results to HTML Viewer component // ------------------------------------- var HTMLFileName : String ; HTMLFile : TextFile ; i : Integer ; begin // Create file to hold results HTMLFileName := 'c:\curvefitter.htm' ; AssignFile( HTMLFile, HTMLFileName ) ; Rewrite( HTMLFile ) ; WriteLn( HTMLFile, '<HTML>' ); WriteLn( HTMLFile, '<TITLE>Fit Results</TITLE>' ) ; if FEqnType <> None then begin // Fitted equation WriteLn( HTMLFile, GetName + '<br>' ) ; { Best fit parameters and standard error } for i := 0 to GetNumParameters-1 do begin if not FixedParameters[i] then WriteLn( HTMLFile, format(' %s = %.4g ± %.4g (sd) %s <br>', [ParNames[i], Parameters[i], ParameterSDs[i], ParUnits[i]] ) ) else { Fixed parameter } WriteLn( HTMLFile, format(' %s = %.4g (fixed) %s <br>', [ParNames[i], Parameters[i], ParUnits[i]] ) ) ; end ; { Residual standard deviation } WriteLn( HTMLFile, format(' Residual S.D. = %.4g %s <br>',[ResidualSD,'' ] )) ; { Statistical degrees of freedom } WriteLn( HTMLFile, format(' Degrees of freedom = %d <br>',[DegreesOfFreedom]) ); end ; // Close page WriteLn( HTMLFile, '</HTML>' ); CloseFile( HTMLFile ) ; WebBrowser.Navigate( HTMLFileName ) ; end ; { Make sure plot is updated with changes } function TCurveFitter.GetFitResults : String ; // ------------------------------------- // Get fit results // ------------------------------------- var s : String ; i : Integer ; begin s := 'Fit Results<br>' ; if FEqnType <> None then begin // Fitted equation s := s + GetName + '<br>' ; { Best fit parameters and standard error } for i := 0 to GetNumParameters-1 do begin if not FixedParameters[i] then s := s + format(' %s = %.4g ± %.4g (sd) %s <br>', [ParNames[i], Parameters[i], ParameterSDs[i], ParUnits[i]] ) else { Fixed parameter } s := s + format(' %s = %.4g (fixed) %s <br>', [ParNames[i], Parameters[i], ParUnits[i]] ) ; end ; { Residual standard deviation } s := s + format(' Residual S.D. = %.4g %s <br>',[ResidualSD,'' ] ) ; { Statistical degrees of freedom } s := s + format(' Degrees of freedom = %d <br>',[DegreesOfFreedom]) ; end ; Result := s ; end ; function TCurveFitter.GetNumParameters ; { ------------------------------------ Get number of parameters in equation ------------------------------------} var nPars : Integer ; begin Case FEqnType of Lorentzian : nPars := 2 ; Lorentzian2 : nPars := 4 ; LorAndOneOverF : nPars := 3 ; Linear : nPars := 2 ; Parabola : nPars := 3 ; Exponential : nPars := 3 ; Exponential2 : nPars := 5 ; Exponential3 : nPars := 7 ; EPC : nPars := 4 ; HHK : nPars := 3 ; HHNa : nPars := 5 ; MEPCNoise : nPArs := 3 ; Gaussian : nPars := 3 ; Gaussian2 : nPars := 6 ; Gaussian3 : nPars := 9 ; PDFExp : nPars := 2 ; PDFExp2 : nPars := 4 ; PDFExp3 : nPars := 6 ; PDFExp4 : nPars := 8 ; PDFExp5 : nPars := 10 ; Quadratic : nPars := 3 ; Cubic : nPars := 4 ; DecayingExp : nPars := 2 ; DecayingExp2 : nPars := 4 ; DecayingExp3 : nPars := 6 ; Boltzmann : nPars := 4 ; PowerFunc : nPars := 2 ; else nPars := 0 ; end ; Result := nPars ; end ; function TCurveFitter.GetParameter( Index : Integer ) : single ; { ---------------------------- Get function parameter value ----------------------------} begin Index := IntLimitTo(Index,0,GetNumParameters-1) ; Result := Pars[Index] ; end ; function TCurveFitter.GetParameterSD( Index : Integer ) : single ; { ----------------------------------------- Get function parameter standard deviation -----------------------------------------} begin Index := IntLimitTo(Index,0,GetNumParameters-1) ; Result := ParSDs[Index] ; end ; function TCurveFitter.GetLogParameter( Index : Integer ) : boolean ; { -------------------------------------- Read the parameter log transform array --------------------------------------} begin Index := IntLimitTo(Index,0,GetNumParameters-1) ; Result := LogPars[Index] ; end ; function TCurveFitter.GetFixed( Index : Integer ) : boolean ; { -------------------------------------- Read the parameter fixed/unfixed array --------------------------------------} begin Index := IntLimitTo(Index,0,GetNumParameters-1) ; Result := FixedPars[Index] ; end ; procedure TCurveFitter.SetFixed( Index : Integer ; Fixed : Boolean ) ; { -------------------------------------- Set the parameter fixed/unfixed array --------------------------------------} begin Index := IntLimitTo(Index,0,GetNumParameters-1) ; FixedPars[Index] := Fixed ; end ; procedure TCurveFitter.SetParameter( Index : Integer ; Value : single ) ; { ----------------------------- Set function parameter value -----------------------------} begin Index := IntLimitTo(Index,0,GetNumParameters-1) ; Pars[Index] := Value ; end ; function TCurveFitter.GetParName( Index : Integer { Parameter index number (IN) } ) : string ; { --------------------------- Get the name of a parameter ---------------------------} var ParNames : Array[0..LastParameter] of string ; begin Case FEqnType of Lorentzian : begin ParNames[0] := 'S^-0' ; ParNames[1] := 'f^-c' ; end ; Lorentzian2 : begin ParNames[0] := 'S<sub>1</sub>' ; ParNames[1] := 'f<sub>c1</sub>' ; ParNames[2] := 'S<sub>2</sub>' ; ParNames[3] := 'f<sub>c2</sub>' ; end ; LorAndOneOverF : begin ParNames[0] := 'S<sub>1</sub>' ; ParNames[1] := 'f<sub>c1</sub>' ; ParNames[2] := 'S<sub>2</sub>' ; end ; Linear : begin ParNames[0] := 'C' ; ParNames[1] := 'M' ; end ; Parabola : begin ParNames[0] := 'I<sub>u</sub>' ; ParNames[1] := 'N<sub>c</sub>' ; ParNames[2] := 'V<sub>b</sub>' ; end ; Exponential : begin ParNames[0] := 'A' ; ParNames[1] := '<Font face=symbol>t</Font>' ; ParNames[2] := 'Ss' ; end ; Exponential2 : begin ParNames[0] := 'A<sub>1</sub>' ; ParNames[1] := '<Font face=symbol>t</Font><sub>1</sub>' ; ParNames[2] := 'A<sub>2</sub>' ; ParNames[3] := '<Font face=symbol>t</Font><sub>2</sub>' ; ParNames[4] := 'Ss' ; end ; Exponential3 : begin ParNames[0] := 'A<sub>1</sub>' ; ParNames[1] := '<Font face=symbol>t</Font><sub>1</sub>' ; ParNames[2] := 'A<sub>2</sub>' ; ParNames[3] := '<Font face=symbol>t</Font><sub>2</sub>' ; ParNames[4] := 'A<sub>3</sub>' ; ParNames[5] := '<Font face=symbol>t</Font><sub>3</sub>' ; ParNames[6] := 'Ss' ; end ; EPC : begin ParNames[0] := 'A' ; ParNames[1] := 'x<sub>0' ; ParNames[2] := '<Font face=symbol>t</Font><sub>R</sub>' ; ParNames[3] := '<Font face=symbol>t</Font><sub>D</sub>' ; end ; HHK : begin ParNames[0] := 'A' ; ParNames[1] := '<Font face=symbol>t</Font><sub>M</sub>' ; ParNames[2] := 'P' ; end ; HHNa : begin ParNames[0] := 'A' ; ParNames[1] := '<Font face=symbol>t</Font><sub>M</sub>' ; ParNames[2] := 'P' ; ParNames[3] := 'H<sub>inf</sub>' ; ParNames[4] := '<Font face=symbol>t</Font><sub>H</sub>' ; end ; MEPCNoise : begin ParNames[0] := 'A' ; ParNames[1] := 'F<sub>d</sub>' ; ParNames[2] := 'F<sub>r</sub>' ; end ; Gaussian : begin ParNames[0] := '<Font face=symbol>m</Font>' ; ParNames[1] := '<Font face=symbol>s</Font>' ; ParNames[2] := 'Peak' ; end ; Gaussian2 : begin ParNames[0] := '<Font face=symbol>m</Font><sub>1</sub>' ; ParNames[1] := '<Font face=symbol>s</Font><sub>1</sub>' ; ParNames[2] := 'Pk<sub>1</sub>' ; ParNames[3] := '<Font face=symbol>m</Font><sub>2</sub>' ; ParNames[4] := '<Font face=symbol>s</Font><sub>2</sub>' ; ParNames[5] := 'Pk<sub>2</sub>' ; end ; Gaussian3 : begin ParNames[0] := '<Font face=symbol>m</Font><sub>1</sub>' ; ParNames[1] := '<Font face=symbol>s</Font><sub>1</sub>' ; ParNames[2] := 'Pk<sub>1</sub>' ; ParNames[3] := '<Font face=symbol>m</Font><sub>2</sub>' ; ParNames[4] := '<Font face=symbol>s</Font><sub>2</sub>' ; ParNames[5] := 'Pk<sub>2</sub>' ; ParNames[6] := '<Font face=symbol>m</Font><sub>3</sub>' ; ParNames[7] := '<Font face=symbol>s</Font><sub>3</sub>' ; ParNames[8] := 'Pk<sub>3</sub>' ; end ; PDFExp : PDFExpNames( ParNames, 1 ) ; PDFExp2 : PDFExpNames( ParNames, 2 ) ; PDFExp3 : PDFExpNames( ParNames, 3 ) ; PDFExp4 : PDFExpNames( ParNames, 4 ) ; PDFExp5 : PDFExpNames( ParNames, 5 ) ; Quadratic : begin ParNames[0] := 'C' ; ParNames[1] := 'B' ; ParNames[2] := 'A' ; end ; Cubic : begin ParNames[0] := 'D' ; ParNames[1] := 'C' ; ParNames[2] := 'B' ; ParNames[3] := 'A' ; end ; DecayingExp : begin ParNames[0] := 'A' ; ParNames[1] := '<Font face=symbol>t</Font>' ; end ; DecayingExp2 : begin ParNames[0] := 'A<sub>1</sub>' ; ParNames[1] := '<Font face=symbol>t</Font><sub>1</sub>' ; ParNames[2] := 'A<sub>2</sub>' ; ParNames[3] := '<Font face=symbol>t</Font><sub>2</sub>' ; end ; DecayingExp3 : begin ParNames[0] := 'A<sub>1</sub>' ; ParNames[1] := '<Font face=symbol>t</Font><sub>1</sub>' ; ParNames[2] := 'A<sub>2</sub>' ; ParNames[3] := '<Font face=symbol>t</Font><sub>2</sub>' ; ParNames[4] := 'A<sub>3</sub>' ; ParNames[5] := '<Font face=symbol>t</Font><sub>3</sub>' ; end ; Boltzmann : begin ParNames[0] := 'y<sub>max</sub>' ; ParNames[1] := 'x<sub>1</sub>^-/<sub>2</sub>' ; ParNames[2] := 'x<sub>slp</sub>' ; ParNames[3] := 'y<sub>min</sub>' ; end ; PowerFunc : Begin ParNames[0] := 'A' ; ParNames[1] := 'B' ; end ; else begin end ; end ; if (Index >= 0) and (Index < GetNumParameters) then begin Result := ParNames[Index] ; end else Result := '?' ; end ; procedure TCurveFitter.PDFExpNames ( var ParNames : Array of String ; nExp : Integer ) ; { -------------------------------- Exponential PDF parameter names -------------------------------- } var i : Integer ; begin for i := 0 to nExp-1 do begin ParNames[2*i] := format('A<sub>%d</sub>',[i+1]) ; ParNames[2*i+1] := format('<Font face=symbol>t</Font><sub>%d</sub>',[i+1]) ; end ; end ; function TCurveFitter.GetParUnits( Index : Integer { Parameter index number (IN) } ) : string ; { --------------------------- Get the units of a parameter ---------------------------} var ParUnits : Array[0..LastParameter] of string ; begin Case FEqnType of Lorentzian : begin ParUnits[0] := FYUnits + '<sup>2</sup>' ; ParUnits[1] := FXUnits ; end ; Lorentzian2 : begin ParUnits[0] := FYUnits + '<sup>2</sup>'; ParUnits[1] := FXUnits ; ParUnits[2] := FYUnits + '<sup>2</sup>'; ParUnits[3] := FXUnits ; end ; LorAndOneOverF : begin ParUnits[0] := FYUnits + '<sup>2</sup>'; ParUnits[1] := FXUnits ; ParUnits[2] := FYUnits + '<sup>2</sup>'; end ; Linear : begin ParUnits[0] := FYUnits ; ParUnits[1] := FYUnits + '/' + FXUnits ; end ; Parabola : begin ParUnits[0] := FYUnits ; ParUnits[1] := ' ' ; ParUnits[2] := FYUnits ; end ; Exponential : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := FYUnits ; end ; Exponential2 : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := FYUnits ; ParUnits[3] := FXUnits ; ParUnits[4] := FYUnits ; end ; Exponential3 : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := FYUnits ; ParUnits[3] := FXUnits ; ParUnits[4] := FYUnits ; ParUnits[5] := FXUnits ; ParUnits[6] := FYUnits ; end ; EPC : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := FXUnits ; ParUnits[3] := FXUnits ; end ; HHK : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := '' ; end ; HHNa : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := '' ; ParUnits[3] := '' ; ParUnits[4] := FXUnits ; end ; MEPCNoise : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := FXUnits ; end ; Gaussian : begin ParUnits[0] := FXUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := FYUnits ; end ; Gaussian2 : begin ParUnits[0] := FXUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := FYUnits ; ParUnits[3] := FXUnits ; ParUnits[4] := FXUnits ; ParUnits[5] := FYUnits ; end ; Gaussian3 : begin ParUnits[0] := FXUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := FYUnits ; ParUnits[3] := FXUnits ; ParUnits[4] := FXUnits ; ParUnits[5] := FYUnits ; ParUnits[6] := FXUnits ; ParUnits[7] := FXUnits ; ParUnits[8] := FYUnits ; end ; PDFExp : PDFExpUnits( ParUnits, FXUnits, 1 ) ; PDFExp2 : PDFExpUnits( ParUnits, FXUnits, 2 ) ; PDFExp3 : PDFExpUnits( ParUnits, FXUnits, 3 ) ; PDFExp4 : PDFExpUnits( ParUnits, FXUnits, 4 ) ; PDFExp5 : PDFExpUnits( ParUnits, FXUnits, 5 ) ; Quadratic : begin ParUnits[0] := FYUnits ; ParUnits[1] := FYUnits + '/' + FXUnits ; ParUnits[2] := FYUnits + '/' + FXUnits + '<sup>2</sup>'; end ; Cubic : begin ParUnits[0] := FYUnits ; ParUnits[1] := FYUnits + '/' + FXUnits ; ParUnits[2] := FYUnits + '/' + FXUnits + '<sup>2</sup>'; ParUnits[3] := FYUnits + '/' + FXUnits + '^3'; end ; DecayingExp : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; end ; DecayingExp2 : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := FYUnits ; ParUnits[3] := FXUnits ; end ; DecayingExp3 : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := FYUnits ; ParUnits[3] := FXUnits ; ParUnits[4] := FYUnits ; ParUnits[5] := FXUnits ; end ; Boltzmann : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; ParUnits[2] := FXUnits ; ParUnits[3] := FYUnits ; end ; PowerFunc : begin ParUnits[0] := FYUnits ; ParUnits[1] := FXUnits ; end ; else begin end ; end ; if (Index >= 0) and (Index < GetNumParameters) then begin Result := ParUnits[Index] ; end else Result := '?' ; end ; procedure TCurveFitter.PDFExpUnits( var ParUnits : Array of String ; FXUnits : String ; nExp : Integer ) ; { -------------------------------- Exponential PDF parameter units -------------------------------- } var i : Integer ; begin for i := 0 to nExp-1 do begin ParUnits[2*i] := '%' ; ParUnits[2*i+1] := FXUnits ; end ; end ; Function TCurveFitter.EquationValue( X : Single { X (IN) } ) : Single ; { Return f(X) } { --------------------------------------------------- Return value of equation with current parameter set ---------------------------------------------------} var Y,A,A1,A2,Theta1,Theta2 : Single ; begin Case FEqnType of Lorentzian : begin if Pars[1] <> 0.0 then begin A := X/Pars[1] ; Y := Pars[0] /( 1.0 + (A*A)) ; end else Y := 0.0 ; end ; Lorentzian2 : begin if (Pars[1] <> 0.0) and (Pars[3] <> 0.0)then begin A1 := X/Pars[1] ; A2 := X/Pars[3] ; Y := (Pars[0]/(1.0 + (A1*A1))) + (Pars[2]/(1.0 + (A2*A2))) ; end else Y := 0.0 ; end ; LorAndOneOverF : begin if Pars[1] <> 0.0 then begin A := X/Pars[1] ; Y := (Pars[0] /( 1.0 + (A*A))) + (Pars[2]/(X*X)); end else Y := 0.0 ; end ; Linear : begin Y := Pars[0] + X*Pars[1] ; end ; Parabola : begin if Pars[1] <> 0.0 then begin Y := X*Pars[0] - ((X*X)/Pars[1]) + Pars[2] ; end else Y := 0.0 ; end ; Exponential : begin Y := Pars[2] ; if Pars[1] <> 0.0 then Y := Y + Pars[0]*exp(-X/Abs(Pars[1])) ; end ; Exponential2 : begin Y := Pars[4]; if Pars[1] <> 0.0 then Y := Y + Pars[0]*exp(-X/Abs(Pars[1])) ; if Pars[3] <> 0.0 then Y := Y + Pars[2]*exp(-X/Abs(Pars[3])) ; end ; Exponential3 : begin Y := Pars[6]; if Pars[1] <> 0.0 then Y := Y + Pars[0]*exp(-X/Abs(Pars[1])) ; if Pars[3] <> 0.0 then Y := Y + Pars[2]*exp(-X/Abs(Pars[3])) ; if Pars[5] <> 0.0 then Y := Y + Pars[4]*exp(-X/Abs(Pars[5])) ; end ; EPC : begin if (Pars[2] <> 0.0) and (Pars[3] <> 0.0) then Y := Pars[0]*0.5*(1. + erf( (X-Pars[1])/Abs(Pars[2]) )) *exp(-(X-Pars[1])/Abs(Pars[3])) else Y := 0.0 ; end ; HHK : begin if Pars[1] <> 0.0 then Y := Pars[0]*FPower( 1. - exp(-x/Abs(Pars[1])),Abs(Pars[2]) ) else Y := 0.0 ; end ; HHNa : begin if (Pars[1] <> 0.0) and (Pars[4] <> 0.0) then Y := (Pars[0]*FPower( 1. - exp(-x/Abs(Pars[1])),Abs(Pars[2]) )) * (Abs(Pars[3]) - (Abs(Pars[3]) - 1. )*exp(-x/Abs(Pars[4])) ) else Y := 0.0 ; end ; MEPCNoise : begin if (Pars[1] <> 0.0) and (Pars[2] <> 0.0) then begin Theta2 := 1.0 / Pars[1] ; Theta1 := 1.0 / Pars[2] ; Y := (Pars[0]) / (1.0 + (X*X*(Theta1*Theta1 + Theta2*Theta2)) + (X*X*X*X*Theta1*Theta1*Theta2*Theta2) ) ; end else Y := 0.0 ; end ; Gaussian : Y := GaussianFunc( Pars, 1, X ) ; Gaussian2 : Y := GaussianFunc( Pars, 2, X ) ; Gaussian3 : Y := GaussianFunc( Pars, 3, X ) ; PDFExp : Y := PDFExpFunc( Pars, 1, X ) ; PDFExp2 : Y := PDFExpFunc( Pars, 2, X ) ; PDFExp3 : Y := PDFExpFunc( Pars, 3, X ) ; PDFExp4 : Y := PDFExpFunc( Pars, 4, X ) ; PDFExp5 : Y := PDFExpFunc( Pars, 5, X ) ; Quadratic : begin Y := Pars[0] + X*Pars[1] + X*X*Pars[2] ; end ; Cubic : begin Y := Pars[0] + X*Pars[1] + X*X*Pars[2] + X*X*X*Pars[3] ; end ; DecayingExp : begin Y := 0.0 ; if Pars[1] <> 0.0 then Y := Y + Pars[0]*exp(-X/Abs(Pars[1])) ; end ; DecayingExp2 : begin Y := 0.0 ; if Pars[1] <> 0.0 then Y := Pars[0]*exp(-X/Abs(Pars[1])) ; if Pars[3] <> 0.0 then Y := Y + Pars[2]*exp(-X/Abs(Pars[3])) ; end ; DecayingExp3 : begin Y := 0.0 ; if Pars[1] <> 0.0 then Y := Y + Pars[0]*exp(-X/Abs(Pars[1])) ; if Pars[3] <> 0.0 then Y := Y + Pars[2]*exp(-X/Abs(Pars[3])) ; if Pars[5] <> 0.0 then Y := Y + Pars[4]*exp(-X/Abs(Pars[5])) ; end ; Boltzmann : begin if Pars[2] <> 0.0 then Y := Pars[0] / ( 1.0 + exp( -(X - pars[1])/Pars[2])) + Pars[3] else Y := 0.0 ; end ; PowerFunc : Begin Y := Pars[0]*FPower(x,Pars[1]) ; end ; else Y := 0. ; end ; Result := Y ; end ; function TCurveFitter.PDFExpFunc( Pars : Array of single ; nExp : Integer ; X : Single ) : Single ; { ------------------------------------ General exponential p.d.f. function ------------------------------------ } var i,j : Integer ; y : Single ; begin y := 0.0 ; for i := 0 to nExp-1 do begin j := 2*i ; if Pars[j+1] > 0.0 then y := y + Pars[j]/Pars[j+1]*SafeExp(-X/pars[j+1]) ; end ; Result := y ; end ; function TCurveFitter.GaussianFunc( Pars : Array of single ; nGaus : Integer ; X : Single ) : Single ; { ------------------- Gaussian function ------------------- } var i,j : Integer ; z,Variance,y : Single ; begin Y := 0.0 ; for i := 0 to nGaus-1 do begin j := 3*i ; z := X - Pars[j] ; Variance := Pars[j+1]*Pars[j+1] ; if Variance > 0.0 then Y := Y + Pars[j+2]*Exp( -(z*z)/(2.0*Variance) ) ; end ; Result := y ; end ; procedure TCurveFitter.SetupNormalisation( xScale : single ; yScale : single ) ; { -------------------------------------------------------- Determine scaling factors necessary to adjust parameters for data normalised to range 0-1 --------------------------------------------------------} begin { Scaling factor for residual standard deviation } ResidualSDScaleFactor := yScale ; { Set values for each equation type } Case FEqnType of Lorentzian : begin AbsPars[0] := True ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; end ; Lorentzian2 : begin AbsPars[0] := True ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := True ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale ; AbsPars[3] := True ; LogPars[3] := False ; ParameterScaleFactors[3] := xScale ; end ; LorAndOneOverF : begin AbsPars[0] := True ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := True ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale ; end ; Linear : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := False ; LogPars[1] := False ; ParameterScaleFactors[1] := yScale/xScale ; end ; Parabola : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale/xScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := (xScale*xScale)/yScale ; AbsPars[2] := False ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale ; end ; Exponential : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := False ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale ; end ; Exponential2 : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := False ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale ; AbsPars[3] := True ; LogPars[3] := False ; ParameterScaleFactors[3] := xScale ; AbsPars[4] := False ; LogPars[4] := False ; ParameterScaleFactors[4] := yScale ; end ; Exponential3 : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := False ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale ; AbsPars[3] := True ; LogPars[3] := False ; ParameterScaleFactors[3] := xScale ; AbsPars[4] := False ; LogPars[4] := False ; ParameterScaleFactors[4] := yScale ; AbsPars[5] := True ; LogPars[5] := False ; ParameterScaleFactors[5] := xScale ; AbsPars[6] := False ; LogPars[6] := False ; ParameterScaleFactors[6] := yScale ; end ; EPC : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := False ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := True ; LogPars[2] := False ; ParameterScaleFactors[2] := xScale ; AbsPars[3] := True ; LogPars[3] := False ; ParameterScaleFactors[3] := xScale ; end ; HHK : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := True ; LogPars[2] := False ; ParameterScaleFactors[2] := 1. ; end ; HHNa : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := True ; LogPars[2] := False ; ParameterScaleFactors[2] := 1. ; AbsPars[3] := True ; LogPars[3] := False ; ParameterScaleFactors[3] := 1. ; AbsPars[4] := True ; LogPars[4] := False ; ParameterScaleFactors[4] := xScale ; end ; MEPCNoise : begin AbsPars[0] := True ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := True ; LogPars[2] := False ; ParameterScaleFactors[2] := xScale ; end ; Gaussian : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := xScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := True ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale ; end ; Gaussian2 : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := xScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := True ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale ; AbsPars[3] := False ; LogPars[3] := False ; ParameterScaleFactors[3] := xScale ; AbsPars[4] := True ; LogPars[4] := False ; ParameterScaleFactors[4] := xScale ; AbsPars[5] := True ; LogPars[5] := False ; ParameterScaleFactors[5] := yScale ; end ; Gaussian3 : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := xScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := True ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale ; AbsPars[3] := False ; LogPars[3] := False ; ParameterScaleFactors[3] := xScale ; AbsPars[4] := True ; LogPars[4] := False ; ParameterScaleFactors[4] := xScale ; AbsPars[5] := True ; LogPars[5] := False ; ParameterScaleFactors[5] := yScale ; AbsPars[6] := False ; LogPars[6] := False ; ParameterScaleFactors[6] := xScale ; AbsPars[7] := True ; LogPars[7] := False ; ParameterScaleFactors[7] := xScale ; AbsPars[8] := True ; LogPars[8] := False ; ParameterScaleFactors[8] := yScale ; end ; PDFExp : PDFExpScaling(AbsPars,LogPars,ParameterScaleFactors,yScale,1) ; PDFExp2 : PDFExpScaling(AbsPars,LogPars,ParameterScaleFactors,yScale,2) ; PDFExp3 : PDFExpScaling(AbsPars,LogPars,ParameterScaleFactors,yScale,3) ; PDFExp4 : PDFExpScaling(AbsPars,LogPars,ParameterScaleFactors,yScale,4) ; PDFExp5 : PDFExpScaling(AbsPars,LogPars,ParameterScaleFactors,yScale,5) ; Quadratic : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := False ; LogPars[1] := False ; ParameterScaleFactors[1] := yScale/xScale ; AbsPars[2] := False ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale/(xScale*xScale) ; end ; Cubic : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := False ; LogPars[1] := False ; ParameterScaleFactors[1] := yScale/xScale ; AbsPars[2] := False ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale/(xScale*xScale) ; AbsPars[3] := False ; LogPars[3] := False ; ParameterScaleFactors[3] := yScale/(xScale*xScale*xScale) ; end ; DecayingExp : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; end ; DecayingExp2 : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := False ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale ; AbsPars[3] := True ; LogPars[3] := False ; ParameterScaleFactors[3] := xScale ; end ; DecayingExp3 : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := True ; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := False ; LogPars[2] := False ; ParameterScaleFactors[2] := yScale ; AbsPars[3] := True ; LogPars[3] := False ; ParameterScaleFactors[3] := xScale ; AbsPars[4] := False ; LogPars[4] := False ; ParameterScaleFactors[4] := yScale ; AbsPars[5] := True ; LogPars[5] := False ; ParameterScaleFactors[5] := xScale ; end ; Boltzmann : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := False; LogPars[1] := False ; ParameterScaleFactors[1] := xScale ; AbsPars[2] := False ; LogPars[2] := False ; ParameterScaleFactors[2] := xScale ; AbsPars[3] := False ; LogPars[3] := False ; ParameterScaleFactors[3] := yScale ; end ; PowerFunc : begin AbsPars[0] := False ; LogPars[0] := False ; ParameterScaleFactors[0] := yScale ; AbsPars[1] := False; LogPars[1] := False ; ParameterScaleFactors[1] := 1.0 ; end ; end ; Normalised := True ; end ; procedure TCurveFitter.PDFExpScaling( var AbsPars : Array of Boolean ; var LogPars : Array of Boolean ; var ParameterScaleFactors : Array of Single ; yScale : Single ; nExp : Integer ) ; { -------------------------------- Exponential PDF scaling factors ------------------------------- } var i,j : Integer ; begin for i := 0 to nExp-1 do begin j := 2*i ; AbsPars[j] := True ; LogPars[j] := False ; ParameterScaleFactors[j] := yScale ; AbsPars[j+1] := false ; LogPars[j+1] := true ; ParameterScaleFactors[j+1] := 1.0 ; end ; end ; function TCurveFitter.NormaliseParameter( Index : Integer ; { Parameter Index (IN) } Value : single { Parameter value (IN) } ) : single ; { ----------------------------------------------------------------- Adjust a parameter to account for data normalisation to 0-1 range -----------------------------------------------------------------} var NormValue : single ; begin if (Index >= 0) and (Index<GetNumParameters) and Normalised then begin NormValue := Value * ParameterScaleFactors[Index] ; if AbsPars[Index] then NormValue := Abs(NormValue) ; if LogPars[Index] then NormValue := ln(NormValue) ; Result := NormValue ; end else Result := Value ; ; end ; function TCurveFitter.DenormaliseParameter( Index : Integer ; { Parameter Index (IN) } Value : single { Parameter value (IN) } ) : single ; { ---------------------------------------- Restore a parameter to actual data range ----------------------------------------} var NormValue : single ; begin if (Index >= 0) and (Index<GetNumParameters) and Normalised then begin NormValue := Value / ParameterScaleFactors[Index] ; if AbsPars[Index] then NormValue := Abs(NormValue) ; if LogPars[Index] then NormValue := exp(NormValue) ; Result := NormValue ; end else Result := Value ; ; end ; function TCurveFitter.InitialGuess( Index : Integer { Function parameter No. } ) : single ; { -------------------------------------------------------------- Make an initial guess at parameter value based upon (X,Y) data pairs in Data --------------------------------------------------------------} var i,j,iEnd,iY25,iY50,iY75,AtPeak,iBiggest,iStep : Integer ; xMin,xMax,yMin,yMax,x,y,yRange,XAtYMax,XAtYMin,Slope,XStart : Single ; YSum,XYSum,XMean : single ; Guess : Array[0..LastParameter] of single ; YPeak : Array[0..6] of single ; XStDev : Array[0..6] of single ; XAtYPeak : Array[0..6] of single ; OnPeak : Boolean ; nPeaks : Integer ; begin iEnd := nPoints - 1 ; { Find Min./Max. limits of data } xMin := MaxSingle ; xMax := -xMin ; yMin := MaxSingle ; yMax := -yMin ; for i := 0 to iEnd do begin x := XData[i] ; y := YData[i] ; if xMin > x then xMin := x ; if xMax < x then xMax := x ; if yMin > y then begin yMin := y ; XAtYMin := x ; end ; if yMax < y then begin yMax := y ; XAtYMax := x ; end ; end ; { Find points which are 75%, 50% and 25% of yMax } for i := 0 to iEnd do begin y := YData[i] - yMin ; yRange := yMax - yMin ; if y > (yRange*0.75) then iY75 := i ; if y > (yRange*0.5) then iY50 := i ; if y > (yRange*0.25) then iY25 := i ; end ; { Find mean X value weighted by Y values } XYSum := 0.0 ; YSum := 0.0 ; for i := 0 to iEnd do begin XYSum := XYSum + YData[i]*XData[i] ; YSum := YSum + YData[i] ; end ; if YSum <> 0.0 then XMean := XYSum / YSum ; // Locate peaks and determine peak and width (for gaussian fits) nPeaks := 0 ; iStep := MaxInt([(iEnd + 1) div 20,1]) ; OnPeak := False ; for i := 0 to iEnd do begin { Get slope of line around data point (i) } Slope := YData[MinInt([i+iStep,iEnd])] - YData[MaxInt([i-iStep,0])] ; X := XData[i] ; Y := YData[i] ; // Rising slope of a peak detected when slope > 20% of peak Y value if (Slope > YMax*0.2) and (not OnPeak) then begin OnPeak := True ; YPeak[nPeaks] := 0.0 ; XStart := X ; end ; // Find location and amplitude of peak if OnPeak then begin if YPeak[nPeaks] < Y then begin YPeak[nPeaks] := Y ; XAtYPeak[nPeaks] := X end ; // End of peak when downward slope > 20% of ma Y value if (Slope < (-YMax*0.2)) then begin OnPeak := False ; XStDev[nPeaks] := X - XStart ; nPeaks := MinInt([nPeaks+1,High(YPeak)]) ; end ; end ; end ; Case FEqnType of Lorentzian : begin Guess[0] := YData[0] ; Guess[1] := XData[iY50] ; end ; Lorentzian2 : begin Guess[0] := YData[0] ; Guess[1] := XData[iY75] ; Guess[2] := YData[0]/4.0 ; Guess[3] := XData[iY25] ; end ; LorAndOneOverF : begin Guess[0] := YData[0]*0.75 ; Guess[1] := XData[iY50] ; Guess[2] := YData[0]*0.25 ; end ; Linear : begin Guess[0] := yMin ; Guess[1] := (yMax - yMin) / (xMax - xMin); end ; Parabola : begin Guess[0] := (yMax - yMin) / (xMax - xMin); Guess[1] := Guess[0]*0.1 ; Guess[2] := yMin ; end ; Exponential : begin Guess[0] := YData[0] - YData[iEnd] ; Guess[1] := (XData[iEnd] - XData[0]) / 4.0 ; Guess[2] := YData[iEnd] ; end ; Exponential2 : begin Guess[0] := YData[0] - YData[iEnd]*0.5 ; Guess[1] := (XData[iEnd] - XData[0]) / 20.0 ; Guess[2] := YData[0] - YData[iEnd]*0.5 ; Guess[3] := (XData[iEnd] - XData[0]) / 2.0 ; Guess[4] := YData[iEnd] ; end ; Exponential3 : begin Guess[0] := YData[0] - YData[iEnd]*0.33 ; Guess[1] := (XData[iEnd] - XData[0]) / 20.0 ; Guess[2] := YData[0] - YData[iEnd]*0.33 ; Guess[3] := (XData[iEnd] - XData[0]) / 5.0 ; Guess[4] := YData[0] - YData[iEnd]*0.33 ; Guess[5] := (XData[iEnd] - XData[0]) / 1.0 ; Guess[6] := YData[iEnd] ; end ; EPC : begin { Peak amplitude } if Abs(yMax) > Abs(yMin) then begin Guess[0] := yMax ; AtPeak := Round(XAtYmax) ; end else begin Guess[0] := yMin ; AtPeak := Round(XAtYMin) ; end ; { Set initial latency to time of signal peak } Guess[1] := XData[AtPeak] ; { Rising time constant } Guess[2] := (XData[1] - XData[0])*5.0 ; { Decay time constant } Guess[3] := (XData[iEnd] - XData[0]) / 4. ; end ; HHK : begin if Abs(yMax) > Abs(yMin) then Guess[0] := yMax else Guess[0] := yMin ; Guess[1] := (XData[iEnd] - XData[0]) / 6. ; Guess[2] := 2. ; end ; HHNa : begin if Abs(yMax) > Abs(yMin) then Guess[0] := yMax else Guess[0] := yMin ; Guess[1] := (XData[iEnd] - XData[0]) / 10. ; Guess[2] := 3. ; Guess[3] := Abs( YData[iEnd]/Guess[0] ) ; Guess[4] := (XData[iEnd] - XData[0]) / 3. ; end ; MEPCNoise : begin Guess[0] := YData[0] ; Guess[1] := XData[iY50] ; Guess[2] := Guess[1]*10.0 ; end ; Gaussian : begin iBiggest := 0 ; for i := 0 to nPeaks-1 do if YPeak[i] >= YPeak[iBiggest] then begin iBiggest := i ; Guess[0] := XAtYPeak[i] ; Guess[1] := XStDev[i] ; Guess[2] := YPeak[i] ; end ; end ; Gaussian2 : begin for j := 0 to 1 do begin iBiggest := 0 ; for i := 0 to nPeaks-1 do if YPeak[i] >= YPeak[iBiggest] then begin iBiggest := i ; Guess[3*j] := XAtYPeak[i] ; Guess[3*j+1] := XStDev[i] ; Guess[3*j+2] := YPeak[i] ; end ; YPeak[iBiggest] := 0.0 ; end ; end ; Gaussian3 : begin for j := 0 to 2 do begin iBiggest := 0 ; for i := 0 to nPeaks-1 do if YPeak[i] >= YPeak[iBiggest] then begin iBiggest := i ; Guess[3*j] := XAtYPeak[i] ; Guess[3*j+1] := XStDev[i] ; Guess[3*j+2] := YPeak[i] ; end ; YPeak[iBiggest] := 0.0 ; end ; end ; PDFExp : begin Guess[0] := 100.0 ; Guess[1] := XMean ; end ; PDFExp2 : begin Guess[0] := 75.0 ; Guess[1] := XMean*0.3 ; Guess[2] := 25.0 ; Guess[3] := XMean*3.0 ; end ; PDFExp3 : begin Guess[0] := 50.0 ; Guess[1] := XMean*0.2 ; Guess[2] := 25.0 ; Guess[3] := XMean*5.0 ; Guess[4] := 25.0 ; Guess[5] := XMean*50.0 ; end ; PDFExp4 : begin Guess[0] := 50.0 ; Guess[1] := XMean*0.2 ; Guess[2] := 25.0 ; Guess[3] := XMean*5.0 ; Guess[4] := 15.0 ; Guess[5] := XMean*50.0 ; Guess[6] := 10.0 ; Guess[7] := XMean*200.0 ; end ; PDFExp5 : begin Guess[0] := 50.0 ; Guess[1] := XMean*0.2 ; Guess[2] := 25.0 ; Guess[3] := XMean*5.0 ; Guess[4] := 10.0 ; Guess[5] := XMean*50.0 ; Guess[6] := 5.0 ; Guess[7] := XMean*200.0 ; Guess[8] := 5.0 ; Guess[9] := XMean*500.0 ; end ; Quadratic : begin Guess[0] := yMin ; Guess[1] := (yMax - yMin) / (xMax - xMin); Guess[2] := Guess[1]*0.1 ; end ; Cubic : begin Guess[0] := yMin ; Guess[1] := (yMax - yMin) / (xMax - xMin); Guess[2] := Guess[1]*0.1 ; Guess[3] := Guess[2]*0.1 ; end ; DecayingExp : begin Guess[0] := YData[0] - YData[iEnd] ; Guess[1] := (XData[iEnd] - XData[0]) / 4.0 ; end ; DecayingExp2 : begin Guess[0] := YData[0] - YData[iEnd]*0.5 ; Guess[1] := (XData[iEnd] - XData[0]) / 20.0 ; Guess[2] := YData[0] - YData[iEnd]*0.5 ; Guess[3] := (XData[iEnd] - XData[0]) / 2.0 ; end ; DecayingExp3 : begin Guess[0] := YData[0] - YData[iEnd]*0.33 ; Guess[1] := (XData[iEnd] - XData[0]) / 20.0 ; Guess[2] := YData[0] - YData[iEnd]*0.33 ; Guess[3] := (XData[iEnd] - XData[0]) / 5.0 ; Guess[4] := YData[0] - YData[iEnd]*0.33 ; Guess[5] := (XData[iEnd] - XData[0]) / 1.0 ; end ; Boltzmann : begin Guess[0] := YMax - YMin ; Guess[1] := (XMax + XMin) / 2.0 ; Guess[2] := Guess[1]*0.25 ; Guess[3] := YMin ; end ; PowerFunc : begin Guess[0] := YData[0] ; if (YData[iEnd] > YData[0]) then Guess[1] := 2.0 else Guess[1] := -2.0 ; end ; end ; if (Index >= 0) and (Index<GetNumParameters) then begin Result := Guess[Index] ; end else Result := 1.0 ; end ; procedure TCurveFitter.FitCurve ; // ----------------------------------- // Find curve which best fits X,Y data // ----------------------------------- var NumSig,nSigSq,iConv,Maxiterations,i : Integer ; nVar,nFixed : Integer ; SSQ,DeltaMax : Single ; F,W : ^TDataArray ; sltjj : Array[0..300] of Single ; FitPars : TPars ; begin { Create buffers for SSQMIN } New(F) ; New(W) ; try { Determine an initial set of parameter guesses } if not ParsSet then begin for i := 0 to GetNumParameters-1 do if not FixedPars[i] then Pars[i] := InitialGuess( i ) ; end ; { Scale X & Y data into 0-1 numerical range } ScaleData ; { Re-arrange parameters putting fixed parameters at end of array } nVar := 0 ; nFixed := GetNumParameters ; for i := 0 to GetNumParameters-1 do begin if FixedPars[i] then begin FitPars.Value[nFixed] := Pars[i] ; FitPars.Map[nFixed] := i ; Dec(nFixed) ; end else begin Inc(nVar) ; FitPars.Value[nVar] := Pars[i] ; FitPars.Map[nVar] := i ; end ; end ; { Set weighting array to unity } for i := 1 to nPoints do W^[i] := 1. ; NumSig := 5 ; nSigSq := 5 ; deltamax := 1E-16 ; maxiterations := 100 ; iconv := 0 ; if nVar > 0 then begin try ssqmin ( FitPars , nPoints, nVar, maxiterations, NumSig,NSigSq,DeltaMax, W^,SLTJJ,iConv,IterationsValue,SSQ,F^ ) except { on EOverFlow do MessageDlg( ' Fit abandoned -FP Overflow !', mtWarning, [mbOK], 0 ) ; on EUnderFlow do MessageDlg( ' Fit abandoned -FP Underflow !', mtWarning, [mbOK], 0 ) ; on EZeroDivide do MessageDlg( ' Fit abandoned -FP Zero divide !', mtWarning, [mbOK], 0 ) ; } GoodFitFlag := False ; end ; { Calculate parameter and residual standard deviations (If the fit has been successful) } if iConv > 0 then begin if nPoints > nVar then begin STAT( nPoints,nVar,F^,YData,W^,SLTJJ,SSQ, FitPars.SD,ResidualSDValue,RValue,FitPars.Value ) ; for i := 1 to nVar do Pars[FitPars.Map[i]] := FitPars.Value[i] ; for i := 1 to nVar do ParSDs[FitPars.Map[i]] := FitPars.SD[i] ; DegreesOfFreedomValue := nPoints-GetNumParameters ; end else DegreesOfFreedomValue := 0 ; GoodFitFlag := True ; ParsSet := False ; end else GoodFitFlag := False ; end else GoodFitFlag := True ; { Return parameter scaling to normal } UnScaleParameters ; finally ; Dispose(W) ; Dispose(F) ; end ; end ; procedure TCurveFitter.ScaleData ; { ---------------------------------------------------------- Scale Y data to lie in same range as X data (The iterative fitting routine is more stable when the X and Y data do not differ too much in numerical value) ----------------------------------------------------------} var i,iEnd : Integer ; xMax,yMax,xScale,yScale,x,y,ySum : Single ; begin iEnd := nPoints - 1 ; { Find absolute value limits of data } xMax := -MaxSingle ; yMax := -MaxSingle ; ySum := 0.0 ; for i := 0 to iEnd do begin x := Abs(XData[i]) ; y := Abs(YData[i]) ; if xMax < x then xMax := x ; if yMax < y then yMax := y ; ySum := ySum + y ; end ; {Calc. scaling factor} if xMax > 0. then xScale := 1./xMax else xScale := 1. ; if yMax > 0. then yScale := 1./yMax else yScale := 1. ; { Disable x,y scaling in special case of exponential prob. density functions } if (FEqnType = PDFExp) or (FEqnType = PDFExp2) or (FEqnType = PDFExp3) or (FEqnType = PDFExp4) or (FEqnType = PDFExp5) then begin xScale := 1.0 ; yScale := 1.0 ; end ; { Scale data to lie in same numerical range as X data } for i := 0 to iEnd do begin XData[i] := xScale * XData[i] ; YData[i] := yScale * YData[i] ; end ; { Set parameter scaling factors which adjust for data normalisation to 0-1 range } SetupNormalisation( xScale, yScale ) ; { Scale equation parameters } for i := 0 to GetNumParameters-1 do begin Pars[i] := NormaliseParameter(i,Pars[i]) ; end ; end ; { ---------------------------------------------------- Correct best-fit parameters for effects of Y scaling ----------------------------------------------------} procedure TCurveFitter.UnScaleParameters ; var i : Integer ; UpperLimit,LowerLimit : single ; begin for i := 0 to GetNumParameters-1 do begin { Don't denormalise a fixed parameter } if not FixedPars[i] then begin UpperLimit := DenormaliseParameter(i,Pars[i]+ParSDs[i]) ; LowerLimit := DenormaliseParameter(i,Pars[i]-ParSDs[i]) ; ParSDs[i] := Abs(UpperLimit - LowerLimit)*0.5 ; end ; { Denormalise parameter } Pars[i] := DenormaliseParameter(i,Pars[i]) ; end ; {Unscale residual standard deviation } ResidualSDValue := ResidualSDValue/ResidualSDScaleFactor ; end ; procedure TCurveFitter.SsqMin ( var Pars : TPars ; nPoints,nPars,ItMax,NumSig,NSiqSq : LongInt ; Delta : Single ; var W,SLTJJ : Array of Single ; var ICONV,ITER : LongInt ; var SSQ : Single ; var F : Array of Single ) ; { SSQMIN routine based on an original FORTRAN routine written by Kenneth Brown and modified by S.H. Bryant C C Work buffer structure C C (1+N(N-1)/2) C :---------:------N*M----------:-----------: C 1 JACSS GRADSS GRDEND C C :--N--: :----M------------:---N----: C DELEND FPLSS DIAGSS ENDSS C :--->cont. C FMNSS C C :-------M------:--N-1---: C FMNSS XBADSS XBEND C C C C C SSQMIN ------ VERSION II. C C ORIGINAL SOURCE FOR SSQMIN WAS GIFT FROM K. BROWN, 3/19/76. C PROGRAM WAS MODIFIED A FOLLOWS: C C 1. WEIGHTING VECTOR W(1) WAS ADDED SO THAT ALL RESIDUALS C EQUAL F(I) * SQRT1(W(I)). C C 2. THE VARIABLE KOUT WHICH INDICATED ON EXIT WHETHER F(I) C WAS CALCULATED FROM UPDATED X(J) WAS REMOVED. IN C CONDITIONS WHERE KOUT =0 THE NEW F(I)'S AND AN UPDATED C SSQ IS OUTPUTTED . SSQ ( SUM WEIGHTED F(I) SQUARED ) C WAS PUT INTO THE CALL STRING. C C 3. A NEW ARRAY SLTJJ(K) WHICH CONTAINS THE SUPER LOWER C TRIANGLE OF JOCOBIAN (TRANSPOSE)*JACOBIAN WAS ADDED TO THE C CALL STRING. IT HAS THE SIZE N*(N+1)/2 AND IS USED FOR C CALCULATING THE STATSTICS OF THE FIT. STORAGE OF C ELEMENTS IS AS FOLLOWS:C(1,1),C(2,1),C(2,2),C(3,2),C(3,3), C C(4,1)........ C NOTE THE AREA WORK (1) THROU WORK (JACM1) IN WHICH SLTJJ C IS INITALLY STORED IS WRITTEN OVER (DO 52) IN CHOLESKY C AND IS NOT AVAILABLE ON RETURN. C C 4. A BUG DUE TO SUBSCRIPTING W(I) OUT OF BOUNDS WAS C CORRECTED IN MAY '79. THE CRITERION FOR SWITCHING FROM C FORWARD DIFFERENCES (ISW=1) TO CENTRAL DIFFERENCES C (ISW = 2) FOR THE PARTIAL DERIVATIVE ESTIMATES IS SET C IN STATEMENT 27 (ERL2.LT.GRCIT).GRCIT IS INITALIZED C TO 1.E-3 AS IN ORIGINAL PROGRAM. THE VARIABLE T IN C CHOLESKY WAS MADE TT TO AVIOD CONFUSION WITH ARRAY T. C C SSQMIN -- IS A FINITE DIFFERENCE LEVENBERG-MARQUARDT LEAST C SQUARES ALGORTHM. GIVEN THE USER SUPPLIED INITIAL C ESTIMATE FOR X, SSQMIN FINDS THE MINIMUM OF C SUM ((F (X ,....,X ) ) ** 2) J=1,2,.....M C J 1 N J C BY A MODIFICATION OF THE LEVENBERG-MARQUARDT ALGORITHM C WHICH INCLUDES INTERNAL SCALING AND ELIMINATES THE C NEED FOR EXPLICIT DERIVATIVES. THE F (X ,...,X ) C J 1 N C CAN BE TAKEN TO BE THE RESIDUALS OBTAINED WHEN FITTING C NON-LINEAR MODEL, G, TO DATA Y IN THE LEAST SQUARES C SENSE ..., I.E.,TAKE C F (X ,...,X ) = G (X ,...,X ) - Y C J 1 N J 1 N C REFERENCES: C C BROWN,K.M. AND DENNIS,J.S. DERIVATIVE FREE ANALOGS OF C THE LEVENBERG-MARQUARDT AND GAUSS ALGORITHMS FOR C NON-LINEAR LEAST SQUARES APPROXIMATION. NUMERISCHE C MATHEMATIK 18:289 -297 (1972). C BROWN,K.M. COMPUTER ORIENTED METHODS FOR FITTING C TABULAR DATA IN THE LINEAR AND NON-LINEAR LEAST SQUARES C SENSE. TECHNICIAL REPORT NO. 72-13. DEPT..COMPUTER & C INFORM. SCIENCES; 114 LIND HALL, UNIVERSITY OF C MINNESOTA, MINNEAPOLIS, MINNESOTA 5545. C C PARAMETERS : C C X REAL ARRAY WITH DIMENSION N. C INPUT --- INITIAL ESTIMATES C OUTPUT -- VALUES AT MIN (OR FINAL APPROXIMATION) C C M THE NUMBER OF RESIDUALS (OBSERVATIONS) C C N THE NUMBER OF UNKNOWN PARAMETERS C C ITMAX THE MAXIMUM NUMBER OF ITERATIONS TO BE ALLOWED C NOTE-- THE MAXIMUM NUMBER OF FUNCTION EVALUATIONS C ALLOWED IS ROUGHLY (N+1)*ITMAX . C C IPRINT AN OUTPUT PARAMETER. IF IPRINT IS NON ZERO CONTROL C IS PASSED ONCE DURING EACH ITERATION TO SUBROUTINE C PRNOUT WHICH PRINTS INTERMEDIATE RESULTS (SEE BELOW) C IF IPRINT IS ZERO NO CALL IS MADE. C C NUMSIG FIRST CONVERGENCE CRITERION. CONVERGENCE CONDITION C SATISFIED IF ALL COMPONENTS OF TWO SUCCESSIVE C ITERATES AGREE TO NUMSIG DIGITS. C C NSIGSQ SECOND CONVERGENCE CRITERION. CONVERGENCE CONDITIONS C SATISFIED IF SUM OF SQUARES OF RESIDUALS FOR TWO C SUCCESSIVE ITERATIONS AGREE TO NSIGSQ DIGITS. C C DELTA THIRD CONVERGENCE CRITERION. CONVERGENCE CONDITIONS C SATISFIED IF THE EUCLIDEAN NORM OF THE APPROXIMATE C GRADIENT VECTOR IS LESS THAN DELTA. C C *************** NOTE ******************************** C C THE ITERATION WILL TERMIATE ( CONVERGENCE WILL CONSIDERED C ACHIEVED ) IF ANY ONE OF THE THREE CONDITIONS IS SATISFIED. C C RMACH A REAL ARRAY OF LENGTH TWO WHICH IS DEPENDENT C UPON THE MACHINE SIGNIFICANCE; C SIG (MAXIMUM NUMBER OF SIGNIFICANT C DIGITS ) AND SHOULD BE COMPUTED AS FOLLOWS: C C RMACH(1)= 5.0*10.0 **(-SIG+3) C RMACH(2)=10.0 **(-(SIG/2)-1) C C WORK SCRATCH ARRAY OF LENGTH 2*M+(N*(N+2*M+9))/2 C WHOSE CONTENTS ARE C C 1 TO JACM1 N*(N+1)/2 LOWER SUPER TRIANGLE OF C JACOBIAN( TRANSPOSED ) C TIMES JACOBIAN C C JACESS TO GRDM1 N*M JACOBIAN MATRIX C C JACSS TO DELEND N DELTA X C C GRADSS TO GRDEND N GRADIENT C C GRADSS TO DIAGM1 M INCREMENTED FUNCTION VECTOR C C DIAGSS TO ENDSS N SCALING VECTOR C C FMNSS TO XBADSS-1 M DECREMENTED FUNCTION VECTOR C C XBADSS TO XBEND N LASTEST SINGULAR POINT C C NOTE: C SEVERAL WORDS ARE USED FOR TWO DIFFERENT QUANTITIES (E.G., C JACOBIAN AND DELTA X) SO THEY MAY NOT BE AVAILABLE C THROUGHOUT THE PROGRAM. C C W WEIGHTING VECTOR OF LENGTH M C C SLTJJ ARRAY OF LENGTH N*(N+1)/2 WHICH CONTAINS THE LOWER SUPER C TRIANGLE OF J(TRANS)*J RETAINED FROM WORK(1) THROUGH C WORK(JACM1) IN DO 30. ELEMENTS STORED SERIALLY AS C(1,1), C C(2,1),C(2,2),C(3,1),C(3,2),...,C(N,N). USED IN STATISTICS C SUBROUTINES FOR STANDARD DEVIATIONS AND CORRELATION C COEFFICIENTS OF PARAMETERS. C C ICONV AN INTEGER OUTPUT PARAMETER INDICATING SUCCESSFUL C CONVERGENCE OR FAILURE C C .GT. 0 MEANS CONVERGENCE IN ITER ITERATION C = 1 CONVERGENCE BY FIRST CRITERION C = 2 CONVERGENCE BY SECOND CRITERION C = 3 CONVERGENCE BY THIRD CRITERION C .EQ. 0 MEANS FAILURE TO CONVERGE IN ITMAX ITERATIONS C .EQ. -1 MEANS FAILURE TO CONVERGE IN ITER ITERATIONS C BECAUSE OF UNAVOIDABLE SINGULARITY WAS ENCOUNTERED C C ITER AN INTEGER OUTPUT PARAMETER WHOSE VALUE IS THE NUMBER OF C ITERATIONS USED. THE NUMBER OF FUNCTION EVALUATIONS USED C IS ROUGHLY (N+1)*ITER. C C SSQ THE SUM OF THE SQUARES OF THE RESIDUALS FOR THE CURRENT C X AT RETURN. C C F A REAL ARRAY OF LENGTH M WHICH CONTAINS THE FINAL VALUE C OF THE RESIDUALS (THE F(I)'S) . C C C EXPLANATION OF PARAMETERS ---- C C X CURRENT X VECTOR C N NUMBER OF UNKNOWNS C ICONV CONVERGENCE INDICATOR (SEE ABOVE) C ITER NUMBER OF THE CURRENT ITERATION C SSQ THE NUMBER OF THE SQUARES OF THE RESIDUALS FOR THE C CURRENT X C ERL2 THE EUCLICEAN NORM OF THE GRADIENT FOR THE CURRENT X C GRAD THE REAL ARRAY OF LENGTH N CONTAINING THE GRADIENT C AT THE CURRENT X C C NOTE ---- C C N AND ITER MUST NOT BE CHANGED IN PRNOUT C X AND ERL2 SHOULD NOT BE CAPRICIOUSLY CHANGED. C C C C S.H. BRYANT ---- REVISION MAY 12, 1979 ---- C C DEPARTMENT OF PHARACOLOGY AND CELL BIOPHYSICS, C COLLEGE OF MEDICINE, C UNIVERSITY OF CINCINNATI, C 231 BETHESDA AVE., C CINCINNATI, C OHIO. 45267. C TELEPHONE 513/ 872-5621. } { Initialisation } var i,j,jk,k,kk,l,jacss,jacm1,delend,GRADSS,GRDEND,GRDM1,FPLSS,FPLM1 : LongInt ; DIAGSS,DIAGM1,ENDSS,FMNSS,XBADSS,XBEND,IBAD,NP1,ISW : LongInt ; Iis,JS,LI,Jl,JM,KQ,JK1,LIM,JN,MJ : LongInt ; PREC,REL,DTST,DEPS,RELCON,RELSSQ,GCrit,ERL2,RN,OldSSQ,HH,XDABS,ParHold,SUM,TT : Single ; RHH,DNORM : Single ; Quit,Singular,retry,Converged : Boolean ; WorkSpaceSize : Integer ; Work : ^TWorkArray ; begin { Set machine precision constants } PREC := 0.01 ; REL := 0.005 ; DTST := SQRT1(PREC) ; DEPS := SQRT1(REL) ; { Set convergence limits } { RELCON := 10.**(-NUMSIG) ; RELSSQ := 10.**(-NSIGSQ) ; } RELCON := 1E-4 ; RELSSQ := 1E-4 ; { Set up pointers into WORK buffer } JACSS := 1+(nPars*(nPars+1)) div 2 ; JACM1 := JACSS-1 ; DELEND := JACM1 + nPars ; { Gradient } GRADSS := JACSS+nPars*nPoints ; GRDM1 := GRADSS-1 ; GRDEND := GRDM1 + nPars ; { Forward trial residuals } FPLSS := GRADSS ; FPLM1 := FPLSS-1 ; { Diagonal elements of Jacobian } DIAGSS := FPLSS + nPoints ; DIAGM1 := DIAGSS - 1 ; ENDSS := DIAGM1 + nPars ; { Reverse trial residuals } FMNSS := ENDSS + 1 ; XBADSS := FMNSS + nPoints ; XBEND := XBADSS + nPars - 1 ; ICONV := -5 ; ERL2 := 1.0E35 ; GCRIT := 10.0E-3 ; IBAD := -99 ; RN := 1. / nPars ; NP1 := nPars + 1 ; ISW := 1 ; ITER := 1 ; // Allocate work buffer WorkSpaceSize := ((2*nPoints) + (nPars*(nPars+2*nPoints+9)) div 2)*4 ; GetMem( Work, WorkSpaceSize ) ; { Iterative loop to find best fit parameter values } Quit := False ; While Not Quit do begin { Compute sum of squares SSQ := W * (Ydata - Yfunction)*(Ydata - Yfunction) } SSQ := SSQCAL(Pars,nPoints,nPars,F,1,W) ; { Convergence test - 2 Sum of squares nPointsatch to NSIGSQ figures } IF ITER <> 1 then begin {125} IF ABS(SSQ-OLDSSQ) <= (RELSSQ*MaxFlt([ 0.5,SSQ])) then begin ICONV := 2 ; break ; end ; end ; OLDSSQ := SSQ ;{125} { Compute trial residuals by incrementing and decrementing X(j) by HH j := 1...N R := Zi (Y(i) - Yfunc(i)) i := 1...M } K := JACM1 ; for J := 1 to nPars do begin { Compute size of increment in parameter } XDABS := ABS(Pars.Value[J]) ; HH := REL*XDABS ; if ISW = 2 then HH := HH*1.0E3 ; if HH <= PREC then HH := PREC ; { Compute forward residuals Rf := X(J)+dX(J) } ParHold := Pars.Value[J] ; Pars.Value[j] := Pars.Value[j] + HH ; FITFUNC(Pars, nPoints, nPars, Work^,FPLSS) ; Pars.Value[j] := ParHold ; { ISW = 1 then skip reverse residuals } IF ISW <> 1 then begin {GO TO 16 } { Compute reverse residual Rr := Pars[j] - dPars[j] } Pars.Value[j] := ParHold - HH ; FITFUNC(Pars, nPoints, nPars, Work^,FMNSS ) ; Pars.Value[j] := ParHold ; { Compute gradients (Central differences) Store in JACSS - GRDM1 SQRT1(W(j))(Rf(j) - Rr)j))/2HH for j := 1..M and X(i) i := 1..N } L := ENDSS ; RHH := 0.5/HH ; KK := 0 ; for I := FPLSS to DIAGM1 do begin L := L + 1 ; K := K + 1 ; KK := KK + 1 ; Work^[K] := SQRT1(W[KK])*(Work^[I] - Work^[L])*RHH ; end ; end else begin { 16 } { Case of no reverse residuals Forward difference G := SQRT1(W(j)(Rf(j) - Ro(j))/HH j := 1..M X(i) i := 1..N } L := FPLM1 ; RHH := 1./HH ; for I := 1 to nPoints do begin K := K + 1 ; L := L + 1 ; Work^[K] := (SQRT1(W[I])*Work^[L] - F[I])*RHH ; end ; end ; end ; {20 } {22 CONTINUE} {C C G2 := Z W(j)* ((Rf(j) - Rr(j))/2HH) * Ro(j) C j := 1..M C C ERL2 := Z G2 C i := 1..N C } ERL2 := 0. ; K := JACM1 ; for I := GRADSS to GRDEND do begin SUM := 0. ; for J := 1 to nPoints do begin K := K + 1 ; SUM := SUM + Work^[K]*F[J] ; end ; Work^[I] := SUM ; ERL2 := ERL2 + SUM*SUM ; end ; ERL2 := SQRT1(ERL2) ; { Convergence test - 3 Euclidian norm < DELTA } IF(ERL2 <= DELTA) then begin ICONV := 3 ; break ; end ; IF(ERL2 < GCRIT) then ISW := 2 ; { Compute summed cross - products of residual gradients Sik := Z Gi(j) * Gk(j) (i,k := 1...N) j := 1...M S11,S12,S22,S13,S23,S33,..... } repeat Retry := False ; L := 0 ; Iis := JACM1 - nPoints ; for I := 1 to nPars do begin Iis := Iis + nPoints ; JS := JACM1 ; for J := 1 to I do begin L := L + 1 ; SUM := 0. ; for K := 1 to nPoints do begin LI := Iis + K ; JS := JS + 1 ; SUM := SUM + Work^[LI]*Work^[JS] ; end ; SLTJJ[L] := SUM ; Work^[L] := SUM ; end ; end ; { Compute normalised diagonal matrix SQRT1(Sii)/( SQRT1(Zi (Sii)**2) ) i := 1..N } L := 0 ; J := 0 ; DNORM := 0. ; for I := DIAGSS to ENDSS do begin {34} J := J + 1 ; L := L + J ; Work^[I] := SQRT1(Work^[L]) ; DNORM := DNORM + Work^[L]*Work^[L] ; end ; DNORM := 1./SQRT1(MinFlt([DNORM,3.4E38])) ; for I := DIAGSS to ENDSS do Work^[I] := Work^[I]*DNORM ; { Add ERL2 * Nii i := 1..N Diagonal elements of summed cross - products } L := 0 ; K := 0 ; for J := DIAGSS to ENDSS do begin K := K + 1 ; L := L + K ; Work^[L] := Work^[L] + ERL2*Work^[J] ; IF(IBAD > 0) then Work^[L] := Work^[L]*1.5 + DEPS ; end ; JK := 1 ; Singular := False ; JK1 := 0 ; for I := 1 to nPars do begin {52} JL := JK ; JM := 1 ; for J := 1 to I do begin {52} TT := Work^[JK] ; IF(J <> 1) then begin for K := JL to JK1 do begin TT := TT - Work^[K]*Work^[JM] ; JM := JM + 1 ; end ; end ; IF(I = J) then begin IF (Work^[JK] + TT*RN) <= Work^[JK] then Singular := True ;{GO TO 76} Work^[JK] := 1./SQRT1(TT) ; end else Work^[JK] := TT*Work^[JM] ; JK1 := JK ; JM := JM + 1 ; JK := JK + 1 ; end ; if Singular then Break ; end ; if Singular then begin { Singularity processing 76 } IF IBAD >= 2 then ReTry := False {GO TO 92} else if iBad < 0 then begin iBad := 0 ; ReTry := True ; {IF(IBAD) 81,78,78 } end else begin J := 0 ; {78} ReTry := False ; for I := XBADSS to XBEND do begin{80} J := J + 1 ; IF(ABS(Pars.Value[j] - Work^[I]) > MaxFlt( [DTST,ABS(Work^[I])*DTST]) ) then ReTry := True ; end ; {80} end ; end ; if ReTry then begin J := 0 ; {82} for I := XBADSS to XBEND do begin J := J + 1 ; Work^[I] := Pars.Value[j] end ; IBAD := IBAD + 1 ; end ; until not ReTry ; JK := 1 ; JL := JACM1 ; KQ := GRDM1 ; for I := 1 to nPars do begin {60} KQ := KQ + 1 ; TT := Work^[KQ] ; IF JL <> JACM1 then begin JK := JK + JL - 1 - JACM1 ; LIM := I - 1 + JACM1 ; for J := JL to LIM do begin TT := TT - Work^[JK]*Work^[J] ; JK := JK + 1 ; end ; end else begin IF(TT <> 0. ) then JL := JACM1 + I ; JK := JK + I - 1 ; end ; Work^[JACM1 + I] := TT*Work^[JK] ; JK := JK + 1 ; end ; {60} for I := 1 to nPars do begin{66} J := NP1 - I + JACM1 ; JK := JK - 1 ; JM := JK ; JN := NP1 - I + 1 ; TT := Work^[J] ; IF (nPars >= JN) then begin {GO TO 64} LI := nPars + JACM1 ; for MJ := JN to nPars do begin TT := TT - Work^[JM]*Work^[LI] ; LI := LI - 1 ; JM := JM - LI + JACM1 ; end ; end ; {64} Work^[J] := TT*Work^[JM] ; end ; {66} IF (IBAD <> - 99 ) then IBAD := 0 ; J := JACM1 ; for I := 1 to nPars do begin {68} J := J + 1 ; Pars.Value[I] := Pars.Value[I] - Work^[J] ; end ; {68} { Convergence condition - 1 Xnew := Xold to NUMSIG places 5E - 20 V1.1 .5 in V1. } Converged := True ; J := JACM1 ; for I := 1 to nPars do begin {70} J := J + 1 ; IF ABS(Work^[J]) > (RELCON*MaXFlt([0.5,ABS(Pars.Value[I])])) then Converged := False ; end ; if Converged then begin ICONV := 1 ; Quit := True ; end ; ITER := ITER + 1 ; IF (ITER > ITMAX) then Quit := True ; end ; SSQ := SSQCAL(Pars,nPoints,nPars,F,1,W) ; Dispose(Work) ; end ; function TCurveFitter.SSQCAL( const Pars : TPars ; nPoints : Integer ; nPars : Integer ; var Residuals : Array of Single ; iStart : Integer ; const W : Array of Single ) : Single ; { Compute sum of squares of residuals } { Enter with : Pars = Array of function parameters nPoints = Number of data points to be fitted nPars = Number of parameters in Pars Residuals = array of residual differences W = array of weights } var I : LongInt ; SSQ : single ; begin FitFunc(Pars,nPoints,nPars,Residuals,iStart ) ; SSQ := 0. ; for I := 1 to nPoints do begin Residuals[I] := SQRT1(W[I])*Residuals[iStart+I-1] ; SSQ := SSQ + Sqr(Residuals[iStart+I-1]) ; end ; SSQCAL := SSQ ; end ; procedure TCurveFitter.FitFunc( Const FitPars :TPars ; nPoints : Integer ; nPars : Integer ; Var Residuals : Array of Single ; iStart : Integer ) ; var i : Integer ; begin { Un-map parameters from compressed array to normal } for i := 1 to nPars do Pars[FitPars.Map[i]] := FitPars.Value[i] ; { Convert log-transformed parameters to normal } for i := 0 to nPars-1 do if LogPars[i] then Pars[i] := Exp(Pars[i]) ; if UseBinWidthsFlag then begin { Apply bin width multiplier when fitting probability density functions to histograms } for i := 0 to nPoints-1 do Residuals[iStart+I] := YData[I] - (BinWidth[i]*EquationValue(XData[I])) ; end else begin { Normal curve fitting } for i := 0 to nPoints-1 do Residuals[iStart+I] := YData[I] - EquationValue(XData[I]) ; end ; end ; procedure TCurveFitter.STAT( nPoints : Integer ; { no. of residuals (observations) } nPars : Integer ; { no. of fitted parameters } var F : Array of Single ; { final values of the residuals (IN) } var Y : Array of Single ; { Y Data (IN) } var W : Array of Single ; { Y Data weights (IN) } var SLT : Array of Single ; { lower super triangle of J(TRANS)*J from SLTJJ in SSQMIN (IN) } var SSQ : Single; { Final sum of squares of residuals (IN) Returned containing parameter corr. coeffs. as CX(1,1),CX(2,1),CX(2,2),CX(3,1)....CX(N,N)} var SDPars : Array of Single ; { OUT standard deviations of each parameter X } var SDMIN : Single ; { OUT Minimised standard deviation } var R : Single ; { OUT Hamilton's R } var XPAR : Array of Single { IN Fitted parameter array } ) ; {C C J.DEMPSTER 1 - FEB - 82 C Adapted from STAT by S.H. Bryant CC Subroutine to supply statistics for non - linear least - C squares fit of tabular data by SSQMIN. C After minminsation takes J(TRANSPOSE)*J matrix from C ssqmin which is stored serially as a lower super tr - C angle in SLTJJ(1) through SLTJJ(JACM1). Creates full C matrix in C(N,N) which is then inverted to give the var - C iance/covariance martix from which standard deviances C and correlation coefficients are calculated by the C methods of Hamilton (1964). Hamilton's R is calculated from C the data and theoretical values C C Variables in call string: C C M - Integer no. of residuals (observations) C N - Integer no. of fitted parameters C F - Real array of length M which contains the C final values of the residuals C Y - Real array of length M containing Y data C W - Real weighting array of length M C SLT - Real array of length N*(N + 1)/2 C on input stores lower super triangle of C J(TRANS)*J from SLTJJ in SSQMIN C on return contains parameter corr. coeffs. C as CX(1,1),CX(2,1),CX(2,2),CX(3,1)....CX(N,N) C SSQ - Final sum of squares of residuals C SDX - REal array of length N containing the % standard C deviations of each parameter X C SDMIN - Minimised standard deviation C R - Hamilton's R C XPAR - Fitted parameter array C C C Requires matrix inversion srtn. MINV C DIMENSION Y(M),SLT(1),SDX(N),C(8,8),A(64) C REAL F(M),W(M),XPAR(N) INTEGER LROW(8),MCOL(8) } var I,J,L : LongInt ; LROW,MCOL : Array[0..8] of LongInt ; C : Array[1..8,1..8] of Single ; A : Array[0..80] of Single ; SUMP,YWGHT,DET : Single ; begin SDMIN := SQRT1( (SSQ/(nPoints - nPars)) ) ; SUMP := 0. ; for I := 1 to nPoints do begin YWGHT := Y[I-1]*SQRT1(W[I]) ; SUMP := SUMP + Sqr(F[I] + YWGHT) ; end ; R := SQRT1(MinFlt([3.4E38,SSQ])/SUMP) ; { Restore J(TRANSP)*J and place in C(I,J) } L := 0 ; for I := 1 to nPars do begin for J := 1 to I do begin L := L + 1 ; C[I,J] := SLT[L] ; end ; end ; for I := 1 to nPars do for J := 1 to nPars do IF (I < J) then C[I,J] := C[J,I] ; { Invert C(I,J) } L := 0 ; for J := 1 to nPars do begin for I := 1 to nPars do begin L := L + 1 ; A[L] := C[I,J] ; end ; end ; MINV (A,nPars,DET,LROW,MCOL) ; L := 0 ; for J := 1 to nPars do begin for I := 1 to nPars do begin L := L + 1 ; C[I,J] := A[L] ; end ; end ; { Calculate std. dev. Pars[j] } for J := 1 to nPars do SDPars[j] := SDMIN * SQRT1(ABS(C[J,J])) ; {C *** REMOVED since causing F.P. error and not used C Calculate correlation coefficients for C X(1) on Pars[j]. Return in lower super C triangle as X(1,1),X(2,2),X(3,1),X(3,2) .... C C L := 0 C DO 7 I := 1 to N C DO 7 J := 1,I C L := L + 1 C SLT(L) := C(I,J)/SQRT1(C(I,I)*C(J,J)) C7 CONTINUE RETURN} end ; procedure TCurveFitter.MINV( var A : Array of Single ; N : LongInt ; var D : Single ; var L,M : Array of LongInt ) ; { C A - INPUT MATRIX, DESTROYED IN COMPUTATION AND REPLACED BY C RESULTANT INVERSE. C N - ORDER OF MATRIX A C D - RESULTANT DETERMINANT C L - Work^ VECTOR OF LENGTH N C M - Work^ VECTOR OF LENGTH N C C REMARKS C MATRIX A MUST BE A GENERAL MATRIX C C C METHOD C THE STANDARD GAUSS - JORDAN METHOD IS USED. THE DETERMINANT C IS ALSO CALCULATED. A DETERMINANT OF ZERO INDICATES THAT C THE MATRIX IS SINGULAR. C } var NK,K,I,J,KK,IJ,IK,IZ,KI,KJ,JP,JQ,JR,JI,JK : LongInt ; BIGA,HOLD : Single ; begin D := 1.0 ; NK := -N ; for K := 1 to N do begin {80} NK := NK + N ; L[K] := K ; M[K] := K ; KK := NK + K ; BIGA := A[KK] ; for J := K to N do begin{20} IZ := N*(J - 1) ; for I := K to N do begin {20} IJ := IZ + I ; IF( ABS(BIGA) - ABS(A[IJ])) < 0. then begin {15,20,20} BIGA := A[IJ] ; L[K] := I ; M[K] := J ; end ; end ; end ; { INTERCHANGE ROWS } J := L[K] ; IF(J - K) > 0. then begin {35,35,25} KI := K - N ; for I := 1 to N do begin {30} KI := KI + N ; HOLD := - A[KI] ; JI := KI - K + J ; A[KI] := A[JI] ; A[JI] := HOLD ; end ; {30} end ; { INTERCHANGE COLUMNS } I := M[K] ; {35} IF(I - K) > 0. then begin JP := N*(I - 1) ; for J := 1 to N do begin {40} JK := NK + J ; JI := JP + J ; HOLD := - A[JK] ; A[JK] := A[JI] ; A[JI] := HOLD end ;{40} end ; { DIVIDE COLUMN BY MINUS PIVOT (VALUE OF PIVOT ELEMENT IS CONTAINED IN BIGA } IF BIGA = 0. then begin D := 0.0 ; break ; end ; for I := 1 to N do begin {55} IF(I - K) <> 0 then begin {50,55,50} IK := NK + I ; A[IK] := A[IK]/( -BIGA) ; end ; end ; {55} { REDUCE MATRIX } for I := 1 to N do begin {65} IK := NK + I ; HOLD := A[IK] ; IJ := I - N ; for J := 1 to N do begin {65} IJ := IJ + N ; IF(I - K) <> 0 then begin {60,65,60} IF(J - K) <> 0 then begin {62,65,62} KJ := IJ - I + K ; A[IJ] := HOLD*A[KJ] + A[IJ] ; end ; end ; end ; end ; {65} { DIVIDE ROW BY PIVOT } KJ := K - N ; for J := 1 to N do begin {75} KJ := KJ + N ; IF(J <> K) then {70,75,70} A[KJ] := A[KJ]/BIGA ; end ; {75} { PRODUCT OF PIVOTS } D := D*BIGA ; { REPLACE PIVOT BY RECIPROCAL } A[KK] := 1.0/BIGA ; end ; { FINAL ROW AND COLUMN INTERCHANGE } K := N - 1 ; while (K>0) do begin {150,150,105} I := L[K] ;{105} IF(I - K) > 0 then begin {120,120,108} JQ := N*(K - 1) ; {108} JR := N*(I - 1) ; for J := 1 to N do begin {110} JK := JQ + J ; HOLD := A[JK] ; JI := JR + J ; A[JK] := -A[JI] ; A[JI] := HOLD ; end ; {110} end ; J := M[K] ;{120} IF(J - K) > 0 then begin {100,100,125} KI := K - N ; {125} for I := 1 to N do begin {130} KI := KI + N ; HOLD := A[KI] ; JI := KI - K + J ; A[KI] := -A[JI] ; A[JI] := HOLD ; end ; {130} end ; K := (K - 1) ; end ; end ; FUNCTION TCurveFitter.SQRT1 ( R : single ) : single ; begin SQRT1 := SQRT( MINFlt([R,MaxSingle]) ) ; end ; function TCurveFitter.MinInt( const Buf : array of LongInt { List of numbers (IN) } ) : LongInt ; { Returns Minimum of Buf } { ------------------------------------------- Return the smallest value in the array 'Buf' -------------------------------------------} var i,Min : LongInt ; begin Min := High(Min) ; for i := 0 to High(Buf) do if Buf[i] < Min then Min := Buf[i] ; Result := Min ; end ; function TCurveFitter.MinFlt( const Buf : array of Single { List of numbers (IN) } ) : Single ; { Returns minimum of Buf } { --------------------------------------------------------- Return the smallest value in the floating point array 'Buf' ---------------------------------------------------------} var i : Integer ; Min : Single ; begin Min := MaxSingle ; for i := 0 to High(Buf) do if Buf[i] < Min then Min := Buf[i] ; Result := Min ; end ; function TCurveFitter.MaxInt( const Buf : array of LongInt { List of numbers (IN) } ) : LongInt ; { Returns maximum of Buf } { --------------------------------------------------------- Return the largest long integer value in the array 'Buf' ---------------------------------------------------------} var Max : LongInt ; i : Integer ; begin Max:= -High(Max) ; for i := 0 to High(Buf) do if Buf[i] > Max then Max := Buf[i] ; Result := Max ; end ; function TCurveFitter.MaxFlt( const Buf : array of Single { List of numbers (IN) } ) : Single ; { Returns maximum of Buf } { --------------------------------------------------------- Return the largest floating point value in the array 'Buf' ---------------------------------------------------------} var i : Integer ; Max : Single ; begin Max:= -MaxSingle ; for i := 0 to High(Buf) do if Buf[i] > Max then Max := Buf[i] ; Result := Max ; end ; function TCurveFitter.IntLimitTo( Value : Integer ; { Value to be tested (IN) } LowerLimit : Integer ; { Lower limit (IN) } UpperLimit : Integer { Upper limit (IN) } ) : Integer ; { Return limited Value } { ------------------------------------------------------------------- Make sure Value is kept within the limits LowerLimit and UpperLimit -------------------------------------------------------------------} begin if Value < LowerLimit then Value := LowerLimit ; if Value > UpperLimit then Value := UpperLimit ; Result := Value ; end ; function TCurveFitter.erf(x : Single ) : Single ; { -------------- Error function --------------} var t,z,y,erfx : single ; begin if x < 10. then begin z := abs( x ) ; t := 1./( 1. + 0.5*z ) ; y := t*exp( -z*z - 1.26551223 + t*(1.00002368 + t*(0.37409196 + t*(0.09678418 + t*( -0.18628806 + t*(0.27886807 + t*( -1.13520398 + t*(1.48851587 + t*( -0.82215223 + t*0.17087277 ))))))))) ; if ( x < 0. ) then y := 2. - y ; erfx := 1. - y ; end else erfx := 1. ; Result := erfx ; end ; function TCurveFitter.FPower( x,y : Single ) : Single ; { ---------------------------------- Calculate x to the power y (x^^y) ----------------------------------} begin if x > 0. then FPower := exp( ln(x)*y ) else FPower := 0. ; end ; function TCurveFitter.SafeExp( x : single ) : single ; { ------------------------------------------------------- Exponential function which avoids underflow errors for large negative values of x -------------------------------------------------------} const MinSingle = 1.5E-45 ; var MinX : single ; begin MinX := ln(MinSingle) + 1.0 ; if x < MinX then SafeExp := 0.0 else SafeExp := exp(x) ; end ; end.
unit VisibleDSA.MergeSort; interface uses System.SysUtils; type UChar = Char; UString = String; TArray_int = TArray<integer>; TMergeSort = class private // 将arr[l...mid]和arr[mid+1...r]两部分进行归并 class procedure __merge(arr: TArray_int; l, mid, r: integer); // 递归使用归并排序,对arr[l...r]的范围进行排序 class procedure __sort(arr: TArray_int; l, r, depth: integer); class function __repeatCharacters(character: UChar; length: integer): UString; public class procedure Sort(arr: TArray_int); end; implementation { TMergeSort } class procedure TMergeSort.Sort(arr: TArray_int); var n: integer; begin n := length(arr); __sort(arr, 0, n - 1, 0); end; class procedure TMergeSort.__merge(arr: TArray_int; l, mid, r: integer); var aux: TArray_int; i: integer; leftIndex, rightIndex: integer; begin SetLength(aux, r - l + 1); for i := l to r do aux[i - l] := arr[i]; // 初始化,leftIndex指向左半部分的起始索引位置l; // rightIndex指向右半部分起始索引位置mid+1 leftIndex := l; rightIndex := mid + 1; for i := l to r do begin if leftIndex > mid then // 如果左半部分元素已经全部处理完毕 begin arr[i] := aux[rightIndex - l]; Inc(rightIndex); end else if rightIndex > r then // 如果右半部分元素已经全部处理完毕 begin arr[i] := aux[leftIndex - l]; Inc(leftIndex); end else if aux[leftIndex - l] < aux[rightIndex - l] then // 左半部分所指元素 < 右半部分所指元素 begin arr[i] := aux[leftIndex - l]; Inc(leftIndex); end else // 左半部分所指元素 >= 右半部分所指元素 begin arr[i] := aux[rightIndex - l]; Inc(rightIndex); end; end; end; class function TMergeSort.__repeatCharacters(character: UChar; length: integer): UString; var s: TStringBuilder; i: integer; begin s := TStringBuilder.Create; try for i := 0 to length - 1 do begin s.Append(character); end; Result := s.ToString; finally s.Free; end; end; class procedure TMergeSort.__sort(arr: TArray_int; l, r, depth: integer); var mid: integer; begin Write(__repeatCharacters('-', depth * 2)); Writeln(' Deal with [' + l.ToString + ', ' + r.ToString + ']'); if (l >= r) then Exit; mid := l + (r - l) shr 1; __sort(arr, l, mid, depth + 1); __sort(arr, mid + 1, r, depth + 1); __merge(arr, l, mid, r); end; end.
unit UHTTPStreamReader; interface uses Classes {$IFDEF MSWINDOWS} , Windows {$ENDIF}, SysUtils, IdIntercept, IdInterceptThrottler, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP; type TTestStream = class(TCustomMemoryStream) private FPosition: Longint; //procedure SetCapacity(NewCapacity: Longint); override; public function Seek(Offset: Longint; Origin: Word): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; end; THTTPStreamReader = class(TThread) protected procedure Execute; override; private procedure OnHTTPProgress(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); procedure Log; public idHTTP: TIdHTTP; idInterceptThrottler: TIdInterceptThrottler; m_sNum: Integer; m_sURL: string; m_uMaxSpeed: UInt64; m_uResponseCode: Int64; m_uResponseContentLength: Int64; m_uStartPosition: Int64; m_uEndPosition: Int64; m_lastError: string; m_sLastMessage: string; m_sNullStream: TTestStream; constructor Create(Num: Integer; URL: string; MaxSpeed: UInt64); destructor Destroy(); override; end; implementation uses wMain, IdHTTPHeaderInfo; { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure HTTPStreamReader.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } {procedure TTestStream.SetCapacity(NewCapacity: Longint); begin // end; } function TTestStream.Write(const Buffer; Count: Longint): Longint; begin Result := Count; end; function TTestStream.Seek(Offset: Longint; Origin: Word): Longint; begin case Origin of soFromBeginning: FPosition := Offset; soFromCurrent: Inc(FPosition, Offset); //soFromEnd: FPosition := FSize + Offset; end; Result := FPosition; end; { HTTPStreamReader } constructor THTTPStreamReader.Create(Num: Integer; URL: string; MaxSpeed: UInt64); begin inherited Create(true); m_sNum := Num; m_sURL := URL; m_uMaxSpeed := MaxSpeed; m_sNullStream := TTestStream.Create; Self.FreeOnTerminate := false; end; destructor THTTPStreamReader.Destroy(); begin if (Assigned(idHTTP)) then FreeAndNil(idHTTP); if (Assigned(idInterceptThrottler)) then FreeAndNil(idInterceptThrottler); if (Assigned(m_sNullStream)) then FreeAndNil(m_sNullStream); inherited Destroy; end; procedure THTTPStreamReader.Execute; var idRange: TIdEntityRange; begin NameThreadForDebugging('HTTPStreamReader-' + IntToStr(m_sNum)); idInterceptThrottler := TIdInterceptThrottler.Create(nil); idInterceptThrottler.BitsPerSec := m_uMaxSpeed; idHTTP := TIdHTTP.Create(nil); idHTTP.Intercept := idInterceptThrottler; idHTTP.OnWork := Self.OnHTTPProgress; Randomize; try idHTTP.Head(m_sURL); m_uResponseCode := idHTTP.Response.ResponseCode; m_uResponseContentLength := idHTTP.Response.ContentLength; m_uStartPosition := Random(m_uResponseContentLength div 4); m_uEndPosition := m_uStartPosition + ((100 + Random(100)) * 1024 * 1024); //m_uEndPosition := m_uResponseContentLength - 1; while (not Terminated) do begin idHTTP.Request.Ranges.Clear; idRange := IdHTTP.Request.Ranges.Add; idRange.StartPos := m_uStartPosition; idRange.EndPos := m_uEndPosition; m_sLastMessage := 'Thread #' + IntToStr(m_sNum) + ' :: Start: ' + IntToStr(m_uStartPosition) + '; End: ' + IntToStr(m_uEndPosition) + '; Code: ' + IntToStr(m_uResponseCode); Synchronize(Log); idHTTP.Get(m_sURL, m_sNullStream); if (m_uEndPosition <= m_uResponseContentLength) then m_uStartPosition := m_uEndPosition else m_uStartPosition := 0; m_uEndPosition := m_uStartPosition + ((100 + Random(100)) * 1024 * 1024); end; except on E: Exception do begin m_lastError := E.ClassName + ': ' + E.Message; Synchronize( procedure begin fMain.Log(m_lastError); end ); end; end; end; procedure THTTPStreamReader.OnHTTPProgress(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); begin if Self.Terminated then begin if (idHTTP.Connected) then begin idHTTP.Disconnect; idHTTP.IOHandler.InputBuffer.Clear; if (idHTTP.Connected) then Abort; end; end; end; procedure THTTPStreamReader.Log; begin fMain.Log(m_sLastMessage); end; end.
unit Unit1; { Record/Buffer Exchange Client Demo Indy 10.5.5 It just shows how to send/receive Record/Buffer. No error handling. **** GENERIC RECORD HANDLING ***** Instruction : select correct means corresponding recordtype for client send = server get and server send = client get version november 2011 & march, april 2012 } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, StdCtrls, Unit_Indy_Classes, Vcl.ExtCtrls; type TRecordClientForm = class(TForm) CheckBox1: TCheckBox; Memo1: TMemo; Button_SendBuffer: TButton; IdTCPClient1: TIdTCPClient; BuildButton: TButton; RadioGroup1: TRadioGroup; RadioGroup2: TRadioGroup; procedure CheckBox1Click(Sender: TObject); procedure IdTCPClient1Connected(Sender: TObject); procedure IdTCPClient1Disconnected(Sender: TObject); procedure Button_SendBufferClick(Sender: TObject); procedure BuildButtonClick(Sender: TObject); procedure RadioGroup1Click(Sender: TObject); procedure RadioGroup2Click(Sender: TObject); private procedure SetClientState(aState: Boolean); procedure ShowTMyRecord(aRecord: TMyrecord); procedure ShowTINDYCMD(aINDYCMD: TINDYCMD); { Private declarations } public { Public declarations } RecordTypeIndex : Integer; RecordTypeIndex2 : Integer; end; var RecordClientForm: TRecordClientForm; implementation uses Unit_Indy_Functions, Unit_DelphiCompilerversionDLG; {$R *.dfm} procedure TRecordClientForm.BuildButtonClick(Sender: TObject); begin OKRightDlgDelphi.Show; end; procedure TRecordClientForm.Button_SendBufferClick(Sender: TObject); var aMyRecord : TGenericRecord<TMyRecord> ; aINDYCMD : TGenericRecord<TINDYCMD> ; LBuffer: TBytes; LMyRecord: TMyRecord; LIndyCMD : TINDYCMD; LSize: LongInt; begin /// create generic records aINDYCMD := TGenericRecord<TINDYCMD>.Create; aMyRecord := TGenericRecord<TMyRecord>.Create; LMyRecord.Details := 'My personal data'; LMyRecord.FileName := 'MyFile.txt on Client Side '; LMyRecord.FileSize := random(20000); LMyRecord.FileDate := now; LMyRecord.Recordsize := sizeof(LMyRecord); LIndyCMD.CMD_CLASS := 1; LIndyCMD.CMD_VALUE := ' data from the client'; LIndyCMD.CMD_TIMESTAMP := now; aINDYCMD.Value := LINDYCMD; aMyRecord.Value := LMyRecord; case RecordTypeIndex of 0: LBuffer := aMyRecord.MyRecordToByteArray(aMyRecord.Value); 1: LBuffer := aINDYCMD.MyRecordToByteArray(aINDYCMD.Value); else end; if (SendBuffer(IdTCPClient1, LBuffer) = False) then begin Memo1.Lines.Add('Cannot send record/buffer to server.'); Exit; end else Memo1.Lines.Add('Succesfully send record/buffer to server.'); if (ReceiveBuffer(IdTCPClient1, LBuffer) = False) then begin Memo1.Lines.Add('Cannot get "OK" message from server, Unknown error occured'); Exit; end; case RecordTypeIndex2 of 0: begin aMyRecord.Value := aMyRecord.ByteArrayToMyRecord(LBuffer); ShowTMyRecord(aMyRecord.Value); end; 1: begin aINDYCMD.Value := aINDYCMD.ByteArrayToMyRecord(LBuffer); ShowTINDYCMD( aINDYCMD.Value); end else end; /// optional : avoid TimeOut Errors /// SetClientState(false) end; procedure TRecordClientForm.CheckBox1Click(Sender: TObject); begin if ( CheckBox1.Checked = True ) then begin SetClientState(true); end else SetClientState(false); end; procedure TRecordClientForm.SetClientState (aState : Boolean); begin if ( aState = True ) then begin IdTCPClient1.Host := '127.0.0.1'; IdTCPClient1.Port := 5000; IdTCPClient1.Connect; end else IdTCPClient1.Disconnect; CheckBox1.Checked := aState; end; procedure TRecordClientForm.IdTCPClient1Connected(Sender: TObject); begin Memo1.Lines.Add('Client has connected to server'); end; procedure TRecordClientForm.IdTCPClient1Disconnected(Sender: TObject); begin Memo1.Lines.Add('Client has disconnected from server'); end; procedure TRecordClientForm.ShowTMyRecord (aRecord : TMyrecord); begin Memo1.Lines.Add('-------------------<START>----------------'); Memo1.Lines.Add('Server says it has received your record, "OK" message received.'); Memo1.Lines.Add('received data ' + aRecord .Details ); Memo1.Lines.Add('received data ' + aRecord .FileName ); Memo1.Lines.Add('received data ' + IntToStr(aRecord .FileSize) ); Memo1.Lines.Add('received data ' + IntToStr(aRecord .Recordsize) ); Memo1.Lines.Add('received data ' + dateToStr(aRecord.FileDate) ); Memo1.Lines.Add('received data ' + TimeToStr(aRecord.FileDate) ); Memo1.Lines.Add('-------------------<END>----------------'); end; procedure TRecordClientForm.ShowTINDYCMD (aINDYCMD : TINDYCMD); begin Memo1.Lines.Add('-------------------<start>----------------'); Memo1.Lines.Add('Server says it has received your record, "OK" message received.'); Memo1.Lines.Add('received data ' + IntToStr( aINDYCMD.CMD_CLASS )); Memo1.Lines.Add('received data ' + aINDYCMD.CMD_VALUE); Memo1.Lines.Add('received data ' + Datetostr(aINDYCMD.CMD_TIMESTAMP)); Memo1.Lines.Add('received data ' + Timetostr(aINDYCMD.CMD_TIMESTAMP)); Memo1.Lines.Add('-------------------<END>----------------'); end; procedure TRecordClientForm.RadioGroup1Click(Sender: TObject); begin RecordTypeIndex := RadioGroup1.ItemIndex; end; procedure TRecordClientForm.RadioGroup2Click(Sender: TObject); begin RecordTypeIndex2 := RadioGroup2.ItemIndex; end; end.
unit CommonUnit; interface uses Grids, AlienRFID2_TLB; function HexToString(H: String): String; function StringToHex(S: String): string; function ValidHexKey(AKey:Char):Char; procedure MyGridSize(Grid: TStringGrid); procedure SetReaderMask(AMask:String; AOffset:Integer; AmReader:TclsReader); implementation uses StrUtils,SysUtils; function HexToString(H: String): String; var I: Integer; begin Result:= ''; H:=ReplaceStr(H,' ',''); for I := 1 to length (H) div 2 do Result:= Result+Char(StrToInt('$'+Copy(H,(I-1)*2+1,2))); end; function StringToHex(S: String): string; var I: Integer; begin Result:= ''; for I := 1 to length (S) do Result:= Result+IntToHex(ord(S[i]),2); end; procedure MyGridSize(Grid: TStringGrid); const DEFBORDER = 10; var temp, n,m: Integer; lmax: array [0..30] of Integer; cmax:Integer; k:real; begin cmax:=0; with Grid do begin Canvas.Font := Font; for n := 0 to ColCount - 1 do lmax[n] := Canvas.TextWidth(Grid.cells[n,0]) + DEFBORDER; for m := 1 to RowCount - 1 do begin for n := 0 to ColCount - 1 do begin temp := Canvas.TextWidth(trim(Grid.cells[n,m])) + DEFBORDER; if temp > lmax[n] then lmax[n] := temp; end; {for} end; for n := 0 to ColCount - 1 do if lmax[n] > 0 then cmax:=cmax+lmax[n]; k:=Grid.Width/cmax; for n := 0 to ColCount - 1 do if lmax[n] > 0 then ColWidths[n] := trunc(lmax[n]*k); end; end; procedure SetReaderMask(AMask:String; AOffset:Integer; AmReader:TclsReader); var Offset:integer; i,l:integer; resultMask:string; begin if AmReader.IsConnected then begin if AMask='' then AmReader.Mask:='00' else begin AMask:=ReplaceStr(AMask,' ',''); resultMask:=''; for I := 1 to length (AMask) div 2 do resultMask:= resultMask+Copy(AMask,(I-1)*2+1,2)+' '; resultMask:=trim(resultMask); l:=length(AMask); l:=(l div 2)*8; Offset:=32+AOffset*8; AmReader.SetAcqG2Mask(IntToStr(eG2Bank_EPC),IntToStr(Offset),IntToStr(l),resultMask); end; end; end; function ValidHexKey(AKey:Char):Char; begin Akey:=UpCase(AKey); Result:=AKey; if not (AKey in ['0'..'9','A'..'F',#8]) then Result:=chr(0); end; end.
unit Atividade1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, database, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.Mask, Vcl.DBCtrls, Atividade1Janela2, UNSpeciality, UNadmingroup, UNcontroller, Data.DBXMySQL, Data.FMTBcd, Datasnap.DBClient, Datasnap.Provider, Data.SqlExpr, Atividade1Janela3; type TForm1 = class(TForm, IAtualizaTela) Panel1: TPanel; Label1: TLabel; Edit1: TEdit; CheckBox1: TCheckBox; Button1: TButton; Incluir: TButton; Alterar: TButton; Excluir: TButton; SO: TButton; Cancelar: TButton; DBGrid1: TDBGrid; Label2: TLabel; Label3: TLabel; DBEdit2: TDBEdit; Label4: TLabel; Label5: TLabel; DBEdit3: TDBEdit; ComboBox1: TComboBox; DataSource1: TDataSource; ClientDataSet1: TClientDataSet; procedure IncluirClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure AlterarClick(Sender: TObject); procedure ExcluirClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure CancelarClick(Sender: TObject); procedure SOClick(Sender: TObject); private { Private declarations } public procedure AtualizaTela; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.AlterarClick(Sender: TObject); var Form2 : TForm2; begin Form2 := TForm2.Create(Form2); try Form2.Alterar := true; Form2.ClientDataSet := ClientDataSet1; Form2.Edit1.Text := ClientDataSet1.Fields[0].AsString; Form2.Edit1.ReadOnly := true; Form2.Edit2.Text := ClientDataSet1.Fields[1].AsString; if ClientDataSet1.Fields[2].AsString = 'B' then begin Form2.CheckBox1.Checked := true; end; //Form2.ComboBox1.Text := ClientDataSet1.Fields[3].AsString; Form2.ComboBox1.ItemIndex := Form2.ComboBox1.Items.IndexOf(ClientDataSet1.Fields[3].AsString); Form2.ShowModal; finally Form2.Free; end; end; procedure TForm1.AtualizaTela; begin ComboBox1.Clear; TController.getinstance.ClientRefresh(ClientDataSet1); TController.getinstance.carregarCBAdmGroup(combobox1); end; procedure TForm1.Button1Click(Sender: TObject); begin if checkbox1.Checked = true then begin tcontroller.getinstance.pesquisar(edit1.text,combobox1.text, ClientDataSet1); end else begin tcontroller.getinstance.pesquisar(edit1.text,'', ClientDataSet1); end; end; procedure TForm1.CancelarClick(Sender: TObject); begin close; end; procedure TForm1.CheckBox1Click(Sender: TObject); begin if CheckBox1.Checked then begin ComboBox1.Enabled := true; end; if not CheckBox1.Checked then begin ComboBox1.Enabled := false; end; end; procedure TForm1.ExcluirClick(Sender: TObject); var CSpeciality : TSpeciality; begin try CSpeciality := TSpeciality.Create; CSpeciality.specialityid := DBGrid1.Fields[0].AsString; CSpeciality.comando := CMDDetalhes; CSpeciality := TController.GetInstance.CtrlSpeciality(CSpeciality, ClientDataSet1); //l CSpeciality.comando := CMDExcluir; TController.GetInstance.CtrlSpeciality(CSpeciality, ClientDataSet1); finally CSpeciality.Free; end; end; procedure TForm1.FormCreate(Sender: TObject); begin TController.GetInstance.TelaPrincipal := self; AtualizaTela; ComboBox1.Enabled := false; ComboBox1.Style := csDropDownList; end; procedure TForm1.IncluirClick(Sender: TObject); var Form2 : TForm2; begin Form2.Alterar :=false; Form2 := TForm2.Create(Form2); Form2.ClientDataSet := ClientDataSet1; try Form2.ShowModal; finally Form2.Free; end; end; procedure TForm1.SOClick(Sender: TObject); var Form3 : TForm3; begin Form3 := TForm3.Create(Form3); //Form3.ClientDataSet1 := clientdataset1; try Form3.ShowModal; finally Form3.Free; end; end; end.
unit U_Menu; interface uses System.SysUtils, System.NetEncoding, System.Types, System.IOUtils, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.Layouts, FMX.TabControl, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.FMXUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, System.Rtti, System.Bindings.Outputs, FMX.Bind.Editors, Data.Bind.EngExt, FMX.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, FireDAC.Comp.DataSet, FMX.Edit, FMX.StdActns, FMX.MediaLibrary.Actions, System.Actions, FMX.ActnList, FMX.Objects, FMX.platform, {$IF DEFINED (ANDROID) || (IOS)} FMX.helpers.android, androidapi.JNI.GraphicsContentViewText, androidapi.JNI.JavaTypes ; {$ELSE} ; {$ENDIF} type TF_Menu = class(TForm) ToolBar1: TToolBar; teste: TLabel; TabControl1: TTabControl; TabItemCadastro: TTabItem; Label7: TLabel; ListView3: TListView; Label1: TLabel; Label2: TLabel; label3: TLabel; TabItemMeusCursos: TTabItem; Layout1: TLayout; Label5: TLabel; ListView1: TListView; TabItemOutrosCursos: TTabItem; ListView2: TListView; Button1: TButton; Label6: TLabel; BindingsList2: TBindingsList; FDConnection1: TFDConnection; FDQ_usuario: TFDQuery; FDQ_usuarioidUsuario: TIntegerField; FDQ_usuarionomeUsuario: TStringField; FDQ_usuarioemail: TStringField; FDQ_usuariosenha: TStringField; FDQ_usuarioCPF: TIntegerField; FDQ_usuarionivel: TStringField; FDQ_usuariostatusUsuario: TStringField; FDQ_OutrosCursos: TFDQuery; BindSourceDB2: TBindSourceDB; LinkListControlToField1: TLinkListControlToField; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; FDQ_OutrosCursosidCursos: TIntegerField; FDQ_OutrosCursosnomeCurso: TStringField; FDQ_OutrosCursosdescricao: TStringField; FDQ_OutrosCursosstatusCurso: TStringField; FDQ_OutrosCursosmodulo_idModulo: TIntegerField; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var F_Menu: TF_Menu; implementation {$R *.fmx} uses ULogin, U_facebook, uCComunicacao, U_Curso; procedure TF_Menu.Button1Click(Sender: TObject); begin ShowMessage('Somente para teste! Implementação futura'); end; end.
unit UDmImage; interface uses SysUtils, Classes, ImgList, Controls, cxGraphics, cxImageList, cxLocalization, cxClasses, cxLookAndFeels, dxSkinsForm, dxSkinsDefaultPainters, dxSkinsdxBarPainter, dxSkinsdxStatusBarPainter; type TDmImage = class(TDataModule) imgCheckTree: TcxImageList; imgLarge: TcxImageList; imgTree: TcxImageList; imgNavBar: TcxImageList; dxskncntrlrSkinSys: TdxSkinController; cxLocalizer1: TcxLocalizer; private public procedure LoadSysSkin(SkinFile: string); procedure LoadLocalizer(AFileName: string); end; var DmImage: TDmImage; implementation {$R *.dfm} procedure TDmImage.LoadLocalizer(AFileName: string); begin cxLocalizer1.StorageType := lstIni; cxLocalizer1.FileName := AFileName; cxLocalizer1.Active := True; cxLocalizer1.Locale := 2052; end; procedure TDmImage.LoadSysSkin(SkinFile: string); begin if not FileExists(SkinFile) then Exit; with Self.dxskncntrlrSkinSys do begin SkinName := 'UserSkin'; dxSkinsUserSkinLoadFromFile(SkinFile); NativeStyle := False; UseSkins := True; end; end; end.
PROGRAM CopyOdds(INPUT, OUTPUT); {Копирует через один символы из INPUT в OUTPUT, но до тех пор, пока не встретится первое #.} VAR Ch, Next: CHAR; {Next - это переключатель между нечетными (odd (O)) и четными (even (E)} BEGIN Next := 'O'; {odd} READ(Ch); WHILE Ch <> '#' DO BEGIN IF Next = 'O' THEN {Копирование нечетных символов} WRITE(Ch); READ(Ch); {Переключение величины Next} IF Next = 'O' THEN Next := 'E' {even} ELSE Next := 'O' {odd} END; WRITELN END.
unit uImport; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBase, StdCtrls, Buttons, ExtCtrls, DBGridEh, Mask, RzEdit, ExcelXP, RzBtnEdt, Grids, ComCtrls, RzGrids, ComObj, DB, ADODB; type TfrmImport = class(TfrmBase) Label1: TLabel; bePath: TRzButtonEdit; Label2: TLabel; sgField: TRzStringGrid; cbField: TComboBox; lbSheet: TListBox; Label3: TLabel; cbNoSameStaNo: TCheckBox; pnlShow: TPanel; lblDis: TLabel; pbDis: TProgressBar; procedure bePathButtonClick(Sender: TObject); procedure bePathChange(Sender: TObject); procedure sgFieldClick(Sender: TObject); procedure sgFieldTopLeftChanged(Sender: TObject); procedure lbSheetClick(Sender: TObject); procedure cbFieldChange(Sender: TObject); private { Private declarations } FDBGrid: TDBGridEh; FLastIndex: Integer; procedure ClearData; procedure LoadExcel(AFileName: string); procedure LoadSheet(ASheet: OleVariant); function GetFieldNameByCaption(const ACaption: string): string; function GetSqlStr: string; procedure UpdateDept; procedure UpdateDict; //function GetSheetRecordCount(const ASheetName: string): Integer; protected //数据操作过程... procedure InitData; override; procedure SaveData; override; //检查数据 function CheckData: Boolean; override; public { Public declarations } end; var frmImport: TfrmImport; function ShowImport(ADBGrid: TDBGridEh): Boolean; implementation uses uGlobal, uData, uLunar; {$R *.dfm} function ShowImport(ADBGrid: TDBGridEh): Boolean; begin with TfrmImport.Create(Application.MainForm) do begin HelpHtml := 'import.html'; FDBGrid := ADBGrid; try InitData(); Result := ShowModal() = mrOk; finally Free; end; end; end; procedure TfrmImport.InitData; var i: Integer; begin sgField.RowCount := FDBGrid.Columns.Count; sgField.ColWidths[0] := 25; sgField.ColWidths[1] := 120; sgField.ColWidths[2] := 120; sgField.Cells[1, 0] := '目标字段'; sgField.Cells[2, 0] := 'Excel列'; cbField.Visible := False; cbField.Width := 120; //信息提示面板 pnlShow.Visible := False; pnlShow.Left := (Width - pnlShow.Width) div 2; pnlShow.Top := (Height - pnlShow.Height) div 2 - 6; for i := 1 to FDBGrid.Columns.Count - 1 do begin sgField.Cells[0, i] := IntToStr(i); sgField.Cells[1, i] := FDBGrid.Columns[i].Title.Caption; end; cbNoSameStaNo.Checked := App.NoImpSameStaNo; end; procedure TfrmImport.ClearData; begin cbField.Visible := False; //填充ComboBox cbField.Items.Clear; sgField.Cols[2].Clear; sgField.Cells[2, 0] := 'Excel列'; end; procedure TfrmImport.LoadExcel(AFileName: string); var v, sheet: OleVariant; i: Integer; begin if not ExcelInstalled(Handle) then Exit; FLastIndex := -1; v := CreateOleObject('Excel.Application'); try v.WorkBooks.Open(AFileName); if v.Worksheets.Count = 0 then begin MessageBox(Handle, PAnsiChar('您选择的Excel没有活动的工作表,Excel数据不能被导入'), '提示', MB_OK + MB_ICONWARNING); Exit; end; lbSheet.Items.Clear; for i := 1 to v.Worksheets.Count do begin sheet := v.WorkSheets[i]; lbSheet.Items.Append(sheet.Name); end; lbSheet.ItemIndex := 0; lbSheet.OnClick(lbSheet); finally v.ActiveWorkBook.Saved := True; v.WorkBooks.Close; v.Quit; v := Unassigned; end; end; procedure TfrmImport.LoadSheet(ASheet: OleVariant); var i, j: Integer; begin ClearData(); //填充ComboBox cbField.items.Append(''); for i := 1 to ASheet.Columns.Count do if Trim(ASheet.Cells[1, i]) <> '' then cbField.Items.Append(ASheet.Cells[1, i]) else Break; //初始化对应字段 for i := 1 to sgField.RowCount - 1 do for j := 0 to cbField.Items.Count - 1 do if (Pos(sgField.Cells[1, i], cbField.Items[j]) > 0) or (Pos(cbField.Items[j], sgField.Cells[1, i]) > 0) then sgField.Cells[2, i] := cbField.Items[j]; end; function TfrmImport.GetFieldNameByCaption(const ACaption: string): string; var i: Integer; begin for i := 0 to FDBGrid.Columns.Count - 1 do if FDBGrid.Columns[i].Title.Caption = ACaption then begin Result := FDBGrid.Columns[i].FieldName; Break; end; end; function TfrmImport.GetSqlStr: string; var i: Integer; sTableFields, sSheetFields, sCurTableField, sCurSheetField: string; begin for i := 1 to sgField.RowCount - 1 do begin if Trim(sgField.Cells[2, i]) = '' then Continue; sCurTableField := GetFieldNameByCaption(sgField.Cells[1, i]); sTableFields := sTableFields + ', ' + sCurTableField; sCurSheetField := sgField.Cells[2, i]; if sCurTableField = 'workState' then sSheetFields := sSheetFields + ', iif(' + sCurSheetField + '="离职", 1, iif(' + sCurSheetField + '="请假", 2, 0)) AS [' + sCurSheetField + ']' else sSheetFields := sSheetFields + ', [' + sgField.Cells[2, i] + ']'; end; sTableFields := Copy(sTableFields, 3, Length(sTableFields) - 2); sSheetFields := Copy(sSheetFields, 3, Length(sSheetFields) - 2); Result := 'INSERT INTO [staffs](' + sTableFields + ') SELECT ' + sSheetFields + ' FROM [Excel 8.0; database=' + bePath.Text + '].[' + lbSheet.Items[lbSheet.ItemIndex] + '$] tblXls WHERE [' + sgField.Cells[2, 1] + ']&"" <> ""'; if cbNoSameStaNo.Checked then Result := Result + ' AND NOT EXISTS (SELECT id FROM [staffs] WHERE staffNo=tblXls.[' + sgField.Cells[2, 1] + '])'; end; {function TfrmImport.GetSheetRecordCount(const ASheetName: string): Integer; var ac: TADOConnection; aq: TADOQuery; begin ac := TADOConnection.Create(Self); aq := TADOQuery.Create(Self); try ac.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=' + bePath.Text + ';Mode=Read;Extended Properties="Excel 8.0;"'; ac.LoginPrompt := False; ac.Open(); aq.Connection := ac; aq.SQL.Text := 'SELECT * FROM [' + lbSheet.Items[lbSheet.ItemIndex] + '$] WHERE [' + sgField.Cells[2, 1] + ']<>'''''; aq.Open; Result := aq.RecordCount; ac.Close; aq.Close; finally ac.Free; aq.Free; end; end;} procedure TfrmImport.UpdateDept; procedure DoUpdateDept(const ADeptStr: string); var sl: TStrings; i: Integer; sDeptName, sSql, sParId, sSortNo: string; begin sl := TStringList.Create; try sl.Delimiter := '/'; sl.DelimitedText := ADeptStr; for i := 0 to sl.Count - 1 do begin sDeptName := sl[i]; if Trim(sDeptName) = '' then Exit; sSql := 'SELECT id FROM [dept] WHERE deptName=' + QuotedStr(sDeptName); if VarToStr(dmPer.GetFieldValue(sSql, 'id')) = '' then begin //根节点 if i = 0 then sParId := '0' else sParId := dmPer.GetFieldValue('SELECT id FROM [dept] WHERE deptName=' + QuotedStr(sl[i - 1]), 'id'); if sParId = '' then sParId := '0'; //取当前部门排序号 sSortNo := dmPer.GetFieldValue('SELECT Count(id) AS recCount FROM [dept] WHERE parId=' + sParId, 'recCount'); sSql := 'INSERT INTO [dept](deptName, parId, sortNo) VALUES(' + QuotedStr(sDeptName) + ', ' + sParId + ', ' + sSortNo + ')'; dmPer.ExecSQL(sSql); end; end; finally sl.Free; end; end; var i: Integer; HasDept: Boolean; sSql, sDeptStr: string; begin HasDept := False; //找是否有对应的部门数据列 for i := 1 to sgField.RowCount - 1 do begin if Trim(sgField.Cells[2, i]) = '' then Continue; if GetFieldNameByCaption(sgField.Cells[1, i]) = 'deptName' then begin HasDept := True; Break; end; end; if not HasDept then Exit; sSql := 'SELECT DISTINCT deptName FROM [staffs]'; //数据查询 with dmPer do begin OpenQuery(aqTemp, sSql); if not aqTemp.Eof then begin if not pnlShow.Visible then pnlShow.Show; lblDis.Caption := '正在更新部门信息...'; pbDis.Position := 0; pbDis.Max := aqTemp.RecordCount; while not aqTemp.Eof do begin pbDis.Position := pbDis.Position + 1; pnlShow.Update; sDeptStr := aqTemp.FieldByName('deptName').AsString; if sDeptStr <> '' then DoUpdateDept(sDeptStr); aqTemp.Next; end; end; end; end; procedure TfrmImport.UpdateDict; procedure DoUpdateDict(const AFieldName, AFieldCaption: string); var sFieldName, sSql, sKindName, sKindType, sSortNo: string; begin sFieldName := GetFieldNameByCaption(AFieldCaption); sKindType := IntToStr(Ord(GetKindTypeByFieldName(sFieldName))); sSql := 'SELECT DISTINCT ' + sFieldName + ' FROM [staffs]'; with dmPer do begin OpenQuery(aqTemp, sSql); if not aqTemp.Eof then begin if not pnlShow.Visible then pnlShow.Show; lblDis.Caption := '正在更新' + AFieldCaption + '信息...'; pbDis.Position := 0; pbDis.Max := aqTemp.RecordCount; while not aqTemp.Eof do begin pbDis.Position := pbDis.Position + 1; pnlShow.Update; sKindName := aqTemp.FieldByName(sFieldName).AsString; if sKindName <> '' then begin sSql := 'SELECT id FROM [dict] WHERE kindName=' + QuotedStr(sKindName) + ' AND kindType=' + sKindType; if VarToStr(GetFieldValue(sSql, 'id')) = '' then begin //取记录数当前序号 sSortNo := GetFieldValue('SELECT Count(id) AS recCount FROM [dict] WHERE kindType=' + sKindType, 'recCount'); //插入记录 sSql := 'INSERT INTO [dict](kindName, kindType, sortNo) VALUES(' + QuotedStr(sKindName) + ', ' + sKindType + ', ' + sSortNo + ')'; ExecSQL(sSql); end; end; aqTemp.Next; end; end; end; end; var i: Integer; sFieldName: string; begin //找是否有对应的部门数据列 for i := 1 to sgField.RowCount - 1 do begin if Trim(sgField.Cells[2, i]) = '' then Continue; sFieldName := GetFieldNameByCaption(sgField.Cells[1, i]); //需要处理 if Pos('|' + sFieldName + '|', '|duty|workKind|technic|folk|marriage|politics|culture|special|bankName|') <> 0 then DoUpdateDict(sFieldName, sgField.Cells[1, i]); end; end; function TfrmImport.CheckData: Boolean; var v: OleVariant; begin Result := False; if not ExcelInstalled(Handle) then Exit; if not FileExists(bePath.Text) or (lbSheet.Count = 0) then begin MessageBox(Handle, PAnsiChar('请选择您要导入的有效的Excel文件。'), '提示', MB_OK + MB_ICONINFORMATION); bePath.OnButtonClick(bePath); Exit; end; if Trim(sgField.Cols[2].Text) = 'Excel列' then begin MessageBox(Handle, PAnsiChar('请选择Excel中与数据字段对应列!'), '提示', MB_OK + MB_ICONINFORMATION); Exit; end; if Trim(sgField.Cells[2, 1]) = '' then begin MessageBox(Handle, PAnsiChar('请选择Excel中与工号字段对应的列!'), '提示', MB_OK + MB_ICONINFORMATION); Exit; end; //重存一次Excel文件,以解决Stream写的Excel不标准问题 v := CreateOleObject('Excel.Application'); v.Workbooks.Open(bePath.Text); try FileSetReadOnly(bePath.Text, False); v.ActiveWorkbook.Save; finally v.Quit; v := Unassigned; end; Result := inherited CheckData(); end; procedure TfrmImport.SaveData; var sSql: string; RecCount: Integer; begin sSql := GetSqlStr(); try RecCount := dmPer.ExecSQL(sSql); //有符合条件的数据导入 if RecCount > 0 then begin //MessageBox(Handle, PAnsiChar('您选择的Excel数据已成功导入到数据库中。'), '提示', MB_OK + MB_ICONINFORMATION); //处理拼音 Screen.Cursor := crHourGlass; try with dmPer do begin OpenQuery(aqTemp, 'SELECT id, birth, birthGreg, staffName, staffPY FROM [staffs]'); if aqTemp.RecordCount > 0 then begin aqTemp.First; while not aqTemp.Eof do begin Application.ProcessMessages; if aqTemp.FieldByName('staffPY').IsNull then begin aqTemp.Edit; if aqTemp.FieldByName('staffPY').AsString = '' then aqTemp.FieldByName('staffPY').AsString := GetPYStr(aqTemp.FieldByName('staffName').AsString); if not aqTemp.FieldByName('birth').IsNull then aqTemp.FieldByName('birthGreg').AsDateTime := ToGreg(aqTemp.FieldByName('birth').AsDateTime); aqTemp.Post; end; aqTemp.Next; end; aqTemp.UpdateBatch(); end; end; //重构部门 UpdateDept(); //重构字典 UpdateDict(); //刷新数据 PostMessage(Application.MainForm.Handle, WM_DATARESTORE, 0, 0); finally pnlShow.Hide; Screen.Cursor := crDefault; end; end; ModalResult := mrOk; App.NoImpSameStaNo := cbNoSameStaNo.Checked; Log.Write(App.UserID + '导入Excel文档:[' + bePath.Text + '-> ' + lbSheet.Items[lbSheet.ItemIndex] + '],导入记录数:' + IntToStr(RecCount)); except on E: Exception do begin Log.Write(App.UserID + '导入Excel文档:[' + bePath.Text + '-> ' + lbSheet.Items[lbSheet.ItemIndex] + ']失败,信息:' + E.Message); MessageBox(Handle, PAnsiChar('Excel数据导入失败!信息为:' + E.Message), '提示', MB_OK + MB_ICONWARNING); end; end; end; procedure TfrmImport.bePathButtonClick(Sender: TObject); var od: TOpenDialog; begin od := TOpenDialog.Create(Self); try od.Title := '您要导入哪个Excel文件?'; od.Filter := 'Microsoft Excel 文件 (*.xls)|*.xls'; od.Options := od.Options + [ofFileMustExist]; if od.Execute then bePath.Text := od.FileName; finally od.Free; end; end; procedure TfrmImport.bePathChange(Sender: TObject); begin if FileExists(bePath.Text) and (ExtractFileExt(bePath.Text) = '.xls') then LoadExcel(bePath.Text) else begin ClearData(); lbSheet.Items.Clear; end; end; procedure TfrmImport.sgFieldClick(Sender: TObject); begin cbField.Visible := sgField.Col = 2; if cbField.Visible then begin cbField.Left := sgField.Left + sgField.CellRect(sgField.Col, sgField.Row).Left + 2; cbField.Top := sgField.Top + sgField.CellRect(sgField.Col, sgField.Row).Top + 1; cbField.ItemIndex := cbField.Items.IndexOf(sgField.Cells[sgField.Col, sgField.Row]); end; end; procedure TfrmImport.sgFieldTopLeftChanged(Sender: TObject); begin cbField.Visible := False; end; procedure TfrmImport.lbSheetClick(Sender: TObject); var v, sheet: OleVariant; i: Integer; begin if lbSheet.ItemIndex = FLastIndex then Exit; v := CreateOleObject('Excel.Application'); try v.WorkBooks.Open(bePath.Text); for i := 1 to v.Worksheets.Count do begin sheet := v.WorkSheets[i]; if sheet.Name = lbSheet.Items[lbSheet.ItemIndex] then begin LoadSheet(sheet); FLastIndex := lbSheet.ItemIndex; Break; end; end; finally v.ActiveWorkBook.Saved := True; v.WorkBooks.Close; v.Quit; v := Unassigned; end; end; procedure TfrmImport.cbFieldChange(Sender: TObject); begin sgField.Cells[sgField.Col, sgField.Row] := cbField.Text; end; end.
// calculates amount of material needed to craft an item function calcAmountOfMainMaterial(itemRecord: IInterface): Integer; var itemWeight: IInterface; begin Result := 1; itemWeight := GetElementEditValues(itemRecord, 'DATA\Weight'); if Assigned(itemWeight) then begin Result := 1 + round(itemWeight * 0.2); end; end;
unit AllProperties; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, FireDAC.Comp.DataSet, FireDAC.Comp.Client, dmProperty; type TProperties = class(TForm) AgencyconnectionConnection: TFDConnection; PropertyTable: TFDQuery; PropertyData: TDataSource; PropertyGrid: TDBGrid; Exit: TButton; Houses: TButton; Apartments: TButton; Lands: TButton; AllHouses: TFDQuery; HousesData: TDataSource; AllApartments: TFDQuery; ApartmentData: TDataSource; AllLand: TFDQuery; LandData: TDataSource; PropertiesAllData: TButton; procedure HousesClick(Sender: TObject); procedure ApartmentsClick(Sender: TObject); procedure LandsClick(Sender: TObject); procedure PropertiesAllDataClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Properties: TProperties; implementation {$R *.dfm} procedure TProperties.ApartmentsClick(Sender: TObject); begin ApartmentData.DataSet.Refresh; PropertyGrid.DataSource := ApartmentData; end; procedure TProperties.FormCreate(Sender: TObject); begin PropertyData.DataSet.Refresh; end; procedure TProperties.HousesClick(Sender: TObject); begin HousesData.DataSet.Refresh; PropertyGrid.DataSource := HousesData; end; procedure TProperties.LandsClick(Sender: TObject); begin LandData.DataSet.Refresh; PropertyGrid.DataSource := LandData; end; procedure TProperties.PropertiesAllDataClick(Sender: TObject); begin PropertyData.DataSet.Refresh; PropertyGrid.DataSource := PropertyData; end; end.
{$include kode.inc} unit kode_editor; { connect(wdg,par) - connected parameter/widget must have (internal) values from 0..1 vst/setParameter - FParamValues, return - plugin.process, -> FProcValues - editor.idle -> FEditorValues widget.do_update - widget -> parameter (connections) - plugin.updateParamFromEditor !!! saving/restoring editor state is untested !!! } //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses //kode_array, //kode_canvas, kode_color, kode_object, kode_parameter, kode_rect, kode_widget, kode_window; //---------- const KODE_MAX_PARAMETERS = 1024; type KEditor = class(KWindow) protected FPlugin : KObject; FBackColor : KColor; public constructor create(APlugin:KObject; ARect:KRect; AParent:Pointer=nil); destructor destroy; override; { parameters } procedure connect(AWidget:KWidget; AParameter:KParameter); procedure updateParameterFromHost(AParameter:KParameter; AValue:Single); { catch events } procedure do_update(AWidget:KWidget); override; procedure do_sizer(AWidget:KWidget; ADeltaX,ADeltaY:longint; AMode:longint); override; { editor state } function on_getStateSize : LongWord; virtual; procedure on_saveState(ABuffer:Pointer; ASize:LongWord); virtual; procedure on_restoreState(ABuffer:Pointer; ASize:LongWord); virtual; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses {$ifdef KODE_DEBUG} kode_const, kode_debug, {$endif} kode_flags, kode_plugin, kode_utils; //------------------------------ // //------------------------------ constructor KEditor.create(APlugin:KObject; ARect:KRect; AParent:Pointer=nil); begin inherited create(ARect,AParent); FPlugin := APlugin; FBackColor := KGrey; end; //---------- destructor KEditor.destroy; begin inherited; end; //------------------------------ // //------------------------------ procedure KEditor.connect(AWidget:KWidget; AParameter:KParameter); begin AParameter._widget := AWidget;//.connection; AWidget._parameter := AParameter; //AWidget._parameter2 := AParameter2; end; //---------- { called from: - KPlugin_Vst.updateEditorInIdle } procedure KEditor.updateParameterFromHost(AParameter:KParameter; AValue:Single); var wdg : KWidget; rec : KRect; begin //KTrace(['KEditor.updateParameterFromHost(',AParameter.getName,') = ',AValue,KODE_CR]); wdg := KWidget( AParameter._widget ); if Assigned(wdg) then begin wdg.setValue(AValue); rec := wdg._rect; { this was commented out... why? } do_redraw(wdg,rec); invalidate(rec.x,rec.y,rec.w,rec.h); //do_redraw(wdg); //paint(wdg); end; end; //---------------------------------------------------------------------- // on_ //---------------------------------------------------------------------- {procedure KEditor.on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0); begin ACanvas.setFillColor(FBackColor); ACanvas.fillRect(FRect.x,FRect.y,FRect.x2,FRect.y2); inherited; // KWindow.. end;} //---------------------------------------------------------------------- // do_ //---------------------------------------------------------------------- { when we tweak a widget in the editor, we need to let the host know about it... } procedure KEditor.do_update(AWidget: KWidget); var param : KParameter; value : Single; begin //KTrace(['KEditor.do_update',KODE_CR] ); param := AWidget._parameter; if Assigned(param) then begin value := AWidget.getValue; (FPlugin as KPlugin).updateParameterFromEditor(param,value); end; inherited; // KWindow.. end; //---------- { overloads the window version.. we are a plugin, so we call host -> resize window } procedure KEditor.do_sizer({%H-}AWidget: KWidget; {%H-}ADeltaX,{%H-}ADeltaY: longint; {%H-}AMode: longint); begin //KTrace('KEditor.do_sizer'+KODE_CR); if AMode = ksm_Window then begin (FPlugin as KPlugin).resizeWindow(FRect.w+ADeltaX,FRect.h+ADeltaY); end; if KHasFlag(FFlags,kwf_align) then on_align; paint(self); end; //---------------------------------------------------------------------- // state //---------------------------------------------------------------------- function KEditor.on_getStateSize : LongWord; begin result := 0; end; //---------- procedure KEditor.on_saveState(ABuffer:Pointer; ASize:LongWord); begin end; //---------- procedure KEditor.on_restoreState(ABuffer:Pointer; ASize:LongWord); begin end; //---------------------------------------------------------------------- end.
unit DrawComponents; interface uses Classes, Buttons, GR32; const ButtonWidth = 40; CaptionHeight = 0; ButtonColumnCount = 4; type //DJ Changed to object from record to better use in Medical information TMedProcedure = class(TComponent) public ID: Integer; ProcLabel: String; ICD: String; PostCode: String; TextForField: String; FieldToUpdate: String; Color: String; end; TDropToolButton = class(TSpeedButton) private FDropBitMap: TBitMap32; FMedProcedure: TMedProcedure; procedure SetMedProcedure(const Value: TMedProcedure); public property MedProcedure: TMedProcedure read FMedProcedure Write SetMedProcedure; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property DropBitMap: TBitMap32 read FDropBitMap write FDropBitMap; end; implementation uses ExtCtrls; { TDropToolButton } constructor TDropToolButton.Create(AOwner: TComponent); begin inherited Create(AOwner); FMedProcedure := TMedProcedure.Create(Self); FDropBitMap := TBitMap32.Create; Width := ButtonWidth; Height := ButtonWidth+CaptionHeight; end; destructor TDropToolButton.Destroy; begin FMedProcedure.Free; inherited; end; procedure TDropToolButton.SetMedProcedure(const Value: TMedProcedure); begin FMedProcedure := Value; end; end.
Unit StrProcs; { ***** Misc. String Functions ******************************************** } Interface Uses Dos; Function Upper(StrIn : String) : String; { Convert a string to upper case } Function PathOnly(FileName : String) : String; { Strip any filename information from a file specification } Function NameOnly(FileName : String) : String; { Strip any path information from a file specification } Function BaseNameOnly(FileName : String) : String; { Strip any path and extension information from a file specification } Function ExtOnly(FileName : String) : String; { Return only the extension portion of a filename } Function IntStr(Int : LongInt; Form : Integer) : String; { Convert an Integer variable to a string } Function SameFile(File1, File2 : String) : Boolean; { Call to find out if File1 has a name equivalent to File2. Both filespecs } { may contain wildcards. } { ************************************************************************** } Implementation Function Upper(StrIn : String) : String; Begin Inline( { Thanks to Phil Burns for this routine } $1E/ { PUSH DS ; Save DS} $C5/$76/$06/ { LDS SI,[BP+6] ; Get source string address} $C4/$7E/$0A/ { LES DI,[BP+10] ; Get result string address} $FC/ { CLD ; Forward direction for strings} $AC/ { LODSB ; Get length of source string} $AA/ { STOSB ; Copy to result string} $30/$ED/ { XOR CH,CH} $88/$C1/ { MOV CL,AL ; Move string length to CL} $E3/$0E/ { JCXZ Exit ; Skip if null string} {;} $AC/ {UpCase1: LODSB ; Get next source character} $3C/$61/ { CMP AL,'a' ; Check if lower-case letter} $72/$06/ { JB UpCase2} $3C/$7A/ { CMP AL,'z'} $77/$02/ { JA UpCase2} $2C/$20/ { SUB AL,'a'-'A' ; Convert to uppercase} {;} $AA/ {UpCase2: STOSB ; Store in result} $E2/$F2/ { LOOP UpCase1} {;} $1F); {Exit: POP DS ; Restore DS} end {Upper}; { -------------------------------------------------------------------------- } Function PathOnly(FileName : String) : String; Var Dir : DirStr; Name : NameStr; Ext : ExtStr; Begin FSplit(FileName, Dir, Name, Ext); PathOnly := Dir; End {PathOnly}; { --------------------------------------------------------------------------- } Function NameOnly(FileName : String) : String; { Strip any path information from a file specification } Var Dir : DirStr; Name : NameStr; Ext : ExtStr; Begin FSplit(FileName, Dir, Name, Ext); NameOnly := Name + Ext; End {NameOnly}; { --------------------------------------------------------------------------- } Function BaseNameOnly(FileName : String) : String; { Strip any path and extension from a file specification } Var Dir : DirStr; Name : NameStr; Ext : ExtStr; Begin FSplit(FileName, Dir, Name, Ext); BaseNameOnly := Name; End {BaseNameOnly}; { --------------------------------------------------------------------------- } Function ExtOnly(FileName : String) : String; { Strip the path and name from a file specification. Return only the } { filename extension. } Var Dir : DirStr; Name : NameStr; Ext : ExtStr; Begin FSplit(FileName, Dir, Name, Ext); If Pos('.', Ext) <> 0 then Delete(Ext, 1, 1); ExtOnly := Ext; End {ExtOnly}; { --------------------------------------------------------------------------- } Function IntStr(Int : LongInt; Form : Integer) : String; Var S : String; Begin If Form = 0 then Str(Int, S) else Str(Int:Form, S); IntStr := S; End {IntStr}; { --------------------------------------------------------------------------- } Function SameName(N1, N2 : String) : Boolean; { Function to compare filespecs. Wildcards allowed in either name. Filenames should be compared seperately from filename extensions by using seperate calls to this function e.g. FName1.Ex1 FName2.Ex2 are they the same? they are if SameName(FName1, FName2) AND SameName(Ex1, Ex2) Wildcards work the way DOS should've let them work (eg. *XX.DAT doesn't match just any file...only those with 'XX' as the last two characters of the name portion and 'DAT' as the extension). This routine calls itself recursively to resolve wildcard matches. } Var P1, P2 : Integer; Match : Boolean; Begin P1 := 1; P2 := 1; Match := TRUE; If (Length(N1) = 0) and (Length(N2) = 0) then Match := True else If Length(N1) = 0 then If N2[1] = '*' then Match := TRUE else Match := FALSE else If Length(N2) = 0 then If N1[1] = '*' then Match := TRUE else Match := FALSE; While (Match = TRUE) and (P1 <= Length(N1)) and (P2 <= Length(N2)) do If (N1[P1] = '?') or (N2[P2] = '?') then begin Inc(P1); Inc(P2); end {then} else If N1[P1] = '*' then begin Inc(P1); If P1 <= Length(N1) then begin While (P2 <= Length(N2)) and Not SameName(Copy(N1,P1,Length(N1)-P1+1), Copy(N2,P2,Length(N2)-P2+1)) do Inc(P2); If P2 > Length(N2) then Match := FALSE else begin P1 := Succ(Length(N1)); P2 := Succ(Length(N2)); end {if}; end {then} else P2 := Succ(Length(N2)); end {then} else If N2[P2] = '*' then begin Inc(P2); If P2 <= Length(N2) then begin While (P1 <= Length(N1)) and Not SameName(Copy(N1,P1,Length(N1)-P1+1), Copy(N2,P2,Length(N2)-P2+1)) do Inc(P1); If P1 > Length(N1) then Match := FALSE else begin P1 := Succ(Length(N1)); P2 := Succ(Length(N2)); end {if}; end {then} else P1 := Succ(Length(N1)); end {then} else If UpCase(N1[P1]) = UpCase(N2[P2]) then begin Inc(P1); Inc(P2); end {then} else Match := FALSE; If P1 > Length(N1) then begin While (P2 <= Length(N2)) and (N2[P2] = '*') do Inc(P2); If P2 <= Length(N2) then Match := FALSE; end {if}; If P2 > Length(N2) then begin While (P1 <= Length(N1)) and (N1[P1] = '*') do Inc(P1); If P1 <= Length(N1) then Match := FALSE; end {if}; SameName := Match; End {SameName}; { ---------------------------------------------------------------------------- } Function SameFile(File1, File2 : String) : Boolean; Var Path1, Path2 : String; Begin File1 := FExpand(File1); File2 := FExpand(File2); Path1 := PathOnly(File1); Path2 := PathOnly(File2); SameFile := SameName(BaseNameOnly(File1), BaseNameOnly(File2)) AND SameName(ExtOnly(File1), ExtOnly(File2)) AND (Path1 = Path2); End {SameFile}; { ---------------------------------------------------------------------------- } End {Unit StrProcs}.
{ Visual workshop menu editor for Fallout 4 Allows to edit workshop menues based on form list FLST records which contain other form lists or keyword KYWD records linked by COBJ recipes. Apply to menu FLST record, for example WorkshopMenuMain "Main Menu" [FLST:00106DA2] When editing vanilla menues, copy them as override into a plugin, apply script to edit there, then remove unchanged records using ITM clean menu of xEdit. Drag&drop nodes in the left tree to rearrange tree structure. Hold Shift when dragging to move a node as a child to other form list node. Right click for additional options (add, remove, edit). Press * to full expand. Right panel lists COBJ recipes linked to keyword of the selected node. Requires built references (in xEdit right click -> Other -> Build Reference Info menu). Drag&drop recipe over the keyword node in the left tree to move (relink) recipe to another keyword. } unit Fallout4WorkshopMenuEditor; var TopFLST: IInterface; frm: TForm; tvList: TTreeView; lbRefs: TListBox; NodeNameMode: integer; //=========================================================================== procedure UpdateNodeFLST(aNode: TTreeNode); var flst, entries, entry: IInterface; rec: string; i: integer; begin if not Assigned(aNode) then Exit; flst := ObjectToElement(aNode.Data); entries := ElementByName(flst, 'FormIDs'); if not Assigned(entries) then entries := Add(flst, 'FormIDs', True); for i := 0 to Pred(aNode.Count) do begin if i = ElementCount(entries) then entry := ElementAssign(entries, HighInteger, nil, False) else entry := ElementByIndex(entries, i); rec := Name(ObjectToElement(aNode.Item[i].Data)); if GetEditValue(entry) <> rec then SetEditValue(entry, rec); end; while ElementCount(entries) > aNode.Count do RemoveByIndex(entries, Pred(ElementCount(entries)), True); end; //=========================================================================== procedure TreeViewDragDrop(Sender, Source: TObject; X, Y: Integer); var Src, Dst, SrcParent: TTreeNode; cobj, keywords, kold, knew: IInterface; i: integer; begin Src := tvList.Selected; Dst := tvList.GetNodeAt(X,Y); // dragged COBJ over keyword, update COBJ if Source = lbRefs then begin cobj := ObjectToElement(lbRefs.Items.Objects[lbRefs.ItemIndex]); keywords := ElementBySignature(cobj, 'FNAM'); kold := ObjectToElement(Src.Data); knew := ObjectToElement(Dst.Data); for i := 0 to Pred(ElementCount(keywords)) do if GetEditValue(ElementByIndex(keywords, i)) = Name(kold) then begin SetEditValue(ElementByIndex(keywords, i), Name(knew)); Break; end; TreeViewChange(nil, Src); Exit; end; // store the Parent (FLST) of dragged node to update later // because after the MoveTo it could be lost when moved under a different parent // and we need to update it later SrcParent := Src.Parent; // if Shift is pressed to insert as a child if GetKeyState(VK_SHIFT) < 0 then begin // append dragged node as a child of destination node Src.MoveTo(Dst, naAddChild); // update the list we moved from UpdateNodeFLST(SrcParent); // update destination list UpdateNodeFLST(Dst); Exit; end // Shift is not pressed else // not dragging over the node below us, insert after the destination node if Dst <> Src.GetNextSibling then Src.MoveTo(Dst, naInsert) // otherwise insert destination node after us (swap positions) else Dst.MoveTo(Src, naInsert); // update dragged node's former parent UpdateNodeFLST(SrcParent); // if we moved under a different parent then update it too if Dst.Parent <> SrcParent then UpdateNodeFLST(Dst.Parent); end; //=========================================================================== procedure TreeViewDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var Src, Dst: TTreeNode; begin Src := tvList.Selected; Dst := tvList.GetNodeAt(X,Y); Accept := Assigned(Dst) and (Src <> Dst); // when dragging from COBJs list, can drag over keywords only if Accept and (Source = lbRefs) then begin Accept := Signature(ObjectToElement(Dst.Data)) = 'KYWD'; Exit; end; // don't drag to the root level if Accept then Accept := Dst.Level <> 0; // don't drag over KYWD when Shift is pressed if Accept then if (GetKeyState(VK_SHIFT) < 0) and (Signature(ObjectToElement(Dst.Data)) <> 'FLST') then Accept := False; end; //=========================================================================== procedure TreeViewChange(Sender: TObject; Node: TTreeNode); var e, r: IInterface; i: integer; begin if not Assigned(Node) then Exit; lbRefs.Clear; e := MasterOrSelf(ObjectToElement(Node.Data)); if Signature(e) <> 'KYWD' then Exit; for i := 0 to Pred(ReferencedByCount(e)) do begin r := WinningOverride(ReferencedByIndex(e, i)); if Signature(r) = 'COBJ' then lbRefs.Items.AddObject(EditorID(r), r); end; end; //=========================================================================== procedure TreeViewDblClick(Sender: TObject); begin if Assigned(tvList.Selected) then JumpTo(ObjectToElement(tvList.Selected.Data), False); end; //=========================================================================== // on key down event handler for form procedure TreeViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_DELETE then MenuRemoveClick(nil); end; //=========================================================================== procedure lbRefsDblClick(Sender: TObject); begin if lbRefs.ItemIndex <> -1 then JumpTo(ObjectToElement(lbRefs.Items.Objects[lbRefs.ItemIndex]), False); end; //=========================================================================== procedure UpdateNodeText(aNode: TTreeNode); begin if NodeNameMode = 0 then aNode.Text := GetElementEditValues(ObjectToElement(aNode.Data), 'FULL') else if NodeNameMode = 1 then aNode.Text := EditorID(ObjectToElement(aNode.Data)) else if NodeNameMode = 2 then aNode.Text := Name(ObjectToElement(aNode.Data)); end; //=========================================================================== procedure rbNameClick(Sender: TObject); var i: integer; node: TTreeNode; begin NodeNameMode := TRadioButton(Sender).Tag; tvList.Items.BeginUpdate; for i := 0 to Pred(tvList.Items.Count) do UpdateNodeText(tvList.Items.Item(i)); tvList.Items.EndUpdate; tvList.SetFocus; end; //=========================================================================== function EditEditorIDandName(var aEditorID, aName: WideString): Boolean; begin repeat Result := InputQuery('Enter', 'Editor ID', aEditorID); if not Result then Exit; until aEditorID <> ''; Result := InputQuery('Enter', 'Name', aName); end; //=========================================================================== // Edit popup menu click procedure MenuEditClick(Sender: TObject); var e: IInterface; edid, fullname: WideString; begin e := ObjectToElement(tvList.Selected.Data); edid := EditorID(e); fullname := GetElementEditValues(e, 'FULL'); if not EditEditorIDandName(edid, fullname) then Exit; if edid <> EditorID(e) then SetElementEditValues(e, 'EDID', edid); if fullname <> GetElementEditValues(e, 'FULL') then SetElementEditValues(e, 'FULL', fullname); UpdateNodeText(tvList.Selected); end; //=========================================================================== // Remove popup menu click procedure MenuRemoveClick(Sender: TObject); var Parent: TTreeNode; begin Parent := tvList.Selected.Parent; if not Assigned(Parent) then Exit; if Parent.Count = 1 then begin ShowMessage('Can not remove the last remaining item from the list, remove the list itself instead'); Exit; end; tvList.Selected.Delete; UpdateNodeFLST(Parent); end; //=========================================================================== // Add existing keyword popup menu click procedure MenuAddKeywordClick(Sender: TObject); var g, e: IInterface; sl: TStringList; sel, n: TTreeNode; i: integer; frm: TForm; clb: TCheckListBox; begin frm := frmFileSelect; frm.Width := 500; try frm.Caption := 'Select keyword(s) to add'; clb := TCheckListBox(frm.FindComponent('CheckListBox1')); g := GroupBySignature(GetFile(TopFLST), 'KYWD'); sl := TStringList.Create; for i := 0 to Pred(ElementCount(g)) do begin e := ElementByIndex(g, i); if GetElementEditValues(e, 'TNAM') = 'Recipe Filter' then sl.AddObject(EditorID(e), e); end; sl.Sort; clb.Items.Assign(sl); sl.Free; if frm.ShowModal <> mrOk then Exit; sel := tvList.Selected; tvList.Items.BeginUpdate; for i := 0 to Pred(clb.Items.Count) do if clb.Checked[i] then begin e := ObjectToElement(clb.Items.Objects[i]); n := tvList.Items.AddChildObject(sel.Parent, '', e); UpdateNodeText(n); n.MoveTo(sel, naInsert); end; tvList.Items.EndUpdate; UpdateNodeFLST(sel.Parent); finally frm.Free; end; end; //=========================================================================== // Add new keyword popup menu click procedure MenuAddNewKeywordClick(Sender: TObject); var e: IInterface; n: TTreeNode; edid, fullname: WideString; begin edid := 'NewEditorID'; fullname := 'NewName'; if not EditEditorIDandName(edid, fullname) then Exit; // use WorkshopAlwaysShowIconKeyword [KYWD:00237B63] as a template e := RecordByFormID(FileByIndex(0), $00237B63, False); e := wbCopyElementToFile(e, GetFile(TopFLST), True, True); SetElementEditValues(e, 'EDID', edid); if fullname <> '' then SetElementEditValues(e, 'FULL', fullname); n := tvList.Items.AddChildObject(tvList.Selected.Parent, '', e); n.MoveTo(tvList.Selected, naInsert); UpdateNodeText(n); end; //=========================================================================== // Add existing list popup menu click procedure MenuAddListClick(Sender: TObject); var g, e: IInterface; sl: TStringList; sel, n: TTreeNode; i: integer; frm: TForm; clb: TCheckListBox; begin frm := frmFileSelect; frm.Width := 500; try frm.Caption := 'Select list(s) to add'; clb := TCheckListBox(frm.FindComponent('CheckListBox1')); g := GroupBySignature(GetFile(TopFLST), 'FLST'); sl := TStringList.Create; for i := 0 to Pred(ElementCount(g)) do begin e := ElementByIndex(g, i); sl.AddObject(EditorID(e), e); end; sl.Sort; clb.Items.Assign(sl); sl.Free; if frm.ShowModal <> mrOk then Exit; sel := tvList.Selected; tvList.Items.BeginUpdate; for i := 0 to Pred(clb.Items.Count) do if clb.Checked[i] then begin e := ObjectToElement(clb.Items.Objects[i]); n := BuildMenuTree(e, sel.Parent); n.MoveTo(sel, naInsert); end; tvList.Items.EndUpdate; UpdateNodeFLST(sel.Parent); finally frm.Free; end; end; //=========================================================================== // Add new list popup menu click procedure MenuAddNewListClick(Sender: TObject); var e: IInterface; n: TTreeNode; edid, fullname: WideString; begin edid := 'NewEditorID'; fullname := 'NewName'; if not EditEditorIDandName(edid, fullname) then Exit; e := Add(GroupBySignature(GetFile(TopFLST), 'FLST'), 'FLST', True); SetElementEditValues(e, 'EDID', edid); if fullname <> '' then SetElementEditValues(e, 'FULL', fullname); n := tvList.Items.AddChildObject(tvList.Selected.Parent, '', e); n.MoveTo(tvList.Selected, naInsert); UpdateNodeText(n); end; //=========================================================================== // on popup menu event handler procedure MenuPopup(Sender: TObject); var mnPopup: TPopupMenu; MenuItem: TMenuItem; begin mnPopup := TPopupMenu(Sender); mnPopup.Items.Clear; if not Assigned(tvList.Selected) then Exit; // focus the right click selected node tvList.Selected := tvList.Selected; // can't add/remove from the root node if tvList.Selected.Level > 0 then begin MenuItem := TMenuItem.Create(mnPopup); MenuItem.Caption := 'Add existing keyword(s)'; MenuItem.OnClick := MenuAddKeywordClick; mnPopup.Items.Add(MenuItem); MenuItem := TMenuItem.Create(mnPopup); MenuItem.Caption := 'Add new keyword'; MenuItem.OnClick := MenuAddNewKeywordClick; mnPopup.Items.Add(MenuItem); MenuItem := TMenuItem.Create(mnPopup); MenuItem.Caption := '-'; mnPopup.Items.Add(MenuItem); MenuItem := TMenuItem.Create(mnPopup); MenuItem.Caption := 'Add existing list(s)'; MenuItem.OnClick := MenuAddListClick; mnPopup.Items.Add(MenuItem); MenuItem := TMenuItem.Create(mnPopup); MenuItem.Caption := 'Add new list'; MenuItem.OnClick := MenuAddNewListClick; mnPopup.Items.Add(MenuItem); MenuItem := TMenuItem.Create(mnPopup); MenuItem.Caption := '-'; mnPopup.Items.Add(MenuItem); MenuItem := TMenuItem.Create(mnPopup); MenuItem.Caption := 'Remove'; MenuItem.OnClick := MenuRemoveClick; mnPopup.Items.Add(MenuItem); end; MenuItem := TMenuItem.Create(mnPopup); MenuItem.Caption := 'Edit'; MenuItem.OnClick := MenuEditClick; mnPopup.Items.Add(MenuItem); end; //=========================================================================== function BuildMenuTree(e: IInterface; aNode: TTreeNode): TTreeNode; var i: integer; entries: IInterface; begin Result := tvList.Items.AddChildObject(aNode, '', e); UpdateNodeText(Result); if Signature(e) = 'FLST' then begin entries := ElementByName(e, 'FormIDs'); for i := 0 to Pred(ElementCount(entries)) do BuildMenuTree(WinningOverride(LinksTo(ElementByIndex(entries, i))), Result); end; end; //=========================================================================== procedure MenuEditor(e: IInterface); var pnl: TPanel; sp: TSplitter; rbName, rbEDID, rbRec: TRadioButton; mnPopup: TPopupMenu; begin frm := TForm.Create(nil); try frm.Caption := wbGameName + ' Workshop Menu Editor'; frm.Width := 850; frm.Height := 700; frm.Position := poScreenCenter; frm.PopupMode := pmAuto; pnl := TPanel.Create(frm); pnl.Parent := frm; pnl.Height := 28; pnl.Align := alTop; pnl.BevelOuter := bvNone; rbName := TRadioButton.Create(frm); rbName.Parent := pnl; rbName.Left := 8; rbName.Top := 4; rbName.Width := 60; rbName.Caption := 'Name'; rbName.Checked := True; rbName.OnClick := rbNameClick; rbEDID := TRadioButton.Create(frm); rbEDID.Parent := pnl; rbEDID.Left := rbName.Left + rbName.Width + 12;; rbEDID.Top := rbName.Top; rbEDID.Width := 60; rbEDID.Caption := 'EditorID'; rbEDID.Tag := 1; rbEDID.OnClick := rbNameClick; rbRec := TRadioButton.Create(frm); rbRec.Parent := pnl; rbRec.Left := rbEDID.Left + rbEDID.Width + 12;; rbRec.Top := rbName.Top; rbRec.Width := 60; rbRec.Caption := 'Record'; rbRec.Tag := 2; rbRec.OnClick := rbNameClick; lbRefs := TListBox.Create(frm); lbRefs.Parent := frm; lbRefs.Align := alRight; lbRefs.DragMode := dmAutomatic; lbRefs.BorderStyle := bsNone; lbRefs.Width := 350; lbRefs.OnDblClick := lbRefsDblClick; sp := TSplitter.Create(frm); sp.Parent := frm; sp.Align := alRight; sp.Width := 5; tvList := TTreeView.Create(frm); tvList.Parent := frm; tvList.Align := alClient; tvList.DragMode := dmAutomatic; tvList.BorderStyle := bsNone; tvList.ShowLines := False; tvList.RowSelect := True; tvList.ToolTips := False; tvList.HotTrack := True; tvList.RightClickSelect := True; tvList.ReadOnly := True; tvList.OnDragDrop := TreeViewDragDrop; tvList.OnDragOver := TreeViewDragOver; tvList.OnChange := TreeViewChange; tvList.OnDblClick := TreeViewDblClick; tvList.OnKeyDown := TreeViewKeyDown; mnPopup := TPopupMenu.Create(frm); mnPopup.OnPopup := MenuPopup; tvList.PopupMenu := mnPopup; TopFLST := e; BuildMenuTree(TopFLST, nil); tvList.Items.GetFirstNode.Expand(False); frm.ShowModal; finally frm.Free; end; end; //=========================================================================== function Process(e: IInterface): integer; begin if Signature(e) <> 'FLST' then Exit; MenuEditor(e); Result := 1; end; end. end.
{ Resource library. WORK IN PROGRESS. PROPERTY TYPE VALUES: 1 - Object (any forms or aliases) 2 - String 3 - Int32 4 - Float 5 - Bool 11 - Array of Object 12 - Array of String 13 - Array of Int32 14 - Array of Float 15 - Array of Bool } Unit CobbPapyrus; {Searches for and returns a script attached to a form.} Function GetScript(aeForm: IInterface; asName: String): IInterface; Var sElemName: String; eVMAD: IInterface; eScripts: IInterface; iCurrentScript: Integer; eCurrentScript: IInterface; sCurrentScript: String; eNewScript: IInterface; Begin eVMAD := ElementBySignature(aeForm, 'VMAD'); If Not Assigned(eVMAD) Then Exit; eScripts := ElementByPath(eVMAD, 'Data\Scripts'); If Signature(aeForm) = 'QUST' Then eScripts := ElementByPath(eVMAD, 'Data\Quest VMAD\Scripts'); For iCurrentScript := 0 To ElementCount(eScripts) - 1 Do Begin eCurrentScript := ElementByIndex(eScripts, iCurrentScript); If Name(eCurrentScript) = 'Script' Then Begin sCurrentScript := GetEditValue(ElementByName(eCurrentScript, 'scriptName')); If sCurrentScript = asName Then Begin Result := eCurrentScript; Exit; End; End; End; End; {Attaches a script to a form, but only if the form doesn't already have that script (or if the abRedundant argument is True).} Function AttachScript(aeForm: IInterface; asName: String; abRedundant: Boolean): IInterface; Var sElemName: String; eVMAD: IInterface; eScripts: IInterface; iCurrentScript: Integer; eCurrentScript: IInterface; sCurrentScript: String; eNewScript: IInterface; Begin Result := GetScript(aeForm, asName); If Not Assigned(Result) Or abRedundant Then Begin Add(aeForm, 'VMAD', True); SetElementNativeValues(aeForm, 'VMAD\Version', 5); SetElementNativeValues(aeForm, 'VMAD\Object Format', 2); eVMAD := ElementBySignature(aeForm, 'VMAD'); eScripts := ElementByPath(eVMAD, 'Data\Scripts'); If Signature(aeForm) = 'QUST' Then eScripts := ElementByPath(eVMAD, 'Data\Quest VMAD\Scripts'); eNewScript := ElementAssign(eScripts, HighInteger, nil, False); SetEditValue(ElementByName(eNewScript, 'scriptName'), asName); Result := eNewScript; End; End; {Removes all attached copies of a given script from a given form.} Procedure RemoveScript(aeForm: IInterface; asName: String); Var sElemName: String; eVMAD: IInterface; eScripts: IInterface; iCurrentScript: Integer; eCurrentScript: IInterface; sCurrentScript: String; eNewScript: IInterface; iScriptsToKillCount: Integer; elScriptsToKill: Array[0..512] of IInterface; Begin eVMAD := ElementBySignature(aeForm, 'VMAD'); If Not Assigned(eVMAD) Then Exit; eScripts := ElementByPath(eVMAD, 'Data\Scripts'); If Signature(aeForm) = 'QUST' Then eScripts := ElementByPath(eVMAD, 'Data\Quest VMAD\Scripts'); // iScriptsToKillCount := 0; // For iCurrentScript := 0 To ElementCount(eScripts) - 1 Do Begin eCurrentScript := ElementByIndex(eScripts, iCurrentScript); If Name(eCurrentScript) = 'Script' Then Begin sCurrentScript := GetEditValue(ElementByName(eCurrentScript, 'scriptName')); If (sCurrentScript = asName) And (iScriptsToKillCount < 512) Then Begin // // Mark this script for removal. // elScriptsToKill[iScriptsToKillCount] := eCurrentScript; iScriptsToKillCount := iScriptsToKillCount + 1; End; End; End; // // Remove the found scripts. // For iCurrentScript := 0 To iScriptsToKillCount Do Begin Remove(elScriptsToKill[iCurrentScript]); End; //If iScriptsToKillCount > 0 Then AddMessage(Format('Removed %d copies of script %s from %s.', [iScriptsToKillCount, asName, Name(aeForm)])); End; {Returns the matching property node in the given script. Pass -1 as the type to select any type.} Function GetPropertyFromScript(aeScript: IInterface; asPropertyName: String; aiPropertyType: Integer) : IInterface; Var eProperties: IInterface; iCurrentProperty: Integer; eCurrentProperty: IInterface; sCurrentProperty: String; iCurrentPropertyType: Integer; Begin eProperties := ElementByName(aeScript, 'Properties'); For iCurrentProperty := 0 To ElementCount(eProperties) - 1 Do Begin eCurrentProperty := ElementByIndex(eProperties, iCurrentProperty); If Name(eCurrentProperty) = 'Property' Then Begin sCurrentProperty := GetEditValue(ElementByName(eCurrentProperty, 'propertyName')); iCurrentPropertyType := GetNativeValue(ElementByName(eCurrentProperty, 'Type')); If (sCurrentProperty = asPropertyName) And ((iCurrentPropertyType = aiPropertyType) Or (aiPropertyType = -1)) Then Begin Result := eCurrentProperty; Exit; End; End; End; End; {Returns or creates a property on a script. Sets the out variable to True if the property had to be created.} Function GetOrMakePropertyOnScript(aeScript: IInterface; asPropertyName: String; aiPropertyType: Integer; out abResult : Boolean) : IInterface; Var eProperties: IInterface; iCurrentProperty: Integer; eCurrentProperty: IInterface; sCurrentProperty: String; iCurrentPropertyType: Integer; Begin eProperties := ElementByName(aeScript, 'Properties'); Result := GetPropertyFromScript(aeScript, asPropertyName, aiPropertyType); If Assigned(Result) Then Exit; abResult := True; // // Create the property if it does not exist. The immediate child nodes (propertyName // and friends) will be created and managed by TES5Edit, more-or-less automatically; // we'll just have to set their values. // eCurrentProperty := ElementAssign(eProperties, HighInteger, nil, False); SetEditValue(ElementByName(eCurrentProperty, 'propertyName'), asPropertyName); SetNativeValue(ElementByName(eCurrentProperty, 'Type'), aiPropertyType); SetNativeValue(ElementByName(eCurrentProperty, 'Flags'), 1); // "Edited" Result := eCurrentProperty; End; Procedure RenamePropertyOnScript(aeScript: IInterface; asPropertyName: String; asNewName: String); Var eProperty: IInterface; Begin eProperty := GetPropertyFromScript(aeScript, asPropertyName, -1); If Not Assigned(eProperty) Then Exit; SetEditValue(ElementByName(eProperty, 'propertyName'), asNewName); End; {$REGION 'Functions to set scalar script properties.'} {Function for Type 1 (Form) properties. Accepts an integer FormID, a string FormID, or an element; these must be passed in as a Variant variable.} Function SetFormPropertyOnScript(aeScript: IInterface; asPropertyName: String; avPropertyValue: Variant) : Boolean; Var eProperties: IInterface; eTargetProperty: IInterface; bAlreadyExisted: Boolean; iFormID: Integer; Begin Try iFormID := avPropertyValue; Except Try iFormID := StrToIntDef('$' + avPropertyValue, 0); Except iFormID := FormID(avPropertyValue); End; End; eProperties := ElementByName(aeScript, 'Properties'); eTargetProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 1, bAlreadyExisted); SetNativeValue(ElementByName(eTargetProperty, 'Flags'), 1); // "Edited" SetElementNativeValues(eTargetProperty, 'Value\Object Union\Object v2\FormID', iFormID); SetElementNativeValues(eTargetProperty, 'Value\Object Union\Object v2\Alias', -1); Result := Not bAlreadyExisted; End; { Function for Type 1 (Alias) properties. Accepts the quest as a variant, and the ID of an alias in that quest. } Function SetAliasPropertyOnScript(aeScript: IInterface; asPropertyName: String; avPropertyQuest: Variant, aiAliasIndex: Integer = 0) : Boolean; Var eProperties: IInterface; eTargetProperty: IInterface; bAlreadyExisted: Boolean; iQuestFormID: Integer; Begin Try iQuestFormID := avPropertyQuest; Except Try iQuestFormID := StrToIntDef('$' + avPropertyQuest, 0); Except iQuestFormID := FormID(avPropertyQuest); End; End; eProperties := ElementByName(aeScript, 'Properties'); eTargetProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 1, bAlreadyExisted); SetNativeValue(ElementByName(eTargetProperty, 'Flags'), 1); // "Edited" SetElementNativeValues(eTargetProperty, 'Value\Object Union\Object v2\FormID', iQuestFormID); SetElementNativeValues(eTargetProperty, 'Value\Object Union\Object v2\Alias', aiAliasIndex); Result := Not bAlreadyExisted; End; {Function for Type 2 (String) properties.} Function SetStringPropertyOnScript(aeScript: IInterface; asPropertyName: String; asPropertyValue: String) : Boolean; Var eProperties: IInterface; eTargetProperty: IInterface; bAlreadyExisted: Boolean; Begin eProperties := ElementByName(aeScript, 'Properties'); eTargetProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 2, bAlreadyExisted); SetNativeValue(ElementByName(eTargetProperty, 'Flags'), 1); // "Edited" SetEditValue(ElementByName(eTargetProperty, 'String'), asPropertyValue); Result := Not bAlreadyExisted; End; {Function for Type 3 (Int) properties.} Function SetIntPropertyOnScript(aeScript: IInterface; asPropertyName: String; aiPropertyValue: Integer) : Boolean; Var eProperties: IInterface; eTargetProperty: IInterface; bAlreadyExisted: Boolean; Begin eProperties := ElementByName(aeScript, 'Properties'); eTargetProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 3, bAlreadyExisted); SetNativeValue(ElementByName(eTargetProperty, 'Flags'), 1); // "Edited" SetNativeValue(ElementByName(eTargetProperty, 'Int32'), aiPropertyValue); Result := Not bAlreadyExisted; End; {Function for Type 4 (Float) properties.} Function SetFloatPropertyOnScript(aeScript: IInterface; asPropertyName: String; afPropertyValue: Float) : Boolean; Var eProperties: IInterface; eTargetProperty: IInterface; bAlreadyExisted: Boolean; Begin eProperties := ElementByName(aeScript, 'Properties'); eTargetProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 4, bAlreadyExisted); SetNativeValue(ElementByName(eTargetProperty, 'Flags'), 1); // "Edited" SetNativeValue(ElementByName(eTargetProperty, 'Float'), afPropertyValue); Result := Not bAlreadyExisted; End; {Function for Type 5 (Bool) properties.} Function SetBoolPropertyOnScript(aeScript: IInterface; asPropertyName: String; abPropertyValue: Boolean) : Boolean; Var eProperties: IInterface; eTargetProperty: IInterface; bAlreadyExisted: Boolean; Begin eProperties := ElementByName(aeScript, 'Properties'); eTargetProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 5, bAlreadyExisted); SetNativeValue(ElementByName(eTargetProperty, 'Flags'), 1); // "Edited" SetNativeValue(ElementByName(eTargetProperty, 'Float'), abPropertyValue); Result := Not bAlreadyExisted; End; {$ENDREGION} {$REGION 'Functions to set Form array script properties.'} {Function for Type 11 (Form) properties. The values must be specified as a TStringList of FormIDs.} Procedure SetFormArrayPropertyOnScript(aeScript: IInterface; asPropertyName: String; aslPropertyValues: TStringList); Var eProperties: IInterface; eProperty: IInterface; eValues: IInterface; iIterator: Integer; eValue: IInterface; iValue: Integer; bThrowaway: Boolean; Begin eProperties := ElementByName(aeScript, 'Properties'); eProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 11, bThrowaway); SetNativeValue(ElementByName(eProperty, 'Flags'), 1); // "Edited" eValues := ElementByIndex(ElementByName(eProperty, 'Value'), 0); For iIterator := 0 To aslPropertyValues.Count - 1 Do Begin iValue := StrToIntDef('$' + aslPropertyValues[iIterator], 0); eValue := ElementByIndex(eValues, iIterator); If Not Assigned(eValue) Then eValue := ElementAssign(eValues, HighInteger, nil, False); SetElementNativeValue(eValue, 'Object v2\FormID', iValue); SetElementNativeValue(eValue, 'Object v2\Alias', -1); End; If aslPropertyValues.Count < ElementCount(eValues) Then Begin iThrowaway := ElementCount(eValues) - 1; For iIterator := aslPropertyValues.Count To iThrowaway Do Begin Remove(ElementByIndex(eValues, aslPropertyValues.Count)); End; End; End; {Function for Type 11 (Form) properties, to set an individual array element.} Procedure SetFormArrayPropertyItemOnScript(aeScript: IInterface; asPropertyName: String; aiIndex: Integer; avValue: Variant); Var eProperties: IInterface; eProperty: IInterface; eValues: IInterface; iIterator: Integer; eValue: IInterface; iValue: Integer; bThrowaway: Boolean; Begin Try iValue := avValue; Except Try iValue := StrToIntDef('$' + avValue, 0); Except iValue := FormID(avValue); End; End; eProperties := ElementByName(aeScript, 'Properties'); eProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 11, bThrowaway); SetNativeValue(ElementByName(eProperty, 'Flags'), 1); // "Edited" eValues := ElementByIndex(ElementByName(eProperty, 'Value'), 0); For iIterator := 0 To aiIndex Do Begin eValue := ElementByIndex(eValues, iIterator); If Not Assigned(eValue) Then eValue := ElementAssign(eValues, HighInteger, nil, False); If iIterator = aiIndex Then Begin SetElementNativeValues(eValue, 'Object v2\FormID', iValue); SetElementNativeValues(eValue, 'Object v2\Alias', -1); End; End; End; {$ENDREGION} {$REGION 'UNIMPLEMENTED - Functions to set Alias array script properties.'} {$ENDREGION} {$REGION 'Functions to set String array script properties.'} {Function for Type 12 (String) properties. The values must be specified as a TStringList of FormIDs.} Procedure SetStringArrayPropertyOnScript(aeScript: IInterface; asPropertyName: String; aslPropertyValues: TStringList); Var eProperties: IInterface; eProperty: IInterface; eValues: IInterface; iIterator: Integer; eValue: IInterface; bThrowaway: Boolean; Begin eProperties := ElementByName(aeScript, 'Properties'); eProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 12, bThrowaway); SetNativeValue(ElementByName(eProperty, 'Flags'), 1); // "Edited" eValues := ElementByIndex(ElementByName(eProperty, 'Value'), 0); For iIterator := 0 To aslPropertyValues.Count - 1 Do Begin eValue := ElementByIndex(eValues, iIterator); If Not Assigned(eValue) Then eValue := ElementAssign(eValues, HighInteger, nil, False); SetEditValue(eValue, aslPropertyValues[iIterator]); End; If aslPropertyValues.Count < ElementCount(eValues) Then Begin iThrowaway := ElementCount(eValues) - 1; For iIterator := aslPropertyValues.Count To iThrowaway Do Begin Remove(ElementByIndex(eValues, aslPropertyValues.Count)); End; End; End; {Function for Type 12 (String) properties, to set an individual array element.} Procedure SetStringArrayPropertyItemOnScript(aeScript: IInterface; asPropertyName: String; aiIndex: Integer; asValue: String); Var eProperties: IInterface; eProperty: IInterface; eValues: IInterface; iIterator: Integer; eValue: IInterface; bThrowaway: Boolean; Begin eProperties := ElementByName(aeScript, 'Properties'); eProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 12, bThrowaway); SetNativeValue(ElementByName(eProperty, 'Flags'), 1); // "Edited" eValues := ElementByIndex(ElementByName(eProperty, 'Value'), 0); For iIterator := 0 To aiIndex Do Begin eValue := ElementByIndex(eValues, iIterator); If Not Assigned(eValue) Then eValue := ElementAssign(eValues, HighInteger, nil, False); If iIterator = aiIndex Then Begin SetEditValue(eValue, asValue); End; End; End; {$ENDREGION} {$REGION 'Functions to set Int array script properties.'} {Function for Type 13 (Int) properties. The values must be specified as a TStringList.} Procedure SetIntArrayPropertyOnScript(aeScript: IInterface; asPropertyName: String; aslPropertyValues: TStringList); Var eProperties: IInterface; eProperty: IInterface; eValues: IInterface; iIterator: Integer; eValue: IInterface; iValue: Integer; bThrowaway: Boolean; iThrowaway: Integer; Begin eProperties := ElementByName(aeScript, 'Properties'); eProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 13, bThrowaway); SetNativeValue(ElementByName(eProperty, 'Flags'), 1); // "Edited" eValues := ElementByIndex(ElementByName(eProperty, 'Value'), 0); For iIterator := 0 To aslPropertyValues.Count - 1 Do Begin iValue := StrToIntDef(aslPropertyValues[iIterator], 0); eValue := ElementByIndex(eValues, iIterator); If Not Assigned(eValue) Then eValue := ElementAssign(eValues, HighInteger, nil, False); SetNativeValue(eValue, iValue); End; If aslPropertyValues.Count < ElementCount(eValues) Then Begin iThrowaway := ElementCount(eValues) - 1; For iIterator := aslPropertyValues.Count To iThrowaway Do Begin Remove(ElementByIndex(eValues, aslPropertyValues.Count)); End; End; End; {Function for Type 13 (Int) properties, to set an individual array element.} Procedure SetIntArrayPropertyItemOnScript(aeScript: IInterface; asPropertyName: String; aiIndex: Integer; aiValue: Integer); Var eProperties: IInterface; eProperty: IInterface; eValues: IInterface; iIterator: Integer; eValue: IInterface; iValue: Integer; bThrowaway: Boolean; Begin eProperties := ElementByName(aeScript, 'Properties'); eProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 13, bThrowaway); SetNativeValue(ElementByName(eProperty, 'Flags'), 1); // "Edited" eValues := ElementByIndex(ElementByName(eProperty, 'Value'), 0); For iIterator := 0 To aiIndex Do Begin eValue := ElementByIndex(eValues, iIterator); If Not Assigned(eValue) Then eValue := ElementAssign(eValues, HighInteger, nil, False); If iIterator = aiIndex Then SetNativeValue(eValue, aiValue); End; End; {$ENDREGION} {$REGION 'Functions to set Float array script properties.'} {Function for Type 14 (Int) properties. The values must be specified as a TStringList.} Procedure SetFloatArrayPropertyOnScript(aeScript: IInterface; asPropertyName: String; aslPropertyValues: TStringList); Var eProperties: IInterface; eProperty: IInterface; eValues: IInterface; iIterator: Integer; eValue: IInterface; fValue: Float; bThrowaway: Boolean; iThrowaway: Integer; Begin eProperties := ElementByName(aeScript, 'Properties'); eProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 14, bThrowaway); SetNativeValue(ElementByName(eProperty, 'Flags'), 1); // "Edited" eValues := ElementByIndex(ElementByName(eProperty, 'Value'), 0); For iIterator := 0 To aslPropertyValues.Count - 1 Do Begin fValue := StrToFloatDef(aslPropertyValues[iIterator], 0); eValue := ElementByIndex(eValues, iIterator); If Not Assigned(eValue) Then eValue := ElementAssign(eValues, HighInteger, nil, False); SetNativeValue(eValue, fValue); End; If aslPropertyValues.Count < ElementCount(eValues) Then Begin iThrowaway := ElementCount(eValues) - 1; For iIterator := aslPropertyValues.Count To iThrowaway Do Begin Remove(ElementByIndex(eValues, aslPropertyValues.Count)); End; End; End; {Function for Type 14 (Int) properties, to set an individual array element.} Procedure SetFloatArrayPropertyItemOnScript(aeScript: IInterface; asPropertyName: String; aiIndex: Integer; afValue: Float); Var eProperties: IInterface; eProperty: IInterface; eValues: IInterface; iIterator: Integer; eValue: IInterface; bThrowaway: Boolean; Begin eProperties := ElementByName(aeScript, 'Properties'); eProperty := GetOrMakePropertyOnScript(aeScript, asPropertyName, 14, bThrowaway); SetNativeValue(ElementByName(eProperty, 'Flags'), 1); // "Edited" eValues := ElementByIndex(ElementByName(eProperty, 'Value'), 0); For iIterator := 0 To aiIndex Do Begin eValue := ElementByIndex(eValues, iIterator); If Not Assigned(eValue) Then eValue := ElementAssign(eValues, HighInteger, nil, False); If iIterator = aiIndex Then SetNativeValue(eValue, afValue); End; End; {$ENDREGION} {$REGION 'UNIMPLEMENTED - Functions to set Boolean array script properties.'} {$ENDREGION} End.
{==============================================================================| | MicroCoin | | Copyright (c) 2017-2018 MicroCoin Developers | |==============================================================================| | Permission is hereby granted, free of charge, to any person obtaining a copy | | of this software and associated documentation files (the "Software"), to | | deal in the Software without restriction, including without limitation the | | rights to use, copy, modify, merge, publish, distribute, sublicense, and/or | | sell opies of the Software, and to permit persons to whom the Software is | | furnished to do so, subject to the following conditions: | | | | The above copyright notice and this permission notice shall be included in | | all copies or substantial portions of the Software. | |------------------------------------------------------------------------------| | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | | DEALINGS IN THE SOFTWARE. | |==============================================================================| | File: MicroCoin.Forms.AccountSelectDialog.pas | Created at: 2018-09-04 | Purpose: Account Selector dialog |==============================================================================} unit MicroCoin.Forms.AccountSelectDialog; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, VirtualTrees, MicroCoin.Node.Node, MicroCoin.Account.Data, MicroCoin.Common, Menus, MicroCoin.Common.Lists, ActnList, Buttons, PngBitBtn, UITypes; type TAccountSelectDialog = class(TForm) accountVList: TVirtualStringTree; Panel1: TPanel; Panel2: TPanel; cbMyAccounts: TCheckBox; cbForSale: TCheckBox; btnOk: TPngBitBtn; btnCancel: TPngBitBtn; procedure accountVListInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure accountVListGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure FormCreate(Sender: TObject); procedure cbMyAccountsClick(Sender: TObject); procedure cbForSaleClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure edAccountNameExit(Sender: TObject); procedure accountVListNodeDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo); procedure accountVListFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure accountVListInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); private FAccounts: TOrderedList; FSelectedAccount : TAccount; FJustForSale: boolean; FJustMyAccounts: boolean; FShowSubaccounts: boolean; procedure UpdateAccounts; procedure SetJustForSale(const Value: boolean); procedure SetJustMyAccounts(const Value: boolean); procedure SetShowSubAccounts(const Value: boolean); public property SelectedAccount : TAccount read FSelectedAccount; property JustMyAccounts : boolean read FJustMyAccounts write SetJustMyAccounts; property JustForSale : boolean read FJustForSale write SetJustForSale; {$IFDEF EXTENDEDACCOUNT} property ShowSubAccounts: boolean read FShowSubaccounts write SetShowSubAccounts; {$ENDIF} end; var AccountSelectDialog: TAccountSelectDialog; implementation {$R *.dfm} procedure TAccountSelectDialog.accountVListFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); begin TAccount(Node.GetData^):=Default(TAccount); end; procedure TAccountSelectDialog.accountVListGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var xPa : PAccount; begin if Sender.GetNodeLevel(Node) = 0 then begin xPa := Sender.GetNodeData(Node); case Column of 0: CellText := string(TAccount.AccountNumberToString(xPa.AccountNumber)); 1: CellText := string(xPa.Name); 2: CellText := string(TCurrencyUtils.CurrencyToString(xPa.Balance)); 3: CellText := xPa.NumberOfTransactions.ToString; end; end else begin {$IFDEF EXTENDEDACCOUNT} xPa := Sender.GetNodeData(Node.Parent); case Column of 0: CellText := string(TAccount.AccountNumberToString(xPa.AccountNumber)+'/'+IntToStr(Node.Index+1)); 1: CellText := ''; 2: CellText := string(TCurrencyUtils.CurrencyToString(xPa.SubAccounts[Node.Index].Balance)); 3: CellText := xPa.NumberOfTransactions.ToString; end; {$ENDIF} end; end; procedure TAccountSelectDialog.accountVListInitChildren( Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); begin {$IFDEF EXTENDEDACCOUNT} if ShowSubAccounts then ChildCount := Length(TAccount(Node.GetData^).SubAccounts); {$ENDIF} end; procedure TAccountSelectDialog.accountVListInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var xAccount : TAccount; begin if cbMyAccounts.Checked or cbForSale.Checked then begin xAccount := TNode.Node.TransactionStorage.BlockManager.AccountStorage.Accounts[FAccounts.Get(Node.Index)]; end else begin xAccount := TNode.Node.TransactionStorage.BlockManager.AccountStorage.Accounts[Node.Index]; end; {$IFDEF EXTENDEDACCOUNT} if accountVList.GetNodeLevel(Node)=0 then Sender.ChildCount[Node] := Length(xAccount.SubAccounts); {$ENDIF} Sender.SetNodeData(Node, xAccount); end; procedure TAccountSelectDialog.accountVListNodeDblClick( Sender: TBaseVirtualTree; const HitInfo: THitInfo); begin FSelectedAccount := PAccount(HitInfo.HitNode.GetData)^; ModalResult := mrOk; CloseModal; end; procedure TAccountSelectDialog.btnOkClick(Sender: TObject); begin if accountVList.FocusedNode = nil then begin MessageDlg('Please select an account', mtError, [mbOK],0); exit; end; FSelectedAccount := PAccount(accountVList.FocusedNode.GetData)^; end; procedure TAccountSelectDialog.cbForSaleClick(Sender: TObject); begin UpdateAccounts; end; procedure TAccountSelectDialog.cbMyAccountsClick(Sender: TObject); begin UpdateAccounts; end; procedure TAccountSelectDialog.edAccountNameExit(Sender: TObject); begin accountVList.ReinitNode(nil, true); end; procedure TAccountSelectDialog.FormCreate(Sender: TObject); begin accountVList.NodeDataSize := sizeof(TAccount); accountVList.RootNodeCount := TNode.Node.TransactionStorage.BlockManager.AccountStorage.AccountsCount; end; procedure TAccountSelectDialog.FormDestroy(Sender: TObject); begin if assigned(FAccounts) then FreeAndNil(FAccounts); end; procedure TAccountSelectDialog.SetJustForSale(const Value: boolean); begin FJustForSale := Value; cbForSale.Checked := Value; cbForSale.Enabled := not Value; end; procedure TAccountSelectDialog.SetJustMyAccounts(const Value: boolean); begin FJustMyAccounts := Value; cbMyAccounts.Checked := Value; cbMyAccounts.Enabled := not Value; end; procedure TAccountSelectDialog.SetShowSubAccounts(const Value: boolean); begin FShowSubaccounts := Value; end; procedure TAccountSelectDialog.UpdateAccounts; var i: integer; begin if cbForSale.Checked then begin if not assigned(FAccounts) then FAccounts := TOrderedList.Create else FAccounts.Clear; if cbMyAccounts.Checked then begin for i := 0 to FAccounts.Count - 1 do begin if TNode.Node.TransactionStorage.BlockManager.AccountStorage.Accounts[FAccounts.Get(i)].AccountInfo.State <> as_ForSale then FAccounts.Delete(i); end; end else begin FAccounts.Clear; for i := 0 to TNode.Node.TransactionStorage.BlockManager.AccountStorage.AccountsCount - 1 do begin if TNode.Node.TransactionStorage.BlockManager.AccountStorage.Accounts[i].AccountInfo.State = as_ForSale then FAccounts.Add(TNode.Node.TransactionStorage.BlockManager.AccountStorage.Accounts[i].AccountNumber); end; end; accountVList.RootNodeCount := FAccounts.Count; end else begin if cbMyAccounts.Checked then begin if not assigned(FAccounts) then FAccounts := TOrderedList.Create else FAccounts.Clear; for i:=0 to TNode.Node.KeyManager.AccountsKeyList.Count - 1 do begin FAccounts.AppendFrom(TNode.Node.KeyManager.AccountsKeyList.AccountList[i]); end; accountVList.RootNodeCount := FAccounts.Count; end else begin accountVList.RootNodeCount := TNode.Node.TransactionStorage.BlockManager.AccountStorage.AccountsCount; FreeAndNil(FAccounts); end; end; accountVList.ReinitNode(nil, true); end; end.
unit Atm.Tests.Fixtures.Machine; interface uses System.SysUtils, DUnitX.TestFramework, Delphi.Mocks, // our isolation framework! Atm.Services.CardReader, Atm.Services.Communicator, Atm.Services.Machine; type [TestFixture] TAtmMachineTests = class(TObject) private FMachine: TAtmMachine; FCardReader: TMock<IAtmCardReader>; FCommunicator: TMock<IAtmCommunicator>; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure Create_NoOp_CheckWithdrawalDisabled; [Test] procedure StartSession_WithRightPin_CheckWithdrawalEnabled; [Test] procedure StartSession_WithWrongPin_CheckWithdrawalDisabled; [Test] procedure EndSession_WithRightPin_CheckWithdrawalDisabled; [Test] procedure StartSession_WithRightPin_NoWarning; [Test] procedure StartSession_WithWrongPin_WarningSent; [Test] procedure StartSession_WithWrongPin_WarningTextMatch; end; implementation uses Atm.Tests.Globals; procedure TAtmMachineTests.Setup; begin // STUB: CardReader FCardReader := TMock<IAtmCardReader>.Create; FCardReader.Setup.WillReturn(True).When.CheckForValidPin(PinRightValue); FCardReader.Setup.WillReturn(False).When.CheckForValidPin(PinWrongValue); // MOCK: Communicator FCommunicator := TMock<IAtmCommunicator>.Create; // SUT: Machine FMachine := TAtmMachine.Create(FCardReader, FCommunicator); end; procedure TAtmMachineTests.TearDown; begin FreeAndNil(FMachine); end; procedure TAtmMachineTests.Create_NoOp_CheckWithdrawalDisabled; begin Assert.IsFalse(FMachine.WithdrawalEnabled); end; procedure TAtmMachineTests.EndSession_WithRightPin_CheckWithdrawalDisabled; begin FMachine.StartSession(PinRightValue); FMachine.EndSession; Assert.IsFalse(FMachine.WithdrawalEnabled); end; procedure TAtmMachineTests.StartSession_WithRightPin_CheckWithdrawalEnabled; begin FMachine.StartSession(PinRightValue); Assert.IsTrue(FMachine.WithdrawalEnabled); end; procedure TAtmMachineTests.StartSession_WithWrongPin_CheckWithdrawalDisabled; begin FMachine.StartSession(PinWrongValue); Assert.IsFalse(FMachine.WithdrawalEnabled); end; procedure TAtmMachineTests.StartSession_WithRightPin_NoWarning; begin // Assign FCommunicator.Setup.Expect.Never('SendMessage'); // Act FMachine.StartSession(PinRightValue); // Assert Assert.IsEmpty(FCommunicator.CheckExpectations); end; procedure TAtmMachineTests.StartSession_WithWrongPin_WarningSent; begin FCommunicator.Setup.Expect.Once('SendMessage'); FMachine.StartSession(PinWrongValue); Assert.IsEmpty(FCommunicator.CheckExpectations); end; procedure TAtmMachineTests.StartSession_WithWrongPin_WarningTextMatch; begin FCommunicator.Setup.Expect.Once.When.SendMessage('Wrong PIN alert'); Assert.WillNotRaise( procedure begin FMachine.StartSession(PinWrongValue); FCommunicator.Verify; end, EMockVerificationException); end; initialization TDUnitX.RegisterTestFixture(TAtmMachineTests); end.
unit DbBase; interface uses SysUtils,Classes,DbLib,ShareLib,ShareWin; type EDbError=class(Exception); TDbCursor=class private FActiveBuffer:Pointer; FOffsets:TCommonArray; FDataSizes:TCommonArray; function GetFieldCount: Integer; function GetOffset(Index: Integer): Integer; function GetDataSizes(Index: Integer): Integer; procedure SetActiveBuffer(Buffer:Pointer); function GetDataBuffer(Index: Integer): Pointer; protected function AddField(Offset,Size:Integer):Integer; procedure DelField(Index:Integer); procedure SetFieldCount(const Value: Integer); procedure SetOffset(Index: Integer; const Value: Integer); procedure SetDataSizes(Index: Integer; const Value: Integer); public constructor Create; destructor Destroy;override; property ActiveBuffer:Pointer read FActiveBuffer write SetActiveBuffer; property FieldCount:Integer read GetFieldCount; property Offset[Index:Integer]:Integer read GetOffset; property DataSize[Index:Integer]:Integer read GetDataSizes; property DataBuffer[Index:Integer]:Pointer read GetDataBuffer; public function AsBoolean(Index:Integer):Boolean; procedure GetBoolean(Index:Integer;var Value:Boolean); procedure SetBoolean(Index:Integer;Value:Boolean); function AsByte(Index:Integer):Byte; procedure GetByte(Index:Integer;var Value:Byte); procedure SetByte(Index:Integer;const Value:Byte); function AsInteger(Index:Integer):LongInt; procedure GetInteger(Index:Integer;var Value:LongInt); procedure SetInteger(Index:Integer;const Value:LongInt); function AsDouble(Index:Integer):Double; procedure GetDouble(Index:Integer;var Value:Double); procedure SetDouble(Index:Integer;const Value:Double); function AsCurrency(Index:Integer):Currency; procedure GetCurrency(Index:Integer;var Value:Currency); procedure SetCurrency(Index:Integer;const Value:Currency); function AsDateTime(Index:Integer):TDateTime; procedure GetDateTime(Index:Integer;var Value:TDateTime); procedure SetDateTime(Index:Integer;const Value:TDateTime); function GetPChar(Index:Integer;Value:PChar):Integer; procedure SetPChar(Index:Integer;Value:PChar); function GetString(Index:Integer):string; procedure SetString(Index:Integer;const Value:string); function GetPChar1(Index:Integer;Value:PChar):Integer; procedure SetPChar1(Index:Integer;Value:PChar); function GetString1(Index:Integer):string; procedure SetString1(Index:Integer;const Value:string); function AsNumber(Index:Integer):LongInt; procedure GetNumber(Index:Integer;var Value:LongInt); procedure SetNumber(Index:Integer;Value:LongInt); function AsFloat(Index:Integer):Double; procedure GetFloat(Index:Integer;var Value:Double); procedure SetFloat(Index:Integer;const Value:Double); public procedure GetData(Index:Integer;var Value);overload; procedure GetData(Indexes:TCommonArray;var Value);overload; procedure GetData(Indexes:array of Integer;var Value);overload; procedure SetData(Index:Integer;const Value);overload; procedure SetData(Indexes:array of Integer;const Value);overload; procedure CopyValue(Source:TDbCursor;FromIndex,ToIndex:Integer); procedure CopyValues(Source:TDbCursor;IndexMaps:TCommonArray); procedure ReadValue(Stream:TStream;Index:Integer);overload; procedure ReadValue(Stream:TStream;Indexes:TCommonArray);overload; procedure ReadValue(Stream:TStream;Indexes:array of Integer);overload; procedure WriteValue(Stream:TStream;Index:Integer);overload; procedure WriteValue(Stream:TStream;Indexes:TCommonArray);overload; procedure WriteValue(Stream:TStream;Indexes:array of Integer);overload; end; TRecordsBuffer=class private FRecordList:TCommonArray; FDeleteList:TCommonArray; FRecordSize: Integer; procedure SetRecordSize(const Value: Integer); function GetRecordCount: Integer; procedure SetRecordCount(const Value: Integer); function GetRecBuffer(Index: Integer): Pointer; protected function AllocBuffer(nSize:Integer):Pointer;virtual; procedure FreeBuffer(Buffer:Pointer);virtual; function AllocRecord:Pointer;virtual; procedure FreeRecord(Buffer:Pointer);virtual; property DeleteList:TCommonArray read FDeleteList; public constructor Create; destructor Destroy;override; procedure Clear;virtual; function AddRecord:Pointer; function InsRecord(Index:Integer):Pointer; procedure DelRecord(Index:Integer);overload; procedure DelRecord(Buffer:Pointer);overload; procedure DeleteRecord(Index:Integer); procedure PackBuffers; property RecordSize:Integer read FRecordSize write SetRecordSize; property RecordList:TCommonArray read FRecordList; property RecordCount:Integer read GetRecordCount write SetRecordCount; property RecBuffer[Index:Integer]:Pointer read GetRecBuffer;default; end; type TFieldType=(ftString,ftInteger,ftBoolean,ftFloat,ftCurrency,ftDateTime); TMemIndexField=record DataType :TFieldType; DataSize :Integer; Descending :Boolean; CaseSensitive :Boolean; end; TMemIndexFields=array of TMemIndexField; TMemIndex=class private FKeys:TCommonArray; FMemMgr:TMiniMemAllocator; FKeyLength:Integer; FKeyBuffer:Pointer; procedure ExtractKeyFields; function GetCount:Integer; function GetData(Index:Integer):Integer; function GetCapacity: Integer; procedure SetCapacity(const Value: Integer); protected function Compare(Key1,Key2:Pointer):Integer; public IndexFields:TMemIndexFields; constructor Create; destructor Destroy;override; procedure Reset; procedure Insert(Index:Integer;KeyBuffer:Pointer;Data:Integer); function Find(KeyBuffer:Pointer;var Index:Integer):Boolean; function FindFirst(KeyBuffer:Pointer;var Index:Integer):Boolean; function FindLast(KeyBuffer:Pointer;var Index:Integer):Boolean; property Count:Integer read GetCount; property Data[Index:Integer]:Integer read GetData; property KeyLength:Integer read FKeyLength; property KeyBuffer:Pointer read FKeyBuffer; property Capacity:Integer read GetCapacity write SetCapacity; end; const FieldSizes:array[TFieldType] of Integer= (0,4,1,8,8,8); function DSGetStringValue1(Buffer:PChar;Len:Integer):string; procedure DSSetStringValue1(Buffer:PChar;Len:Integer;const Value:string); function DSGetPCharValue1(Buffer:PChar;Len:Integer;Value:Pchar):Integer; procedure DSSetPCharValue1(Buffer:PChar;Len:Integer;const Value:PChar); implementation function DSGetStringValue1(Buffer:PChar;Len:Integer):string; var p:PChar; SaveChar:Char; begin Assert(Len>0); p:=Buffer+Len-1; SaveChar:=Buffer[0];Buffer[0]:=#0;//not 32 while(p^=#32)do Dec(p); Buffer[0]:=SaveChar;Len:=p-Buffer+1; if(Len=1)and(SaveChar=#32)then Dec(Len); SetString(Result,Buffer,Len); end; procedure DSSetStringValue1(Buffer:PChar;Len:Integer;const Value:string); var sl:Integer; begin Assert(Len>0); sl:=Length(Value); if(sl>Len)then sl:=Len; if(sl>0)then System.Move(Pointer(Value)^,Buffer^,sl); for sl:=sl to Len-1 do Buffer[sl]:=#32; end; function DSGetPCharValue1(Buffer:PChar;Len:Integer;Value:Pchar):Integer; var p:PChar; SaveChar:Char; begin Assert(Len>0); p:=Buffer+Len-1; SaveChar:=Buffer[0];Buffer[0]:=#0;//not 32 while(p^=#32)do Dec(p); Buffer[0]:=SaveChar;Len:=p-Buffer+1; if(Len=1)and(SaveChar=#32)then Dec(Len); StrLCopy(Value,Buffer,Len); Result:=Len; end; procedure DSSetPCharValue1(Buffer:PChar;Len:Integer;const Value:PChar); var sl:Integer; begin Assert(Len>0); sl:=strLen(Value); if(sl>Len)then sl:=Len; if(sl>0)then System.Move(Pointer(Value)^,Buffer^,sl); for sl:=sl to Len-1 do Buffer[sl]:=#32; end; { TDbCursor } constructor TDbCursor.Create; begin inherited Create; FOffsets:=TCommonArray.Create; FDataSizes:=TCommonArray.Create; end; destructor TDbCursor.Destroy; begin inherited; FOffsets.Free; FDataSizes.Free; end; procedure TDbCursor.SetActiveBuffer(Buffer: Pointer); begin FActiveBuffer:=Buffer; end; function TDbCursor.GetFieldCount: Integer; begin Result:=FOffsets.Count; end; procedure TDbCursor.SetFieldCount(const Value: Integer); begin FOffsets.Count:=Value; FDataSizes.Count:=Value; end; function TDbCursor.GetOffset(Index: Integer): Integer; begin Result:=FOffsets.Elems2[Index]; end; procedure TDbCursor.SetOffset(Index: Integer; const Value: Integer); begin Assert(Value>=0); FOffsets.Elems2[Index]:=Value; end; function TDbCursor.GetDataSizes(Index: Integer): Integer; begin Result:=FDataSizes.Elems2[Index]; end; procedure TDbCursor.SetDataSizes(Index: Integer; const Value: Integer); begin Assert(Value>=0); FDataSizes.Elems2[Index]:=Value; end; function TDbCursor.GetDataBuffer(Index: Integer): Pointer; begin Result:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); end; function TDbCursor.AddField(Offset, Size: Integer): Integer; begin Assert((Offset>=0)and(Size>=0)); Result:=FOffsets.Add2(Offset); FDataSizes.Add2(Size); end; procedure TDbCursor.DelField(Index: Integer); begin FOffsets.Delete(Index,1); FDataSizes.Delete(Index,1); end; procedure TDbCursor.GetData(Index:Integer;var Value); begin System.Move(Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index])^,Value,FDataSizes.Elems2[Index]); end; procedure TDbCursor.GetData(Indexes:TCommonArray;var Value); var Offset:Cardinal; I,Index,Size:Integer; begin Offset:=0; for I:=0 to Indexes.Count-1 do begin Index:=Indexes.Elems2[I];Size:=FDataSizes.Elems2[Index]; System.Move(Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index])^, Pointer(Cardinal(@Value)+Offset)^, Size); Inc(Offset,Size); end; end; procedure TDbCursor.GetData(Indexes:array of Integer;var Value); var Offset:Cardinal; I,Index,Size:Integer; begin Offset:=0; for I:=Low(Indexes) to High(Indexes) do begin Index:=Indexes[I];Size:=FDataSizes.Elems2[Index]; System.Move(Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index])^, Pointer(Cardinal(@Value)+Offset)^, Size); Inc(Offset,Size); end; end; procedure TDbCursor.SetData(Index:Integer;const Value); begin System.Move(Value,Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index])^,FDataSizes.Elems2[Index]); end; procedure TDbCursor.SetData(Indexes:array of Integer;const Value); var Offset:Cardinal; I,Index,Size:Integer; begin Offset:=0; for I:=Low(Indexes) to High(Indexes) do begin Index:=Indexes[I];Size:=FDataSizes.Elems2[Index]; System.Move(Pointer(Cardinal(@Value)+Offset)^, Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index])^, Size); Inc(Offset,Size); end; end; procedure TDbCursor.CopyValue(Source:TDbCursor;FromIndex,ToIndex:Integer); begin System.Move(Source.DataBuffer[FromIndex]^, Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[ToIndex])^, FDataSizes.Elems2[ToIndex]); end; procedure TDbCursor.CopyValues(Source:TDbCursor;IndexMaps:TCommonArray); var I,Index:Integer; begin for I:=0 to IndexMaps.Count-1 do begin Index:=IndexMaps.Elems2[I]; if(Index<0)then Continue; System.Move(Source.DataBuffer[Index]^, Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[I])^, FDataSizes.Elems2[I]); end; end; procedure TDbCursor.ReadValue(Stream:TStream;Index:Integer); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Stream.Read(Buffer^,FDataSizes.Elems2[Index]); end; procedure TDbCursor.WriteValue(Stream:TStream;Index:Integer); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Stream.Write(Buffer^,FDataSizes.Elems2[Index]); end; procedure TDbCursor.ReadValue(Stream:TStream;Indexes:TCommonArray); var Buffer:Pointer; I,Index:Integer; begin for I:=0 to Indexes.Count-1 do begin Index:=Indexes.Elems2[I]; Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Stream.Read(Buffer^,FDataSizes.Elems2[Index]); end; end; procedure TDbCursor.ReadValue(Stream:TStream;Indexes:array of Integer); var Buffer:Pointer; I,Index:Integer; begin for I:=Low(Indexes) to High(Indexes) do begin Index:=Indexes[I]; Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Stream.Read(Buffer^,FDataSizes.Elems2[Index]); end; end; procedure TDbCursor.WriteValue(Stream:TStream;Indexes:TCommonArray); var Buffer:Pointer; I,Index:Integer; begin for I:=0 to Indexes.Count-1 do begin Index:=Indexes.Elems2[I]; Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Stream.Write(Buffer^,FDataSizes.Elems2[Index]); end; end; procedure TDbCursor.WriteValue(Stream:TStream;Indexes:array of Integer); var Buffer:Pointer; I,Index:Integer; begin for I:=Low(Indexes) to High(Indexes) do begin Index:=Indexes[I]; Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Stream.Write(Buffer^,FDataSizes.Elems2[Index]); end; end; function TDbCursor.AsBoolean(Index:Integer):Boolean; var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Result:=Byte(Buffer^)<>0; end; procedure TDbCursor.GetBoolean(Index:Integer;var Value:Boolean); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Value:=Byte(Buffer^)<>0; end; procedure TDbCursor.SetBoolean(Index:Integer;Value:Boolean); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Byte(Buffer^):=Ord(Value); end; function TDbCursor.AsByte(Index:Integer):Byte; var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Result:=Byte(Buffer^); end; procedure TDbCursor.GetByte(Index:Integer;var Value:Byte); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Value:=Byte(Buffer^); end; procedure TDbCursor.SetByte(Index:Integer;const Value:Byte); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Byte(Buffer^):=Value; end; function TDbCursor.AsInteger(Index:Integer):LongInt; var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Result:=LongInt(Buffer^); end; procedure TDbCursor.GetInteger(Index:Integer;var Value:LongInt); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Value:=LongInt(Buffer^); end; procedure TDbCursor.SetInteger(Index:Integer;const Value:LongInt); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); LongInt(Buffer^):=Value; end; function TDbCursor.AsDouble(Index:Integer):Double; var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Result:=Double(Buffer^); end; procedure TDbCursor.GetDouble(Index:Integer;var Value:Double); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); CopyDouble(Buffer^,Value); end; procedure TDbCursor.SetDouble(Index:Integer;const Value:Double); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); CopyDouble(Pointer(@Value)^,Buffer^); end; function TDbCursor.AsCurrency(Index:Integer):Currency; var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Result:=Currency(Buffer^); end; procedure TDbCursor.GetCurrency(Index:Integer;var Value:Currency); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); CopyDouble(Buffer^,Value); end; procedure TDbCursor.SetCurrency(Index:Integer;const Value:Currency); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); CopyDouble(Pointer(@Value)^,Buffer^); end; function TDbCursor.AsDateTime(Index:Integer):TDateTime; var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Result:=TDateTime(Buffer^); end; procedure TDbCursor.GetDateTime(Index:Integer;var Value:TDateTime); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); CopyDateTime(Buffer^,Value); end; procedure TDbCursor.SetDateTime(Index:Integer;const Value:TDateTime); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); CopyDateTime(Pointer(@Value)^,Buffer^); end; function TDbCursor.GetPChar(Index:Integer;Value:PChar):Integer; var Buffer:PChar; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Result:=StrLen(Buffer); System.Move(Buffer^,Value^,Result); Value[Result]:=#0; end; procedure TDbCursor.SetPChar(Index:Integer;Value:PChar); var Buffer:PChar; I,sLen,MaxLen:Integer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); MaxLen:=DataSize[Index]; sLen:=StrLen(Value); if(sLen>=MaxLen)then sLen:=MaxLen-1; System.Move(Value^,Buffer^,sLen); for I:=sLen to MaxLen-1 do Buffer[I]:=#0; end; function TDbCursor.GetString(Index:Integer):string; var Buffer:PChar; sLen:Integer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); sLen:=StrLen(Buffer); System.SetString(Result,Buffer,sLen); end; procedure TDbCursor.SetString(Index:Integer;const Value:string); var Buffer:PChar; I,sLen,MaxLen:Integer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); MaxLen:=DataSize[Index]; sLen:=Length(Value); if(sLen>=MaxLen)then sLen:=MaxLen-1; System.Move(Pointer(Value)^,Buffer^,sLen); for I:=sLen to MaxLen-1 do Buffer[I]:=#0; end; function TDbCursor.GetPChar1(Index:Integer;Value:PChar):Integer; var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Result:=DSGetPCharValue1(Buffer,FDataSizes.Elems2[Index],Value); end; procedure TDbCursor.SetPChar1(Index:Integer;Value:PChar); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); DSSetPCharValue1(Buffer,FDataSizes.Elems2[Index],Value); end; function TDbCursor.GetString1(Index:Integer):string; var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); Result:=DSGetStringValue1(Buffer,FDataSizes.Elems2[Index]); end; procedure TDbCursor.SetString1(Index:Integer;const Value:string); var Buffer:Pointer; begin Buffer:=Pointer(Cardinal(ActiveBuffer)+FOffsets.Elems1[Index]); DSSetStringValue1(Buffer,FDataSizes.Elems2[Index],Value); end; function TDbCursor.AsNumber(Index:Integer):LongInt; var sNumber:string; begin sNumber:=GetString1(Index); Result:=NumberToInteger(sNumber); end; procedure TDbCursor.GetNumber(Index:Integer;var Value:LongInt); begin Value:=AsNumber(Index); end; procedure TDbCursor.SetNumber(Index:Integer;Value:LongInt); begin SetString1(Index,IntToStr(Value)); end; function TDbCursor.AsFloat(Index:Integer):Double; begin GetFloat(Index,Result); end; procedure TDbCursor.GetFloat(Index:Integer;var Value:Double); var sNumber:string; begin sNumber:=GetString1(Index); Value:=NumberToFloat(sNumber); end; procedure TDbCursor.SetFloat(Index:Integer;const Value:Double); begin SetString1(Index,FloatToStr(Value)); end; { TRecordsBuffer } constructor TRecordsBuffer.Create; begin inherited Create; FRecordList:=TCommonArray.Create; FDeleteList:=TCommonArray.Create; end; destructor TRecordsBuffer.Destroy; begin Clear; inherited; FRecordList.Free; FDeleteList.Free; end; procedure TRecordsBuffer.SetRecordSize(const Value: Integer); begin Assert(Value>0); if(Value=FRecordSize)then Exit; Assert(RecordList.Count=0); if(DeleteList.Count>0)then PackBuffers(); FRecordSize := Value; end; function TRecordsBuffer.AllocBuffer(nSize:Integer):Pointer; begin GetMem(Result,nSize) end; procedure TRecordsBuffer.FreeBuffer(Buffer: Pointer); begin FreeMem(Buffer); end; function TRecordsBuffer.AllocRecord:Pointer; begin if(DeleteList.IsEmpty)then Result:=AllocBuffer(RecordSize) else Result:=DeleteList.Pop3; end; procedure TRecordsBuffer.FreeRecord(Buffer:Pointer); begin DeleteList.Push3(Buffer); end; function TRecordsBuffer.GetRecBuffer(Index: Integer): Pointer; begin Result:=RecordList[Index]; end; function TRecordsBuffer.AddRecord: Pointer; begin Result:=InsRecord(RecordList.Count); end; function TRecordsBuffer.InsRecord(Index: Integer): Pointer; begin Result:=AllocRecord; RecordList.Insert3(Index,1,Result); end; procedure TRecordsBuffer.DelRecord(Index: Integer); var Buffer:Pointer; begin Buffer:=RecordList[Index]; RecordList.Delete(Index,1); FreeRecord(Buffer); end; procedure TRecordsBuffer.DelRecord(Buffer:Pointer); begin RecordList.Remove3(Buffer); FreeRecord(Buffer); end; procedure TRecordsBuffer.DeleteRecord(Index:Integer); var Buffer:Pointer; begin Buffer:=RecordList[Index]; RecordList.Delete(Index,1); FreeBuffer(Buffer); end; function TRecordsBuffer.GetRecordCount: Integer; begin Result:=RecordList.Count; end; procedure TRecordsBuffer.SetRecordCount(const Value: Integer); var I:Integer; begin for I:=RecordList.Count-1 downto Value do DelRecord(I); for I:=RecordList.Count to Value-1 do InsRecord(I); end; procedure TRecordsBuffer.PackBuffers; begin while(not DeleteList.IsEmpty)do FreeBuffer(DeleteList.Pop3); end; procedure TRecordsBuffer.Clear; begin PackBuffers; while(not RecordList.IsEmpty)do FreeBuffer(RecordList.Pop3); end; { TMemIndex } function CompareDouble(P1,P2:Pointer):Integer; asm fld QWORD PTR [EAX] fcomp QWORD PTR [EDX] fwait fstsw AX SAHF MOV EAX,-1 JB @@3 JE @@2 @@1: INC EAX @@2: INC EAX @@3: RET end; function CompareCurrency(P1,P2:Pointer):Integer; asm fild QWORD PTR [EDX] fild QWORD PTR [EAX] fcompp fwait fstsw AX SAHF MOV EAX,-1 JB @@3 JE @@2 @@1: INC EAX @@2: INC EAX @@3: RET end; constructor TMemIndex.Create; begin inherited Create; FKeys:=TCommonArray.Create(256); FMemMgr:=TMiniMemAllocator.Create; end; destructor TMemIndex.Destroy; begin FMemMgr.Free; FKeys.Free; inherited; end; procedure TMemIndex.Reset; begin FKeyBuffer:=nil; FKeys.Reset; FMemMgr.FreeAll; ExtractKeyFields; FKeyBuffer:=FMemMgr.AllocMem(FKeyLength+1); end; procedure TMemIndex.ExtractKeyFields; var I,S:Integer; begin FKeyLength:=0; for I:=Low(IndexFields) to High(IndexFields) do begin S:=FieldSizes[IndexFields[I].DataType]; if(S=0)then Inc(FKeyLength,IndexFields[I].DataSize) else begin Inc(FKeyLength,S); IndexFields[I].DataSize:=S; end; end; end; function TMemIndex.Compare(Key1,Key2:Pointer):Integer; var I:Integer; begin for I:=Low(IndexFields) to High(IndexFields) do with IndexFields[I] do begin case DataType of ftString: if(not CaseSensitive)then Result:=AnsiStrLIComp0(Key1,Key2,DataSize) else Result:=AnsiStrLComp0(Key1,Key2,DataSize); ftInteger:Result:=Integer(Key1^)-Integer(Key2^); ftBoolean:Result:=Byte(Key1^)-Byte(Key2^); ftFloat,ftDateTime:Result:=CompareDouble(Key1,Key2); ftCurrency:Result:=CompareCurrency(Key1,Key2); else raise EDbError.Create('不可识别的类型'); end; if(Result<>0)then begin if(Descending)then Result:=-Result; Exit; end; Inc(Integer(Key1),DataSize); Inc(Integer(Key2),DataSize); end; Result:=0; end; function TMemIndex.GetCount:Integer; begin Result:=FKeys.Count; end; function TMemIndex.GetCapacity: Integer; begin Result:=FKeys.Capacity; end; procedure TMemIndex.SetCapacity(const Value: Integer); begin FKeys.Capacity:=Value; end; function TMemIndex.GetData(Index:Integer):Integer; begin Result:=Integer(FKeys.Elems3[Index]^); end; procedure TMemIndex.Insert(Index:Integer;KeyBuffer:Pointer;Data:Integer); var NewKey:Pointer; begin Assert(FKeyLength>0,'索引字段信息错误'); NewKey:=FMemMgr.AllocMem(sizeof(Integer)+FKeyLength); FKeys.Insert3(Index,1,NewKey); Integer(NewKey^):=Data; Inc(Integer(NewKey),sizeof(Integer)); System.Move(KeyBuffer^,NewKey^,FKeyLength); end; function TMemIndex.Find(KeyBuffer:Pointer;var Index:Integer):Boolean; var sb,se,sp,flag:Integer; begin flag:=-1; sb:=0;se:=FKeys.Count-1; while(sb<=se)do begin sp:=(sb+se) shr 1; flag:=Compare(KeyBuffer,Pointer(FKeys.Elems1[sp]+sizeof(Integer))); if(flag>0)then sb:=sp+1 else if(flag<0)then se:=sp-1 else begin sb:=sp; Break; end; end; Index:=sb; Result:=flag=0; end; function TMemIndex.FindFirst(KeyBuffer:Pointer;var Index:Integer):Boolean; var sb,se,sp,flag:Integer; begin flag:=-1; sb:=0;se:=FKeys.Count-1; while(sb<=se)do begin sp:=(sb+se) shr 1; flag:=Compare(KeyBuffer,Pointer(FKeys.Elems1[sp]+sizeof(Integer))); if(flag>0)then sb:=sp+1 else if(flag<0)then se:=sp-1 else begin se:=sp; if(sb=sp)then Break; end; end; Index:=sb; Result:=flag=0; end; function TMemIndex.FindLast(KeyBuffer: Pointer; var Index: Integer): Boolean; var sb,se,sp,flag:Integer; begin flag:=-1; sb:=0;se:=FKeys.Count-1; while(sb<=se)do begin sp:=(sb+se+1) shr 1; flag:=Compare(KeyBuffer,Pointer(FKeys.Elems1[sp]+sizeof(Integer))); if(flag>0)then sb:=sp+1 else if(flag<0)then se:=sp-1 else begin sb:=sp; if(se=sp)then Break; end; end; Index:=sb; Result:=flag=0; end; end.
{ ************************************************************************* } { Rave Reports version 5.1.1 } { this file is based on rpFormSetup.pas from the rave 5.1.1 beX-version } { description in http://www.nevrona.com/rave/tips/rvtip72.html } { Copyright (c), 1995-2002, Nevrona Designs, all rights reserved } { ************************************************************************* } unit dtFormSetup; interface uses Windows, Messages, Graphics, Controls, Forms, StdCtrls, Buttons, Dialogs, ComCtrls, SysUtils, Classes, RpDevice, RpDefine, RpSystem, RpRenderPrinter, printers, JvSpin, Mask, JvExMask; type TdtSetupForm = class(TForm) bbtnOK: TBitBtn; SetupBB: TBitBtn; dlogSave: TSaveDialog; GroupBox1: TGroupBox; PrinterLabel: TLabel; GroupBox2: TGroupBox; CopiesLabel: TLabel; CollateCK: TCheckBox; DuplexCK: TCheckBox; CopiesED: TJvSpinEdit; DestGB: TGroupBox; FileNameSB: TSpeedButton; Label1: TLabel; PrinterRB: TRadioButton; PreviewRB: TRadioButton; FileRB: TRadioButton; editFileName: TEdit; cboxFormat: TComboBox; RangeGB: TGroupBox; ToLabel: TLabel; SelectionED: TEdit; AllRB: TRadioButton; SelectionRB: TRadioButton; PagesRB: TRadioButton; FromED: TEdit; ToED: TEdit; procedure SetupBBClick(Sender: TObject); procedure FileNameSBClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PagesRBClick(Sender: TObject); procedure SelectionRBClick(Sender: TObject); procedure AllRBClick(Sender: TObject); procedure PrinterRBClick(Sender: TObject); procedure FileRBClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure bbtnOKClick(Sender: TObject); procedure editFileNameChange(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure SelectionEDKeyPress(Sender: TObject; var Key: Char); procedure cboxFormatChange(Sender: TObject); private procedure UpdateForm; procedure GetRenderList; public ReportSystem: TRvSystem; FilePrinter: TRvRenderPrinter; PreviewSetup: boolean; end; var RPSetupForm: TdtSetupForm; implementation uses RpRender; {$R *.dfm} procedure TdtSetupForm.UpdateForm; begin { UpdateForm } if (RPDev = nil) or (RPDev.printers.Count = 0) then begin PrinterLabel.Caption := Trans('No printers installed!'); end else begin RPDev.State := dsIC; if RPDev.Output = '' then begin PrinterLabel.Caption := RPDev.Device; end else begin PrinterLabel.Caption := Trans(Format( { Trans+ } '%s on %s', [RPDev.Device, RPDev.Output])); end; { else } end; { if } end; { UpdateForm } procedure TdtSetupForm.SetupBBClick(Sender: TObject); begin if RPDev <> nil then begin RPDev.PrinterSetupDialog; UpdateForm; end; { if } end; procedure TdtSetupForm.FileNameSBClick(Sender: TObject); begin if dlogSave.Execute then begin editFileName.Text := dlogSave.FileName; cboxFormat.ItemIndex := dlogSave.FilterIndex - 1; end; { if } end; procedure TdtSetupForm.FormCreate(Sender: TObject); begin SelectionED.Enabled := false; editFileName.Enabled := false; FileNameSB.Enabled := false; end; procedure TdtSetupForm.PagesRBClick(Sender: TObject); begin with Sender as TRadioButton do begin if Checked then begin FromED.Enabled := true; ToLabel.Enabled := true; ToED.Enabled := true; end; { if } end; { with } end; procedure TdtSetupForm.SelectionRBClick(Sender: TObject); begin with Sender as TRadioButton do begin if Checked then begin SelectionED.Enabled := true; end; { if } end; { with } end; procedure TdtSetupForm.AllRBClick(Sender: TObject); begin SelectionED.Enabled := false; FromED.Enabled := false; ToLabel.Enabled := false; ToED.Enabled := false; end; procedure TdtSetupForm.PrinterRBClick(Sender: TObject); begin editFileName.Enabled := false; FileNameSB.Enabled := false; cboxFormat.Enabled := false; bbtnOK.Enabled := true; SetupBB.Enabled := true; // GroupBox2.Enabled := Sender = PrinterRB; CopiesED.Enabled := Sender = PrinterRB; CollateCK.Enabled := Sender = PrinterRB; DuplexCK.Enabled := Sender = PrinterRB; end; procedure TdtSetupForm.FileRBClick(Sender: TObject); begin editFileName.Enabled := true; FileNameSB.Enabled := true; cboxFormat.Enabled := true; // GroupBox2.Enabled := false; SetupBB.Enabled := false; bbtnOK.Enabled := Trim(editFileName.Text) <> ''; end; procedure TdtSetupForm.FormShow(Sender: TObject); begin GetRenderList; { Enable/Disable items on setup form } with ReportSystem do begin UpdateForm; if PreviewSetup then begin { Init Page range variables here for FilePrinter.ExecuteCustom } FromED.Text := '1'; ToED.Text := IntToStr(FilePrinter.Pages); SelectionED.Text := { Trans- } '1-' + IntToStr(FilePrinter.Pages); end else begin { Initial setup, ask for destination } if cboxFormat.ItemIndex < 0 then begin cboxFormat.ItemIndex := 0; end; if (RPDev = nil) or RPDev.InvalidPrinter then begin PrinterRB.Enabled := false; FileRB.Enabled := false; if not(ssAllowDestPreview in SystemSetups) then begin PreviewRB.Enabled := false; end else begin PreviewRB.Checked := true; end; { else } end else begin if not(ssAllowDestPrinter in SystemSetups) then begin PrinterRB.Enabled := false; end; { if } if not(ssAllowDestPreview in SystemSetups) then begin PreviewRB.Enabled := false; end; { if } if not(ssAllowDestFile in SystemSetups) then begin FileRB.Enabled := false; end; { if } case DefaultDest of rdPrinter: begin PrinterRB.Checked := true; end; rdPreview: begin PreviewRB.Checked := true; end; rdFile: begin FileRB.Checked := true; end; end; { case } end; { else } end; { else } if (RPDev = nil) or RPDev.InvalidPrinter then begin CollateCK.Enabled := false; CopiesED.Enabled := false; CopiesLabel.Enabled := false; CopiesED.Text := IntToStr(SystemPrinter.Copies); DuplexCK.Enabled := false; SetupBB.Enabled := false; end else begin if not(ssAllowCollate in SystemSetups) then begin CollateCK.Enabled := false; end; { if } if not(ssAllowCopies in SystemSetups) then begin CopiesED.Enabled := false; CopiesLabel.Enabled := false; end; { if } CopiesED.Text := IntToStr(SystemPrinter.Copies); if not(ssAllowDuplex in SystemSetups) then begin DuplexCK.Enabled := false; end; { if } if not(ssAllowPrinterSetup in SystemSetups) then begin SetupBB.Enabled := false; end; { if } end; { else } end; { with } end; procedure TdtSetupForm.bbtnOKClick(Sender: TObject); var I1: integer; ErrCode: integer; DefExtension: string; begin with ReportSystem do begin { Gather information that was changed in setup window } if PreviewSetup then begin { Put code here to retrieve page range info } FilePrinter.FirstPage := 1; FilePrinter.LastPage := 9999; FilePrinter.Selection := ''; if SelectionRB.Checked then begin FilePrinter.Selection := SelectionED.Text; end else if PagesRB.Checked then begin FilePrinter.FirstPage := StrToInt(FromED.Text); FilePrinter.LastPage := StrToInt(ToED.Text); end; { else } if ssAllowCopies in SystemSetups then begin Val(CopiesED.Text, I1, ErrCode); if ErrCode = 0 then begin FilePrinter.Copies := I1; end; { if } end; { if } if ssAllowCollate in SystemSetups then begin FilePrinter.Collate := CollateCK.Checked; end; { if } if (ssAllowDuplex in SystemSetups) then begin if DuplexCK.Checked then begin if FilePrinter.Duplex = dupSimplex then begin FilePrinter.Duplex := dupVertical; end; { if } end else begin FilePrinter.Duplex := dupSimplex; end; { else } end; { if } end else begin if PrinterRB.Checked then begin ReportDest := rdPrinter; OutputFileName := ''; end else if PreviewRB.Checked then begin ReportDest := rdPreview; OutputFileName := ''; end else begin ReportDest := rdFile; OutputFileName := Trim(editFileName.Text); if cboxFormat.ItemIndex = 0 then begin // Do NDR if Pos('.', OutputFileName) < 1 then begin OutputFileName := OutputFileName + { Trans- } '.ndr'; end; { if } ReportSystem.DoNativeOutput := false; ReportSystem.RenderObject := nil; end else if cboxFormat.ItemIndex = 1 then begin // Do Native Output PRN if Pos('.', OutputFileName) < 1 then begin OutputFileName := OutputFileName + { Trans- } '.prn'; end; { if } ReportSystem.DoNativeOutput := true; ReportSystem.RenderObject := nil; end else begin // Do Renderer ReportSystem.DoNativeOutput := false; ReportSystem.RenderObject := TRPRender(cboxFormat.Items.Objects[cboxFormat.ItemIndex]); if Pos('.', OutputFileName) < 1 then begin with ReportSystem.RenderObject do begin DefExtension := Copy(FileExtension, 2, Length(FileExtension) - 1); end; { with } OutputFileName := OutputFileName + DefExtension; end; { if } end; { else } end; { else } end; { else } if ssAllowCopies in SystemSetups then begin Val(CopiesED.Text, I1, ErrCode); if ErrCode = 0 then begin SystemPrinter.Copies := I1; end; { if } end; { if } if ssAllowCollate in SystemSetups then begin SystemPrinter.Collate := CollateCK.Checked; end; { if } if (ssAllowDuplex in SystemSetups) then begin if DuplexCK.Checked then begin if SystemPrinter.Duplex = dupSimplex then begin SystemPrinter.Duplex := dupVertical; end; { if } end else begin SystemPrinter.Duplex := dupSimplex; end; { else } end; { if } end; { with } end; procedure TdtSetupForm.GetRenderList; const DefOutputStr: array [0 .. 1] of string = ( { Trans+ } 'Rave Snapshot File (NDR)', { Trans+ } 'Native Printer Output (PRN)'); begin cboxFormat.Items.Clear; if Assigned(RpRender.RenderList) then begin RpRender.GetRenderList(cboxFormat.Items); end; { if } cboxFormat.Items.Insert(0, Trans(DefOutputStr[0])); cboxFormat.Items.Insert(1, Trans(DefOutputStr[1])); dlogSave.Filter := DefOutputStr[0] + { Trans- } '|*.NDR|' + DefOutputStr[1] + { Trans- } '|*.PRN'; if RpRender.GetRenderFilter <> '' then begin dlogSave.Filter := dlogSave.Filter + '|' + RpRender.GetRenderFilter; end; { if } end; procedure TdtSetupForm.editFileNameChange(Sender: TObject); begin bbtnOK.Enabled := Trim(editFileName.Text) <> ''; end; procedure TdtSetupForm.FormKeyPress(Sender: TObject; var Key: Char); var ValidKeys: string; begin ValidKeys := { Trans- } '0123456789'#8; if (Sender <> editFileName) and (Pos(Key, ValidKeys) <= 0) then begin Key := #0; end; end; procedure TdtSetupForm.SelectionEDKeyPress(Sender: TObject; var Key: Char); var ValidKeys: string; begin ValidKeys := { Trans- } '0123456789-,'#8; if (Sender <> editFileName) and (Pos(Key, ValidKeys) <= 0) then begin Key := #0; end; end; procedure TdtSetupForm.cboxFormatChange(Sender: TObject); begin dlogSave.FilterIndex := (Sender as TComboBox).ItemIndex + 1; end; end.
unit uClassConexaoBanco; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Comp.UI; type TConexao = class(TFDConnection) private oObjetoWaitCursor: TFDGUIxWaitCursor; oObjetoMysqlLink: TFDPhysMySQLDriverLink; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation { TConexao } constructor TConexao.Create(AOwner: TComponent); begin inherited; DriverName := 'MySQL'; Params.Database := 'Empreiteira'; Params.UserName := 'root'; Params.Password := ''; LoginPrompt := False; Connected := True; oObjetoWaitCursor := TFDGUIxWaitCursor.Create(nil); oObjetoMysqlLink := TFDPhysMySQLDriverLink.Create(nil); end; destructor TConexao.Destroy; begin if (Assigned(oObjetoWaitCursor)) then FreeAndNil(oObjetoWaitCursor); if (Assigned(oObjetoMysqlLink)) then FreeAndNil(oObjetoMysqlLink); inherited; end; end.
program ejercicio_4; { Escriba un programa que lea código, rubro y precio de productos de un supermercado e informe: - El código y precio de los dos productos mas caros. - La cantidad de productos cuyo código incluya al menos un 0. - Para cada código de producto, la cantidad de dígitos 5 que posee. - La cantidad de productos del rubro “Librería”. Nota: la lectura finaliza cuando se lee precio de producto 0. } {tipos de definidos por el usuario} type cadena = string[50]; {declaración de los procesos y/o funciones} {proceso que actualiza los máximos. En este caso se calculan dos máximos} procedure maximos(p: real; c: integer; var pm1, pm2: real; var cm1, cm2: integer); begin {se verifica si el precio recibido supera el primer máximo} if (p > pm1) then begin {se actualizan ambos máximos. Si es mayor al primero también es mayor al segundo} pm2 := pm1; pm1 := p; cm2 := cm1; cm1 := c; end else begin {se verifica si el precio supera el segundo máximo} if (p > pm2) then begin {se actualiza solamente el segundo máximo} pm2 := p; cm2 := c; end; end; end; {función que verifica si el código recibido contiene un dígito 0} function codigo_con_digito_cero(c: integer): boolean; begin {se utiliza la función MOD para quedarse con el dígito menos significativo y si es cero finaliza el while} while ((c MOD 10) <> 0) do {se utiliza DIV para cortar el número y descartar e dígito menos significativo} c := c DIV 10; {retorno de la función} codigo_con_digito_cero := (c > 0); end; {función que calcula la cantidad de digitos 5 que posee el codigo recibido} function cantidad_digitos_cinco(c: integer): integer; var cant_dig_cinco: integer; begin cant_dig_cinco := 0; while (c > 0) do begin {se utiliza la función MOD para quedarse con el dígito menos significativo y verificar si es un 5} if ((c MOD 10) = 5) then cant_dig_cinco := cant_dig_cinco + 1; {se utiliza DIV para cortar el número y descartar e dígito menos significativo} c := c DIV 10; end; {retorno de la función} cantidad_digitos_cinco := cant_dig_cinco; end; {variables del programa principal} var {variables de lectura de información} codigo: integer; precio: real; rubro: cadena; {variables para el calculo de ambos máximos} cod_max_1, cod_max_2: integer; precio_max_1, precio_max_2: real; {variable para la cantidad de productos que incluyen un 0} cant_prod_0: integer; {variable para la cantidad de productos con rubro Libreria} cant_rub_lib: integer; begin {se inicializan los máximos en 0, debido a que el 0 no es considerado un precio válido a procesar} precio_max_1 := 0; cod_max_1 := 0; {los contadores se inicializan en 0} cant_prod_0 := 0; cant_rub_lib := 0; {se inicia con la lectura de productos} write('- Precio: '); readln(precio); {se utiliza una estructura iterativa precondicional debido que no se conoce cuantos productos se van a leer} while (precio <> 0) do begin write('- Codigo: '); readln(codigo); write('- Rubro: '); readln(rubro); {se verifica si hay nuevos máximos} maximos(precio, codigo, precio_max_1, precio_max_2, cod_max_1, cod_max_2); {se verifica si el código contiene un 0} if (codigo_con_digito_cero(codigo)) then cant_prod_0 := cant_prod_0 + 1; {se calcula e imprime la cantidad de digitos 5 que posee cada producto. Es por cada producto} writeln; writeln('-- La cantidad de digitos 5 que posee el codigo es: ', cantidad_digitos_cinco(codigo)); {se verifica el rubro} if (rubro = 'Libreria') then cant_rub_lib := cant_rub_lib + 1; {se vuelve a leer el precio de otro producto} writeln; write('- Precio: '); readln(precio); end; writeln; writeln('---- Informes solicitados ----'); writeln; {verificamos que se han leídos productos y hay al menos un máximo} if (precio_max_1 > 0) then begin writeln('-- El codigo del produco mas caro es: ', cod_max_1, ' y el precio es: ', precio_max_1:0:2); writeln('-- El codigo del segundo producto mas caro es: ', cod_max_2, ' y el precio es: ', precio_max_2:0:2); end else writeln ('-- Los maximos no han sido actualizados'); writeln; writeln('-- La cantidad de productos que posee al menos un cero en su codigo es: ', cant_prod_0); writeln; writeln('-- La cantidad de productos del rubro Libreria es: ', cant_rub_lib); writeln; writeln('---- Presione entrar para finalizar ----'); readln; end.
(*Два сотрудника подали своему начальнику заявления на отпуск. Первый попросил отпустить его с A1 по B1 день (дни отсчитываются с начала года), второй - с A2 по B2 день (полагаем, что A1<B1 и A2<B2). Однако дело требует, чтобы кто-то из сотрудников находился на рабочем месте. Мало того, при смене отдыхающих необходимо не менее 3-х дней их совместной работы - для передачи дел. Напишите программу с процедурой, принимающей четыре указанных выше параметра, и печатающей заключение о том, удовлетворяют ли заявления работников требованиям начальника. *) var a1, b1, a2, b2 : integer; procedure Vacation(a1, b1, a2, b2 : integer); var ok: boolean; begin ok := false; if (a2 - b1) > 3 then ok := true else if (a1 - b2) > 3 then ok := true; if ok then Writeln('Разрешено') else Writeln('Не разрешено'); end; begin Write('Отпуск первого с-по: '); Readln(a1, b1); Write('Отпуск второго с-по: '); Readln(a2, b2); Vacation(a1, b1, a2, b2); end.
unit Repositorio.Interfaces.Base; interface uses EF.Mapping.Base, Context, FactoryEntity,DB; type IRepositoryBase<T:TEntitybase> = interface(IInterface) ['{5E02D175-02F4-4DA3-9201-AC1DEC6CA3C1}'] procedure RefreshDataSet; function LoadDataSet(iId:Integer; Fields: string = ''): TDataSet; function Load(iId: Integer = 0): T; procedure Delete; procedure AddOrUpdate( State: TEntityState); procedure Commit; function GetEntity: T; property Entity: T read GetEntity; function dbContext: TContext<T>; end; IRepository<T:TEntityBase> = interface(IInterface) ['{0CA799B5-84C6-49D5-8615-ED1278D3043A}'] procedure RefreshDataSet; function LoadDataSet(iId:Integer; Fields: string = ''): TDataSet; function Load(iId: Integer = 0): T; procedure Delete; procedure AddOrUpdate( State: TEntityState); procedure Commit; function GetEntity: T; function GetContext:TContext<T>; property Entity: T read GetEntity; property dbContext: TContext<T> read GetContext; end; implementation end.
unit UMaterialReport; interface uses Windows, SysUtils, Messages, Classes, Graphics, Controls, StdCtrls, ExtCtrls, Forms, Quickrpt, QRCtrls, tc; type TMaterialsReport = class(TQuickRep) QRBand1: TQRBand; QRLabel1: TQRLabel; QRLabel2: TQRLabel; QTime: TQRLabel; QMaterials: TQRLabel; QBunkersLine: TQRShape; QMaterialName: TQRLabel; QDone: TQRLabel; QCurAmount: TQRLabel; QRefusal: TQRLabel; public Model : TModel; procedure LoadFromModel; end; var MaterialsReport: TMaterialsReport; implementation const TOP_MATERIAL_MARGIN = 30; {$R *.DFM} { TMaterialReport } procedure TMaterialsReport.LoadFromModel; var i : integer; QMaterialName1, QDone1, QCurAmount1, QRefusal1 : TQRLabel; begin if not assigned(Model) then exit; QTime.Caption := Time2Works(Model.AllTime); with Model.Materials do for i := Low(List) to High(List) do begin QMaterialName1 := TQRLabel.Create(self); QDone1 := TQRLabel.Create(self); QCurAmount1 := TQRLabel.Create(self); QRefusal1 := TQRLabel.Create(self); QMaterialName1.Parent := MaterialsReport; QDone1.Parent := MaterialsReport; QCurAmount1.Parent := MaterialsReport; QRefusal1.Parent := MaterialsReport; QMaterialName1.AutoSize := false; QDone1.AutoSize := false; QCurAmount1.AutoSize := false; QRefusal1.AutoSize := false; QMaterialName1.Font.Name := 'MS Sans Serif'; QMaterialName1.Font.Size := 10; QDone1.Font.Name := 'MS Sans Serif'; QDone1.Font.Size := 10; QCurAmount1.Font.Name := 'MS Sans Serif'; QCurAmount1.Font.Size := 10; QRefusal1.Font.Name := 'MS Sans Serif'; QRefusal1.Font.Size := 10; QDone1.Alignment := taRightJustify; QCurAmount1.Alignment := taRightJustify; QRefusal1.Alignment := taRightJustify; QMaterialName1.Left := QMaterialName.Left; QDone1.Left := QDone.Left; QCurAmount1.Left := QCurAmount.Left; QRefusal1.Left := QRefusal.Left; QMaterialName1.width := QMaterialName.width; QDone1.width := QDone.width; QCurAmount1.width := QCurAmount.width; QRefusal1.width := QRefusal.width; QMaterialName1.top := QMaterialName.Top + i * TOP_MATERIAL_MARGIN + 60; QDone1.top := QDone.Top + i * TOP_MATERIAL_MARGIN + 60; QCurAmount1.top := QCurAmount.top + i * TOP_MATERIAL_MARGIN + 60; QRefusal1.top := QRefusal.top + i * TOP_MATERIAL_MARGIN + 60; QMaterialName1.Caption := (List[i] as TMaterial).Name; QDone1.Caption := Massa2Str((List[i] as TMaterial).Done); QCurAmount1.Caption := Massa2Str((List[i] as TMaterial).Queue); QRefusal1.Caption := Massa2Str((List[i] as TMaterial).AllRefusal); end; end; end.
unit UnitFindText; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, hrdTypes, BCEditor.Editor; type TFormFind = class(TForm) Panel1: TPanel; Label1: TLabel; Label2: TLabel; EditFind: TEdit; EditReplace: TEdit; RadioGroupDirection: TRadioGroup; ButtonFind: TButton; ButtonReplaceFind: TButton; ButtonClose: TButton; ButtonReplaceAll: TButton; procedure ButtonFindClick(Sender: TObject); procedure ButtonReplaceFindClick(Sender: TObject); procedure ButtonReplaceAllClick(Sender: TObject); procedure ButtonCloseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure EditReplaceEnter(Sender: TObject); procedure EditFindChange(Sender: TObject); procedure RadioGroupDirectionClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormFind: TFormFind; i : Integer; currentLine : integer; implementation {$R *.dfm} uses UnitCodeGenerator; procedure TFormFind.ButtonCloseClick(Sender: TObject); begin Self.Close; end; procedure TFormFind.ButtonFindClick(Sender: TObject); begin if i < 1 then begin Inc(i); with EZCodeGenerator.BCEditorCodePreview do begin Search.Enabled := True; Search.SearchText := EditFind.Text; Exit; end; end; if RadioGroupDirection.ItemIndex = 0 then begin EZCodeGenerator.BCEditorCodePreview.FindNext(true); currentLine := EZCodeGenerator.GetLineOfText(EZCodeGenerator.BCEditorCodePreview, EditFind.Text, currentLine+1); end else EZCodeGenerator.BCEditorCodePreview.FindPrevious(true); end; procedure TFormFind.ButtonReplaceAllClick(Sender: TObject); begin EZCodeGenerator.BCEditorCodePreview.ReplaceText(EditFind.Text, EditReplace.Text); end; procedure TFormFind.ButtonReplaceFindClick(Sender: TObject); begin try currentLine := EZCodeGenerator.GetLineOfText(EZCodeGenerator.BCEditorCodePreview, EditFind.Text, currentLine + 1); EZCodeGenerator.BCEditorCodePreview.GotoLineAndCenter(currentLine+1); EZCodeGenerator.BCEditorCodePreview.ReplaceLine(currentLine + 1, EZCodeGenerator.BCEditorCodePreview.Lines.GetLineText(currentLine).Replace(EditFind.Text, EditReplace.Text)); except on E: Exception do end; end; procedure TFormFind.EditFindChange(Sender: TObject); begin i := 0; currentLine := 0; end; procedure TFormFind.EditReplaceEnter(Sender: TObject); begin ButtonReplaceFind.Enabled := True; ButtonReplaceAll.Enabled := True; end; procedure TFormFind.FormCreate(Sender: TObject); begin ButtonReplaceFind.Enabled := False; ButtonReplaceAll.Enabled := false; end; procedure TFormFind.RadioGroupDirectionClick(Sender: TObject); begin if RadioGroupDirection.ItemIndex = 1 then ButtonReplaceFind.Enabled := False else ButtonReplaceFind.Enabled := True; end; end.
unit FadeEffect; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TFadeEffect = class private Masks: array [0..7] of hBrush; NegMasks: array [0..7] of hBrush; public constructor Create; destructor Destroy; override; procedure FadeInTo(Target: TCanvas; X, Y: integer; Pic: TBitmap); function FadeInText(Target: TCanvas; X, Y: integer; FText: String): TRect; procedure FadeOutText(Target: TCanvas; TarRect: TRect; Orig: TBitmap); procedure FadeOut(Target: TCanvas; TarRect: TRect; Orig: TBitmap); end; implementation {$R merge.res} constructor TFadeEffect.Create; var m: Integer; BrName: String[8]; lb: TLogBrush; bm, oldbm: HBitmap; mDC: HDC; R: TRect; begin mDC := CreateCompatibleDC(0); for m := 0 to 7 do begin BrName := 'merge' + IntToStr(m); BrName[7] := #0; bm := LoadBitmap(HInstance, @BrName[1]); lb.lbStyle := bs_Pattern; lb.lbHatch := bm; Masks[m] := CreateBrushIndirect(lb); R := Rect(0, 0, 8, 8); oldbm := SelectObject(mDC, bm); WinProcs.InvertRect(mDC, R); lb.lbHatch := bm; NegMasks[m] := CreateBrushIndirect(lb); SelectObject(mDC, oldbm); DeleteObject(bm); end; DeleteDC(mDC); end; destructor TFadeEffect.Destroy; var m: integer; begin for m := 0 to 7 do begin DeleteObject(Masks[m]); DeleteObject(NegMasks[m]); end; end; procedure TFadeEffect.FadeInTo(Target: TCanvas; X, Y: integer; Pic: TBitmap); var m: integer; memDC1, memDC2: hDC; memBM1, memBM2, oldBM1, oldBM2: hBitmap; oldB1, oldB2: hBrush; begin memDC1 := CreateCompatibleDC(Target.Handle); memBM1 := CreateCompatibleBitmap(Target.Handle, Pic.Width, Pic.Height); oldBM1 := SelectObject(memDC1, memBM1); BitBlt(memDC1, 0, 0, Pic.Width, Pic.Height, Target.Handle, X, Y, SrcCopy); oldB1 := Selectobject(memDC1, Masks[0]); memDC2 := CreateCompatibleDC(Target.Handle); memBM2 := CreateCompatibleBitmap(Target.Handle, Pic.Width, Pic.Height); oldBM2 := SelectObject(memDC2, memBM2); oldB2 := Selectobject(memDC2, NegMasks[0]); for m := 0 to 7 do begin SelectObject(memDC1, Masks[m]); BitBlt(memDC1, 0, 0, Pic.Width, Pic.Height, memDC1, 0, 0, MergeCopy); BitBlt(memDC2, 0, 0, Pic.Width, Pic.Height, Pic.Canvas.Handle, 0, 0, SrcCopy); SelectObject(memDC2, NegMasks[m]); BitBlt(memDC2, 0, 0, Pic.Width, Pic.Height, memDC2, 0, 0, MergeCopy); BitBlt(memDC1, 0, 0, Pic.Width, Pic.Height, memDC2, 0, 0, SrcPaint); BitBlt(Target.Handle, X, Y, Pic.Width, Pic.Height, memDC1, 0, 0, SrcCopy); end; SelectObject(memDC1, oldB1); SelectObject(memDC1, oldBM1); DeleteObject(memBM1); DeleteDC(memDC1); SelectObject(memDC2, oldB2); SelectObject(memDC2, oldBM2); DeleteObject(memBM2); DeleteDC(memDC2); Target.Draw(X, Y, Pic); end; function TFadeEffect.FadeInText(Target: TCanvas; X, Y: integer; FText: String): TRect; var Pic: TBitmap; W, H: integer; PicRect, TarRect: TRect; begin Pic := TBitmap.Create; Pic.Canvas.Font := Target.Font; W := Pic.Canvas.TextWidth(FText); H := Pic.Canvas.TextHeight(FText); Pic.Width := W; Pic.Height := H; PicRect := Rect(0, 0, W, H); TarRect := Rect(X, Y, X + W, Y + H); Pic.Canvas.CopyRect(PicRect, Target, TarRect); SetBkMode(Pic.Canvas.Handle, Transparent); Pic.Canvas.TextOut(0, 0, FText); FadeInto(Target, X, Y, Pic); Pic.Free; FadeInText := TarRect; end; procedure TFadeEffect.FadeOutText(Target: TCanvas; TarRect: TRect; Orig: TBitmap); var Pic: TBitmap; PicRect: TRect; begin Pic := TBitmap.Create; Pic.Width := TarRect.Right - TarRect.Left; Pic.Height := TarRect.Bottom - TarRect.Top; PicRect := Rect(0, 0, Pic.Width, Pic.Height); Pic.Canvas.CopyRect(PicRect, Orig.Canvas, TarRect); FadeInto(Target, TarRect.Left, TarRect.Top, Pic); Pic.Free; end; procedure TFadeEffect.FadeOut(Target: TCanvas; TarRect: TRect; Orig: TBitmap); var Pic: TBitmap; NewRect: TRect; begin Pic := TBitmap.Create; Pic.Width := TarRect.Right - TarRect.Left; Pic.Height := TarRect.Bottom - TarRect.Top; NewRect := Rect(0, 0, Pic.Width, Pic.Height); Pic.Canvas.CopyRect(NewRect, Orig.Canvas, TarRect); FadeInto(Target, TarRect.Left, TarRect.Top, Pic); Pic.Free; end; end.
{*********************************************************} {* OVCTHEMES.PAS 4.06 *} {*********************************************************} {* ***** BEGIN LICENSE BLOCK ***** *} {* Version: MPL 1.1 *} {* *} {* The contents of this file are subject to the Mozilla Public License *} {* Version 1.1 (the "License"); you may not use this file except in *} {* compliance with the License. You may obtain a copy of the License at *} {* http://www.mozilla.org/MPL/ *} {* *} {* Software distributed under the License is distributed on an "AS IS" basis, *} {* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *} {* for the specific language governing rights and limitations under the *} {* License. *} {* *} {* The Original Code is TurboPower Orpheus *} {* *} {* The Initial Developer of the Original Code is TurboPower Software *} {* *} {* Portions created by TurboPower Software Inc. are Copyright (C)1995-2002 *} {* TurboPower Software Inc. All Rights Reserved. *} {* *} {* Contributor(s): *} {* *} {* ***** END LICENSE BLOCK ***** *} unit ovcThemes; {$I OVC.INC} interface uses Windows, Graphics; type TovcThemes = class(TObject) class procedure DrawSelection(Canvas: TCanvas; ARect: TRect); end; implementation {$IFDEF VERSION2010} uses SysUtils, Themes, UxTheme; {$ENDIF} { TovcThemes } class procedure TovcThemes.DrawSelection(Canvas: TCanvas; ARect: TRect); {$IFDEF VERSION2010} var LTheme: HTHEME; LRect, Rect2: TRect; BRC: TBrushRecall; {$ENDIF VERSION2010} begin {$IFDEF VERSION2010} if ThemeServices.ThemesEnabled and (Win32MajorVersion >= 6) and (Canvas.Brush.Color = clHighLight) then begin BRC := TBrushRecall.Create(Canvas.Brush); try Canvas.Brush.Color := clWindow; LRect := ARect; Rect2 := ARect; LTheme := ThemeServices.Theme[teMenu]; DrawThemeBackground(LTheme, Canvas.Handle, MENU_POPUPITEM, MPI_HOT, LRect, @Rect2); finally BRC.Free; end; end else {$ENDIF VERSION2010} Canvas.FillRect(ARect); end; end.
unit TypeWorkPoster; interface uses PersistentObjects, DBGate, BaseObjects, DB, TypeWork, MeasureUnits; type TStateWorkDataPoster = class(TImplementedDataPoster) private FAllTypeWorks: TTypeWorks; procedure SetAllTypeWorks(const Value: TTypeWorks); public property AllTypeWorks: TTypeWorks read FAllTypeWorks write SetAllTypeWorks; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TTypeWorkDataPoster = class (TImplementedDataPoster) private FAllMeasureUnits: TMeasureUnits; procedure SetAllMeasureUnits(const Value: TMeasureUnits); public property AllMeasureUnits: TMeasureUnits read FAllMeasureUnits write SetAllMeasureUnits; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; implementation uses Facade, SysUtils; { TStateWorkDataPoster } constructor TStateWorkDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_STATE_WORKS_DICT'; KeyFieldNames := 'ID_STATE_WORK'; FieldNames := 'ID_STATE_WORK, ID_TYPE_WORKS, VCH_STATE_WORK_NAME'; AccessoryFieldNames := 'ID_STATE_WORK, ID_TYPE_WORKS, VCH_STATE_WORK_NAME'; AutoFillDates := false; Sort := 'VCH_STATE_WORK_NAME'; end; function TStateWorkDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TStateWorkDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TStateWork; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TStateWork; o.ID := ds.FieldByName('ID_STATE_WORK').AsInteger; o.Name := trim(ds.FieldByName('VCH_STATE_WORK_NAME').AsString); ds.Next; end; ds.First; end; end; function TStateWorkDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; o: TStateWork; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); o := TStateWork(AObject); ds.FieldByName('ID_STATE_WORK').AsInteger := o.ID; if Assigned (o.Owner) then ds.FieldByName('ID_TYPE_WORKS').AsInteger := o.Owner.ID; ds.FieldByName('VCH_STATE_WORK_NAME').AsString := trim(o.Name); ds.Post; if o.ID <= 0 then o.ID := (ds as TCommonServerDataSet).CurrentRecordFilterValues[0]; end; procedure TStateWorkDataPoster.SetAllTypeWorks(const Value: TTypeWorks); begin if FAllTypeWorks <> Value then FAllTypeWorks := Value; end; { TTypeWorkDataPoster } constructor TTypeWorkDataPoster.Create; begin inherited; Options := [soSingleDataSource]; DataSourceString := 'TBL_TYPE_WORKS_DICT'; //DataPostString := 'SPD_ADD_TYPE_WORK_PLAN_GRR'; //DataDeletionString := 'TBL_TYPE_WORKS_DICT'; KeyFieldNames := 'ID_TYPE_WORKS'; FieldNames := 'ID_TYPE_WORKS, NUMBER_COLUMN, MEASURE_UNIT_ID, VCH_WORK_TYPE_NAME, ID_PARENT_WORK_TYPE'; AccessoryFieldNames := 'ID_TYPE_WORKS, NUMBER_COLUMN, MEASURE_UNIT_ID, VCH_WORK_TYPE_NAME, ID_PARENT_WORK_TYPE'; AutoFillDates := false; Sort := 'NUMBER_COLUMN'; end; function TTypeWorkDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin // если не будет внешнего ключа, то удалять сначала из таблицы с состояниями работ Result := inherited DeleteFromDB(AObject, ACollection); end; function TTypeWorkDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TTypeWork; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TTypeWork; o.ID := ds.FieldByName('ID_TYPE_WORKS').AsInteger; o.Name := trim(ds.FieldByName('VCH_WORK_TYPE_NAME').AsString); o.MeasureUnit := FAllMeasureUnits.ItemsByID[ds.FieldByName('MEASURE_UNIT_ID').AsInteger] as TMeasureUnit; o.NumberPP := ds.FieldByName('NUMBER_COLUMN').AsInteger; if Assigned (o.Owner) then o.Level := (o.Owner as TTypeWork).Level + 1; ds.Next; end; ds.First; end; end; function TTypeWorkDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; o: TTypeWork; begin Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName); Result := 0; try ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Active then ds.Open; o := AObject as TTypeWork; if ds.Locate('ID_TYPE_WORKS', o.Owner.ID, []) then ds.Edit else ds.Append; ds.FieldByName('ID_TYPE_WORKS').AsInteger := o.ID; ds.FieldByName('NUMBER_COLUMN').AsInteger := o.NumberPP; if Assigned (o.MeasureUnit) then ds.FieldByName('MEASURE_UNIT_ID').AsInteger := o.MeasureUnit.ID; ds.FieldByName('VCH_WORK_TYPE_NAME').AsString := trim (o.Name); if Assigned (o.Owner) then ds.FieldByName('ID_PARENT_WORK_TYPE').AsInteger := o.Owner.ID; ds.Post; except on E: Exception do begin raise; end; end; end; procedure TTypeWorkDataPoster.SetAllMeasureUnits( const Value: TMeasureUnits); begin if FAllMeasureUnits <> Value then FAllMeasureUnits := Value; end; end.
{$include kode.inc} unit fx_grains; // crashes reaper instantly.. //{$define KODE_MAX_GRAINS := 1024} //{$define KODE_BUFFERSIZE := 1024*1024} //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_const, kode_types, kode_plugin; const KODE_MAX_GRAINS = 1024; KODE_BUFFERSIZE = 1024*1024; type KGrain = record _on : boolean; _pos : single; _sta : single; _end : single; _dur : single; _spd : single; _ph : single; _pa : single; _dh : single; _da : single; end; //---------- myPlugin = class(KPlugin) private FGrains : array[0..KODE_MAX_GRAINS-1] of KGrain; FBuffer : array[0..KODE_BUFFERSIZE-1] of Single; master : single; numgrains : longint; buffersize : longint; freeze : boolean; graindist : single; grainsize : single; graindur : single; grainpitch : single; grainenv : single; startjit : single; pitchjit : single; sizejit : single; durjit : single; index : longint; countdown : single; public procedure on_create; override; procedure on_parameterChange(AIndex:LongWord; AValue:Single); override; procedure on_processSample(AInputs,AOutputs:PPSingle); override; end; KPluginClass = myPlugin; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses _plugin_id, Math, kode_flags, kode_parameter, kode_random, kode_rect, kode_utils; //---------- procedure myPlugin.on_create; begin FName := 'fx_grains'; FAuthor := 'skei_audio'; FProduct := FName; FVersion := 0; FUniqueId := KODE_MAGIC + fx_grains_id; FNumInputs := 2; FNumOutputs := 2; //FEditorRect := rect(400,400); KSetFlag(FFlags,kpf_perSample{+kpf_receiveMidi}{+kpf_hasEditor}); // master := 0; numgrains := 0; buffersize := 0; freeze := false; graindist := 0; grainsize := 0; graindur := 0; grainpitch := 0; grainenv := 0; startjit := 0; pitchjit := 0; sizejit := 0; durjit := 0; // appendParameter( KParamFloat.create( 'master (db)', -6, -60, 6 )); appendParameter( KParamInt.create( 'num grains', 10, 1, 100 )); appendParameter( KParamFloat.create( 'buf size (ms)', 1000, 1, 1000 )); appendParameter( KParamFloat.create( 'freeze', 0 )); // text appendParameter( KParamFloat.create( 'grain dist (ms)', 20, 0, 100 )); appendParameter( KParamFloat.create( 'grain size (ms)', 30, 1, 100 )); appendParameter( KParamFloat.create( 'grain dur (ms)', 300, 1, 1000 )); appendParameter( KParamFloat.create( 'grain pitch', 1, 0, 10 )); appendParameter( KParamFloat.create( 'grain env', 0 )); appendParameter( KParamFloat.create( 'dist jitter', 0.2 )); appendParameter( KParamFloat.create( 'pitch jutter', 0.2 )); appendParameter( KParamFloat.create( 'size jitter', 0.2 )); appendParameter( KParamFloat.create( 'dur jitter', 0.2 )); // index := 0; countdown := 0; end; //---------- procedure myPlugin.on_parameterChange(AIndex:LongWord; AValue:Single); begin case AIndex of 0: master := power(2,(AValue/6)); 1: numgrains := trunc( AValue ); 2: buffersize := trunc( (AValue/1000) * FSampleRate ); 3: if AValue > 0.5 then freeze := True else freeze := false; 4: graindist := (AValue/1000) * FSampleRate; 5: grainsize := (AValue/1000) * FSampleRate; 6: graindur := (AValue/1000) * FSampleRate; 7: grainpitch := AValue; 8: grainenv := AValue; 9: startjit := AValue; 10: pitchjit := AValue; 11: sizejit := AValue; 12: durjit := AValue; end; end; //---------- procedure myPlugin.on_processSample(AInputs,AOutputs:PPSingle); var i:longint; spl0,spl1 : single; in0,in1 : single; out0,out1 : single; newgrain : longint; gvol : single; dvol : single; startrnd : single; pitchrnd : single; sizernd : single; durrnd : single; siz,st,en,du : single; temp : longint; begin spl0 := AInputs[0]^; spl1 := AInputs[1]^; in0 := spl0; in1 := spl1; out0 := 0; out1 := 0; newgrain := -1; if numgrains > 0 then begin for i := 0 to numgrains-1 do begin if (FGrains[i]._on) then begin FGrains[i]._pos += FGrains[i]._spd; if FGrains[i]._pos >= FGrains[i]._end then FGrains[i]._pos := FGrains[i]._sta; if FGrains[i]._pos >= buffersize then FGrains[i]._pos -= buffersize; FGrains[i]._ph += (FGrains[i]._pa*2); if FGrains[i]._ph >= 2 then FGrains[i]._ph -= 2; FGrains[i]._dh += (FGrains[i]._da*2); if FGrains[i]._dh >=2 then FGrains[i]._dh -= 2; FGrains[i]._dur -= 1; if FGrains[i]._dur <= 0 then FGrains[i]._on := false; gvol := FGrains[i]._ph * (2-abs(FGrains[i]._ph)); // abs-neg ? dvol := FGrains[i]._dh * (2-abs(FGrains[i]._dh)); temp := trunc( FGrains[i]._pos ); temp *= 2; out0 += FBuffer[ temp ] * dvol * gvol; out1 += FBuffer[ temp+1 ] * dvol * gvol; end else newgrain := i; end; end; if countdown <= 0 then begin countdown := graindist; if newgrain > 0 then begin startrnd := 1 + (startjit * KRandomSigned); pitchrnd := 1 + (pitchjit * KRandomSigned); sizernd := 1 + (sizejit * KRandomSigned); durrnd := 1 + (durjit * KRandomSigned); siz := (grainsize*sizernd); st := index * startrnd; if st >= buffersize then st -= buffersize; if st < 0 then st += buffersize; en := st + siz; if en >= buffersize then en := buffersize; // clamp if en < 0 then en := 0; du := graindur*durrnd; FGrains[newgrain]._on := true; FGrains[newgrain]._pos := st; FGrains[newgrain]._sta := st; FGrains[newgrain]._end := en; FGrains[newgrain]._dur := du; FGrains[newgrain]._spd := grainpitch * pitchrnd; FGrains[newgrain]._ph := 0; FGrains[newgrain]._pa := 1 / siz; FGrains[newgrain]._dh := 0; FGrains[newgrain]._da := 1 / du; end; end; countdown -= 1; if not freeze then begin FBuffer[index*2] := in0; FBuffer[index*2+1] := in1; end; index += 1; if index >= buffersize then index -= buffersize; spl0 := out0 * master; spl1 := out1 * master; AOutputs[0]^ := spl0; AOutputs[1]^ := spl1; end; //---------------------------------------------------------------------- end.
unit PascalCoin.RPC.Block; interface uses System.Generics.Collections, System.JSON, PascalCoin.RPC.Interfaces; type TPascalCoinBlock = class(TInterfacedObject, IPascalCoinBlock) private Fblock: Integer; Fenc_pubkey: String; Freward: Currency; Freward_s: string; Ffee: Currency; Ffee_s: String; Fver: Integer; Fver_a: Integer; Ftimestamp: Integer; Ftarget: Integer; Fnonce: Integer; Fpayload: String; Fsbh: String; Foph: String; Fpow: String; Foperations: Integer; Fhashratekhs: Integer; Fmaturation: Integer; protected function GetBlock: Integer; function GetEnc_PubKey: String; function GetFee: Currency; function GetFee_s: String; function GetHashRateKHS: Integer; function GetMaturation: Integer; function GetNonce: Integer; function GetOperations: Integer; function GetOPH: String; function GetPayload: String; function GetPOW: String; function GetReward: Currency; function GetReward_s: String; function GetSBH: String; function GetTarget: Integer; function GetTimeStamp: Integer; function GetVer: Integer; function GetVer_a: Integer; function GetTimeStampAsDateTime: TDateTime; public end; TPascalCoinBlocks = Class(TInterfacedObject, IPascalCoinBlocks) private {TDictionary blockNum, BlockInfo ?} FBlocks: TArray<IPascalCoinBlock>; protected Function GetBlock(Const Index: integer): IPascalCoinBlock; Function GetBlockNumber(Const Index: integer): IPascalCoinBlock; Function Count: integer; public class function FromJsonValue(ABlocks: TJSONArray): TPascalCoinBlocks; End; implementation uses System.DateUtils, Rest.Json; { TPascalCoinBlock } function TPascalCoinBlock.GetBlock: Integer; begin result := Fblock; end; function TPascalCoinBlock.GetTimeStampAsDateTime: TDateTime; begin result := UnixToDateTime(Ftimestamp); end; function TPascalCoinBlock.GetEnc_PubKey: String; begin result := Fenc_pubkey; end; function TPascalCoinBlock.GetFee: Currency; begin result := Ffee; end; function TPascalCoinBlock.GetFee_s: String; begin result := FFee_s; end; function TPascalCoinBlock.GetHashRateKHS: Integer; begin result := Fhashratekhs; end; function TPascalCoinBlock.GetMaturation: Integer; begin result := Fmaturation; end; function TPascalCoinBlock.GetNonce: Integer; begin result := Fnonce; end; function TPascalCoinBlock.GetOperations: Integer; begin result := Foperations; end; function TPascalCoinBlock.GetOPH: String; begin result := Foph; end; function TPascalCoinBlock.GetPayload: String; begin result := Fpayload; end; function TPascalCoinBlock.GetPOW: String; begin result := Fpow; end; function TPascalCoinBlock.GetReward: Currency; begin result := Freward; end; function TPascalCoinBlock.GetReward_s: String; begin result := FReward_s; end; function TPascalCoinBlock.GetSBH: String; begin result := Fsbh; end; function TPascalCoinBlock.GetTarget: Integer; begin result := Ftarget; end; function TPascalCoinBlock.GetTimeStamp: Integer; begin result := Ftimestamp; end; function TPascalCoinBlock.GetVer: Integer; begin result := Fver; end; function TPascalCoinBlock.GetVer_a: Integer; begin result := Fver_a; end; { TPascalCoinBlocks } function TPascalCoinBlocks.Count: integer; begin Result := Length(FBlocks); end; class function TPascalCoinBlocks.FromJsonValue(ABlocks: TJSONArray): TPascalCoinBlocks; var I: Integer; begin Result := TPascalCoinBlocks.Create; SetLength(Result.FBlocks, ABlocks.Count); for I := 0 to ABlocks.Count - 1 do begin Result.FBlocks[I] := TJSON.JsonToObject<TPascalCoinBlock>(ABlocks[I] As TJSONObject); end; end; function TPascalCoinBlocks.GetBlock(const Index: integer): IPascalCoinBlock; begin Result := FBlocks[Index]; end; function TPascalCoinBlocks.GetBlockNumber(const Index: integer): IPascalCoinBlock; var lBlock: IPascalCoinBlock; begin Result := Nil; for lBlock in FBlocks do begin if lBlock.block = Index then Exit(lBlock); end; end; end.
program Server; {$I mormot.defines.inc} uses {$I mormot.uses.inc} opensslsockets, SysUtils, mormot.core.log, mormot.net.ws.core, mormot.core.text, Classes, SharedInterface, ServerUnit; var Server: TServer; HeaptraceFile: String; begin {$IF DECLARED(heaptrc)} HeaptraceFile := ExtractFileDir(ParamStr(0)) + PathDelim + 'heaptrace.log'; if FileExists(HeaptraceFile) then DeleteFile(HeaptraceFile); SetHeapTraceOutput(HeaptraceFile); {$ENDIF} with TSynLog.Family do begin // enable logging to file and to console Level := LOG_VERBOSE; EchoToConsole := LOG_VERBOSE; PerThreadLog := ptIdentifiedInOnFile; end; WebSocketLog := TSynLog; // verbose log of all WebSockets activity try Server := TServer.Create; try Server.Run; finally Server.Free; end; except on E: Exception do ConsoleShowFatalException(E); end; end.
unit ServerModule; interface uses Classes, SysUtils, uniGUIServer, uniGUIMainModule, uniGUIApplication, uIdCustomHTTPServer, uniGUITypes; type TUniServerModule = class(TUniGUIServerModule) procedure UniGUIServerModuleCreate(Sender: TObject); private { Private declarations } protected procedure FirstInit; override; public { Public declarations } end; function UniServerModule: TUniServerModule; implementation {$R *.dfm} uses UniGUIVars; function UniServerModule: TUniServerModule; begin Result := TUniServerModule(UniGUIServerInstance); end; procedure TUniServerModule.FirstInit; begin InitServerModule(Self); end; procedure TUniServerModule.UniGUIServerModuleCreate(Sender: TObject); begin MimeTable.AddMimeType('xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', False); // correct place to initialize global FormatSettings parameters PFmtSettings.DateSeparator := '/'; PFmtSettings.CurrencyFormat := 0; PFmtSettings.CurrencyString := '$'; PFmtSettings.ShortDateFormat := 'dd/mm/yyyy'; end; initialization RegisterServerModuleClass(TUniServerModule); end.
unit UConflict; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls, UDB, sqldb, UQueryBuild, UMetaData, UFieldCard, UNotification, db; type TConflictType = (ctGroupMultipleLessons, ctGroupMultipleClassrooms, ctGroupMultipleTeacher, ctTeacherMultipleClassrooms, ctClassroomOverflow); TConflictRecord = record FFields: TStringList; FID: Integer; end; TConflictSet = record FConflictRecords: array of TConflictRecord; FConflictType: TConflictType; end; TConflictRecords = array of TConflictRecord; TConflictSets = array of TConflictSet; Integers = array of Integer; TMultiplicity = array of Integer; { TConlfictsForm } TConlfictsForm = class(TForm) TreeView: TTreeView; procedure FormCreate(Sender: TObject); procedure TreeViewDblClick(Sender: TObject); private FRecordsInConflic:TConflictRecords; FConflictSets: TConflictSets; public procedure FillTree; function CreateConfclitRecord(AStrL: TStringList; AType: TConflictType): TConflictRecord; procedure RecalculateConficts; procedure AddConflictNode(var i: Integer; AType: TConflictType; ARootNode: TTreeNode; ACaption: String); function FindeRootNode(ACaption: String):TTreeNode; function GetRecordText(index: integer): String; function GetRecordText(index: integer; indexes: array of integer): String; function GetFieldIndex(AField: String): Integer; procedure CalculateConflict(AType: TConflictType; AEQParam, AUnEQParam: array of string); procedure CalculateClassroomOverflowConflict; function CreateConflictRecordFromQuery(ABegin: Integer; AQuery: TSQLQuery): TConflictRecord; end; var ConlfictsForm: TConlfictsForm; implementation {$R *.lfm} { TConlfictsForm } procedure TConlfictsForm.FormCreate(Sender: TObject); begin CalculateConflict(ctGroupMultipleLessons, ['GROUP_ID', 'WEEKDAY_ID','LESSON_TIME_ID'], ['LESSON_ID']); CalculateConflict(ctGroupMultipleClassrooms, ['GROUP_ID', 'WEEKDAY_ID','LESSON_TIME_ID'], ['CLASSROOM_ID']); CalculateConflict(ctGroupMultipleTeacher, ['GROUP_ID', 'WEEKDAY_ID','LESSON_TIME_ID'], ['TEACHER_ID']); CalculateConflict(ctTeacherMultipleClassrooms, ['TEACHER_ID', 'WEEKDAY_ID','LESSON_TIME_ID'], ['CLASSROOM_ID']); CalculateClassroomOverflowConflict; FillTree; end; procedure TConlfictsForm.TreeViewDblClick(Sender: TObject); var id: Integer; c: TCardForm; begin if TreeView.Selected = Nil then exit; if TreeView.Selected.Data = Nil then exit; id := PInteger(TreeView.Selected.Data)^; if not (Notifier.isCardOpened(High(MetaData.FTables), id)) then begin; c := TCardForm.Create(Self, id, High(MetaData.FTables)); Notifier.RegisterCard(High(MetaData.FTables), id, @c.BringCardToFront); c.Show; end; end; function TConlfictsForm.CreateConfclitRecord(AStrL: TStringList; AType: TConflictType): TConflictRecord; var i: Integer; begin Result.FID := StrToInt(AStrL[0]); Result.FFields := TStringList.Create; Result.FFields.Clear; for i := 1 to AStrL.Count - 1 do Result.FFields.Append(AStrL[i]); end; procedure TConlfictsForm.RecalculateConficts; begin CalculateConflict(ctGroupMultipleLessons, ['GROUP_ID', 'WEEKDAY_ID','LESSON_TIME_ID'], ['LESSON_ID']); CalculateConflict(ctGroupMultipleClassrooms, ['GROUP_ID', 'WEEKDAY_ID','LESSON_TIME_ID'], ['CLASSROOM_ID']); CalculateConflict(ctGroupMultipleTeacher, ['GROUP_ID', 'WEEKDAY_ID','LESSON_TIME_ID'], ['TEACHER_ID']); CalculateConflict(ctTeacherMultipleClassrooms, ['TEACHER_ID', 'WEEKDAY_ID','LESSON_TIME_ID'], ['CLASSROOM_ID']); end; procedure TConlfictsForm.FillTree; var RN, CurCf, CurCFRecords: TTreeNode; i, j, k: Integer; begin RN := TreeView.Items.AddObject(nil, 'Conflicts', nil); i := 0; AddConflictNode(i, ctGroupMultipleLessons, RN, 'Group Mult Lessons'); AddConflictNode(i, ctGroupMultipleClassrooms, RN, 'Group Mult Classrooms'); AddConflictNode(i, ctGroupMultipleTeacher, RN, 'Group Mult Teachers'); AddConflictNode(i, ctTeacherMultipleClassrooms, RN, 'Teacher Mult Classrooms'); AddConflictNode(i, ctClassroomOverflow, RN, 'Classroom Overflow'); end; procedure TConlfictsForm.AddConflictNode(var i: Integer; AType: TConflictType; ARootNode: TTreeNode; ACaption: String); var CurCF, curConflictSet: TTreeNode; s: array of array of string; recordCaptions: array of string; commonInd, ids: Integers; conflictSetCaption: string; j, k: integer; begin CurCf := TreeView.Items.AddChildObject(ARootNode, ACaption, Nil); conflictSetCaption := ''; while ((i < Length(FConflictSets)) and (FConflictSets[i].FConflictType = AType)) do with FConflictSets[i] do begin SetLength(commonInd, FConflictRecords[0].FFields.Count); SetLength(s, Length(FConflictRecords)); SetLength(recordCaptions, Length(s)); SetLength(ids, Length(FConflictRecords)); for j := 0 to High(FConflictRecords) do begin SetLength(s[j], FConflictRecords[j].FFields.Count); for k := 0 to FConflictRecords[j].FFields.Count - 1 do begin if ((j + 1) < Length(FConflictRecords)) then if (FConflictRecords[j].FFields[k] <> FConflictRecords[j + 1].FFields[k]) then commonInd[k] := -1; s[j][k] += FConflictRecords[j].FFields[k] + ' '; end; ids[j] := FConflictRecords[j].FID; end; for j := 0 to FConflictRecords[0].FFields.Count - 1 do if commonInd[j] <> -1 then conflictSetCaption += FConflictRecords[0].FFields[j] + ' '; curConflictSet := TreeView.Items.AddChildObject(curCf, conflictSetCaption, TObject(ids)); for j := 0 to High(s) do for k := 0 to High(s[j]) do if commonInd[k] = -1 then recordCaptions[j] += s[j][k] + ' '; j := 0; for j := 0 to High(FConflictRecords) do TreeView.Items.AddChildObject(curConflictSet, recordCaptions[j], @FConflictRecords[j].FID); SetLength(commonInd, 0); SetLength(s, 0); SetLength(ids, 0); SetLength(recordCaptions, 0); conflictSetCaption := ''; inc(i); end; end; function TConlfictsForm.FindeRootNode(ACaption: String): TTreeNode; var LCount: Integer; begin result := nil; LCount := 0; while (LCount < TreeView.Items.Count) and (result = nil) do begin if (TreeView.Items.Item[LCount].Text = ACaption) and (TreeView.Items.Item[LCount].Parent = nil) then result := TreeView.Items.Item[LCount]; inc(LCount); end; end; function TConlfictsForm.GetRecordText(index: integer): String; var i: Integer; sl: TStringList; begin Result := ''; sl := FRecordsInConflic[index].FFields; for i := 0 to sl.Count - 1 do Result += sl[i] + ' '; end; function TConlfictsForm.GetRecordText(index: integer; indexes: array of integer ): String; var i, j: Integer; sl: TStringList; b: Boolean; begin Result := ''; sl := FRecordsInConflic[index].FFields; for i := 0 to sl.Count - 1 do begin for j := 0 to High(indexes) do if (i = indexes[j]) then begin b := False; Break; end else b := True; if b then Result += sl[i] + ' '; end; end; function TConlfictsForm.GetFieldIndex(AField: String): Integer; var i, tmp: integer; t: TTable; begin Result := 0; t := MetaData.FTables[High(MetaData.FTables)]; for i := 0 to High(t.FFields) do begin tmp := t.FFields[i].FRefTableInd; if tmp = -1 then begin Result += 1; Continue; end; if t.FFields[i].FRealName = AField then Break; Result += MetaData.FTables[t.FFields[i].FRefTableInd].FFieldCount - 1; end; end; procedure TConlfictsForm.CalculateConflict(AType: TConflictType; AEQParam, AUnEQParam: array of string); var q, qpred: TSQLQuery; i, j, k, bgn, lengthEQ, lengthUnEQ, last, cfstcount: Integer; s, tmp, paramList: String; f: array of TField; isConflict, isCurrentSet: Boolean; pred: TConflictRecord; begin cfstcount:= 0; paramList := ''; q := TSQLQuery.Create(Self); q.DataBase := DataModule1.IBConnection1; tmp := BuildSelectPart(High(MetaData.FTables)); Delete(tmp, 1, 7); for i := 0 to High(AEQParam) do paramList += 'TIMETABLE.' + AEQParam[i] + ', '; for i := 0 to High(AUnEQParam) do paramList += 'TIMETABLE.' + AUnEQParam[i] + ', '; Delete(paramList, Length(paramList) - 1, 2); s := ' SELECT '; s += paramList + ', ' + tmp + ' ORDER BY ' + paramList; q.SQL.Text := s; q.SQL.SaveToFile('newcf.txt'); q.Open; qpred := TSQLQuery.Create(Self); qpred.DataBase := DataModule1.IBConnection1; qpred.SQL.Text := s; qpred.Open; lengthEQ := Length(AEQParam); lengthUnEQ := Length(AUnEQParam); SetLength(f, lengthEQ + lengthUnEQ); for i := 0 to High(AEQParam) do f[i] := qpred.FieldByName(AEQParam[i]); for i := i + 1 to lengthUnEQ - 1 + lengthEQ do f[i] := qpred.FieldByName(AUnEQParam[i - lengthEQ]); pred := CreateConflictRecordFromQuery(lengthEQ + lengthUnEQ, q); isCurrentSet := False; q.Next; while (not(q.EOF)) do begin isConflict := True; for i := 0 to lengthEQ - 1 do if f[i].AsInteger <> q.FieldByName(AEQParam[i]).AsInteger then begin isCurrentSet := False; isConflict := False; break; end; if isConflict then for i := i + 1 to lengthUnEQ - 1 + lengthEQ do if f[i].AsInteger = q.FieldByName(AUnEQParam[i - lengthEQ]).AsInteger then begin isConflict := False; break; end; if isConflict then if isCurrentSet then begin with FConflictSets[High(FConflictSets)] do begin SetLength(FConflictRecords, Length(FConflictRecords) + 1); last := High(FConflictRecords); FConflictRecords[last] := CreateConflictRecordFromQuery(lengthEQ + lengthUnEQ, q); pred := FConflictRecords[last]; end; end else begin SetLength(FConflictSets, Length(FConflictSets) + 1); with FConflictSets[High(FConflictSets)] do begin SetLength(FConflictRecords, 2); FConflictRecords[0] := pred; FConflictRecords[1] := CreateConflictRecordFromQuery(lengthEQ + lengthUnEQ, q); pred := FConflictRecords[1]; FConflictType := AType; isCurrentSet := True; inc(cfstcount); end; end; qpred.Next; for i := 0 to High(AEQParam) do f[i] := qpred.FieldByName(AEQParam[i]); for i := i + 1 to lengthUnEQ - 1 + lengthEQ do f[i] := qpred.FieldByName(AUnEQParam[i - lengthEQ]); if not(isConflict) then pred := CreateConflictRecordFromQuery(lengthEQ + lengthUnEQ, q); q.Next; end; q.Free; qpred.Free; end; procedure TConlfictsForm.CalculateClassroomOverflowConflict; var q, qpred: TSQLQuery; i, j, k, sum, last, cfCount: Integer; s: array of array of string; tmp, orderList: string; paramList: array[0..2] of string; pred: array [0..2] of integer; str: string; isCurrentSet, isConflict: Boolean; begin orderList := ''; cfCount := 1; isCurrentSet := False; q := TSQLQuery.Create(Self); q.DataBase := DataModule1.IBConnection1; qpred := TSQLQuery.Create(Self); qpred.DataBase := DataModule1.IBConnection1; tmp := BuildSelectPart(High(MetaData.FTables)); Delete(tmp, 1, 7); paramList[0] := 'LESSON_ID'; paramList[1] := 'WEEKDAY_ID'; paramList[2] := 'LESSON_TIME_ID'; for i := 0 to High(paramList) do orderList += 'TIMETABLE.' + paramList[i] + ', '; str := 'SELECT ' + orderList + tmp + ' ORDER BY ' + orderList; Delete(str, Length(str) - 1, 2); q.SQL.Text := str; qpred.SQL.Text := str; q.SQL.SaveToFile('str.txt'); q.Open; qpred.Open; for i := 0 to High(pred) do pred[i] := qpred.FieldByName(paramList[i]).AsInteger; sum := qpred.FieldByName('STUDENT_NUMBER').AsInteger; q.Next; while (not(q.EOF)) do begin isConflict := True; for i := 0 to High(pred) do if (pred[i] <> q.FieldByName(paramList[i]).AsInteger) then begin isConflict := False; isCurrentSet := False; Break; end; if isConflict then begin sum += q.FieldByName('STUDENT_NUMBER').AsInteger; Inc(cfCount); if (isCurrentSet) then with FConflictSets[High(FConflictSets)] do begin SetLength(FConflictRecords, Length(FConflictRecords) + 1); last := High(FConflictRecords); FConflictRecords[last] := CreateConflictRecordFromQuery(Length(pred), q); end else begin SetLength(FConflictSets, Length(FConflictSets) + 1); with FConflictSets[High(FConflictSets)] do begin SetLength(FConflictRecords, 2); FConflictRecords[0] := CreateConflictRecordFromQuery(Length(pred), qpred); FConflictRecords[1] := CreateConflictRecordFromQuery(Length(pred), q); FConflictType := ctClassroomOverflow; isCurrentSet := True; end; end; end else begin if cfCount > 1 then begin if (sum < qpred.FieldByName('CAPACITY').AsInteger) then SetLength(FConflictSets, Length(FConflictSets) - 1); cfCount := 1; sum := q.FieldByName('STUDENT_NUMBER').AsInteger; end else begin SetLength(FConflictSets, Length(FConflictSets) + 1); if (sum > qpred.FieldByName('CAPACITY').AsInteger) then with FConflictSets[High(FConflictSets)] do begin SetLength(FConflictRecords, 1); FConflictRecords[0] := CreateConflictRecordFromQuery(Length(pred), qpred); FConflictType := ctClassroomOverflow; end; sum := q.FieldByName('STUDENT_NUMBER').AsInteger; end; end; qpred.Next; for i := 0 to High(pred) do pred[i] := qpred.FieldByName(paramList[i]).AsInteger; q.Next; end; qpred.Free; q.Free; end; function TConlfictsForm.CreateConflictRecordFromQuery(ABegin: Integer; AQuery: TSQLQuery): TConflictRecord; var i: Integer; begin Result.FID := AQuery.FieldByName(AQuery.FieldDefs.Items[ABegin].DisplayName).AsInteger; Result.FFields := TStringList.Create; Result.FFields.Clear; inc(ABegin); for i := ABegin to AQuery.FieldCount - 1 do Result.FFields.Append(AQuery.FieldByName(AQuery.FieldDefs.Items[i].DisplayName).AsString); end; end.
{ //BUT:Cette algo doit afficher les deux triangles en appelant leurs procédures. //ENTREE:1 entier //SORTIE:Les deux triangles PROGRAMME Double Triangle CONST MaxTriangle2 = 10 Type MatriceXO = Tableau [1..MaxTriangle1,1..MaxTriangle1] de CAR MatriceChiffre = Tableau [1..MaxTriangle2,1..MaxTriangle2] de ENTIER Procédure Triangle XO(VAR T1:MatriceXO); VAR i,j:ENTIER car:=CAR DEBUT POUR i ALLANT DE 1 A MaxTriangle1 FAIRE POUR j ALLANT DE 1 A MaxTriangle1 FAIRE SI i=j OU i=-j ALORS T1[i,j] <- X SINON SI i=MaxTriangle1 ALORS T1[i,MaxTriangle1] <- X SINON T1[i,j] <- O FINSI FINSI FINPOUR FINPOUR FINPOUR FINPOUR } Program Trianglex2; uses crt; const MaxTriangle2 = 10; Type MatriceXO = array [1..10,1..10] of char; MatriceChiffre = array [1..MaxTriangle2,1..MaxTriangle2] of integer; var T1:MatriceXO; T2:MatriceChiffre; i,j:integer; car:char; procedure TriangleXO(var T1:MatriceXO); BEGIN For i:=1 to 10 do begin For j:=1 to 10 do begin if (i=j) or (i=-j) then T1[i,j]:='X'; if j<i then T1[i,j]:='O'; T1[i,1]:='X'; T1[10,j]:='X'; write(T1[i,j]) end; writeln; end; END; Procedure TriangleChiffre(var T2:MatriceChiffre); var compteur:integer; BEGIN compteur:=0; For i:=1 to MaxTriangle2 do begin for j:=1 to MaxTriangle2 -i+1 do begin T2[i,j]:=compteur; write(T2[i,j]); compteur:=compteur+1; end; writeln; end; readln END; //PROG PRINCIPAL BEGIN clrscr; TriangleXO(T1); readln; TriangleChiffre(T2); readln; END.
unit PascalCoin.RPC.Account; interface uses System.Generics.Collections, PascalCoin.RPC.Interfaces; type TPascalCoinAccount = Class(TInterfacedObject, IPascalCoinAccount) private FAccount: Int64; Fenc_pubkey: HexaStr; FBalance: Currency; FBalance_s: String; FN_Operation: Integer; FUpdated_b: Integer; FUpdated_b_active_mode: Integer; FUpdated_b_passive_Mode: Integer; FState: string; FLocked_Until_Block: Integer; FPrice: Currency; FSeller_Account: Integer; FPrivate_Sale: Boolean; FNew_Enc_PubKey: HexaStr; FName: String; FAccountType: Integer; FSeal: String; FData: TAccountData; protected function GetAccount: Int64; function GetPubKey: HexaStr; function GetBalance: Currency; function GetN_Operation: Integer; function GetUpdated_b: Integer; function GetState: String; function GetLocked_Until_Block: Integer; function GetPrice: Currency; function GetSeller_Account: Integer; function GetPrivate_Sale: Boolean; function GetNew_Enc_PubKey: HexaStr; function GetName: String; function GetAccount_Type: Integer; Function GetBalance_s: String; Function GetUpdated_b_active_mode: Integer; Function GetUpdated_b_passive_mode: Integer; Function GetSeal: String; Function GetData: TAccountData; function SameAs(AAccount: IPascalCoinAccount): Boolean; procedure Assign(AAccount: IPascalCoinAccount); public End; TPascalCoinAccounts = class(TInterfacedObject, IPascalCoinAccounts) private { Use TList as simpler to add to than a TArray } { TODO : Maybe switch to TDictionary } FAccounts: TList<IPascalCoinAccount>; protected function GetAccount(const Index: Integer): IPascalCoinAccount; function FindAccount(const Value: Integer): IPascalCoinAccount; overload; function FindAccount(const Value: String): IPascalCoinAccount; overload; Function FindNamedAccount(Const Value: String): IPascalCoinAccount; function Count: Integer; procedure Clear; function AddAccount(Value: IPascalCoinAccount): Integer; public constructor Create; destructor Destroy; override; end; implementation uses System.SysUtils; { TPascalCoinAccount } procedure TPascalCoinAccount.Assign(AAccount: IPascalCoinAccount); begin FAccount := AAccount.account; Fenc_pubkey := AAccount.enc_pubkey; FBalance := AAccount.balance; FBalance_s := AAccount.balance_s; FN_Operation := AAccount.n_operation; FUpdated_b := AAccount.updated_b; FUpdated_b_active_mode := AAccount.updated_b_active_mode; FUpdated_b_passive_Mode := AAccount.updated_b_passive_mode; FState := AAccount.state; FLocked_Until_Block := AAccount.locked_until_block; FPrice := AAccount.price; FSeller_Account := AAccount.seller_account; FPrivate_Sale := AAccount.private_sale; FNew_Enc_PubKey := AAccount.new_enc_pubkey; FName := AAccount.name; FAccountType := AAccount.account_type; FSeal := AAccount.Seal; FData := AAccount.Data; end; function TPascalCoinAccount.GetAccount: Int64; begin result := FAccount; end; function TPascalCoinAccount.GetAccount_Type: Integer; begin result := FAccountType; end; function TPascalCoinAccount.GetBalance: Currency; begin result := FBalance; end; function TPascalCoinAccount.GetBalance_s: String; begin Result := FBalance_s; end; function TPascalCoinAccount.GetData: TAccountData; begin Result := FData; end; function TPascalCoinAccount.GetLocked_Until_Block: Integer; begin result := FLocked_Until_Block; end; function TPascalCoinAccount.GetName: String; begin result := FName; end; function TPascalCoinAccount.GetNew_Enc_PubKey: String; begin result := FNew_Enc_PubKey; end; function TPascalCoinAccount.GetN_Operation: Integer; begin result := FN_Operation; end; function TPascalCoinAccount.GetPrice: Currency; begin result := FPrice; end; function TPascalCoinAccount.GetPrivate_Sale: Boolean; begin result := FPrivate_Sale; end; function TPascalCoinAccount.GetPubKey: String; begin result := Fenc_pubkey; end; function TPascalCoinAccount.GetSeal: String; begin Result := FSeal; end; function TPascalCoinAccount.GetSeller_Account: Integer; begin result := FSeller_Account; end; function TPascalCoinAccount.GetState: String; begin result := FState; end; function TPascalCoinAccount.GetUpdated_b: Integer; begin result := FUpdated_b; end; function TPascalCoinAccount.GetUpdated_b_active_mode: Integer; begin Result := FUpdated_b_active_mode; end; function TPascalCoinAccount.GetUpdated_b_passive_mode: Integer; begin Result := FUpdated_b_passive_Mode; end; function TPascalCoinAccount.SameAs(AAccount: IPascalCoinAccount): Boolean; begin result := (FAccount = AAccount.account) and (Fenc_pubkey = AAccount.enc_pubkey) and (FBalance = AAccount.balance) and (FN_Operation = AAccount.n_operation) and (FUpdated_b = AAccount.updated_b) and (FState = AAccount.state) and (FLocked_Until_Block = AAccount.locked_until_block) and (FPrice = AAccount.price) and (FSeller_Account = AAccount.seller_account) and (FPrivate_Sale = AAccount.private_sale) and (FNew_Enc_PubKey = AAccount.new_enc_pubkey) and (FName = AAccount.name) and (FAccountType = AAccount.account_type); end; { TPascalCoinAccounts } function TPascalCoinAccounts.AddAccount(Value: IPascalCoinAccount): Integer; begin result := FAccounts.Add(Value); end; procedure TPascalCoinAccounts.Clear; begin FAccounts.Clear; end; function TPascalCoinAccounts.Count: Integer; begin result := FAccounts.Count; end; constructor TPascalCoinAccounts.Create; begin inherited Create; FAccounts := TList<IPascalCoinAccount>.Create; end; destructor TPascalCoinAccounts.Destroy; begin FAccounts.Free; inherited; end; function TPascalCoinAccounts.FindAccount(const Value: String) : IPascalCoinAccount; var lPos, lValue: Integer; begin lPos := Value.IndexOf('-'); if lPos > -1 then lValue := Value.Substring(0, lPos).ToInteger else lValue := Value.ToInteger; result := FindAccount(lValue); end; function TPascalCoinAccounts.FindNamedAccount(const Value: String): IPascalCoinAccount; var lAccount: IPascalCoinAccount; begin result := nil; for lAccount in FAccounts do if SameText(lAccount.Name, Value) then Exit(lAccount); end; function TPascalCoinAccounts.FindAccount(const Value: Integer) : IPascalCoinAccount; var lAccount: IPascalCoinAccount; begin result := nil; for lAccount in FAccounts do if lAccount.Account = Value then Exit(lAccount); end; function TPascalCoinAccounts.GetAccount(const Index: Integer) : IPascalCoinAccount; begin result := FAccounts[Index]; end; end.
unit LuaMemoryRecord; {$mode delphi} interface uses Classes, SysUtils, MemoryRecordUnit, plugin, pluginexports, lua, lualib, lauxlib, LuaHandler, LuaCaller, CEFuncProc, ComCtrls, Graphics, commonTypeDefs; procedure initializeLuaMemoryRecord; implementation uses luaclass, LuaObject; function memoryrecord_getOffsetCount(L: PLUA_State): integer; cdecl; var memrec: TMemoryRecord; begin memrec:=luaclass_getClassObject(L); lua_pushinteger(L, memrec.offsetCount); result:=1; end; function memoryrecord_setOffsetCount(L: PLUA_State): integer; cdecl; var memrec: TMemoryRecord; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)=1 then memrec.offsetCount:=lua_tointeger(L, 1); end; function memoryrecord_getOffset(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; index: integer; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)=1 then begin index:=lua_toInteger(L,1); lua_pushinteger(L, memrec.offsets[index].offset); result:=1; end; end; function memoryrecord_setOffset(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; index: integer; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)=2 then begin index:=lua_toInteger(L,1); memrec.offsets[index].offset:=lua_tointeger(L, 2); end; end; function memoryrecord_getOffsetText(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; index: integer; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)=1 then begin index:=lua_toInteger(L,1); lua_pushstring(L, memrec.offsets[index].offsetText); result:=1; end; end; function memoryrecord_setOffsetText(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; index: integer; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)=2 then begin index:=lua_toInteger(L,1); memrec.offsets[index].offsetText:=Lua_ToString(L, 2); end; end; function memoryrecord_getDropDownValue(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; index: integer; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)=1 then begin index:=lua_toInteger(L,1); lua_pushstring(L, memrec.DropDownValue[index]); result:=1; end; end; function memoryrecord_getDropDownDescription(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; index: integer; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)=1 then begin index:=lua_toInteger(L,1); lua_pushstring(L, memrec.DropDownDescription[index]); result:=1; end; end; function memoryrecord_getchild(L: PLUA_State): integer; cdecl; var memrec: TMemoryRecord; index: integer; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)=1 then begin index:=lua_toInteger(L,1); luaclass_newClass(L, memrec.Child[index]); result:=1; end; end; function memoryrecord_setDescription(L: PLUA_State): integer; cdecl; var memrec: TMemoryRecord; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then memrec.Description:=lua_tostring(L,-1); //description end; function memoryrecord_getDescription(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; begin memrec:=luaclass_getClassObject(L); lua_pushstring(L, memrec.Description); result:=1; end; function memoryrecord_getCurrentAddress(L: PLua_state): integer; cdecl; var memrec: tmemoryrecord; begin memrec:=luaclass_getClassObject(L); lua_pushinteger(L, memrec.GetRealAddress); result:=1; end; function memoryrecord_getAddress(L: PLua_state): integer; cdecl; var memrec: tmemoryrecord; i: integer; tabletop: integer; begin memrec:=luaclass_getClassObject(L); lua_pushstring(L, memrec.interpretableaddress); result:=1; if memrec.isPointer then begin lua_newtable(L); tabletop:=lua_gettop(L); for i:=0 to memrec.offsetCount-1 do begin lua_pushinteger(L,i+1); lua_pushinteger(L, memrec.offsets[i].offset); lua_settable(L, tabletop); end; result:=2; end; end; function memoryrecord_setAddress(L: PLua_state): integer; cdecl; var memrec: tmemoryrecord; i: integer; tabletop: integer; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin //address if lua_type(L,1)=LUA_TNUMBER then memrec.interpretableaddress:=inttohex(lua_tointeger(L,1),8) else memrec.interpretableaddress:=Lua_ToString(L, 1); memrec.ReinterpretAddress(true); memrec.offsetCount:=0; if lua_gettop(L)>=2 then begin //table if lua_istable(L,2) then begin i:=lua_objlen(L,2); if i>512 then exit; //FY memrec.offsetCount:=i; for i:=0 to memrec.offsetCount-1 do begin lua_pushinteger(L, i+1); //get the offset lua_gettable(L, 2); //from the table (table[i+1]) memrec.offsets[i].offset:=lua_tointeger(L,-1); lua_pop(L,1); end; end; end; end; end; function memoryrecord_getAddressOld(L: PLua_state): integer; cdecl; var parameters: integer; memrec: pointer; address: ptruint; offsets: array of dword; offsetcount: integer; i: integer; tabletop: integer; begin result:=0; offsetcount:=0; setlength(offsets,0); parameters:=lua_gettop(L); if parameters=1 then begin memrec:=lua_toceuserdata(L,-1); lua_pop(L, parameters); if ce_memrec_getAddress(memrec, @address, nil, 0, @offsetcount) then begin lua_pushinteger(L,address); result:=1; if offsetcount>0 then begin //pointer, return a secondary result (table) which contains the baseaddress and offsets setlength(offsets,offsetcount); ce_memrec_getAddress(memrec, @address, @offsets[0], length(offsets), @offsetcount); lua_newtable(L); tabletop:=lua_gettop(L); lua_pushinteger(L,1); //index lua_pushinteger(L, TMemoryRecord(memrec).getBaseAddress); //value lua_settable(L, tabletop); for i:=0 to offsetcount-1 do begin lua_pushinteger(L, i+2); lua_pushinteger(L, offsets[i]); lua_settable(L, tabletop); end; inc(result,1); //add the table as a result end; end; end else lua_pop(L, parameters); end; function memoryrecord_setAddressOld(L: PLua_State): integer; cdecl; var memrec: pointer; parameters: integer; address: pchar; s: string; offsets: array of dword; i,j: integer; begin result:=0; parameters:=lua_gettop(L); if parameters>=2 then begin memrec:=lua_toceuserdata(L, (-parameters)); if lua_isstring(L, (-parameters)+1) then address:=lua.lua_tostring(L, (-parameters)+1) else //convert it to a hexadecimal value first begin s:=inttohex(lua_tointeger(L, (-parameters)+1),8); address:=pchar(s); end; setlength(offsets,parameters-2); j:=0; for i:=(-parameters)+2 to -1 do begin offsets[j]:=lua_tointeger(L, i); inc(j); end; lua_pop(L, parameters); ce_memrec_setAddress(memrec, address, @offsets[0], length(offsets)) end else lua_pop(L, parameters); end; function memoryrecord_getType(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; begin memrec:=luaclass_getClassObject(L); lua_pushinteger(L, integer(memrec.VarType)); result:=1; end; function memoryrecord_setType(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then memrec.VarType:=TVariableType(lua_tointeger(L, -1)) ; end; function memoryrecord_getValue(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; begin memrec:=luaclass_getClassObject(L); lua_pushstring(L, memrec.Value); result:=1; end; function memoryrecord_setValue(L: PLUA_State): integer; cdecl; var memrec: TMemoryRecord; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then memrec.Value:=lua_tostring(L,-1); end; function memoryrecord_getNumericalValue(L: PLua_State): integer; cdecl; var r: string; memrec: TMemoryRecord; vi64: qword; vd: double; validinteger: boolean; validdouble: boolean; begin result:=0; memrec:=luaclass_getClassObject(L); r:=memrec.Value; if memrec.ShowAsHex then r:=r+'$'; try vi64:=strtoint64(r); validinteger:=true; except validinteger:=false; end; if memrec.ShowAsHex then begin if validinteger then begin //convert floats to numbers case memrec.VarType of vtSingle: begin vd:=psingle(@vi64)^; lua_pushnumber(L,vd); exit(1); end; vtDouble: begin vd:=pdouble(@vi64)^; lua_pushnumber(L,vd); exit(1); end; vtCustom: begin if memrec.CustomType.scriptUsesFloat then begin vd:=psingle(@vi64)^; lua_pushnumber(L,vd); exit(1); end else begin lua_pushnumber(L,vi64); exit(1); end; end; else begin lua_pushnumber(L,vi64); //the hexadecimal integer is good enough exit(1); end; end; end else exit(0); //show as hex and could not be parsed. Unreadable end else begin //not shown as hex. if (memrec.VarType in [vtSingle, vtDouble, vtCustom]) and ((memrec.vartype<>vtCustom) or memrec.CustomType.scriptUsesFloat) then begin try vd:=StrToFloat(r); lua_pushnumber(L,vd); exit(1); except exit(0); end; end; //still here, so a normal integer type if validinteger then begin lua_pushinteger(L,vi64); exit(1); end; //else not a valid integer, or float, so bug out with nil end; end; function memoryrecord_setNumericalValue(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; vs: string; vd: double; vi64: qword absolute vd; vsi64: int64 absolute vd; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin if (memrec.VarType in [vtSingle, vtDouble, vtCustom]) and ((memrec.vartype<>vtCustom) or memrec.CustomType.scriptUsesFloat) then vd:=lua_tonumber(L,1) else vi64:=lua_tointeger(L,1); if memrec.ShowAsHex then memrec.value:=IntToHex(vi64,1) else begin if (memrec.VarType in [vtSingle, vtDouble, vtCustom]) and ((memrec.vartype<>vtCustom) or memrec.CustomType.scriptUsesFloat) then memrec.value:=FloatToStr(vd) else begin if memrec.ShowAsSigned then memrec.value:=IntToStr(vsi64) else memrec.value:=IntToStr(vi64); end; end; end; end; function memoryrecord_getScript(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; begin memrec:=luaclass_getClassObject(L); if memrec.AutoAssemblerData.script<>nil then begin lua_pushstring(L, memrec.AutoAssemblerData.script.Text); result:=1; end else result:=0; end; function memoryrecord_setScript(L: PLUA_State): integer; cdecl; var memrec: TMemoryRecord; begin result:=0; memrec:=luaclass_getClassObject(L); if (lua_gettop(L)>=1) and (memrec.AutoAssemblerData.script<>nil) then memrec.AutoAssemblerData.script.Text:=lua_tostring(L,-1); end; function memoryrecord_isSelected(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; begin memrec:=luaclass_getClassObject(L); lua_pushboolean(L, memrec.isSelected); result:=1; end; function memoryrecord_disableWithoutExecute(L: PLua_State): integer; cdecl; begin result:=0; TMemoryRecord(luaclass_getClassObject(L)).disablewithoutexecute; end; function memoryrecord_setActive(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; begin result:=0; memrec:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then memrec.active:=lua_toboolean(L, 1); end; function memoryrecord_getActive(L: PLua_State): integer; cdecl; var memrec: TMemoryRecord; begin memrec:=luaclass_getClassObject(L); lua_pushboolean(L, memrec.Active); result:=1; end; function memoryrecord_freeze(L: PLua_State): integer; cdecl; var memrec: pointer; parameters: integer; direction: integer; begin result:=0; parameters:=lua_gettop(L); if parameters>=1 then begin memrec:=lua_toceuserdata(L, -parameters); if parameters=2 then direction:=lua_tointeger(L, -1) else direction:=0; ce_memrec_freeze(memrec, direction); end; lua_pop(L, parameters); end; function memoryrecord_unfreeze(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; direction: integer; begin result:=0; memoryrecord:=luaclass_getClassObject(L); memoryrecord.Active:=false; end; function memoryrecord_setColor(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; color: integer; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin color:=lua_tointeger(L,-1); memoryrecord.Color:=tcolor(color); end; end; function memoryrecord_appendToEntry(L: PLua_State): integer; cdecl; var memrec1,memrec2: TMemoryRecord; parameters: integer; begin result:=0; memrec1:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin memrec2:=lua_toceuserdata(L,-1); memrec1.treenode.MoveTo(memrec2.treenode, naAddChild); memrec2.SetVisibleChildrenState; end; end; function memoryrecord_delete(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin result:=0; memoryrecord:=luaclass_getClassObject(L); memoryrecord.free; end; function memoryrecord_reinterpretAddress(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin result:=0; memoryrecord:=luaclass_getClassObject(L); memoryrecord.ReinterpretAddress(true); end; function memoryrecord_getID(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin memoryrecord:=luaclass_getClassObject(L); lua_pushinteger(L, memoryrecord.id); result:=1; end; function memoryrecord_createHotkey(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; hk: TMemoryRecordHotkey; keys: TKeyCombo; action: TMemrecHotkeyAction; value, description: string; i: integer; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=2 then begin if (not lua_istable(L, 1)) or (not lua_isnumber(L, 2)) then exit(0); for i:=0 to 4 do begin lua_pushinteger(L, i+1); lua_gettable(L, 1); if lua_isnil(L, -1) then //end of the list begin keys[i]:=0; lua_pop(L,1); break; end else begin keys[i]:=lua_tointeger(L,-1); lua_pop(L,1); end; end; action:=TMemrecHotkeyAction(lua_tointeger(L, 2)); if lua_gettop(L)>=3 then value:=Lua_ToString(L, 3) else value:=''; if lua_gettop(L)>=4 then description:=Lua_ToString(L, 4) else description:=''; hk:=memoryrecord.Addhotkey(keys, action, value, description); result:=1; luaclass_newClass(L, hk); end; end; function memoryrecord_getHotkeyCount(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin memoryrecord:=luaclass_getClassObject(L); lua_pushinteger(L, memoryrecord.HotkeyCount); result:=1; end; function memoryrecord_getHotkey(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; index: integer; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin index:=lua_tointeger(L,-1); luaclass_newClass(L, memoryrecord.Hotkey[index]); result:=1; end; end; function memoryrecord_getHotkeyByID(L: PLua_State): integer; cdecl; var parameters: integer; memoryrecord: Tmemoryrecord; id: integer; i: integer; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin id:=lua_tointeger(L,-1); for i:=0 to memoryrecord.Hotkeycount-1 do if memoryrecord.Hotkey[i].id=id then begin luaclass_newClass(L, memoryrecord.Hotkey[i]); result:=1; exit; end; end; end; function memoryrecord_string_getSize(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin memoryrecord:=luaclass_getClassObject(L); lua_pushinteger(L, memoryrecord.Extra.stringData.length); result:=1; end; function memoryrecord_string_setSize(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then memoryrecord.Extra.stringData.length:=lua_tointeger(L, -1); end; function memoryrecord_string_getUnicode(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin memoryrecord:=luaclass_getClassObject(L); lua_pushboolean(L, memoryrecord.Extra.stringData.unicode); result:=1; end; function memoryrecord_string_setUnicode(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then memoryrecord.Extra.stringData.unicode:=lua_toboolean(L, -1); if memoryrecord.Extra.stringData.Unicode then memoryrecord.Extra.stringData.codepage:=false; end; function memoryrecord_string_getCodePage(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin memoryrecord:=luaclass_getClassObject(L); lua_pushboolean(L, memoryrecord.Extra.stringData.CodePage); result:=1; end; function memoryrecord_string_setCodePage(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then memoryrecord.Extra.stringData.CodePage:=lua_toboolean(L, -1); if memoryrecord.Extra.stringData.CodePage then memoryrecord.Extra.stringData.unicode:=false; end; function memoryrecord_binary_getStartbit(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin memoryrecord:=luaclass_getClassObject(L); lua_pushinteger(L, memoryrecord.Extra.bitData.bit); result:=1; end; function memoryrecord_binary_setStartbit(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then memoryrecord.Extra.bitData.bit:=lua_tointeger(L, -1); end; function memoryrecord_binary_getSize(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin memoryrecord:=luaclass_getClassObject(L); lua_pushinteger(L, memoryrecord.Extra.bitData.bitlength); result:=1; end; function memoryrecord_binary_setSize(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then memoryrecord.Extra.bitData.bitlength:=lua_tointeger(L, -1); end; function memoryrecord_aob_getSize(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin memoryrecord:=luaclass_getClassObject(L); lua_pushinteger(L, memoryrecord.Extra.byteData.bytelength); result:=1; end; function memoryrecord_aob_setSize(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then memoryrecord.Extra.byteData.bytelength:=lua_tointeger(L, -1); end; function memoryrecord_onActivate(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; f: integer; routine: string; lc: TLuaCaller; // clickroutine: integer; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin CleanupLuaCall(tmethod(memoryrecord.onActivate)); memoryrecord.onActivate:=nil; if lua_isfunction(L,-1) then begin routine:=Lua_ToString(L,-1); f:=luaL_ref(L,LUA_REGISTRYINDEX); lc:=TLuaCaller.create; lc.luaroutineIndex:=f; memoryrecord.onActivate:=lc.MemoryRecordActivateEvent; end else if lua_isstring(L,-1) then begin routine:=lua_tostring(L,-1); lc:=TLuaCaller.create; lc.luaroutine:=routine; memoryrecord.onActivate:=lc.MemoryRecordActivateEvent; end; end; end; function memoryrecord_onDeactivate(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; f: integer; routine: string; lc: TLuaCaller; // clickroutine: integer; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin CleanupLuaCall(tmethod(memoryrecord.onDeactivate)); memoryrecord.onDeactivate:=nil; if lua_isfunction(L,-1) then begin routine:=Lua_ToString(L,-1); f:=luaL_ref(L,LUA_REGISTRYINDEX); lc:=TLuaCaller.create; lc.luaroutineIndex:=f; memoryrecord.onDeactivate:=lc.MemoryRecordActivateEvent; end else if lua_isstring(L,-1) then begin routine:=lua_tostring(L,-1); lc:=TLuaCaller.create; lc.luaroutine:=routine; memoryrecord.onDeactivate:=lc.MemoryRecordActivateEvent; end; end; end; function memoryrecord_onDestroy(L: PLua_State): integer; cdecl; var memoryrecord: Tmemoryrecord; f: integer; routine: string; lc: TLuaCaller; // clickroutine: integer; begin result:=0; memoryrecord:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin CleanupLuaCall(tmethod(memoryrecord.onDestroy)); memoryrecord.onDestroy:=nil; if lua_isfunction(L,-1) then begin routine:=Lua_ToString(L,-1); f:=luaL_ref(L,LUA_REGISTRYINDEX); lc:=TLuaCaller.create; lc.luaroutineIndex:=f; memoryrecord.onDestroy:=lc.NotifyEvent; end else if lua_isstring(L,-1) then begin routine:=lua_tostring(L,-1); lc:=TLuaCaller.create; lc.luaroutine:=routine; memoryrecord.onDestroy:=lc.NotifyEvent; end; end; end; function memoryrecord_beginEdit(L: PLua_State): integer; cdecl; begin TMemoryRecord(luaclass_getClassObject(L)).beginEdit; exit(0); end; function memoryrecord_endEdit(L: PLua_State): integer; cdecl; begin TMemoryRecord(luaclass_getClassObject(L)).endEdit; exit(0); end; procedure memoryrecord_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); var recordEntry: TRecordEntry; recordentries: TRecordEntries; begin object_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setDescription', memoryrecord_setDescription); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getDescription', memoryrecord_getDescription); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getAddress', memoryrecord_getAddress); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setAddress', memoryrecord_setAddress); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getOffsetCount', memoryrecord_getOffsetCount); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setOffsetCount', memoryrecord_setOffsetCount); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getOffset', memoryrecord_getOffset); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setOffset', memoryrecord_setOffset); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getCurrentAddress', memoryrecord_getCurrentAddress); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getType', memoryrecord_getType); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setType', memoryrecord_setType); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getValue', memoryrecord_getValue); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setValue', memoryrecord_setValue); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getScript', memoryrecord_getScript); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setScript', memoryrecord_setScript); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getActive', memoryrecord_getActive); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setActive', memoryrecord_setActive); luaclass_addClassFunctionToTable(L, metatable, userdata, 'disableWithoutExecute', memoryrecord_disableWithoutExecute); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getChild', memoryrecord_getChild); luaclass_addClassFunctionToTable(L, metatable, userdata, 'isSelected', memoryrecord_isSelected); luaclass_addClassFunctionToTable(L, metatable, userdata, 'appendToEntry', memoryrecord_appendToEntry); luaclass_addClassFunctionToTable(L, metatable, userdata, 'delete', memoryrecord_delete); luaclass_addClassFunctionToTable(L, metatable, userdata, 'reinterpret', memoryrecord_reinterpretAddress); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getHotkeyCount', memoryrecord_getHotkeyCount); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getHotkey', memoryrecord_getHotkey); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getHotkeyByID', memoryrecord_getHotkeyByID); luaclass_addClassFunctionToTable(L, metatable, userdata, 'createHotkey', memoryrecord_createHotkey); luaclass_addClassFunctionToTable(L, metatable, userdata, 'beginEdit', memoryrecord_beginEdit); luaclass_addClassFunctionToTable(L, metatable, userdata, 'endEdit', memoryrecord_endEdit); luaclass_addPropertyToTable(L, metatable, userdata, 'Description', memoryrecord_getDescription, memoryrecord_setDescription); luaclass_addPropertyToTable(L, metatable, userdata, 'Address', memoryrecord_getAddress, memoryrecord_setAddress); luaclass_addPropertyToTable(L, metatable, userdata, 'CurrentAddress', memoryrecord_getCurrentAddress, nil); luaclass_addPropertyToTable(L, metatable, userdata, 'Type', memoryrecord_getType, memoryrecord_setType); luaclass_addPropertyToTable(L, metatable, userdata, 'Value', memoryrecord_getValue, memoryrecord_setValue); luaclass_addPropertyToTable(L, metatable, userdata, 'NumericalValue', memoryrecord_getNumericalValue, memoryrecord_setNumericalValue); luaclass_addPropertyToTable(L, metatable, userdata, 'Script', memoryrecord_getScript, memoryrecord_setScript); luaclass_addPropertyToTable(L, metatable, userdata, 'Active', memoryrecord_getActive, memoryrecord_setActive); luaclass_addPropertyToTable(L, metatable, userdata, 'Selected', memoryrecord_isSelected, nil); luaclass_addPropertyToTable(L, metatable, userdata, 'HotkeyCount', memoryrecord_getHotkeyCount, nil); luaclass_addArrayPropertyToTable(L, metatable, userdata, 'Hotkey', memoryrecord_getHotkey); luaclass_addPropertyToTable(L, metatable, userdata, 'OffsetCount', memoryrecord_getOffsetCount, memoryrecord_setOffsetCount); luaclass_addArrayPropertyToTable(L, metatable, userdata, 'Offset', memoryrecord_getOffset, memoryrecord_setOffset); luaclass_addArrayPropertyToTable(L, metatable, userdata, 'OffsetText', memoryrecord_getOffsetText, memoryrecord_setOffsetText); luaclass_addArrayPropertyToTable(L, metatable, userdata, 'DropDownValue', memoryrecord_getDropDownValue, nil); luaclass_addArrayPropertyToTable(L, metatable, userdata, 'DropDownDescription', memoryrecord_getDropDownDescription, nil); luaclass_addPropertyToTable(L, metatable, userdata, 'Active', memoryrecord_getActive, memoryrecord_setActive); recordEntries:=Trecordentries.create; recordEntry.name:='Size'; recordEntry.getf:=memoryrecord_string_getSize; recordEntry.setf:=memoryrecord_string_setSize; recordEntries.add(recordEntry); recordEntry.name:='Unicode'; recordEntry.getf:=memoryrecord_string_getUnicode; recordEntry.setf:=memoryrecord_string_setUnicode; recordEntries.add(recordEntry); recordEntry.name:='Codepage'; recordEntry.getf:=memoryrecord_string_getCodepage; recordEntry.setf:=memoryrecord_string_setCodepage; recordEntries.add(recordEntry); luaclass_addRecordPropertyToTable(L, metatable, userdata, 'String', recordEntries); recordEntries.clear; recordEntry.name:='Startbit'; recordEntry.getf:=memoryrecord_binary_getStartbit; recordEntry.setf:=memoryrecord_binary_setStartbit; recordEntries.add(recordEntry); recordEntry.name:='Size'; recordEntry.getf:=memoryrecord_binary_getSize; recordEntry.setf:=memoryrecord_binary_setSize; recordEntries.add(recordEntry); luaclass_addRecordPropertyToTable(L, metatable, userdata, 'Binary', recordEntries); recordEntries.clear; recordEntry.name:='Size'; recordEntry.getf:=memoryrecord_aob_getSize; recordEntry.setf:=memoryrecord_aob_setSize; recordEntries.add(recordEntry); luaclass_addRecordPropertyToTable(L, metatable, userdata, 'Aob', recordEntries); recordEntries.free; luaclass_addArrayPropertyToTable(L, metatable, userdata, 'Child', memoryrecord_getchild, nil); luaclass_setDefaultArrayProperty(L, metatable, userdata, memoryrecord_getchild, nil); end; procedure initializeLuaMemoryRecord; begin lua_register(LuaVM, 'memoryrecord_setDescription', memoryrecord_setDescription); lua_register(LuaVM, 'memoryrecord_getDescription', memoryrecord_getDescription); lua_register(LuaVM, 'memoryrecord_getAddress', memoryrecord_getAddressOld); lua_register(LuaVM, 'memoryrecord_setAddress', memoryrecord_setAddressOld); lua_register(LuaVM, 'memoryrecord_getType', memoryrecord_getType); lua_register(LuaVM, 'memoryrecord_setType', memoryrecord_setType); lua_register(LuaVM, 'memoryrecord_getValue', memoryrecord_getValue); lua_register(LuaVM, 'memoryrecord_setValue', memoryrecord_setValue); lua_register(LuaVM, 'memoryrecord_getScript', memoryrecord_getScript); lua_register(LuaVM, 'memoryrecord_setScript', memoryrecord_setScript); lua_register(LuaVM, 'memoryrecord_isActive', memoryrecord_getActive); lua_register(LuaVM, 'memoryrecord_isSelected', memoryrecord_isSelected); lua_register(LuaVM, 'memoryrecord_freeze', memoryrecord_freeze); lua_register(LuaVM, 'memoryrecord_unfreeze', memoryrecord_unfreeze); lua_register(LuaVM, 'memoryrecord_setColor', memoryrecord_setColor); lua_register(LuaVM, 'memoryrecord_appendToEntry', memoryrecord_appendToEntry); lua_register(LuaVM, 'memoryrecord_delete', memoryrecord_delete); lua_register(LuaVM, 'memoryrecord_string_getSize', memoryrecord_string_getSize); lua_register(LuaVM, 'memoryrecord_string_setSize', memoryrecord_string_setSize); lua_register(LuaVM, 'memoryrecord_string_getUnicode', memoryrecord_string_getUnicode); lua_register(LuaVM, 'memoryrecord_string_setUnicode', memoryrecord_string_setUnicode); lua_register(LuaVM, 'memoryrecord_binary_getStartbit', memoryrecord_binary_getStartbit); lua_register(LuaVM, 'memoryrecord_binary_setStartbit', memoryrecord_binary_setStartbit); lua_register(LuaVM, 'memoryrecord_binary_getSize', memoryrecord_binary_getSize); lua_register(LuaVM, 'memoryrecord_binary_setSize', memoryrecord_binary_setSize); lua_register(LuaVM, 'memoryrecord_aob_getSize', memoryrecord_aob_getSize); lua_register(LuaVM, 'memoryrecord_aob_setSize', memoryrecord_aob_setSize); lua_register(LuaVM, 'memoryrecord_getID', memoryrecord_getID); lua_register(LuaVM, 'memoryrecord_getHotkeyCount', memoryrecord_getHotkeyCount); lua_register(LuaVM, 'memoryrecord_getHotkey', memoryrecord_getHotkey); lua_register(LuaVM, 'memoryrecord_getHotkeyByID', memoryrecord_getHotkeyByID); lua_register(LuaVM, 'memoryrecord_onActivate', memoryrecord_onActivate); lua_register(LuaVM, 'memoryrecord_onDeactivate', memoryrecord_onDeactivate); lua_register(LuaVM, 'memoryrecord_onDestroy', memoryrecord_onDestroy); end; initialization luaclass_register(TMemoryRecord, memoryrecord_addMetaData); end.
(* @abstract(Contient un composant non visuel pour facilité le traitement d'evenements de progression) ------------------------------------------------------------------------------------------------------------- @created(2012-11-10) @author(GLScene) Historique : @br @unorderedList( @item(10/11/2012 : Creation ) ) ------------------------------------------------------------------------------------------------------------- @bold(Notes) : ------------------------------------------------------------------------------------------------------------- @bold(Dépendances) : BZSystem ------------------------------------------------------------------------------------------------------------- @bold(Credits :) @unorderedList( @item (Basé sur le code de GLScene http://www.sourceforge.net/glscene) ) ------------------------------------------------------------------------------------------------------------- @bold(LICENCE) : MPL/GPL ------------------------------------------------------------------------------------------------------------- *) Unit BZCadencer; //============================================================================== {$mode objfpc}{$H+} {$WARN 5024 off : Parameter "$1" not used} {$i ..\..\bzscene_options.inc} //============================================================================== Interface Uses Classes, Forms, lmessages, SyncObjs, BZClasses; Type { Détermine comment fonctionne le TBZCadencer.@Br @unorderedlist(     @item(cmManual : vous devez déclencher la progression manuellement (dans votre code).)     @item(cmASAP : la progression est déclenchée aussi tôt que possible après une précédente progression (utilise les messages de Windows).)     @item(cmApplicationIdle : va accrocher Application.OnIdle, cela va écraser toute manipulation d'événement précédente, et un seul cadencer peut être utilisé dans ce mode.)) } TBZCadencerMode = (cmManual, cmASAP, cmApplicationIdle); { Determines à quel moment le TBZCadencer doit "progesser". @unorderedlist(     @item(cmRTC : l'horloge en temps réel est utilisée (précise sur de longues périodes, mais pas précis à la milliseconde. @br Peut limiter la vitesse (efficace à moins de 50 FPS sur certains systèmes) )     @item(cmPerformanceCounter : le compteur de performances a une bonne précision. Il peut dériver sur de longues périodes. @br C'est l'option par défaut car il permet l'animation la plus douce sur les systèmes rapides.)    @item(cmExternal : La propriété CurrentTime est utilisée)) } TBZCadencerTimeReference = (cmRTC, cmPerformanceCounter, cmExternal); { @abstract(Composant permettant une progression automatique d'une animation.)    Envoie les événements de progression en temps réel (le temps sera mesuré en secondes). @br    Ou il gardera la CPU occupée à 100% si possible (c.-à-d. si les choses changent dans votre scène). @br    Le temps de progression (celui que vous verrez dans vos événements de progression)    est calculé en utilisant (CurrentTime-OriginTime) * TimeMultiplier.@br    "CurrentTime" est mis manuellement ou automatiquement à jour en utilisant    "TimeReference" (le paramètre "CurrentTime" NE déclenche PAS la progression). } TBZCadencer = Class(TComponent) Private FSubscribedCadenceableComponents: TList; // FScene: TBZScene; FTimeMultiplier: Double; FInvTimeMultiplier : Double; lastTime, downTime, lastMultiplier: Double; FEnabled: Boolean; FSleepLength: Integer; FMode: TBZCadencerMode; FTimeReference: TBZCadencerTimeReference; FCurrentTime: Double; FOriginTime: Double; FMaxDeltaTime, FMinDeltaTime, FFixedDeltaTime: Double; FOnProgress, FOnTotalProgress: TBZCadencerProgressEvent; FProgressing: Integer; Procedure SetCurrentTime(Const Value: Double); Protected Procedure Notification(AComponent: TComponent; Operation: TOperation); Override; Function StoreTimeMultiplier: Boolean; Procedure SetEnabled(Const val: Boolean); // procedure SetScene(const val: TBZScene); Procedure SetMode(Const val: TBZCadencerMode); Procedure SetTimeReference(Const val: TBZCadencerTimeReference); Procedure SetTimeMultiplier(Const val: Double); { Renvoie le temps de réponse brut (pas de multiplicateur, pas d'offset) } Function GetRawReferenceTime: Double; Procedure RestartASAP; Procedure Loaded; Override; Procedure OnIdleEvent(Sender: TObject; Var Done: Boolean); Public Constructor Create(AOwner: TComponent); Override; Destructor Destroy; Override; Procedure Subscribe(aComponent: TBZCadenceAbleComponent); Procedure UnSubscribe(aComponent: TBZCadenceAbleComponent); { @abstract(Permet de déclencher manuellement une progression.) @br       Le temps est traité automatiquement. Si cadencer est désactivé, cette fonction ne fait rien. } Procedure Progress; { Ajuste "CurrentTime" si nécessaire, puis renvoie sa valeur. } Function GetCurrenttime: Double; { @abstract(Renvoie True si une Progression est en cours.) @br       Soyez conscient que, tant que IsBusy est Vrai, le Cadencer peut envoyer de messages et appeller d'autres progressions vers des autres scènes et composants cadencés. } Function IsBusy: Boolean; { Remise à zero des paramètres et du temps.} Procedure Reset; { Valeur soustraite au temps actuel pour obtenir le temps de progression. } Property OriginTime: Double read FOriginTime write FOriginTime; { Temps actuel (réglé manuellement ou automatiquement, voir TimeReference). } Property CurrentTime: Double read FCurrentTime write SetCurrentTime; Published { The TBZScene that will be cadenced (progressed). } // property Scene: TBZScene read FScene write SetScene; { @abstract(Activer / Désactiver la Candence.)       La désactivation ne provoquera pas de saut lors du redémarrage, mais fonctionne comme       une lecture / pause (c.-à-d. peut modifier OriginTime pour garder une progression douce). } Property Enabled: Boolean read FEnabled write SetEnabled Default True; { @abstract(Définit comment CurrentTime est mis à jour. Voir TBZCadencerTimeReference.)      Le changement dynamique de TimeReference peut provoquer un 'saut'. } Property TimeReference: TBZCadencerTimeReference read FTimeReference write SetTimeReference Default cmPerformanceCounter; { @abstract(Multiplicateur appliqué à la référence de temps.)       Zéro n'est pas une valeur autorisée, et sachez que si des valeurs négatives       sont acceptés, elles peuvent ne pas être pris en charge par d'autres objets.@br       La modification du TimeMultiplier modifiera OriginTime. } Property TimeMultiplier: Double read FTimeMultiplier write SetTimeMultiplier Stored StoreTimeMultiplier; { @abstract(Valeur maximale pour deltaTime dans les événements de progression.)       Si null ou négatif, aucun deltaTime max est défini. Sinon, chaque fois qu'un événement dont le deltaTime réel est supérieur à MaxDeltaTime, le deltaTime sera à son maximum, et le temps supplémentaire est mise en cache       par le cadencer (il n'est pas encore pris en compte dans CurrentTime).@br       Cette option permet de limiter le taux de progression dans les simulations où Des valeurs élevées entraîneraient des erreurs / comportement aléatoire. } Property MaxDeltaTime: Double read FMaxDeltaTime write FMaxDeltaTime; { @abstract(Valeur minimale pour deltaTime dans les événements de progression.)       Si supérieur à zéro, cette valeur spécifie le "pas" du temps minimum entre deux événements de progression.@br       Cette option permet de limiter le taux de progression dans les simulations où les valeurs faibles entraîneraient des erreurs / comportement aléatoire. } Property MinDeltaTime: Double read FMinDeltaTime write FMinDeltaTime; { @abstract(Valeur temporelle fixe pour les événements de progression.)       Si supérieur à zéro, des étapes de progression se produiront avec celles fixées au temps       delta. La progression reste basée sur le temps, donc zéro vers N événements       peut être déclenché en fonction du deltaTime réel (si deltaTime est       inférieur à FixedDeltaTime, aucun événement ne sera déclenché s'il est supérieur       à deux fois FixedDeltaTime, deux événements seront déclenchés, etc.).@br       Cette option permet d'utiliser des étapes de temps fixes dans les simulations (pendant       l'animation et le rendu peuvent se produire à un niveau de fractionnement inférieur ou supérieur). } Property FixedDeltaTime: Double read FFixedDeltaTime write FFixedDeltaTime; { Ajuste comment les évènement de progression doivent être déclenchés. Voir TBZCadencerMode. } Property Mode: TBZCadencerMode read FMode write SetMode Default cmASAP; { @abstract(Permet de laisser du "temps" à d'autres threads / processus.)       Si SleepLength> = 0 alors AVANT chaque progression une pause se produit (voir       la procédure "Sleep" dans FPC pour plus de détails). } Property SleepLength: Integer read FSleepLength write FSleepLength Default -1; { Evenement déclenché apres le progression. } Property OnProgress: TBZCadencerProgressEvent read FOnProgress write FOnProgress; { Evenement déclenché quand toutes les iterations avec DeltaTime fixe sont finis. } Property OnTotalProgress: TBZCadencerProgressEvent read FOnTotalProgress write FOnTotalProgress; End; { Ajoute une propriété "protégée" pour se connecter à un TBZCadencer. } TBZCustomCadencedComponent = Class(TBZUpdateAbleComponent) Private FCadencer: TBZCadencer; Protected Procedure SetCadencer(Const val: TBZCadencer); Property Cadencer: TBZCadencer read FCadencer write SetCadencer; Public Destructor Destroy; Override; Procedure Notification(AComponent: TComponent; Operation: TOperation); Override; End; { Composant à hériter dont la propriété "Cadencer" est publiée } TBZCadencedComponent = Class(TBZCustomCadencedComponent) Published Property Cadencer; End; Implementation Uses SysUtils, BZSystem; Const LM_GLTIMER = LM_INTERFACELAST + 326; Type TASAPHandler = Class; // TTimerThread TTimerThread = Class(TThread) Private FOwner: TASAPHandler; FInterval: Word; Protected Procedure Execute; Override; Public Constructor Create(CreateSuspended: Boolean); Virtual; End; { TASAPHandler } TASAPHandler = Class Private FTimerThread: TThread; FMutex: TCriticalSection; Public Constructor Create; Destructor Destroy; Override; Procedure TimerProc; Procedure Cadence(Var Msg: TLMessage); Message LM_GLTIMER; End; Var vASAPCadencerList: TList; vHandler: TASAPHandler; vCounterFrequency: Int64; Procedure RegisterASAPCadencer(aCadencer: TBZCadencer); Begin If aCadencer.Mode = cmASAP Then Begin If Not Assigned(vASAPCadencerList) Then vASAPCadencerList := TList.Create; If vASAPCadencerList.IndexOf(aCadencer) < 0 Then Begin vASAPCadencerList.Add(aCadencer); If Not Assigned(vHandler) Then vHandler := TASAPHandler.Create; End; End Else If aCadencer.Mode = cmApplicationIdle Then Application.OnIdle := @aCadencer.OnIdleEvent; End; Procedure UnRegisterASAPCadencer(aCadencer: TBZCadencer); Var i: Integer; Begin If aCadencer.Mode = cmASAP Then Begin If Assigned(vASAPCadencerList) Then Begin i := vASAPCadencerList.IndexOf(aCadencer); If i >= 0 Then vASAPCadencerList[i] := nil; End; End Else If aCadencer.Mode = cmApplicationIdle Then Application.OnIdle := nil; End; {%region%=== [ TTimerThread ]==================================================} Constructor TTimerThread.Create(CreateSuspended: Boolean); Begin Inherited Create(CreateSuspended); End; Procedure TTimerThread.Execute; Var lastTick, nextTick, curTick, perfFreq: Int64; Begin LastTick := 0; // Happy Compilo PerfFreq := 0; CurTick := 0; //QueryPerformanceFrequency(perfFreq); perfFreq := vCounterFrequency; QueryPerformanceCounter(lastTick); nextTick := lastTick + (FInterval * perfFreq) Div 1000; While Not Terminated Do Begin FOwner.FMutex.Acquire; FOwner.FMutex.Release; While Not Terminated Do Begin QueryPerformanceCounter(lastTick); If lastTick >= nextTick Then break; //Sleep(1); End; If Not Terminated Then Begin // if time elapsed run user-event Synchronize(@FOwner.TimerProc); //FOwner.TimerProc; QueryPerformanceCounter(curTick); nextTick := lastTick + (FInterval * perfFreq) Div 1000; If nextTick <= curTick Then Begin // CPU too slow... delay to avoid monopolizing what's left nextTick := curTick + (FInterval * perfFreq) Div 1000; End; End; End; End; {%endregion%} {%region%=== [ TASAPHandler ]==================================================} Constructor TASAPHandler.Create; Begin Inherited Create; // create timer thread FMutex := TCriticalSection.Create; FMutex.Acquire; FTimerThread := TTimerThread.Create(False); With TTimerThread(FTimerThread) Do Begin FOwner := Self; FreeOnTerminate := False; Priority := tpTimeCritical; FInterval := 1; FMutex.Release; End; End; Destructor TASAPHandler.Destroy; Begin FMutex.Acquire; FTimerThread.Terminate; CheckSynchronize; // wait & free FTimerThread.WaitFor; FTimerThread.Free; FMutex.Free; Inherited Destroy; End; Procedure TASAPHandler.TimerProc; Var NewMsg: TLMessage; Begin NewMsg.Msg := LM_GLTIMER; Cadence(NewMsg); End; Procedure TASAPHandler.Cadence(Var Msg: TLMessage); Var i,c: Integer; cad: TBZCadencer; Begin If Assigned(vHandler) And Assigned(vASAPCadencerList) And (vASAPCadencerList.Count <> 0) Then begin c := vASAPCadencerList.Count;// - 1; i:=0; repeat Begin cad := TBZCadencer(vASAPCadencerList[i]); If Assigned(cad) And (cad.Mode = cmASAP) And cad.Enabled And (cad.FProgressing = 0) Then Begin If not(Application.Terminated) Then Begin Try // do stuff cad.Progress; Except Application.HandleException(Self); // it faulted, stop it cad.Enabled := False; End; End Else Begin // force stop cad.Enabled := False; End; End; //dec(c); Inc(i); End; until i=c; end; End; {%endregion%} {%region%=== [ TBZCadencer ]==================================================} Constructor TBZCadencer.Create(AOwner: TComponent); Begin Inherited Create(AOwner); FTimeReference := cmPerformanceCounter; downTime := GetRawReferenceTime; FOriginTime := downTime; FTimeMultiplier := 1; FInvTimeMultiplier := 0; FSleepLength := -1; Mode := cmASAP; Enabled := False; End; Destructor TBZCadencer.Destroy; Begin Assert(FProgressing = 0); UnRegisterASAPCadencer(Self); FSubscribedCadenceableComponents.Free; FSubscribedCadenceableComponents := nil; Inherited Destroy; End; Procedure TBZCadencer.Subscribe(aComponent: TBZCadenceAbleComponent); Begin If Not Assigned(FSubscribedCadenceableComponents) Then FSubscribedCadenceableComponents := TList.Create; If FSubscribedCadenceableComponents.IndexOf(aComponent) < 0 Then Begin FSubscribedCadenceableComponents.Add(aComponent); aComponent.FreeNotification(Self); End; End; Procedure TBZCadencer.UnSubscribe(aComponent: TBZCadenceAbleComponent); Var i: Integer; Begin If Assigned(FSubscribedCadenceableComponents) Then Begin i := FSubscribedCadenceableComponents.IndexOf(aComponent); If i >= 0 Then Begin FSubscribedCadenceableComponents.Delete(i); aComponent.RemoveFreeNotification(Self); End; End; End; Procedure TBZCadencer.Notification(AComponent: TComponent; Operation: TOperation); Begin If Operation = opRemove Then Begin // If AComponent = FScene Then FScene := nil; If Assigned(FSubscribedCadenceableComponents) Then FSubscribedCadenceableComponents.Remove(AComponent); End; Inherited; End; Procedure TBZCadencer.Loaded; Begin Inherited Loaded; RestartASAP; End; Procedure TBZCadencer.OnIdleEvent(Sender: TObject; Var Done: Boolean); Begin Progress; Done := False; End; Procedure TBZCadencer.RestartASAP; Begin If Not (csLoading In ComponentState) Then Begin If (Mode In [cmASAP, cmApplicationIdle]) And (Not (csDesigning In ComponentState)) And Enabled Then //And Assigned(FScene) RegisterASAPCadencer(Self) Else UnRegisterASAPCadencer(Self); End; End; Procedure TBZCadencer.SetEnabled(Const val: Boolean); Begin If FEnabled <> val Then Begin FEnabled := val; If Not (csDesigning In ComponentState) Then Begin If Enabled Then FOriginTime := FOriginTime + GetRawReferenceTime - downTime Else begin downTime := GetRawReferenceTime; end; RestartASAP; End; End; End; (* procedure TBZCadencer.SetScene(const val: TBZScene); begin if FScene <> val then begin if Assigned(FScene) then FScene.RemoveFreeNotification(Self); FScene := val; if Assigned(FScene) then FScene.FreeNotification(Self); RestartASAP; end; end; *) Procedure TBZCadencer.SetTimeMultiplier(Const val: Double); Var rawRef: Double; invVal : Double; Begin If val <> FTimeMultiplier Then Begin invVal :=0; If val = 0 Then Begin lastMultiplier := FTimeMultiplier; Enabled := False; End Else Begin invVal := 1/val; rawRef := GetRawReferenceTime; If FTimeMultiplier = 0 Then Begin Enabled := True; // continuity of time: // (rawRef-newOriginTime)*val = (rawRef-FOriginTime)*lastMultiplier FOriginTime := rawRef - (rawRef - FOriginTime) * lastMultiplier * InvVal; End Else Begin // continuity of time: // (rawRef-newOriginTime)*val = (rawRef-FOriginTime)*FTimeMultiplier FOriginTime := rawRef - (rawRef - FOriginTime) * FTimeMultiplier * InvVal; End; End; FTimeMultiplier := val; FInvTimeMultiplier := InvVal; End; End; Function TBZCadencer.StoreTimeMultiplier: Boolean; Begin Result := (FTimeMultiplier <> 1); End; Procedure TBZCadencer.SetMode(Const val: TBZCadencerMode); Begin If FMode <> val Then Begin If FMode <> cmManual Then UnRegisterASAPCadencer(Self); FMode := val; RestartASAP; End; End; Procedure TBZCadencer.SetTimeReference(Const val: TBZCadencerTimeReference); Begin // nothing more, yet FTimeReference := val; End; Procedure TBZCadencer.Progress; Var deltaTime, newTime, totalDelta: Double; fullTotalDelta, firstLastTime: Double; i: Integer; pt: TBZProgressTimes; Begin // basic protection against infinite loops, // shall never happen, unless there is a bug in user code If FProgressing < 0 Then Exit; If Enabled Then Begin // avoid stalling everything else... If SleepLength > 0 Then Sleep(SleepLength); // in manual mode, the user is supposed to make sure messages are handled // in Idle mode, this processing is implicit If Mode = cmASAP Then Begin //Application.ProcessMessages; If (Not Assigned(vASAPCadencerList)) Or (vASAPCadencerList.IndexOf(Self) < 0) Then Exit; End; End; Inc(FProgressing); Try If Enabled Then Begin // One of the processed messages might have disabled us If Enabled Then Begin // ...and progress ! newTime := GetCurrenttime; deltaTime := newTime - lastTime; If (deltaTime >= MinDeltaTime) And (deltaTime >= FixedDeltaTime) Then Begin If FMaxDeltaTime > 0 Then Begin If deltaTime > FMaxDeltaTime Then Begin FOriginTime := FOriginTime + (deltaTime - FMaxDeltaTime) * FInvTimeMultiplier; deltaTime := FMaxDeltaTime; newTime := lastTime + deltaTime; End; End; totalDelta := deltaTime; fullTotalDelta := totalDelta; firstLastTime := lastTime; If FixedDeltaTime > 0 Then deltaTime := FixedDeltaTime; While totalDelta >= deltaTime Do Begin lastTime := lastTime + deltaTime; If (deltaTime <> 0) Then //Assigned(FScene) And Begin FProgressing := -FProgressing; Try // FScene.Progress(deltaTime, lastTime); Finally FProgressing := -FProgressing; End; End; pt.deltaTime := deltaTime; pt.newTime := lastTime; i := 0; While Assigned(FSubscribedCadenceableComponents) And (i <= FSubscribedCadenceableComponents.Count - 1) Do Begin TBZCadenceAbleComponent(FSubscribedCadenceableComponents[i]).DoProgress(pt); inc(i); //i := i + 1; End; If Assigned(FOnProgress) And (Not (csDesigning In ComponentState)) Then FOnProgress(Self, deltaTime, newTime); If deltaTime <= 0 Then Break; totalDelta := totalDelta - deltaTime; End; If Assigned(FOnTotalProgress) And (Not (csDesigning In ComponentState)) Then FOnTotalProgress(Self, fullTotalDelta, firstLastTime); End; End; End; Finally Dec(FProgressing); End; End; Function TBZCadencer.GetRawReferenceTime: Double; Var counter: Int64; Begin counter := 0; Case FTimeReference Of cmRTC: // Real Time Clock Result := Now * (3600 * 24); cmPerformanceCounter: Begin // HiRes Performance Counter QueryPerformanceCounter(counter); Result := counter / vCounterFrequency; End; cmExternal: // User defined value Result := FCurrentTime; Else Result := 0; Assert(False); End; End; Function TBZCadencer.GetCurrenttime: Double; Begin Result := (GetRawReferenceTime - FOriginTime) * FTimeMultiplier; FCurrentTime := Result; End; Function TBZCadencer.IsBusy: Boolean; Begin Result := (FProgressing <> 0); End; Procedure TBZCadencer.Reset; Begin lasttime := 0; downTime := GetRawReferenceTime; FOriginTime := downTime; End; Procedure TBZCadencer.SetCurrentTime(Const Value: Double); Begin LastTime := Value - (FCurrentTime - LastTime); FOriginTime := FOriginTime + (FCurrentTime - Value); FCurrentTime := Value; End; {%endregion%} {%region%=== [ TBZCustomCadencedComponent ]===================================} Destructor TBZCustomCadencedComponent.Destroy; Begin Cadencer := nil; Inherited Destroy; End; Procedure TBZCustomCadencedComponent.Notification(AComponent: TComponent; Operation: TOperation); Begin If (Operation = opRemove) And (AComponent = FCadencer) Then Cadencer := nil; Inherited; End; Procedure TBZCustomCadencedComponent.SetCadencer(Const val: TBZCadencer); Begin If FCadencer <> val Then Begin If Assigned(FCadencer) Then FCadencer.UnSubscribe(Self); FCadencer := val; If Assigned(FCadencer) Then FCadencer.Subscribe(Self); End; End; {%endregion%} Initialization RegisterClasses([TBZCadencer]); vCounterFrequency := 0; // Preparation pour le "timer" haute resolution If Not QueryPerformanceFrequency(vCounterFrequency) Then vCounterFrequency := 0; Finalization FreeAndNil(vHandler); FreeAndNil(vASAPCadencerList); End.
program lista1ex2; // Exercício 1 da Lista 2 de Algorítmos. Autor: Henrique Colodetti Escanferla. var a, b: longint; // Variáveis inteiras para a execução do processo. a=> numero a ser fatorado, b=> variavel que assumirá todos os primos do processo. Longint para fatorar numeros grandes. begin // Começo do processo. writeln('Este algoritmo fornecerá a fatoração em primos de um numero inteiro positivo qualquer. Veja que 1 não é primo e é o menor inteiro positivo. Ele não possui, então, uma fatoração em primos.'); // Apresentação do algoritmo e sua função. write('Digite um numero inteiro a ser fatorado diferente de 1: '); // Aqui é pedido o numero inteiro "a". readln(a); // Leitura da variável "a". b:= 2; // Menor numero primo é o 2, a sequência de divisões começa por ele então. while a<>1 do // Início do loop das divisões de "a" por numeros primos até restar 1 na fatoração. if (a)mod(b)=0 then // Se "a"/"b" tem resto 0 então "b" é um dos primos da fatoração. begin // Começo dos comandos deste "if then". a:=(a)div(b); // Restante a ser fatorado é inserido em "a". write(b,' '); // Apresentação dos primos espaçados entre sí como foi pedido. end // Fim dos comandos deste "if then". else // Caso "a"/"b" não dê resto 0, "b" é incrementado até que isso ocorra. b:=b+1; // Incrementação de "b" em busca dos primos que dividem "a". Fim deste "if then else". end. // Fim do processo.
unit RTF_Zestawienia; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids, Printers, DateUtils, JvUIB, JvUIBLib, RT_Tools, RT_SQL; type TZestawienieKind = (zkDzien, zkOkres); TFrmZestawienia = class(TForm) GrdZestawienie: TStringGrid; PnlButtons: TPanel; BtnPrint: TButton; BtnExcel: TButton; BtnClose: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure BtnPrintClick(Sender: TObject); procedure BtnExcelClick(Sender: TObject); procedure GrdZestawienieKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } procedure SetupAsZestawienieZZakresu(Date1, Date2: TDateTime); public { Public declarations } DialogKind: TZestawienieKind; procedure SetupAsZestawienieZDnia(Date: TDateTime); procedure SetupAsZestawienieWszystkichTaksowekZMiesiaca(Date: TDateTime); procedure SetupAsZestawienieKoncoweZDnia(Data: TDateTime); end; implementation uses Math, RT_Print; {$R *.DFM} { TFrmZestawienia } { Private declarations } procedure TFrmZestawienia.SetupAsZestawienieZZakresu(Date1, Date2: TDateTime); var RowIndex, TotalCount: Integer; begin Caption := 'Zestawienie kursów z dnia: ' + FormatDateTime('YYYY-MM-DD', Date); with TSQL.Instance.CreateQuery do try SQL.Text := Format('SELECT * FROM Zestawienie (%s, %s);', [ QuotedStr(FormatDateTime('YYYY-MM-DD', Date1)), QuotedStr(FormatDateTime('YYYY-MM-DD', Date2)) ]); Open; FetchAll; with GrdZestawienie do begin ColCount := 5; RowCount := 2; FixedRows := 1; Cells[0, 0] := 'L.p.'; ColWidths[0] := 32; Cells[1, 0] := 'Imię, nazwisko'; ColWidths[1] := 291; Cells[2, 0] := 'Numer wywoł.'; ColWidths[2] := 85; Cells[3, 0] := 'Numer boczny'; ColWidths[3] := 85; Cells[4, 0] := 'Ilość kursów'; ColWidths[4] := 120; First; RowIndex := 1; TotalCount := 0; while not Eof do begin RowCount := RowIndex + 1; Cells[0, RowIndex] := IntToStr(RowIndex); Cells[1, RowIndex] := Fields.ByNameAsString['NAZWA']; Cells[2, RowIndex] := Fields.ByNameAsString['NRBOCZNY']; Cells[3, RowIndex] := Fields.ByNameAsString['NRWYWOLAWCZY']; Cells[4, RowIndex] := Fields.ByNameAsString['ILOSCKURSOW']; Inc(RowIndex); Inc(TotalCount, Fields.ByNameAsInteger['ILOSCKURSOW']); Next; end; RowCount := RowCount + 2; Cells[ColCount - 2, RowCount - 1] := 'Razem:'; Cells[ColCount - 1, RowCount - 1] := IntToStr(TotalCount); end; Close; finally Free; end; end; procedure TFrmZestawienia.GrdZestawienieKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RIGHT then with GrdZestawienie do begin if VisibleColCount < ColCount - LeftCol then begin if ssCtrl in Shift then LeftCol := ColCount - LeftCol else LeftCol := LeftCol + 1; end; Key := 0; end; if Key = VK_LEFT then with GrdZestawienie do begin if LeftCol > 0 then begin if ssCtrl in Shift then LeftCol := 0 else LeftCol := LeftCol - 1; end; Key := 0; end; end; procedure TFrmZestawienia.SetupAsZestawienieKoncoweZDnia(Data: TDateTime); function GetAddress(Kurs: TSQLResult): String; begin Result := Kurs.ByNameAsString['ULICA']; if Kurs.ByNameAsString['DOM'] <> '' then Result := Result + ' ' + Kurs.ByNameAsString['DOM']; if Kurs.ByNameAsString['MIESZKANIE'] <> '' then Result := Result + '/' + Kurs.ByNameAsString['MIESZKANIE']; end; procedure WypiszKurs(Kurs: TSQLResult; Index: Integer); var Column, Row: Integer; begin Column := (Index div ((Kurs.RecordCount + 1) div 2)) * 4; Row := Index mod ((Kurs.RecordCount + 1) div 2) + 1; if Column = 0 then GrdZestawienie.RowCount := GrdZestawienie.RowCount + 1; GrdZestawienie.Cells[Column, Row] := IntToStr(Index + 1); GrdZestawienie.Cells[Column + 1, Row] := GetAddress(Kurs); GrdZestawienie.Cells[Column + 2, Row] := Kurs.ByNameAsString['NRWYWOLAWCZY']; GrdZestawienie.Cells[Column + 3, Row] := FormatDateTime('HH:NN', Kurs.ByNameAsDateTime['PRZYJECIE']); end; procedure WypiszTaksowka(Taksowka: TSQLResult; Index: Integer); var Column, Row: Integer; begin Column := (Index mod 2) * 4; Row := Index div 2 + 1; if Column = 0 then GrdZestawienie.RowCount := GrdZestawienie.RowCount + 1; GrdZestawienie.Cells[Column + 1, Row] := Taksowka.ByNameAsString['NAZWA']; GrdZestawienie.Cells[Column + 2, Row] := Taksowka.ByNameAsString['NRWYWOLAWCZY']; GrdZestawienie.Cells[Column + 3, Row] := Taksowka.ByNameAsString['ILOSCKURSOW']; end; var Index: Integer; S: String; begin with GrdZestawienie do begin ColCount := 8; FixedCols := 0; Cells[0, 0] := 'L.P.'; ColWidths[0] := 32; Cells[1, 0] := 'Adres'; ColWidths[1] := 164; Cells[2, 0] := 'Taxi'; ColWidths[2] := 54; Cells[3, 0] := 'Godzina'; ColWidths[3] := 64; Cells[4, 0] := 'L.P.'; ColWidths[4] := 32; Cells[5, 0] := 'Adres'; ColWidths[5] := 164; Cells[6, 0] := 'Taxi'; ColWidths[6] := 54; Cells[7, 0] := 'Godzina'; ColWidths[7] := 64; RowCount := 2; FixedRows := 1; end; Caption := 'Zestawienie końcowe kursów z dnia ' + FormatDateTime('YYYY-MM-DD', Data); with TSQL.Instance.CreateQuery do try SQL.Text := Format('SELECT NRWYWOLAWCZY,ULICA,DOM,MIESZKANIE,PRZYJECIE FROM KURSY WHERE PRZYJECIE BETWEEN %s AND %s', [ QuotedStr(FormatDateTime('YYYY-MM-DD', Data)), QuotedStr(FormatDateTime('YYYY-MM-DD', Data + 1)) ]); Open; Index := 0; FetchAll; First; while not Eof do begin WypiszKurs(Fields, Index); Inc(Index); Next; end; Close; S := Format('SELECT * FROM zestawienie (%s, %s);', [ QuotedStr(FormatDateTime('YYYY-MM-DD', Data)), QuotedStr(FormatDateTime('YYYY-MM-DD', Data + 1)) ]); SQL.Text := S; if Odd(Index) then Inc(Index); Open; Index := (Index div 2) * 2 + 4; while not Eof do begin WypiszTaksowka(Fields, Index); Inc(Index); Next; end; Close; finally Free; end; end; { Public declarations } procedure TFrmZestawienia.SetupAsZestawienieZDnia(Date: TDateTime); begin DialogKind := zkDzien; SetupAsZestawienieZZakresu(Date, Date + 1); end; procedure TFrmZestawienia.BtnPrintClick(Sender: TObject); begin PrintData.PageMark := 'RadioTaxi Manager v3.1 (c) 2001 by Maciej Hryniszak'; PrintData.Title := Caption; PrintData.Grid := GrdZestawienie; PrintGrid; end; procedure TFrmZestawienia.SetupAsZestawienieWszystkichTaksowekZMiesiaca(Date: TDateTime); var Y, M, D: Word; begin DecodeDate(Date, Y, M, D); Date := EncodeDate(Y, M, 1); SetupAsZestawienieZZakresu(Date, IncMonth(Date)); end; { Event handlers } procedure TFrmZestawienia.FormCreate(Sender: TObject); begin Left := 0; Top := 0; Width := Screen.Width; Height := Screen.Height; end; procedure TFrmZestawienia.FormDestroy(Sender: TObject); begin // end; procedure TFrmZestawienia.FormShow(Sender: TObject); begin BtnClose.Left := Width - BtnClose. Width - 14; end; procedure TFrmZestawienia.BtnExcelClick(Sender: TObject); begin // end; end.
unit Ssh; interface type HCkSecureString = Pointer; HCkSsh = Pointer; HCkByteData = Pointer; HCkSshKey = Pointer; HCkString = Pointer; HCkStringArray = Pointer; HCkTask = Pointer; function CkSsh_Create: HCkSsh; stdcall; procedure CkSsh_Dispose(handle: HCkSsh); stdcall; function CkSsh_getAbortCurrent(objHandle: HCkSsh): wordbool; stdcall; procedure CkSsh_putAbortCurrent(objHandle: HCkSsh; newPropVal: wordbool); stdcall; function CkSsh_getAuthFailReason(objHandle: HCkSsh): Integer; stdcall; function CkSsh_getCaretControl(objHandle: HCkSsh): wordbool; stdcall; procedure CkSsh_putCaretControl(objHandle: HCkSsh; newPropVal: wordbool); stdcall; function CkSsh_getChannelOpenFailCode(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_getChannelOpenFailReason(objHandle: HCkSsh; outPropVal: HCkString); stdcall; function CkSsh__channelOpenFailReason(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getClientIdentifier(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putClientIdentifier(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__clientIdentifier(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getClientIpAddress(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putClientIpAddress(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__clientIpAddress(objHandle: HCkSsh): PWideChar; stdcall; function CkSsh_getClientPort(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_putClientPort(objHandle: HCkSsh; newPropVal: Integer); stdcall; function CkSsh_getConnectTimeoutMs(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_putConnectTimeoutMs(objHandle: HCkSsh; newPropVal: Integer); stdcall; procedure CkSsh_getDebugLogFilePath(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putDebugLogFilePath(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__debugLogFilePath(objHandle: HCkSsh): PWideChar; stdcall; function CkSsh_getDisconnectCode(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_getDisconnectReason(objHandle: HCkSsh; outPropVal: HCkString); stdcall; function CkSsh__disconnectReason(objHandle: HCkSsh): PWideChar; stdcall; function CkSsh_getEnableCompression(objHandle: HCkSsh): wordbool; stdcall; procedure CkSsh_putEnableCompression(objHandle: HCkSsh; newPropVal: wordbool); stdcall; procedure CkSsh_getForceCipher(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putForceCipher(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__forceCipher(objHandle: HCkSsh): PWideChar; stdcall; function CkSsh_getHeartbeatMs(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_putHeartbeatMs(objHandle: HCkSsh; newPropVal: Integer); stdcall; procedure CkSsh_getHostKeyAlg(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putHostKeyAlg(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__hostKeyAlg(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getHostKeyFingerprint(objHandle: HCkSsh; outPropVal: HCkString); stdcall; function CkSsh__hostKeyFingerprint(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getHttpProxyAuthMethod(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putHttpProxyAuthMethod(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__httpProxyAuthMethod(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getHttpProxyDomain(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putHttpProxyDomain(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__httpProxyDomain(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getHttpProxyHostname(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putHttpProxyHostname(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__httpProxyHostname(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getHttpProxyPassword(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putHttpProxyPassword(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__httpProxyPassword(objHandle: HCkSsh): PWideChar; stdcall; function CkSsh_getHttpProxyPort(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_putHttpProxyPort(objHandle: HCkSsh; newPropVal: Integer); stdcall; procedure CkSsh_getHttpProxyUsername(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putHttpProxyUsername(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__httpProxyUsername(objHandle: HCkSsh): PWideChar; stdcall; function CkSsh_getIdleTimeoutMs(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_putIdleTimeoutMs(objHandle: HCkSsh; newPropVal: Integer); stdcall; function CkSsh_getIsConnected(objHandle: HCkSsh): wordbool; stdcall; function CkSsh_getKeepSessionLog(objHandle: HCkSsh): wordbool; stdcall; procedure CkSsh_putKeepSessionLog(objHandle: HCkSsh; newPropVal: wordbool); stdcall; procedure CkSsh_getLastErrorHtml(objHandle: HCkSsh; outPropVal: HCkString); stdcall; function CkSsh__lastErrorHtml(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getLastErrorText(objHandle: HCkSsh; outPropVal: HCkString); stdcall; function CkSsh__lastErrorText(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getLastErrorXml(objHandle: HCkSsh; outPropVal: HCkString); stdcall; function CkSsh__lastErrorXml(objHandle: HCkSsh): PWideChar; stdcall; function CkSsh_getLastMethodSuccess(objHandle: HCkSsh): wordbool; stdcall; procedure CkSsh_putLastMethodSuccess(objHandle: HCkSsh; newPropVal: wordbool); stdcall; function CkSsh_getMaxPacketSize(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_putMaxPacketSize(objHandle: HCkSsh; newPropVal: Integer); stdcall; function CkSsh_getNumOpenChannels(objHandle: HCkSsh): Integer; stdcall; function CkSsh_getPasswordChangeRequested(objHandle: HCkSsh): wordbool; stdcall; function CkSsh_getPreferIpv6(objHandle: HCkSsh): wordbool; stdcall; procedure CkSsh_putPreferIpv6(objHandle: HCkSsh; newPropVal: wordbool); stdcall; function CkSsh_getReadTimeoutMs(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_putReadTimeoutMs(objHandle: HCkSsh; newPropVal: Integer); stdcall; procedure CkSsh_getReqExecCharset(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putReqExecCharset(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__reqExecCharset(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getServerIdentifier(objHandle: HCkSsh; outPropVal: HCkString); stdcall; function CkSsh__serverIdentifier(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getSessionLog(objHandle: HCkSsh; outPropVal: HCkString); stdcall; function CkSsh__sessionLog(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getSocksHostname(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putSocksHostname(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__socksHostname(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getSocksPassword(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putSocksPassword(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__socksPassword(objHandle: HCkSsh): PWideChar; stdcall; function CkSsh_getSocksPort(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_putSocksPort(objHandle: HCkSsh; newPropVal: Integer); stdcall; procedure CkSsh_getSocksUsername(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putSocksUsername(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__socksUsername(objHandle: HCkSsh): PWideChar; stdcall; function CkSsh_getSocksVersion(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_putSocksVersion(objHandle: HCkSsh; newPropVal: Integer); stdcall; function CkSsh_getSoRcvBuf(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_putSoRcvBuf(objHandle: HCkSsh; newPropVal: Integer); stdcall; function CkSsh_getSoSndBuf(objHandle: HCkSsh): Integer; stdcall; procedure CkSsh_putSoSndBuf(objHandle: HCkSsh; newPropVal: Integer); stdcall; function CkSsh_getStderrToStdout(objHandle: HCkSsh): wordbool; stdcall; procedure CkSsh_putStderrToStdout(objHandle: HCkSsh; newPropVal: wordbool); stdcall; function CkSsh_getStripColorCodes(objHandle: HCkSsh): wordbool; stdcall; procedure CkSsh_putStripColorCodes(objHandle: HCkSsh; newPropVal: wordbool); stdcall; function CkSsh_getTcpNoDelay(objHandle: HCkSsh): wordbool; stdcall; procedure CkSsh_putTcpNoDelay(objHandle: HCkSsh; newPropVal: wordbool); stdcall; procedure CkSsh_getUncommonOptions(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putUncommonOptions(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__uncommonOptions(objHandle: HCkSsh): PWideChar; stdcall; procedure CkSsh_getUserAuthBanner(objHandle: HCkSsh; outPropVal: HCkString); stdcall; procedure CkSsh_putUserAuthBanner(objHandle: HCkSsh; newPropVal: PWideChar); stdcall; function CkSsh__userAuthBanner(objHandle: HCkSsh): PWideChar; stdcall; function CkSsh_getVerboseLogging(objHandle: HCkSsh): wordbool; stdcall; procedure CkSsh_putVerboseLogging(objHandle: HCkSsh; newPropVal: wordbool); stdcall; procedure CkSsh_getVersion(objHandle: HCkSsh; outPropVal: HCkString); stdcall; function CkSsh__version(objHandle: HCkSsh): PWideChar; stdcall; function CkSsh_AuthenticatePk(objHandle: HCkSsh; username: PWideChar; privateKey: HCkSshKey): wordbool; stdcall; function CkSsh_AuthenticatePkAsync(objHandle: HCkSsh; username: PWideChar; privateKey: HCkSshKey): HCkTask; stdcall; function CkSsh_AuthenticatePw(objHandle: HCkSsh; login: PWideChar; password: PWideChar): wordbool; stdcall; function CkSsh_AuthenticatePwAsync(objHandle: HCkSsh; login: PWideChar; password: PWideChar): HCkTask; stdcall; function CkSsh_AuthenticatePwPk(objHandle: HCkSsh; username: PWideChar; password: PWideChar; privateKey: HCkSshKey): wordbool; stdcall; function CkSsh_AuthenticatePwPkAsync(objHandle: HCkSsh; username: PWideChar; password: PWideChar; privateKey: HCkSshKey): HCkTask; stdcall; function CkSsh_AuthenticateSecPw(objHandle: HCkSsh; login: HCkSecureString; password: HCkSecureString): wordbool; stdcall; function CkSsh_AuthenticateSecPwAsync(objHandle: HCkSsh; login: HCkSecureString; password: HCkSecureString): HCkTask; stdcall; function CkSsh_AuthenticateSecPwPk(objHandle: HCkSsh; username: HCkSecureString; password: HCkSecureString; privateKey: HCkSshKey): wordbool; stdcall; function CkSsh_AuthenticateSecPwPkAsync(objHandle: HCkSsh; username: HCkSecureString; password: HCkSecureString; privateKey: HCkSshKey): HCkTask; stdcall; function CkSsh_ChannelIsOpen(objHandle: HCkSsh; channelNum: Integer): wordbool; stdcall; function CkSsh_ChannelPoll(objHandle: HCkSsh; channelNum: Integer; pollTimeoutMs: Integer): Integer; stdcall; function CkSsh_ChannelPollAsync(objHandle: HCkSsh; channelNum: Integer; pollTimeoutMs: Integer): HCkTask; stdcall; function CkSsh_ChannelRead(objHandle: HCkSsh; channelNum: Integer): Integer; stdcall; function CkSsh_ChannelReadAsync(objHandle: HCkSsh; channelNum: Integer): HCkTask; stdcall; function CkSsh_ChannelReadAndPoll(objHandle: HCkSsh; channelNum: Integer; pollTimeoutMs: Integer): Integer; stdcall; function CkSsh_ChannelReadAndPollAsync(objHandle: HCkSsh; channelNum: Integer; pollTimeoutMs: Integer): HCkTask; stdcall; function CkSsh_ChannelReadAndPoll2(objHandle: HCkSsh; channelNum: Integer; pollTimeoutMs: Integer; maxNumBytes: Integer): Integer; stdcall; function CkSsh_ChannelReadAndPoll2Async(objHandle: HCkSsh; channelNum: Integer; pollTimeoutMs: Integer; maxNumBytes: Integer): HCkTask; stdcall; function CkSsh_ChannelReceivedClose(objHandle: HCkSsh; channelNum: Integer): wordbool; stdcall; function CkSsh_ChannelReceivedEof(objHandle: HCkSsh; channelNum: Integer): wordbool; stdcall; function CkSsh_ChannelReceivedExitStatus(objHandle: HCkSsh; channelNum: Integer): wordbool; stdcall; function CkSsh_ChannelReceiveToClose(objHandle: HCkSsh; channelNum: Integer): wordbool; stdcall; function CkSsh_ChannelReceiveToCloseAsync(objHandle: HCkSsh; channelNum: Integer): HCkTask; stdcall; function CkSsh_ChannelReceiveUntilMatch(objHandle: HCkSsh; channelNum: Integer; matchPattern: PWideChar; charset: PWideChar; caseSensitive: wordbool): wordbool; stdcall; function CkSsh_ChannelReceiveUntilMatchAsync(objHandle: HCkSsh; channelNum: Integer; matchPattern: PWideChar; charset: PWideChar; caseSensitive: wordbool): HCkTask; stdcall; function CkSsh_ChannelReceiveUntilMatchN(objHandle: HCkSsh; channelNum: Integer; matchPatterns: HCkStringArray; charset: PWideChar; caseSensitive: wordbool): wordbool; stdcall; function CkSsh_ChannelReceiveUntilMatchNAsync(objHandle: HCkSsh; channelNum: Integer; matchPatterns: HCkStringArray; charset: PWideChar; caseSensitive: wordbool): HCkTask; stdcall; procedure CkSsh_ChannelRelease(objHandle: HCkSsh; channelNum: Integer); stdcall; function CkSsh_ChannelSendClose(objHandle: HCkSsh; channelNum: Integer): wordbool; stdcall; function CkSsh_ChannelSendCloseAsync(objHandle: HCkSsh; channelNum: Integer): HCkTask; stdcall; function CkSsh_ChannelSendData(objHandle: HCkSsh; channelNum: Integer; byteData: HCkByteData): wordbool; stdcall; function CkSsh_ChannelSendDataAsync(objHandle: HCkSsh; channelNum: Integer; byteData: HCkByteData): HCkTask; stdcall; function CkSsh_ChannelSendEof(objHandle: HCkSsh; channelNum: Integer): wordbool; stdcall; function CkSsh_ChannelSendEofAsync(objHandle: HCkSsh; channelNum: Integer): HCkTask; stdcall; function CkSsh_ChannelSendString(objHandle: HCkSsh; channelNum: Integer; textData: PWideChar; charset: PWideChar): wordbool; stdcall; function CkSsh_ChannelSendStringAsync(objHandle: HCkSsh; channelNum: Integer; textData: PWideChar; charset: PWideChar): HCkTask; stdcall; function CkSsh_CheckConnection(objHandle: HCkSsh): wordbool; stdcall; procedure CkSsh_ClearTtyModes(objHandle: HCkSsh); stdcall; function CkSsh_Connect(objHandle: HCkSsh; domainName: PWideChar; port: Integer): wordbool; stdcall; function CkSsh_ConnectAsync(objHandle: HCkSsh; domainName: PWideChar; port: Integer): HCkTask; stdcall; function CkSsh_ConnectThroughSsh(objHandle: HCkSsh; ssh: HCkSsh; hostname: PWideChar; port: Integer): wordbool; stdcall; function CkSsh_ConnectThroughSshAsync(objHandle: HCkSsh; ssh: HCkSsh; hostname: PWideChar; port: Integer): HCkTask; stdcall; function CkSsh_ContinueKeyboardAuth(objHandle: HCkSsh; response: PWideChar; outStr: HCkString): wordbool; stdcall; function CkSsh__continueKeyboardAuth(objHandle: HCkSsh; response: PWideChar): PWideChar; stdcall; function CkSsh_ContinueKeyboardAuthAsync(objHandle: HCkSsh; response: PWideChar): HCkTask; stdcall; procedure CkSsh_Disconnect(objHandle: HCkSsh); stdcall; function CkSsh_GetChannelExitStatus(objHandle: HCkSsh; channelNum: Integer): Integer; stdcall; function CkSsh_GetChannelNumber(objHandle: HCkSsh; index: Integer): Integer; stdcall; function CkSsh_GetChannelType(objHandle: HCkSsh; index: Integer; outStr: HCkString): wordbool; stdcall; function CkSsh__getChannelType(objHandle: HCkSsh; index: Integer): PWideChar; stdcall; function CkSsh_GetReceivedData(objHandle: HCkSsh; channelNum: Integer; outData: HCkByteData): wordbool; stdcall; function CkSsh_GetReceivedDataN(objHandle: HCkSsh; channelNum: Integer; maxNumBytes: Integer; outData: HCkByteData): wordbool; stdcall; function CkSsh_GetReceivedNumBytes(objHandle: HCkSsh; channelNum: Integer): Integer; stdcall; function CkSsh_GetReceivedStderr(objHandle: HCkSsh; channelNum: Integer; outData: HCkByteData): wordbool; stdcall; function CkSsh_GetReceivedStderrText(objHandle: HCkSsh; channelNum: Integer; charset: PWideChar; outStr: HCkString): wordbool; stdcall; function CkSsh__getReceivedStderrText(objHandle: HCkSsh; channelNum: Integer; charset: PWideChar): PWideChar; stdcall; function CkSsh_GetReceivedText(objHandle: HCkSsh; channelNum: Integer; charset: PWideChar; outStr: HCkString): wordbool; stdcall; function CkSsh__getReceivedText(objHandle: HCkSsh; channelNum: Integer; charset: PWideChar): PWideChar; stdcall; function CkSsh_GetReceivedTextS(objHandle: HCkSsh; channelNum: Integer; substr: PWideChar; charset: PWideChar; outStr: HCkString): wordbool; stdcall; function CkSsh__getReceivedTextS(objHandle: HCkSsh; channelNum: Integer; substr: PWideChar; charset: PWideChar): PWideChar; stdcall; function CkSsh_OpenCustomChannel(objHandle: HCkSsh; channelType: PWideChar): Integer; stdcall; function CkSsh_OpenCustomChannelAsync(objHandle: HCkSsh; channelType: PWideChar): HCkTask; stdcall; function CkSsh_OpenDirectTcpIpChannel(objHandle: HCkSsh; targetHostname: PWideChar; targetPort: Integer): Integer; stdcall; function CkSsh_OpenDirectTcpIpChannelAsync(objHandle: HCkSsh; targetHostname: PWideChar; targetPort: Integer): HCkTask; stdcall; function CkSsh_OpenSessionChannel(objHandle: HCkSsh): Integer; stdcall; function CkSsh_OpenSessionChannelAsync(objHandle: HCkSsh): HCkTask; stdcall; function CkSsh_PeekReceivedText(objHandle: HCkSsh; channelNum: Integer; charset: PWideChar; outStr: HCkString): wordbool; stdcall; function CkSsh__peekReceivedText(objHandle: HCkSsh; channelNum: Integer; charset: PWideChar): PWideChar; stdcall; function CkSsh_QuickCmdCheck(objHandle: HCkSsh; pollTimeoutMs: Integer): Integer; stdcall; function CkSsh_QuickCmdCheckAsync(objHandle: HCkSsh; pollTimeoutMs: Integer): HCkTask; stdcall; function CkSsh_QuickCmdSend(objHandle: HCkSsh; command: PWideChar): Integer; stdcall; function CkSsh_QuickCmdSendAsync(objHandle: HCkSsh; command: PWideChar): HCkTask; stdcall; function CkSsh_QuickCommand(objHandle: HCkSsh; command: PWideChar; charset: PWideChar; outStr: HCkString): wordbool; stdcall; function CkSsh__quickCommand(objHandle: HCkSsh; command: PWideChar; charset: PWideChar): PWideChar; stdcall; function CkSsh_QuickCommandAsync(objHandle: HCkSsh; command: PWideChar; charset: PWideChar): HCkTask; stdcall; function CkSsh_QuickShell(objHandle: HCkSsh): Integer; stdcall; function CkSsh_QuickShellAsync(objHandle: HCkSsh): HCkTask; stdcall; function CkSsh_ReKey(objHandle: HCkSsh): wordbool; stdcall; function CkSsh_ReKeyAsync(objHandle: HCkSsh): HCkTask; stdcall; function CkSsh_SaveLastError(objHandle: HCkSsh; path: PWideChar): wordbool; stdcall; function CkSsh_SendIgnore(objHandle: HCkSsh): wordbool; stdcall; function CkSsh_SendIgnoreAsync(objHandle: HCkSsh): HCkTask; stdcall; function CkSsh_SendReqExec(objHandle: HCkSsh; channelNum: Integer; commandLine: PWideChar): wordbool; stdcall; function CkSsh_SendReqExecAsync(objHandle: HCkSsh; channelNum: Integer; commandLine: PWideChar): HCkTask; stdcall; function CkSsh_SendReqPty(objHandle: HCkSsh; channelNum: Integer; termType: PWideChar; widthInChars: Integer; heightInChars: Integer; widthInPixels: Integer; heightInPixels: Integer): wordbool; stdcall; function CkSsh_SendReqPtyAsync(objHandle: HCkSsh; channelNum: Integer; termType: PWideChar; widthInChars: Integer; heightInChars: Integer; widthInPixels: Integer; heightInPixels: Integer): HCkTask; stdcall; function CkSsh_SendReqSetEnv(objHandle: HCkSsh; channelNum: Integer; name: PWideChar; value: PWideChar): wordbool; stdcall; function CkSsh_SendReqSetEnvAsync(objHandle: HCkSsh; channelNum: Integer; name: PWideChar; value: PWideChar): HCkTask; stdcall; function CkSsh_SendReqShell(objHandle: HCkSsh; channelNum: Integer): wordbool; stdcall; function CkSsh_SendReqShellAsync(objHandle: HCkSsh; channelNum: Integer): HCkTask; stdcall; function CkSsh_SendReqSignal(objHandle: HCkSsh; channelNum: Integer; signalName: PWideChar): wordbool; stdcall; function CkSsh_SendReqSignalAsync(objHandle: HCkSsh; channelNum: Integer; signalName: PWideChar): HCkTask; stdcall; function CkSsh_SendReqSubsystem(objHandle: HCkSsh; channelNum: Integer; subsystemName: PWideChar): wordbool; stdcall; function CkSsh_SendReqSubsystemAsync(objHandle: HCkSsh; channelNum: Integer; subsystemName: PWideChar): HCkTask; stdcall; function CkSsh_SendReqWindowChange(objHandle: HCkSsh; channelNum: Integer; widthInChars: Integer; heightInRows: Integer; pixWidth: Integer; pixHeight: Integer): wordbool; stdcall; function CkSsh_SendReqWindowChangeAsync(objHandle: HCkSsh; channelNum: Integer; widthInChars: Integer; heightInRows: Integer; pixWidth: Integer; pixHeight: Integer): HCkTask; stdcall; function CkSsh_SendReqX11Forwarding(objHandle: HCkSsh; channelNum: Integer; singleConnection: wordbool; authProt: PWideChar; authCookie: PWideChar; screenNum: Integer): wordbool; stdcall; function CkSsh_SendReqX11ForwardingAsync(objHandle: HCkSsh; channelNum: Integer; singleConnection: wordbool; authProt: PWideChar; authCookie: PWideChar; screenNum: Integer): HCkTask; stdcall; function CkSsh_SendReqXonXoff(objHandle: HCkSsh; channelNum: Integer; clientCanDo: wordbool): wordbool; stdcall; function CkSsh_SendReqXonXoffAsync(objHandle: HCkSsh; channelNum: Integer; clientCanDo: wordbool): HCkTask; stdcall; function CkSsh_SetTtyMode(objHandle: HCkSsh; ttyName: PWideChar; ttyValue: Integer): wordbool; stdcall; function CkSsh_StartKeyboardAuth(objHandle: HCkSsh; login: PWideChar; outStr: HCkString): wordbool; stdcall; function CkSsh__startKeyboardAuth(objHandle: HCkSsh; login: PWideChar): PWideChar; stdcall; function CkSsh_StartKeyboardAuthAsync(objHandle: HCkSsh; login: PWideChar): HCkTask; stdcall; function CkSsh_UnlockComponent(objHandle: HCkSsh; unlockCode: PWideChar): wordbool; stdcall; function CkSsh_WaitForChannelMessage(objHandle: HCkSsh; pollTimeoutMs: Integer): Integer; stdcall; function CkSsh_WaitForChannelMessageAsync(objHandle: HCkSsh; pollTimeoutMs: Integer): HCkTask; stdcall; implementation {$Include chilkatDllPath.inc} function CkSsh_Create; external DLLName; procedure CkSsh_Dispose; external DLLName; function CkSsh_getAbortCurrent; external DLLName; procedure CkSsh_putAbortCurrent; external DLLName; function CkSsh_getAuthFailReason; external DLLName; function CkSsh_getCaretControl; external DLLName; procedure CkSsh_putCaretControl; external DLLName; function CkSsh_getChannelOpenFailCode; external DLLName; procedure CkSsh_getChannelOpenFailReason; external DLLName; function CkSsh__channelOpenFailReason; external DLLName; procedure CkSsh_getClientIdentifier; external DLLName; procedure CkSsh_putClientIdentifier; external DLLName; function CkSsh__clientIdentifier; external DLLName; procedure CkSsh_getClientIpAddress; external DLLName; procedure CkSsh_putClientIpAddress; external DLLName; function CkSsh__clientIpAddress; external DLLName; function CkSsh_getClientPort; external DLLName; procedure CkSsh_putClientPort; external DLLName; function CkSsh_getConnectTimeoutMs; external DLLName; procedure CkSsh_putConnectTimeoutMs; external DLLName; procedure CkSsh_getDebugLogFilePath; external DLLName; procedure CkSsh_putDebugLogFilePath; external DLLName; function CkSsh__debugLogFilePath; external DLLName; function CkSsh_getDisconnectCode; external DLLName; procedure CkSsh_getDisconnectReason; external DLLName; function CkSsh__disconnectReason; external DLLName; function CkSsh_getEnableCompression; external DLLName; procedure CkSsh_putEnableCompression; external DLLName; procedure CkSsh_getForceCipher; external DLLName; procedure CkSsh_putForceCipher; external DLLName; function CkSsh__forceCipher; external DLLName; function CkSsh_getHeartbeatMs; external DLLName; procedure CkSsh_putHeartbeatMs; external DLLName; procedure CkSsh_getHostKeyAlg; external DLLName; procedure CkSsh_putHostKeyAlg; external DLLName; function CkSsh__hostKeyAlg; external DLLName; procedure CkSsh_getHostKeyFingerprint; external DLLName; function CkSsh__hostKeyFingerprint; external DLLName; procedure CkSsh_getHttpProxyAuthMethod; external DLLName; procedure CkSsh_putHttpProxyAuthMethod; external DLLName; function CkSsh__httpProxyAuthMethod; external DLLName; procedure CkSsh_getHttpProxyDomain; external DLLName; procedure CkSsh_putHttpProxyDomain; external DLLName; function CkSsh__httpProxyDomain; external DLLName; procedure CkSsh_getHttpProxyHostname; external DLLName; procedure CkSsh_putHttpProxyHostname; external DLLName; function CkSsh__httpProxyHostname; external DLLName; procedure CkSsh_getHttpProxyPassword; external DLLName; procedure CkSsh_putHttpProxyPassword; external DLLName; function CkSsh__httpProxyPassword; external DLLName; function CkSsh_getHttpProxyPort; external DLLName; procedure CkSsh_putHttpProxyPort; external DLLName; procedure CkSsh_getHttpProxyUsername; external DLLName; procedure CkSsh_putHttpProxyUsername; external DLLName; function CkSsh__httpProxyUsername; external DLLName; function CkSsh_getIdleTimeoutMs; external DLLName; procedure CkSsh_putIdleTimeoutMs; external DLLName; function CkSsh_getIsConnected; external DLLName; function CkSsh_getKeepSessionLog; external DLLName; procedure CkSsh_putKeepSessionLog; external DLLName; procedure CkSsh_getLastErrorHtml; external DLLName; function CkSsh__lastErrorHtml; external DLLName; procedure CkSsh_getLastErrorText; external DLLName; function CkSsh__lastErrorText; external DLLName; procedure CkSsh_getLastErrorXml; external DLLName; function CkSsh__lastErrorXml; external DLLName; function CkSsh_getLastMethodSuccess; external DLLName; procedure CkSsh_putLastMethodSuccess; external DLLName; function CkSsh_getMaxPacketSize; external DLLName; procedure CkSsh_putMaxPacketSize; external DLLName; function CkSsh_getNumOpenChannels; external DLLName; function CkSsh_getPasswordChangeRequested; external DLLName; function CkSsh_getPreferIpv6; external DLLName; procedure CkSsh_putPreferIpv6; external DLLName; function CkSsh_getReadTimeoutMs; external DLLName; procedure CkSsh_putReadTimeoutMs; external DLLName; procedure CkSsh_getReqExecCharset; external DLLName; procedure CkSsh_putReqExecCharset; external DLLName; function CkSsh__reqExecCharset; external DLLName; procedure CkSsh_getServerIdentifier; external DLLName; function CkSsh__serverIdentifier; external DLLName; procedure CkSsh_getSessionLog; external DLLName; function CkSsh__sessionLog; external DLLName; procedure CkSsh_getSocksHostname; external DLLName; procedure CkSsh_putSocksHostname; external DLLName; function CkSsh__socksHostname; external DLLName; procedure CkSsh_getSocksPassword; external DLLName; procedure CkSsh_putSocksPassword; external DLLName; function CkSsh__socksPassword; external DLLName; function CkSsh_getSocksPort; external DLLName; procedure CkSsh_putSocksPort; external DLLName; procedure CkSsh_getSocksUsername; external DLLName; procedure CkSsh_putSocksUsername; external DLLName; function CkSsh__socksUsername; external DLLName; function CkSsh_getSocksVersion; external DLLName; procedure CkSsh_putSocksVersion; external DLLName; function CkSsh_getSoRcvBuf; external DLLName; procedure CkSsh_putSoRcvBuf; external DLLName; function CkSsh_getSoSndBuf; external DLLName; procedure CkSsh_putSoSndBuf; external DLLName; function CkSsh_getStderrToStdout; external DLLName; procedure CkSsh_putStderrToStdout; external DLLName; function CkSsh_getStripColorCodes; external DLLName; procedure CkSsh_putStripColorCodes; external DLLName; function CkSsh_getTcpNoDelay; external DLLName; procedure CkSsh_putTcpNoDelay; external DLLName; procedure CkSsh_getUncommonOptions; external DLLName; procedure CkSsh_putUncommonOptions; external DLLName; function CkSsh__uncommonOptions; external DLLName; procedure CkSsh_getUserAuthBanner; external DLLName; procedure CkSsh_putUserAuthBanner; external DLLName; function CkSsh__userAuthBanner; external DLLName; function CkSsh_getVerboseLogging; external DLLName; procedure CkSsh_putVerboseLogging; external DLLName; procedure CkSsh_getVersion; external DLLName; function CkSsh__version; external DLLName; function CkSsh_AuthenticatePk; external DLLName; function CkSsh_AuthenticatePkAsync; external DLLName; function CkSsh_AuthenticatePw; external DLLName; function CkSsh_AuthenticatePwAsync; external DLLName; function CkSsh_AuthenticatePwPk; external DLLName; function CkSsh_AuthenticatePwPkAsync; external DLLName; function CkSsh_AuthenticateSecPw; external DLLName; function CkSsh_AuthenticateSecPwAsync; external DLLName; function CkSsh_AuthenticateSecPwPk; external DLLName; function CkSsh_AuthenticateSecPwPkAsync; external DLLName; function CkSsh_ChannelIsOpen; external DLLName; function CkSsh_ChannelPoll; external DLLName; function CkSsh_ChannelPollAsync; external DLLName; function CkSsh_ChannelRead; external DLLName; function CkSsh_ChannelReadAsync; external DLLName; function CkSsh_ChannelReadAndPoll; external DLLName; function CkSsh_ChannelReadAndPollAsync; external DLLName; function CkSsh_ChannelReadAndPoll2; external DLLName; function CkSsh_ChannelReadAndPoll2Async; external DLLName; function CkSsh_ChannelReceivedClose; external DLLName; function CkSsh_ChannelReceivedEof; external DLLName; function CkSsh_ChannelReceivedExitStatus; external DLLName; function CkSsh_ChannelReceiveToClose; external DLLName; function CkSsh_ChannelReceiveToCloseAsync; external DLLName; function CkSsh_ChannelReceiveUntilMatch; external DLLName; function CkSsh_ChannelReceiveUntilMatchAsync; external DLLName; function CkSsh_ChannelReceiveUntilMatchN; external DLLName; function CkSsh_ChannelReceiveUntilMatchNAsync; external DLLName; procedure CkSsh_ChannelRelease; external DLLName; function CkSsh_ChannelSendClose; external DLLName; function CkSsh_ChannelSendCloseAsync; external DLLName; function CkSsh_ChannelSendData; external DLLName; function CkSsh_ChannelSendDataAsync; external DLLName; function CkSsh_ChannelSendEof; external DLLName; function CkSsh_ChannelSendEofAsync; external DLLName; function CkSsh_ChannelSendString; external DLLName; function CkSsh_ChannelSendStringAsync; external DLLName; function CkSsh_CheckConnection; external DLLName; procedure CkSsh_ClearTtyModes; external DLLName; function CkSsh_Connect; external DLLName; function CkSsh_ConnectAsync; external DLLName; function CkSsh_ConnectThroughSsh; external DLLName; function CkSsh_ConnectThroughSshAsync; external DLLName; function CkSsh_ContinueKeyboardAuth; external DLLName; function CkSsh__continueKeyboardAuth; external DLLName; function CkSsh_ContinueKeyboardAuthAsync; external DLLName; procedure CkSsh_Disconnect; external DLLName; function CkSsh_GetChannelExitStatus; external DLLName; function CkSsh_GetChannelNumber; external DLLName; function CkSsh_GetChannelType; external DLLName; function CkSsh__getChannelType; external DLLName; function CkSsh_GetReceivedData; external DLLName; function CkSsh_GetReceivedDataN; external DLLName; function CkSsh_GetReceivedNumBytes; external DLLName; function CkSsh_GetReceivedStderr; external DLLName; function CkSsh_GetReceivedStderrText; external DLLName; function CkSsh__getReceivedStderrText; external DLLName; function CkSsh_GetReceivedText; external DLLName; function CkSsh__getReceivedText; external DLLName; function CkSsh_GetReceivedTextS; external DLLName; function CkSsh__getReceivedTextS; external DLLName; function CkSsh_OpenCustomChannel; external DLLName; function CkSsh_OpenCustomChannelAsync; external DLLName; function CkSsh_OpenDirectTcpIpChannel; external DLLName; function CkSsh_OpenDirectTcpIpChannelAsync; external DLLName; function CkSsh_OpenSessionChannel; external DLLName; function CkSsh_OpenSessionChannelAsync; external DLLName; function CkSsh_PeekReceivedText; external DLLName; function CkSsh__peekReceivedText; external DLLName; function CkSsh_QuickCmdCheck; external DLLName; function CkSsh_QuickCmdCheckAsync; external DLLName; function CkSsh_QuickCmdSend; external DLLName; function CkSsh_QuickCmdSendAsync; external DLLName; function CkSsh_QuickCommand; external DLLName; function CkSsh__quickCommand; external DLLName; function CkSsh_QuickCommandAsync; external DLLName; function CkSsh_QuickShell; external DLLName; function CkSsh_QuickShellAsync; external DLLName; function CkSsh_ReKey; external DLLName; function CkSsh_ReKeyAsync; external DLLName; function CkSsh_SaveLastError; external DLLName; function CkSsh_SendIgnore; external DLLName; function CkSsh_SendIgnoreAsync; external DLLName; function CkSsh_SendReqExec; external DLLName; function CkSsh_SendReqExecAsync; external DLLName; function CkSsh_SendReqPty; external DLLName; function CkSsh_SendReqPtyAsync; external DLLName; function CkSsh_SendReqSetEnv; external DLLName; function CkSsh_SendReqSetEnvAsync; external DLLName; function CkSsh_SendReqShell; external DLLName; function CkSsh_SendReqShellAsync; external DLLName; function CkSsh_SendReqSignal; external DLLName; function CkSsh_SendReqSignalAsync; external DLLName; function CkSsh_SendReqSubsystem; external DLLName; function CkSsh_SendReqSubsystemAsync; external DLLName; function CkSsh_SendReqWindowChange; external DLLName; function CkSsh_SendReqWindowChangeAsync; external DLLName; function CkSsh_SendReqX11Forwarding; external DLLName; function CkSsh_SendReqX11ForwardingAsync; external DLLName; function CkSsh_SendReqXonXoff; external DLLName; function CkSsh_SendReqXonXoffAsync; external DLLName; function CkSsh_SetTtyMode; external DLLName; function CkSsh_StartKeyboardAuth; external DLLName; function CkSsh__startKeyboardAuth; external DLLName; function CkSsh_StartKeyboardAuthAsync; external DLLName; function CkSsh_UnlockComponent; external DLLName; function CkSsh_WaitForChannelMessage; external DLLName; function CkSsh_WaitForChannelMessageAsync; external DLLName; end.
unit UBackupFileLostConn; interface uses Classes, SysUtils, DateUtils, UModelUtil, UFileBaseInfo, UMyUtil, Math; type // 递归 目录的 过期文件 TFindBackupLostConn = class private ScanPath : string; LostConnPcHash : TStringHash; private ScanCount : Integer; public constructor Create; procedure SetScanPath( _ScanPath : string ); procedure SetLostConnPcHash( _LostConnPcHash : TStringHash ); procedure SetScanInfo( _ScanCount : Integer ); procedure Update;virtual;abstract; protected function getFilePath( FileName : string ): string; virtual; procedure CheckFileInfo( FileInfo : TTempBackupFileInfo ); private procedure RemoveLoadedCopy( PcID : string; FileInfo : TTempBackupFileInfo ); procedure RemoveOfflineCopy( PcID, FileName : string ); end; // 过期目录 TFindBackupFolderLostConn = class( TFindBackupLostConn ) protected TempBackupFolderInfo : TTempBackupFolderInfo; public procedure Update;override; private procedure FindTempBackupFolderInfo; procedure CheckFileLostConn; procedure CheckFolderLostConn; procedure DeleteTempBackupFolderInfo; private function CheckNextSearch : Boolean; end; // 过期文件 TFindBackupFileLostConn = class( TFindBackupLostConn ) public procedure Update;override; protected function getFilePath( FileName : string ): string;override; end; // 处理 TCheckPcLostConnHandle = class private LostConnMin : Integer; LostConnPcHash : TStringHash; BackupPathHash : TStringHash; public constructor Create( _LostConnMin : Integer ); procedure Update; destructor Destroy; override; private function FindLostConnPcHash : Boolean; function FindBackupPathHash: Boolean; procedure FindLostConnFile; end; // 定时 检测 备份副本过期 TBackupFileLostConnThread = class( TThread ) private WaitMins, TotalMins : Integer; IsNowCheck : Boolean; public constructor Create; procedure NowCheck; destructor Destroy; override; protected procedure Execute; override; private procedure CheckPcLostConn; procedure ResetWaitMins; end; // 检测 备份副本过期 控制器 TMyBackupFileLostConnInfo = class private IsRun : Boolean; BackupFileLostConnThread : TBackupFileLostConnThread; public constructor Create; procedure StartLostConnScan; procedure LostConnScanNow; procedure StopLostConnScan; destructor Destroy; override; end; const ScanCount_Sleep : Integer = 10; var MyBackupFileLostConnInfo : TMyBackupFileLostConnInfo; implementation uses USettingInfo, UMyNetPcInfo, UMyBackupInfo, UBackupInfoXml, UBackupInfoControl, UBackupInfoFace; { TBackupFileLostConnThread } procedure TBackupFileLostConnThread.CheckPcLostConn; var CheckPcLostConnHandle : TCheckPcLostConnHandle; begin CheckPcLostConnHandle := TCheckPcLostConnHandle.Create( TotalMins ); CheckPcLostConnHandle.Update; CheckPcLostConnHandle.Free; end; constructor TBackupFileLostConnThread.Create; begin inherited Create( True ); end; destructor TBackupFileLostConnThread.Destroy; begin Terminate; Resume; WaitFor; inherited; end; procedure TBackupFileLostConnThread.Execute; var StartTime : TDateTime; begin while not Terminated do begin // 重设 等待时间 ResetWaitMins; // 等待检测周期 IsNowCheck := False; StartTime := Now; while not Terminated and not IsNowCheck and ( MinutesBetween( Now, StartTime ) < WaitMins ) do Sleep(100); // 程序结束 if Terminated then Break; // 重设 过期时间 ResetWaitMins; // 检测 有没有 Pc 离线 CheckPcLostConn; end; inherited; end; procedure TBackupFileLostConnThread.NowCheck; begin IsNowCheck := True; end; procedure TBackupFileLostConnThread.ResetWaitMins; var NewTotalMinus : Integer; begin NewTotalMinus := TimeTypeUtil.getMins( CloudFileSafeSettingInfo.CloudSafeType, CloudFileSafeSettingInfo.CloudSafeValue ); TotalMins := NewTotalMinus; WaitMins := Min( NewTotalMinus div 2, 60); end; { TCheckPcLostConnHandle } constructor TCheckPcLostConnHandle.Create( _LostConnMin : Integer ); begin LostConnMin := _LostConnMin; LostConnPcHash := TStringHash.Create; BackupPathHash := TStringHash.Create; end; destructor TCheckPcLostConnHandle.Destroy; begin BackupPathHash.Free; LostConnPcHash.Free; inherited; end; function TCheckPcLostConnHandle.FindBackupPathHash : Boolean; var FindBackupPathInPcInfo : TFindBackupPathInPcInfo; begin FindBackupPathInPcInfo := TFindBackupPathInPcInfo.Create( LostConnPcHash ); FindBackupPathInPcInfo.SetOutput( BackupPathHash ); FindBackupPathInPcInfo.Update; FindBackupPathInPcInfo.Free; Result := BackupPathHash.Count > 0; end; procedure TCheckPcLostConnHandle.FindLostConnFile; var i : Integer; p : TStringPart; FullPath : string; FindBackupLostConn : TFindBackupLostConn; begin for p in BackupPathHash do begin FullPath := p.Value; if FileExists( FullPath ) then FindBackupLostConn := TFindBackupFileLostConn.Create else FindBackupLostConn := TFindBackupFolderLostConn.Create; FindBackupLostConn.SetScanPath( FullPath ); FindBackupLostConn.SetLostConnPcHash( LostConnPcHash ); FindBackupLostConn.Update; FindBackupLostConn.Free; end; end; function TCheckPcLostConnHandle.FindLostConnPcHash: Boolean; var NetPcInfoHash : TNetPcInfoHash; p : TNetPcInfoPair; begin MyNetPcInfo.EnterData; NetPcInfoHash := MyNetPcInfo.NetPcInfoHash; for p in NetPcInfoHash do if ( not p.Value.IsOnline ) and ( MinutesBetween( Now, p.Value.LastOnlineTime ) >= LostConnMin ) then LostConnPcHash.AddString( p.Value.PcID ); MyNetPcInfo.LeaveData; Result := NetPcInfoHash.Count > 0; end; procedure TCheckPcLostConnHandle.Update; begin // 寻找 过期 Pc if not FindLostConnPcHash then Exit; // 寻找 过期 Pc 备份的根目录 if not FindBackupPathHash then Exit; // 寻找过期的文件 FindLostConnFile; end; { TBackupFileLostConnScan } procedure TFindBackupLostConn.RemoveOfflineCopy(PcID, FileName: string); var FilePath : string; BackupCopyRemoveHandle : TBackupCopyRemoveHandle; BackupFileSyncHandle : TBackupFileSyncHandle; begin FilePath := getFilePath( FileName ); // 删除 Backup Copy Info BackupCopyRemoveHandle := TBackupCopyRemoveHandle.Create( FilePath ); BackupCopyRemoveHandle.SetCopyOwner( PcID ); BackupCopyRemoveHandle.Update; BackupCopyRemoveHandle.Free; // 立刻 同步文件 BackupFileSyncHandle := TBackupFileSyncHandle.Create( FilePath ); BackupFileSyncHandle.Update; BackupFileSyncHandle.Free; end; procedure TFindBackupLostConn.RemoveLoadedCopy(PcID : string; FileInfo : TTempBackupFileInfo); var FilePath : string; BackupCopyRemoveControl : TBackupCopyRemoveControl; begin FilePath := getFilePath( FileInfo.FileName ); // 删除 副本 BackupCopyRemoveControl := TBackupCopyRemoveControl.Create( FilePath, PcID ); BackupCopyRemoveControl.SetFileSize( FileInfo.FileSize ); BackupCopyRemoveControl.Update; BackupCopyRemoveControl.Free; end; procedure TFindBackupLostConn.CheckFileInfo(FileInfo: TTempBackupFileInfo); var CopyHash : TTempCopyHash; p : TTempCopyPair; begin // 遍历所有 副本信息 CopyHash := FileInfo.TempCopyHash; for p in CopyHash do if LostConnPcHash.ContainsKey( p.Value.CopyOwner ) then begin if p.Value.Status = CopyStatus_Loaded then RemoveLoadedCopy( p.Value.CopyOwner, FileInfo ) else RemoveOfflineCopy( p.Value.CopyOwner, FileInfo.FileName ); end; end; constructor TFindBackupLostConn.Create; begin ScanCount := 0; end; function TFindBackupLostConn.getFilePath(FileName: string): string; begin Result := MyFilePath.getPath( ScanPath ) + FileName; end; procedure TFindBackupLostConn.SetLostConnPcHash( _LostConnPcHash: TStringHash); begin LostConnPcHash := _LostConnPcHash; end; procedure TFindBackupLostConn.SetScanInfo(_ScanCount: Integer); begin ScanCount := _ScanCount; end; procedure TFindBackupLostConn.SetScanPath(_ScanPath: string); begin ScanPath := _ScanPath; end; { TMyBackupFileLostConnInfo } constructor TMyBackupFileLostConnInfo.Create; begin IsRun := True; BackupFileLostConnThread := TBackupFileLostConnThread.Create; end; destructor TMyBackupFileLostConnInfo.Destroy; begin IsRun := False; inherited; end; procedure TMyBackupFileLostConnInfo.LostConnScanNow; begin BackupFileLostConnThread.NowCheck; end; procedure TMyBackupFileLostConnInfo.StartLostConnScan; begin BackupFileLostConnThread.Resume; end; procedure TMyBackupFileLostConnInfo.StopLostConnScan; begin IsRun := False; BackupFileLostConnThread.Free; end; { TFindBackupFolderLostConn } procedure TFindBackupFolderLostConn.CheckFileLostConn; var FileHash : TTempBackupFileHash; p : TTempBackupFilePair; begin FileHash := TempBackupFolderInfo.TempBackupFileHash; for p in FileHash do begin // 程序结束 if not CheckNextSearch then Break; // 检测文件是否包含过期Pc CheckFileInfo( p.Value ); end; end; procedure TFindBackupFolderLostConn.CheckFolderLostConn; var TempFolderHash : TTempBackupFolderHash; p : TTempBackupFolderPair; ChildPath : string; FindBackupFolderLostConn : TFindBackupFolderLostConn; begin TempFolderHash := TempBackupFolderInfo.TempBackupFolderHash; for p in TempFolderHash do begin if not CheckNextSearch then Break; ChildPath := MyFilePath.getPath( ScanPath ) + p.Value.FileName; // 递归目录 FindBackupFolderLostConn := TFindBackupFolderLostConn.Create; FindBackupFolderLostConn.SetScanPath( ChildPath ); FindBackupFolderLostConn.SetLostConnPcHash( LostConnPcHash ); FindBackupFolderLostConn.SetScanInfo( ScanCount ); FindBackupFolderLostConn.Update; ScanCount := FindBackupFolderLostConn.ScanCount; FindBackupFolderLostConn.Free; end; end; function TFindBackupFolderLostConn.CheckNextSearch: Boolean; begin inc( ScanCount ); if ScanCount >= ScanCount_Sleep then begin Sleep(1); ScanCount := 0; end; Result := MyBackupFileLostConnInfo.IsRun; end; procedure TFindBackupFolderLostConn.DeleteTempBackupFolderInfo; begin TempBackupFolderInfo.Free; end; procedure TFindBackupFolderLostConn.FindTempBackupFolderInfo; begin TempBackupFolderInfo := MyBackupFolderInfoUtil.ReadTempBackupFolderInfo( ScanPath ); end; procedure TFindBackupFolderLostConn.Update; begin // 读取 备份目录 缓存信息 FindTempBackupFolderInfo; // 分配 Job CheckFileLostConn; // 分配 子目录 Job CheckFolderLostConn; // 删除 缓存信息 DeleteTempBackupFolderInfo; end; { TFindBackupFileLostConn } function TFindBackupFileLostConn.getFilePath(FileName: string): string; begin Result := ScanPath; end; procedure TFindBackupFileLostConn.Update; var TempBackupFileInfo : TTempBackupFileInfo; begin // 读取文件缓存 TempBackupFileInfo := MyBackupFileInfoUtil.ReadTempBackupFileInfo( ScanPath ); // 文件不存在 if TempBackupFileInfo = nil then Exit; // 检测文件是否包含 过期Pc CheckFileInfo( TempBackupFileInfo ); end; end.
unit Unit12; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, IdBaseComponent, IdComponent, IdRawBase, IdRawClient, IdIcmpClient, IdAntiFreezeBase, IdAntiFreeze, ComCtrls, Strutils; const ICMP_TIMEOUT = 5000; ICMP_MAX_HOPS = 40; NULL_IP = '0.0.0.0'; type TForm9 = class(TForm) Icmp: TIdIcmpClient; edtHost: TEdit; StaticText1: TStaticText; sbTrace: TSpeedButton; cbResolveHosts: TCheckBox; edtIP: TEdit; IdAntiFreeze1: TIdAntiFreeze; StaticText2: TStaticText; sbStop: TSpeedButton; StaticText3: TStaticText; StatusBar: TStatusBar; reLog: TRichEdit; procedure sbTraceClick(Sender: TObject); procedure sbStopClick(Sender: TObject); private { Private declarations } FDestIP : string; FHostName : string; CurrentTTL : integer; PingStart : cardinal; FStop : boolean; procedure PingFirst; procedure PingNext; procedure ProcessResponse( Status: TReplyStatus) ; procedure Report( TTL: integer; ResponseTime: integer;Status: TReplyStatus; info: string ); public { Public declarations } end; var Form9: TForm9; implementation uses IDStack, Main; {$R *.dfm} //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *// procedure TForm9.sbTraceClick(Sender: TObject); begin FStop := false; PingFirst; end; //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *// procedure TForm9.sbStopClick(Sender: TObject); begin FStop := true; end; //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *// procedure TForm9.Report( TTL: integer; ResponseTime: integer; Status: TReplyStatus; info: string ); var HostName : string; begin Application.ProcessMessages; if cbResolveHosts.Checked and (Status.FromIpAddress <> NULL_IP ) then try StatusBar.SimpleText := ' rDNS lookup for ' + Status.FromIpAddress+ ' ...'; HostName := gStack.WSGetHostByAddr( Status.FromIpAddress ); except HostName := Status.FromIpAddress+ ' [no rDNS]'; end else HostName := '...'; with Status do begin case Status.ReplyStatusType of rsECHO : reLog.SelAttributes.Color := clGREEN; rsTIMEOUT, rsERROR, rsERRORUNREACHABLE : reLog.SelAttributes.Color := clRED else reLog.SelAttributes.Color := clNAVY; end; Form1.Memo1.Lines.Add( Format( '%-4d %-18s %4dms %-4d %s', [TTL, FromIPAddress, ResponseTime, Status.TimeToLive, Info]) ); end; Application.ProcessMessages; end; //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *// procedure TForm9.PingFirst; var OldMode : DWORD; begin reLog.Clear; Application.ProcessMessages; CurrentTTL := 1; FHostName := edtHost.Text; ICMP.ReceiveTimeout := ICMP_TIMEOUT; ICMP.TTL := CurrentTTL; OldMode := SetErrorMode( SEM_FAILCRITICALERRORS ); // trap DNS-errors! try StatusBar.SimpleText := 'looking up destination IP of ' + FHostName +' ...' ; reLog.Refresh; FDestIP := GStack.WSGetHostByName(AnsiReplaceStr(Form1.cbURL.Text, 'http://', '')); // pippo edtIP.Text := FDestIP; except edtIP.Text := '?.?.?.?'; StatusBar.SimpleText :=' cannot resolve IP-address of host "' + edtHost.Text +'"'; MessageBeep(0); // Euh Aah... EXIT; end; SetErrorMode( OldMode ); ICMP.Host := FDestIP; PingStart := GetTickCount; if not FStop then begin ICMP.Ping; Processresponse(ICMP.ReplyStatus); end; end; //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *// procedure TForm9.PingNext; var OldMode: DWORD; begin if FStop then begin reLog.Lines.Add('** INTERRUPTED **'); EXIT; end; inc(CurrentTTL); if CurrentTTL < ICMP_MAX_HOPS then begin ICMP.Host := FDestIP ; ICMP.TTL := CurrentTTL; ICMP.ReceiveTimeout := ICMP_TIMEOUT; PingStart := GetTickCount; StatusBar.SimpleText := ' ping ' + FDestIP + ' ...'; OldMode := SetErrorMode( SEM_FAILCRITICALERRORS ); try ICMP.Ping; except reLog.Lines.Add('** ERROR **'); end; SetErrorMode( OldMode ); Processresponse(ICMP.ReplyStatus); end else StatusBar.SimpleText := 'MAX TTL EXCEEDED.'; end; //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *// procedure TForm9.ProcessResponse( Status: TReplyStatus ); begin StatusBar.SimpleText := Status.FromIpAddress + ' responded'; case Status.ReplyStatusType of //------ rsECHO : begin // target host has responded Report( CurrentTTL, GetTickCount-PingStart, Status, 'Eseguito!' ); // done! StatusBar.SimpleText := 'done.'; end; //------ rsErrorTTLExceeded: begin // Time-To-Live exceeded for an ICMP response. Report( CurrentTTL, GetTickCount-PingStart, Status, 'Ok' ); PingNext; end; //------- rsTimeOut : begin // - Timeout occurred before a response was received. Report( CurrentTTL, GetTickCount-PingStart, Status, 'Time out' ); PingNext; end; //------- rsErrorUnreachable: begin // - Destination unreachable Report( CurrentTTL, GetTickCount-PingStart, Status, 'DEST_UNREACH' ); StatusBar.SimpleText := 'destination unreachable!'; end; //------ rsError: begin // - An error has occurred. Report( CurrentTTL, GetTickCount-PingStart, Status, 'ERROR' ); PingNext; end; end // case end; end.
unit uNetstatTable; interface uses GnuGettext, SysUtils, Classes, Windows, Dialogs, uProcesses; const MIB_TCP_STATE_LISTEN = 2; type MIB_TCPROW_OWNER_PID = packed record dwState: DWORD; dwLocalAddr: DWORD; dwLocalPort: DWORD; dwRemoteAddr: DWORD; dwRemotePort: DWORD; dwOwningPid: DWORD; end; // PMIB_TCPROW_OWNER_PID = ^MIB_TCPROW_OWNER_PID; MIB_TCPTABLE_OWNER_PID = packed record dwNumEntries: DWORD; table: array [0 .. 99999] of MIB_TCPROW_OWNER_PID; end; PMIB_TCPTABLE_OWNER_PID = ^MIB_TCPTABLE_OWNER_PID; tNetstatTable = class private hLibModule: THandle; DLLProcPointer: Pointer; procedure LoadExIpHelperProcedures; procedure UnLoadExIpHelperProcedures; public pTcpTable: PMIB_TCPTABLE_OWNER_PID; procedure UpdateTable; function GetPorts4PID(pid: integer): string; function GetPortCount4PID(pid: integer): integer; function isPortInUse(port: integer): string; constructor Create; destructor Destroy; override; end; var NetStatTable: tNetstatTable; implementation uses uMain, uTools; const TCP_TABLE_OWNER_PID_ALL = 5; AF_INET = 2; type TCP_TABLE_CLASS = integer; ULONG = integer; TGetExtendedTcpTable = function(pTcpTable: Pointer; dwSize: PDWORD; bOrder: BOOL; lAf: ULONG; TableClass: TCP_TABLE_CLASS; Reserved: ULONG) : DWORD; stdcall; { tNetStatTable } constructor tNetstatTable.Create; begin DLLProcPointer := nil; hLibModule := 0; pTcpTable := nil; try LoadExIpHelperProcedures; except end; end; destructor tNetstatTable.Destroy; begin try UnLoadExIpHelperProcedures; except end; inherited; end; function tNetstatTable.GetPortCount4PID(pid: integer): integer; var i: integer; // port: string; begin result := 0; for i := 0 to NetStatTable.pTcpTable.dwNumEntries - 1 do if NetStatTable.pTcpTable.table[i].dwOwningPid = Cardinal(pid) then result := result + 1; end; function tNetstatTable.GetPorts4PID(pid: integer): string; var i: integer; port: string; begin result := ''; for i := 0 to NetStatTable.pTcpTable.dwNumEntries - 1 do begin if NetStatTable.pTcpTable.table[i].dwOwningPid = Cardinal(pid) then begin port := IntToStr(NetStatTable.pTcpTable.table[i].dwLocalPort); if result = '' then result := port else result := result + ', ' + port; end; end; end; function tNetstatTable.isPortInUse(port: integer): string; var i: integer; ProcInfo: TProcInfo; pid: Cardinal; begin result := ''; for i := 0 to NetStatTable.pTcpTable.dwNumEntries - 1 do begin if NetStatTable.pTcpTable.table[i].dwLocalPort = Cardinal(port) then begin pid := NetStatTable.pTcpTable.table[i].dwOwningPid; ProcInfo := Processes.GetProcInfo(pid); if ProcInfo <> nil then result := ProcInfo.ExePath else result := _('unknown program'); exit; end; end; end; procedure tNetstatTable.LoadExIpHelperProcedures; begin hLibModule := LoadLibrary('iphlpapi.dll'); if hLibModule = 0 then exit; DLLProcPointer := GetProcAddress(hLibModule, 'GetExtendedTcpTable'); if not Assigned(DLLProcPointer) then begin ShowMessage(IntToStr(GetLastError)); end; end; procedure tNetstatTable.UnLoadExIpHelperProcedures; begin if hLibModule > HINSTANCE_ERROR then FreeLibrary(hLibModule); end; procedure tNetstatTable.UpdateTable; var dwSize: DWORD; Res: DWORD; GetExtendedTcpTable: TGetExtendedTcpTable; i: integer; begin if pTcpTable <> nil then begin FreeMem(pTcpTable); pTcpTable := nil; end; if (DLLProcPointer = nil) or (hLibModule < HINSTANCE_ERROR) then begin exit; end; GetExtendedTcpTable := DLLProcPointer; Try dwSize := 0; Res := GetExtendedTcpTable(pTcpTable, @dwSize, False, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0); If (Res = ERROR_INSUFFICIENT_BUFFER) Then Begin GetMem(pTcpTable, dwSize); // das API hat die "gewünschte" Grösse gesetzt Res := GetExtendedTcpTable(pTcpTable, @dwSize, False, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0); end; If (Res = NO_ERROR) then begin for i := 0 to pTcpTable.dwNumEntries - 1 do begin pTcpTable.table[i].dwLocalPort := ((pTcpTable.table[i].dwLocalPort and $FF00) shr 8) or ((pTcpTable.table[i].dwLocalPort and $00FF) shl 8); pTcpTable.table[i].dwRemotePort := ((pTcpTable.table[i].dwRemotePort and $FF00) shr 8) or ((pTcpTable.table[i].dwRemotePort and $00FF) shl 8); end; end else begin raiseLastOSError(); // Error-Handling end; Finally // If (pTcpTable <> Nil) Then FreeMem(pTcpTable); end; end; initialization NetStatTable := tNetstatTable.Create; finalization NetStatTable.Free; end.
(* VBE 2.0 Version 0.1 -- Access and Use of VBE 2.0 graphics modes Copyright 1995-1997 by Fernando J.A. Silva ( aka ^Magico^ ) _.--.__ _.--. ./' `--.__ ..-' ,' ,/ |`-.__ .' ./ :, : `--_ __ .' ,./'_..... : : / `-:' _\. .' ./..-' _.' : ' ,' : / \ : .' `-'__...-' `. .' . : \@/ : .' '------., ._....____ ./ : .. ` : .-' _____.----' `------------' : | `..-' `---. .---' : ./ _._-----' .---------._____________ `-.__/ : /` ./_-----/': `---...--. `-_| `.`-._______-' / / ,-----.__----. ,----' ,__. . | / `\.________./ ====__....._____.' `-___--.-' ./. .-._-'----\. ./.---..____.--. :_.-' '-' `.. .-'===.__________.' `--...__.--' [ And we must fly with the new tecnology... ] [ From Paul Desjarlais <paul_desjarlais@pharlap.com> ] *) Unit VBE20; { Video Bios Extension 2.0 Unit } { ************************ INTERFACE ******************************} { ********************* } INTERFACE Type VbeInfoRec = Record VBESignature : Array [0..3] OF Char; { Signature - "VESA" } VbeVersion : Word; { VESA Version number } OEMStringPtr : PChar; { Pointer to manufacturer name } Capabilities : DWord; { Capabilities Flags } VideoModePtrOfs : Word; { Pointer to list of VESA modes } VideoModePtrSeg : Word; { Pointer to list of VESA modes } TotalMemory : Word; { Number of 64k memory blocks on card } { VESA 2.0 } OemSoftwareRev : Word; { OEM Software Version } OemVendorNamePtr : PChar; { Pointer to Vendor Name } OemProductNamePtr : PChar; { Pointer to product name } OemProductRevPtr : PChar; { Pointer to product revision string } InfoReserved : Array [0..221] OF Byte; { Reserved } OemData : Array [0..255] OF Char; { OEM scratchpad } End; { VbeInfoRec } ModeInfoRec = Record { Mandatory information for all VBE revisions } ModeAttributes : Word; { Mode Attributes } WinAAttributes : Byte; { Window A attributes } WinBAttributes : Byte; { Window B attributes } WinGranularity : Word; { Window granularity in K bytes } WinSize : Word; { Size of window in K bytes } WinASegment : Word; { Segment address of window A } WinBSegment : Word; { Segment address of window B } WinFuncPtr : DWord; { Windows positioning function } BytesPerScanLine : Word; { Number of bytes per line } { Mandatory information for VBE 1.2 and above } XResolution : Word; { Number of horizontal pixels } YResolution : Word; { Number of vertical pixels } XCharSize : Byte; { Width of character cell } YCharSize : Byte; { Height of character cell } NumberOfPlanes : Byte; { Number of memory planes } BitsPerPixel : Byte; { Number of bits per pixel } NumberOfBanks : Byte; { Number of banks (not used) } MemoryModel : Byte; { Memory model type } BankSize : Byte; { Size of bank (not used) } NumberOfImagePages : Byte; { Number of image pages } Reserved : Byte; { The following are for 15,16,24,32 bit colour modes } { Direct Color fields (required for direct/6 and YUV/7 memory models) } RedMaskSize : Byte; { Size of Red mask in bits } RedFieldPosition : Byte; { Bit position of LSB of Red mask } GreenMaskSize : Byte; { Size of Green mask in bits } GreenFieldPosition : Byte; { Bit position of LSB of Green mask } BlueMaskSize : Byte; { Size of Blue mask in bits } BlueFieldPosition : Byte; { Bit position of LSB of Blue mask } RsvdMaskSize : Byte; { Size of Reserved mask in bits } RsvdFieldPosition : Byte; { Bit pos. of LSB of Reserved mask } DirectColorModeInfo : Byte; { Direct Colour mode attributes } { Mandatory information for VBE 2.0 and above } PhysBasePtr : DWord; { Physical address for flat frame buffer } OffScreenMemOffset : DWord; { Pointer to start of off screen memory } OffScreenMemSize : Word; { Amount of off screen memory in 1k units } ModeReserved : Array [0..205] OF Byte;{ Pad to 256 byte block size } End; { ModeInfoRec } Var VbeInfo : VbeInfoRec; ModeInfo : ModeInfoRec; { -_-_-_-_-_-_-_-_-_-_-_-_-_-_ Public rotines -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-} { Hardware and information detection rotines } FUNCTION GetVbeInfo : Byte; FUNCTION GetVbeModeInfo(Mode : Word) : Byte; FUNCTION SearchMode(XRes, YRes, BPP : Word) : Word; { Accessing VBE rotines } PROCEDURE CloseVbeMode; FUNCTION VbeSetMode(Mode : Word) : Byte; PROCEDURE VBEInit(XRes,YRes,BPP : Word); { Basic usefull rotines } PROCEDURE Retrace; { Primitive drawing rotines } PROCEDURE DrawCircle(X, Y, Radius : Word; Color : Longint); PROCEDURE DrawEllipse(X,Y, RadX, RadY : Word; Color: Longint); PROCEDURE DrawLine(X1, Y1, X2, Y2 : Integer; Color : Longint); PROCEDURE DrawPixel(X, Y : Word; Color : Longint); PROCEDURE DrawRectangle(X1, Y1, X2, Y2 : Word; Color : Longint); FUNCTION GetPixel(X,Y:Word) : Longint; { Palette and color rotines } PROCEDURE SetColor(Color : Longint; Red, Green, Blue : Byte); PROCEDURE GetColor(Color : Longint; Var Red, Green, Blue : Byte); { Frames counter rotines } PROCEDURE CheckFramesCounter; PROCEDURE InitFramesCounter; FUNCTION StopFramesCounter(Var TotalTicks : Longint; Var TotalSeconds : Integer) : Real; { ************************ IMPLEMENTATION ******************************} { ********************* } IMPLEMENTATION Uses Crt,DOS,Math,DPMI; Type TDrawPixel = Procedure(X, Y : Word; Color : Longint); TGetPixel = Function(X,Y:Word):Longint; Var pBase, PageSize : dword; lastmode : byte; wininit : boolean; pScreen : dword; vesainstalled, PModePresent:boolean; A, Ticks, TotalSec : Longint; t1,t2 : longint; VDrawPixel : TDrawPixel; VGetPixel : TGetPixel; MaxX , MaxY : Word; { ======================== Unit =========================== } { ======================== Internal =========================== } { ======================== Rotines =========================== } { *********************** } function CheckPModeInterface:Boolean; var dpmiregs:tdpmiregs; begin fillchar(dpmiregs,sizeof(dpmiregs),0); dpmiregs.eax:=$00004F0A; dpmiregs.es :=buf_16; dpmiregs.edi:=$00000000; callint($10,dpmiregs); CheckPModeInterface:=dpmiregs.eax=$0000004F; end; PROCEDURE DrawPixel8(X, Y : Word; Color : Longint); Begin { 256 Colors } Mem[pScreen + DWord(Y*ModeInfo.BytesPerScanLine + X)] := Color; End; { DrawPixel8 } PROCEDURE DrawPixel16(X, Y : Word; Color : Longint); Begin { 32K, 64K Colors } MemW[pScreen + DWord(Y*ModeInfo.BytesPerScanLine + X SHL 1)] := Color; End; { DrawPixel16 } PROCEDURE DrawPixel32(X, Y : Word; Color : Longint); Begin { 16M Colors + Brigth } MemD[pScreen + DWord(Y*ModeInfo.BytesPerScanLine + X SHL 2)] := Color; End; { DrawPixel32 } FUNCTION GetPixel8(X, Y : Word):Longint; Begin { 256 Colors } GetPixel8 := Mem[pScreen + DWord(Y*ModeInfo.BytesPerScanLine + X)]; End; { GetPixel8 } FUNCTION GetPixel16(X, Y : Word):Longint; Begin { 32k, 64k colors } GetPixel16 := MemW[pScreen + DWord(Y*ModeInfo.BytesPerScanLine + X SHL 1)]; End; { GetPixel16 } FUNCTION GetPixel32(X, Y : Word):Longint; Begin { 16M Colors + Brigth } GetPixel32 := MemD[pScreen + DWord(Y*ModeInfo.BytesPerScanLine + X SHL 2)]; End; { GetPixel32 } Procedure DrawHLine(x,y,x2: word; color: longint); var a:word; Begin for a := x to x2 do DrawPixel(a,y,color); End; Procedure DrawVLine(x,y,y2: word; color: longint); var a: word; Begin for a := y to y2 do DrawPixel(x,a,color); End; PROCEDURE ErrorMsg(Str : String;Bool : Boolean); Begin WriteLn(Str); IF Bool Then Halt; End; { ErrorMsg } { ============== Hardware and ================ } { ============== Information ================ } { ============== Detection Rotines ================ } { ******************************************** } {----------------------------------------------------------------------------} { PROCEDURE } { GetVbeInfo } { - Description : Get Information on VBE modes, etc } { - Input : ---- } { - Return : Returns info into the VbeInfo Record, and } { returns TRUE if VESA is present FALSE if not } {----------------------------------------------------------------------------} FUNCTION GetVbeInfo : Byte; Var DpmiRegs : tDpmiRegs; Begin GetVbeInfo := 0; VbeInfo.VBESignature:='VBE2'; Move(VbeInfo,Pointer(Buf_32)^,Sizeof(VbeInfo)); FillChar(DpmiRegs,Sizeof(DpmiRegs),0); DpmiRegs.eax := $00004F00; DpmiRegs.es := Buf_16; DpmiRegs.edi := $00000000; CallInt($10,DpmiRegs); Move(Pointer(Buf_32)^,VbeInfo,Sizeof(VbeInfo)); With VbeInfo DO Begin VbeSignature[0] := 'V'; VbeSignature[1] := 'B'; VbeSignature[2] := 'E'; VbeSignature[3] := '2'; End; IF Word(DpmiRegs.eax AND $0000FFFF)<>$004F Then Begin GetVbeInfo := 1; Exit; End; IF Not ((VbeInfo.VbeSignature[0]='V') AND (VbeInfo.VbeSignature[1]='B') AND (VbeInfo.VbeSignature[2]='E') AND (VbeInfo.VbeSignature[3]='2')) Then Begin GetVbeInfo := 2; Exit; End; IF Hi(VbeInfo.VbeVersion) < 2 Then Begin GetVbeInfo := 3; Exit; End; IF VbeInfo.TotalMemory < (1024/64) Then Begin GetVbeInfo := 4; Exit; End; End; { GetVbeInfo } {----------------------------------------------------------------------------} { FUNCTION } { GetVbeModeInfo } { - Description : Get Information on a VBE mode } { - Input : Mode --> mode to get information } { - Return : Returns info into the VesaMode Record and } { returns TRUE if mode available FALSE if not } {----------------------------------------------------------------------------} FUNCTION GetVbeModeInfo(Mode : Word) : Byte; Var DpmiRegs : tDpmiRegs; Begin GetVbeModeInfo := 0; FillChar(DpmiRegs,Sizeof(DpmiRegs),0); DpmiRegs.eax := $00004F01; DpmiRegs.ecx := Mode; DpmiRegs.es := Buf_16; DpmiRegs.edi := $00000000; CallInt($10,DpmiRegs); Move(Pointer(Buf_32)^,ModeInfo,Sizeof(ModeInfo)); IF Word(DpmiRegs.eax AND $0000FFFF)<>$004F Then Begin GetVbeModeInfo := 1; Exit; End; End; { GetVbeModeInfo } {----------------------------------------------------------------------------} { FUNCTION } { SearchMode } { - Description : Searchs for a mode with specific parameters } { - Input : XRes --> X Resolution } { YRes --> Y Resolution } { BPP --> number of bits for color } { - Return : The mode available for that parameters. } { Returns 0 if mode not found. } {----------------------------------------------------------------------------} FUNCTION SearchMode(XRes, YRes, BPP : Word) : Word; Var ModeFound : Boolean; ListAdr : DWord; Begin ModeFound := False; ListAdr := VbeInfo.VideoModePtrSeg SHL 4 + VbeInfo.VideoModePtrOfs; While (MemW[ListAdr]<>$FFFF) AND Not ModeFound DO Begin IF (GetVbeModeInfo(DWord(MemW[ListAdr]))=0) AND ((ModeInfo.ModeAttributes AND 1+2+8+16+128) = 1+2+8+16+128) AND (ModeInfo.XResolution = XRes) AND (ModeInfo.YResolution = YRes) AND (ModeInfo.BitsPerPixel = BPP) AND (ModeInfo.PhysBasePtr > 0) Then ModeFound := True Else Inc(ListAdr,2); End; SearchMode := MemW[ListAdr]; IF Not ModeFound Then SearchMode := 0; End; { SearchMode } { ========================= Accessing ========================= } { ========================= Vesa ========================= } { ========================= Rotines ========================= } { ************************ } {----------------------------------------------------------------------------} { PROCEDURE } { CloseVbeMode } { - Description : Closes Vesa mode and returns to text mode } { - Input : ---- } { - Return : ---- } {----------------------------------------------------------------------------} PROCEDURE CloseVbeMode; Assembler; Asm MOV AX,$0003; { Standard way of reseting videocard } INT $10; End; { CloseVbeMode } {----------------------------------------------------------------------------} { FUNCTION } { SetMode } { - Description : Sets a video mode VESA } { - Input : Mode --> Mode to set } { - Return : TRUE if sucessufull } {----------------------------------------------------------------------------} FUNCTION VbeSetMode(Mode : Word) : Byte; Var Limit, LinearAdr : DWord; DpmiRegs : tDpmiRegs; i : Word; Begin VbeSetMode := 0; Asm mov eax,0 mov ebx,0 mov ecx,0 mov edx,0 mov bx,[mode] mov ax,$4F02 int 10h mov [i],ax End; IF I<>$004F Then Begin VbeSetMode := 1; Exit; End; { Map Video Memory } LinearAdr := ModeInfo.PhysBasePtr; Limit := VbeInfo.TotalMemory*64*1024; Asm MOV EAX,$0800 MOV EBX,LinearAdr MOV ECX,EBX SHR EBX,16 AND ECX,$0000FFFF MOV ESI,Limit MOV EDI,ESI SHR ESI,16 AND EDI,$0000FFFF INT $31 JNC @Skip XOR EBX,EBX XOR ECX,ECX @Skip: SHL EBX,16 OR EBX,ECX MOV LinearAdr,EBX End; IF LinearAdr = 0 Then Begin VbeSetMode := 2; Exit; End Else Begin pScreen := LinearAdr; pBase := LinearAdr; IF ModeInfo.NumberOfImagePages > 0 Then PageSize := ModeInfo.YResolution*ModeInfo.BytesPerScanLine Else PageSize:=0; Case ModeInfo.BitsPerPixel OF 8 : Begin VDrawPixel := DrawPixel8; VGetPixel := GetPixel8; End; 15,16 : Begin VDrawPixel := DrawPixel16; VGetPixel := GetPixel16; End; 32 : Begin VDrawPixel := DrawPixel32; VGetPixel := GetPixel32; End; End; End; { IF LinearAdr = 0 } End; { VbeSetMode } PROCEDURE VBEInit(XRes,YRes,BPP : Word); Const InitStr = 'Initializing...'; ModName = 'Video Bios Extension 2.0 Module (TMT)'; ModVersion = '0.1'; Bool : Array [0..1] OF String[3] = ('n/a','OK'); UseLFB = $4000; Var Mode : Word; Begin { InitDpmi; } ClrScr; WriteLn(InitStr); WriteLn(' Module Name : ',ModName); WriteLn(' Module Version : ',ModVersion); Case GetVbeInfo OF 0 : ErrorMsg('þ VESA 2.0 detected',False); 1 : ErrorMsg('VESA Error : VESA not available (function $00 is not supported) ',True); 2 : ErrorMsg('VESA Error : Invalid Block (VESA Signature not found) ',True); 3 : ErrorMsg('VESA Error : VESA 2.0 not detected (Try to load UNIVBE.EXE) ',True); 4 : ErrorMsg('VESA Error : You Need At Least 1 Mb of Video Memory',True); End; Mode := SearchMode(XRes,YRes,BPP); IF Mode = 0 Then ErrorMsg('VESA Error : Mode not supported',True); Case GetVbeModeInfo(Mode) of 0 : ErrorMsg('þ Mode detected ',False); 1 : ErrorMsg('VESA Error : Mode with LFB not supported (Try to Load UNIVBE.EXE) ',True); End; MaxX := ModeInfo.XResolution; MaxY := ModeInfo.YResolution; Delay(100); Case VbeSetMode(Mode+UseLFB) OF 1 : Begin asm mov ax,3; int 10h; end; ErrorMsg('VESA Error : Cannot initialise Mode with LFB (Try to load UNIVBE.EXE) ',True); end; 2 : Begin asm mov ax,3; int 10h; end; ErrorMsg('VESA Error : Cannot remap memory (INT $31,Fct $0800 Error) ',True); End; End; End; { VBEInit } { ======================== Basic =========================== } { ======================== Usefull =========================== } { ======================== Rotines =========================== } { *********************** } {----------------------------------------------------------------------------} { PROCEDURE } { Retrace } { - Description : Waits for vertical retrace } { - Input : ---- } { - Return : ---- } {----------------------------------------------------------------------------} PROCEDURE Retrace; Assembler; Asm MOV DX,3DAh @Wait: IN AL,DX TEST AL,08h JZ @Wait @Retr: IN AL,DX TEST AL,08h JNZ @Retr End; { Retrace } { ======================== Primitive ======================= } { ======================== Drawing ======================= } { ======================== Rotines ======================= } { *************************** } {----------------------------------------------------------------------------} { PROCEDURE } { DrawCircle } { - Description : Draws a circle. } { - Input : X, Y, Radius, Color --> Anyone needs to I } { explain those to you } { - Return : ---- } {----------------------------------------------------------------------------} PROCEDURE DrawCircle(X, Y, Radius : Word; Color : Longint); Var Xs, Ys : Integer; Da, Db, S : Integer; Begin IF (Radius = 0) Then Exit; IF (Radius = 1) Then Begin DrawPixel(X, Y, Color); Exit; End; Xs := 0; Ys := Radius; Repeat Da := (Xs+1)*(Xs+1) + Ys*Ys - Radius*Radius; Db := (Xs+1)*(Xs+1) + (Ys - 1)*(Ys - 1) - Radius*Radius; S := Da + Db; Xs := Xs + 1; IF (S > 0) Then Ys := Ys - 1; DrawPixel(X+Xs-1, Y-Ys+1, Color); DrawPixel(X-Xs+1, Y-Ys+1, Color); DrawPixel(X+Ys-1, Y-Xs+1, Color); DrawPixel(X-Ys+1, Y-Xs+1, Color); DrawPixel(X+Xs-1, Y+Ys-1, Color); DrawPixel(X-Xs+1, Y+Ys-1, Color); DrawPixel(X+Ys-1, Y+Xs-1, Color); DrawPixel(X-Ys+1, Y+Xs-1, Color); Until (Xs >= Ys); End; { DrawCircle } {----------------------------------------------------------------------------} { PROCEDURE } { DrawEllipse } { - Description : Draws an ellipse and a clipped ellipse too } { - Input : X, Y, RadX, RadY, Color --> Anyone needs to I } { explain those to you } { - Return : ---- } {----------------------------------------------------------------------------} PROCEDURE DrawEllipse(X, Y, RadX, RadY : Word; Color: Longint); Var X1, X2, Y1, Y2 : Integer; Aq, Bq, dX, dY, R, rX,rY : Longint; Begin DrawPixel(X + RadX, Y, Color); DrawPixel(X - RadX, Y, Color); X1 := X - RadX; Y1 := Y; X2 := X + RadX; Y2 := Y; Aq := Longint(RadX) * RadX; { Calc Sqr } Bq := Longint(RadY) * RadY; dX := Aq SHL 1; { dX := 2 * RadX * RadX } dY := Bq SHL 1; { dY := 2 * RadY * RadY } R := RadX * Bq; { R := RadX * RadY * RadY } rX := R SHL 1; { rX := 2 * RadX * RadY * RadY } rY := 0; { Because Y = 0 } X := RadX; While X > 0 DO Begin IF R > 0 Then Begin { Y + 1 } INC(Y1); DEC(Y2); INC(rY, dX); { rY := dX * Y } DEC(R, rY); { R := R - dX + Y} End; IF R <= 0 Then Begin { X - 1 } DEC(X); INC(X1); DEC(X2); DEC(rX, dY); { rX := dY * X } INC(R, rX); { R := R + dY * X } End; DrawPixel(X1, Y1, Color); DrawPixel(X1, Y2, Color); DrawPixel(X2, Y1, Color); DrawPixel(X2, Y2, Color); End; End; { DrawEllipse } PROCEDURE DrawPixel(X, Y : Word; Color : Longint); Begin IF ((X>0) AND (X<MaxX)) OR ((Y>0) AND (Y<MaxY)) Then VDrawPixel(X,Y,Color); End; { DrawPixel } {----------------------------------------------------------------------------} { PROCEDURE } { DrawLine } { - Description : Draws a line } { - Input : X1, X2, Y1, Y2, Color --> Anyone needs to I } { explain those to you } { - Return : ---- } {----------------------------------------------------------------------------} PROCEDURE DrawLine(X1, Y1, X2, Y2 : Integer; Color : Longint); Var X, Y, dX, dY, Xs, Ys, Direction : Integer; Begin IF X1 = X2 Then DrawVline(X1,Y1,Y2,Color) Else IF Y1 = Y2 Then DrawHline(X1,Y1,X2,Color) Else Begin X := X1; Y := Y1; Xs := 1; Ys := 1; IF X1 > X2 Then Xs := -1; IF Y1 > Y2 Then Ys := -1; dX := Abs(X2 - X1); dY := Abs(Y2 - Y1); IF dX = 0 Then direction := -1 Else Direction := 0; While NOT ((X = X2) AND (Y = Y2)) DO Begin DrawPixel(X,Y,Color); IF Direction < 0 Then Begin Inc(Y,Ys); Inc(Direction,dX); End Else Begin Inc(X,Xs); Dec(Direction,dY); End; End; End; End; { DrawLine } {----------------------------------------------------------------------------} { PROCEDURE } { DrawRectangle } { - Description : Draws a rectangle } { - Input : X1, X2, Y1, Y2, Color --> Anyone needs to I } { explain those to you} { - Return : ---- } {----------------------------------------------------------------------------} PROCEDURE DrawRectangle(X1, Y1, X2, Y2 : Word; Color : longint); Begin DrawLine(X1,Y1,X1,Y2,Color); { Vertical 1 } DrawLine(X2,Y1,X2,Y2,Color); { Vertical 2 } DrawLine(X1,Y1,X2,Y1,Color); { Horizontal 1 } DrawLine(X1,Y2,X2,Y2,Color); { Horizontal 2 } End; { DrawRectangle } {----------------------------------------------------------------------------} { FUNCTION } { GetPixel } { - Description : Gets the color of a specified pixel } { - Input : X, Y --> Anyone needs to I explain those to you } { - Return : The pixel color } {----------------------------------------------------------------------------} FUNCTION GetPixel(X, Y : Word):Longint; Begin GetPixel := VGetPixel(X,Y); End; { GetPixel } { ========================= Palette ====================== } { ========================= And Color ====================== } { ========================= Rotines ====================== } { *************************** } {----------------------------------------------------------------------------} { PROCEDURE } { SetColor } { - Description : Changes a color with new RGB values } { - Input : Color --> the color to change } { Red, Green, Blue --> the new values } { - Return : ---- } {----------------------------------------------------------------------------} PROCEDURE SetColor(Color : Longint; Red, Green, Blue : Byte); Begin Port[$3C8] := Color; Port[$3C9] := Red; Port[$3C9] := Green; Port[$3C9] := Blue; End; { SetColor } {----------------------------------------------------------------------------} { PROCEDURE } { GetColor } { - Description : Gets the RGB values from a color } { - Input : Color --> the color to get values } { - Return : Red, Green, Blue --> output values } {----------------------------------------------------------------------------} PROCEDURE GetColor(Color : Longint; Var Red, Green, Blue : Byte); Begin Port[$3C7] := Color; Red := Port[$3C9]; Green := Port[$3C9]; Blue := Port[$3C9]; End; { SetColor } { ========================== Frames ======================== } { ========================== Counter ======================== } { ========================== Rotines ======================== } { ************************ } {----------------------------------------------------------------------------} { PROCEDURE } { CheckFramesCounter } { - Description : Checks and updates the new frames values } { - Input : ---- } { - Return : ---- } {----------------------------------------------------------------------------} PROCEDURE CheckFramesCounter; Var Date : DateTime; Dumb : word; Begin Inc(Ticks); { GetTime(date.hour,date.min,date.sec,dumb); t2 := date.hour*3600+date.min*60+date.sec; TotalSec := t2 - t1; } End; { CheckFramesCounter } {----------------------------------------------------------------------------} { PROCEDURE } { InitFramesCounter } { - Description : Initiates the frames counter } { - Input : ---- } { - Return : ---- } {----------------------------------------------------------------------------} PROCEDURE InitFramesCounter; Var Date : DateTime; Dumb : word; Begin Ticks := 0; TotalSec := 0; GetTime(date.hour,date.min,date.sec,dumb); t1 := date.hour*3600+date.min*60+date.sec; End; { InitFramesCounter } {----------------------------------------------------------------------------} { FUNCTION } { StopFramesCounter } { - Description : Stops the frames counter and says the values } { - Input : VAR TotalTicks and TotalSeconds } { - Return : The frames per second value } {----------------------------------------------------------------------------} FUNCTION StopFramesCounter(Var TotalTicks : Longint; Var TotalSeconds : Integer) : Real; Var Date : DateTime; Dumb : word; Begin GetTime(date.hour,date.min,date.sec,dumb); t2 := date.hour*3600+date.min*60+date.sec; TotalSec := t2 - t1; TotalTicks := Ticks; TotalSeconds := TotalSec; StopFramesCounter := Ticks / TotalSec; End; { StopFramesCounter } Begin End.
unit ModelBrokerTests; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, ModelDataModel, ModelBroker; type { TBrokerTest } TBrokerTest = class(TTestCase) private FVariable: boolean; FBroker: IBroker; FObserver: IObserver; procedure TestNotify; procedure TestSubscribe; protected procedure Setup; override; procedure TearDown; override; published {Observer should be capable to subscribe yourself to broker and notify all observers} procedure SubscribeAndNotify; {Broker should be able to subscribe an observer and notify all observers, but in this case observer can't notify broker} procedure SubscribeFromBroker; {If one observer will subscribe yourself more than once then broker should raise an exception} procedure DoubleSubscribe; end; implementation { TBrokerTest } procedure TBrokerTest.TestNotify; begin FVariable := True; end; procedure TBrokerTest.TestSubscribe; begin FBroker.Subscribe(FObserver); end; procedure TBrokerTest.Setup; begin FVariable := False; FBroker := TModelBroker.Create; FObserver := TModelObserver.Create; FObserver.Notify := @TestNotify; end; procedure TBrokerTest.TearDown; begin FBroker := nil; FObserver := nil; end; procedure TBrokerTest.SubscribeAndNotify; begin FObserver.Subscribe(FBroker); FObserver.MessageToBrokers; Sleep(1000); AssertTrue(FVariable = True); end; procedure TBrokerTest.SubscribeFromBroker; begin FBroker.Subscribe(FObserver); FBroker.NotifyAllObservers; Sleep(1000); AssertTrue(FVariable = True); end; procedure TBrokerTest.DoubleSubscribe; begin FObserver.Subscribe(FBroker); AssertException(Exception,@TestSubscribe); end; initialization RegisterTest(TBrokerTest); end.
unit pastinn; {< pastinn (Pascal Tiny Neural Network) @br @br (c) 2018 Matthew Hipkin <https://www.matthewhipkin.co.uk> @author(Matthew Hipkin (www.matthewhipkin.co.uk)) @br @br A Pascal port of tinn a tiny neural network library for C https://github.com/glouw/tinn } {$IFDEF FPC} {$mode delphi}{$H+} {$ENDIF} interface uses Classes, SysUtils; type { Simple string array type } TArray = array of string; { Simple 2d array of Single type } TSingleArray = array of Single; { Data record used by the neural network } TTinnData = record { 2D floating point array of input } inp: array of TSingleArray; { 2D floating point array of target } tg: array of TSingleArray; end; { The neural network record } TPasTinn = record { All the weights } w: TSingleArray; { Hidden to output layer weights } x: TSingleArray; { Biases } b: TSingleArray; { Hidden layer } h: TSingleArray; { Output layer } o: TSingleArray; { Number of biases - always two - Tinn only supports a single hidden layer } nb: Integer; { Number of weights } nw: Integer; { Number of inputs } nips: Integer; { Number of hidden neurons } nhid: Integer; { Number of outputs } nops: Integer; end; { Tiny neural network main class } TTinyNN = class(TObject) private FTinn: TPasTinn; FTinnData: TTinnData; FIndex: Integer; protected { Calculates error } function err(const a: Single; const b: Single): Single; { Calculates partial derivative of error function } function pderr(const a: Single; const b: Single): Single; { Calculates total error of output target } function toterr(index: Integer): Single; { Activation function } function act(const a: Single): Single; { Returns partial derivative of activation function } function pdact(const a: Single): Single; { Performs back propagation } procedure bprop(const rate: Single); { Performs forward propagation } procedure fprop; { Randomize weights and baises } procedure wbrand; public { Trains a tinn with an input and target output with a learning rate. Returns target to output error } function Train(const rate: Single; index: Integer): Single; { Prepare the TPasTinn record for usage } procedure Build(nips: Integer; nhid: Integer; nops: Integer); { Returns an output prediction on given input } function Predict(index: Integer): TSingleArray; { Save neural network to file } procedure SaveToFile(path: String); { Load neural network from file } procedure LoadFromFile(path: String); { Dump contents of array to screen } procedure PrintToScreen(arr: TSingleArray; size: Integer); { Set input data } procedure SetData(inp: TTinnData); { Shuffle input data } procedure ShuffleData; end; { Split string by a delimiter } function explode(cDelimiter, sValue : string; iCount : integer) : TArray; implementation function explode(cDelimiter, sValue : string; iCount : integer) : TArray; var s : string; i,p : integer; begin s := sValue; i := 0; while length(s) > 0 do begin inc(i); SetLength(result, i); p := pos(cDelimiter,s); if ( p > 0 ) and ( ( i < iCount ) OR ( iCount = 0) ) then begin result[i - 1] := copy(s,0,p-1); s := copy(s,p + length(cDelimiter),length(s)); end else begin result[i - 1] := s; s := ''; end; end; end; { TTinyNN } // Computes error function TTinyNN.err(const a: Single; const b: Single): Single; begin Result := 0.5 * (a - b) * (a - b); end; // Returns partial derivative of error function. function TTinyNN.pderr(const a: Single; const b: Single): Single; begin Result := a - b; end; // Computes total error of target to output. function TTinyNN.toterr(index: Integer): Single; var i: Integer; begin Result := 0.00; for i := 0 to FTinn.nops -1 do begin Result := Result + err(FTinnData.tg[index,i], FTinn.o[i]); end; end; // Activation function. function TTinyNN.act(const a: Single): Single; begin Result := 1.0 / (1.0 + exp(-a)); end; // Returns partial derivative of activation function. function TTinyNN.pdact(const a: Single): Single; begin Result := a * (1.0 - a); end; // Performs back propagation procedure TTinyNN.bprop(const rate: Single); var i,j,z: Integer; a,b,sum: Single; begin for i := 0 to FTinn.nhid-1 do begin sum := 0.00; // Calculate total error change with respect to output for j := 0 to FTinn.nops-1 do begin a := pderr(FTinn.o[j], FTinnData.tg[FIndex,j]); b := pdact(FTinn.o[j]); z := j * FTinn.nhid + i; sum := sum + a * b * FTinn.x[z]; // Correct weights in hidden to output layer FTinn.x[z] := FTinn.x[z] - rate * a * b * FTinn.h[i]; end; // Correct weights in input to hidden layer for j := 0 to FTinn.nips-1 do begin z := i * FTinn.nips + j; FTinn.w[z] := FTinn.w[z] - rate * sum * pdact(FTinn.h[i]) * FTinnData.inp[FIndex,j]; end; end; end; // Performs forward propagation procedure TTinyNN.fprop; var i,j,z: Integer; sum: Single; begin // Calculate hidden layer neuron values for i := 0 to FTinn.nhid-1 do begin sum := 0.00; for j := 0 to FTinn.nips-1 do begin z := i * FTinn.nips + j; sum := sum + FTinnData.inp[FIndex,j] * FTinn.w[z]; end; FTinn.h[i] := act(sum + FTinn.b[0]); end; // Calculate output layer neuron values for i := 0 to FTinn.nops-1 do begin sum := 0.00; for j := 0 to FTinn.nhid-1 do begin z := i * FTinn.nhid + j; sum := sum + FTinn.h[j] * FTinn.x[z]; end; FTinn.o[i] := act(sum + FTinn.b[1]); end; end; // Randomizes tinn weights and biases procedure TTinyNN.wbrand; var i: Integer; begin for i := 0 to FTinn.nw-1 do FTinn.w[i] := Random - 0.5; for i := 0 to FTinn.nb-1 do FTinn.b[i] := Random - 0.5; end; // Returns an output prediction given an input function TTinyNN.Predict(index: Integer): TSingleArray; begin FIndex := index; fprop; Result := FTinn.o; end; // Trains a tinn with an input and target output with a learning rate. Returns target to output error function TTinyNN.Train(const rate: Single; index: Integer): Single; begin FIndex := index; fprop; bprop(rate); //Result := toterr(FTinnData.tg[index], FTinn.o, FTinn.nops); Result := toterr(FIndex); end; // Prepare the TfpcTinn record for usage procedure TTinyNN.Build(nips: Integer; nhid: Integer; nops: Integer); begin FTinn.nb := 2; FTinn.nw := nhid * (nips + nops); SetLength(FTinn.w,FTinn.nw); SetLength(FTinn.x,FTinn.nw); SetLength(FTinn.b,FTinn.nb); SetLength(FTinn.h,nhid); SetLength(FTinn.o,nops); FTinn.nips := nips; FTinn.nhid := nhid; FTinn.nops := nops; wbrand; end; procedure TTinyNN.ShuffleData; var a,b: Integer; ot, it: TSingleArray; begin for a := Low(FTinnData.inp) to High(FTinnData.inp) do begin b := Random(32767) mod High(FTinnData.inp); ot := FTinnData.tg[a]; it := FTinnData.inp[a]; // Swap output FTinnData.tg[a] := FTinnData.tg[b]; FTinnData.tg[b] := ot; // Swap input FTinnData.inp[a] := FTinnData.inp[b]; FTinnData.inp[b] := it; end; end; // Save the tinn to file procedure TTinyNN.SaveToFile(path: String); var F: TextFile; i: Integer; begin AssignFile(F,path); Rewrite(F); // Write header writeln(F,FTinn.nips,' ',FTinn.nhid,' ',FTinn.nops); // Write biases for i := 0 to FTinn.nb-1 do begin writeln(F,FTinn.b[i]:1:6); end; // Write weights for i := 0 to FTinn.nw-1 do begin writeln(F,FTinn.w[i]:1:6); end; // Write hidden to output weights for i := 0 to FTinn.nw-1 do begin writeln(F,FTinn.x[i]:1:6); end; CloseFile(F); end; // Load an existing tinn from file procedure TTinyNN.LoadFromFile(path: String); var F: TextFile; i, nips, nhid, nops: Integer; l: Single; s: String; p: TArray; begin AssignFile(F,path); Reset(F); nips := 0; nhid := 0; nops := 0; // Read header Readln(F,s); p := explode(' ',s,0); nips := StrToInt(p[0]); nhid := StrToInt(p[1]); nops := StrToInt(p[2]); // Create initial Tinn Build(nips, nhid, nops); // Read biases for i := 0 to FTinn.nb-1 do begin Readln(F,l); FTinn.b[i] := l; end; // Read weights for i := 0 to FTinn.nw-1 do begin Readln(F,l); FTinn.w[i] := l; end; // Read hidden to output weights for i := 0 to FTinn.nw-1 do begin Readln(F,l); FTinn.x[i] := l; end; CloseFile(F); end; procedure TTinyNN.SetData(inp: TTinnData); begin FTinnData := inp; end; // Dump the contents of the specified array procedure TTinyNN.PrintToScreen(arr: TSingleArray; size: Integer); var i: Integer; begin for i := 0 to size-1 do begin write(arr[i]:1:6,' '); end; writeln; end; end.
program CreateAndReadTextFile; var T: TextFile; // Переменная-дескриптор текстового файла I: Integer; M: Real; S: String; begin AssignFile(T, 'my_data.txt'); // Связь файловой переменной с именем файла на диске ReWrite(T); // Открытие файла для перезаписи (создания) WriteLn(T, 'Hello, world!'); // Запись в файл одной строки символов "Hello, world!" for I := 1 to 5 do // Вычисление m = $0.1 i^2$ и запись значения в файл для i = 1,2,3,4,5 begin M := 0.1 * Sqr(I); WriteLn(T, M:0:2); end; Write(T, 42); // Запись числа 42 без перевода строки Write(T, ';'); // Запись символа ; сразу за числом 42 S := 'See ya!'; WriteLn(T, S); // Запись содержимого строки S CloseFile(T); // Закрытие файла для завершения работы и сохранения результатов на жесткий диск Reset(T); // Открытие текстового файла для чтения while not EOF(T) do begin ReadLn(T, S); // Считываем из файла очередную строку в переменную S WriteLn(S); // Вывод значения строки S на экран (в консоль) end; CloseFile(T); // Закрытие файла ReadLn; end.
{ List all the PICs that are supported by the LProg. } program lprg_list; %include 'sys.ins.pas'; %include 'util.ins.pas'; %include 'string.ins.pas'; %include 'file.ins.pas'; %include 'stuff.ins.pas'; %include 'picprg.ins.pas'; var pr: picprg_t; {PICPRG library state} pic_p: picprg_idblock_p_t; {info about one PIC} npics: sys_int_machine_t; {total number of PICs found} llist: string_list_t; {list of PICs supported by LProg} stat: sys_err_t; {completion status} begin string_cmline_init; {init for reading the command line} string_cmline_end_abort; {no command line parameters allowed} picprg_init (pr); {init library state} picprg_open (pr, stat); {open the PICPRG library} sys_error_abort (stat, '', '', nil, 0); { * Make a list of all the PICs that the LProg can handle. } npics := 0; {init total number of PICs found} string_list_init (llist, util_top_mem_context); {init list of supported PIC names} llist.deallocable := false; {won't individually delete list entries} pic_p := pr.env.idblock_p; {init to first PIC in list} while pic_p <> nil do begin {scan the PICs in the list} npics := npics + 1; {count one more PIC found in the list} case pic_p^.fam of {which family is this PIC in ?} picprg_picfam_18f14k22_k, picprg_picfam_18k80_k, picprg_picfam_16f182x_k, picprg_picfam_16f15313_k, picprg_picfam_16f183xx_k, picprg_picfam_12f1501_k, picprg_picfam_24h_k, picprg_picfam_24fj_k, picprg_picfam_33ep_k: begin string_list_str_add ( {add name of this PIC to the list} llist, pic_p^.name_p^.name); end; end; pic_p := pic_p^.next_p; {to next PIC in list} end; {back to handle this new PIC} { * LLIST is the list of names of all PICs that are supported by the LProg. } picprg_close (pr, stat); sys_error_abort (stat, '', '', nil, 0); string_list_sort ( {sort the list of supported PICs} llist, {the list to sort} [ string_comp_ncase_k, {ignore character case} string_comp_num_k]); {compare numeric fields numerically} string_list_pos_abs (llist, 1); {go to first list entry} while llist.str_p <> nil do begin {loop over all the entries} writeln (llist.str_p^.str:llist.str_p^.len); string_list_pos_rel (llist, 1); end; writeln; writeln (llist.n, ' of ', npics, ' PICs supported by the LProg'); end.
unit MaterialPoster; interface uses DBGate, BaseObjects, PersistentObjects, Material,Table, DB, Organization, Employee, LasFile; type // для типов документов TDocTypeDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; // для документов TSimpleDocumentDataPoster = class(TImplementedDataPoster) private FAllDocTypes:TDocumentTypes; FAllMaterialLocations: TMaterialLocations; FAllOrganizations:TOrganizations; FAllEmployees:TEmployees; public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; property AllDocTypes:TDocumentTypes read FAllDocTypes write FAllDocTypes; property AllMaterialLocations:TMaterialLocations read FAllMaterialLocations write FAllMaterialLocations; property AllOrganizations:TOrganizations read FAllOrganizations write FAllOrganizations; property AllEmployees:TEmployees read FAllEmployees write FAllEmployees; constructor Create; override; end; TMaterialLocationDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TObjectBindTypeDataPoster = class(TImplementedDataPoster) private FAllRiccTables: TRiccTables; FAllRiccAttributes: TRICCAttributes; public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; property AllRiccTables: TRiccTables read FAllRiccTables write FAllRiccTables; property AllRiccAttributes: TRICCAttributes read FAllRiccAttributes write FAllRiccAttributes; constructor Create; override; end; TMaterialBindingDataPoster = class(TImplementedDataPoster) private FAllSimpleDocuments: TSimpleDocuments; FAllObjectBindTypes: TObjectBindTypes; public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; property AllSimpleDocuments: TSimpleDocuments read FAllSimpleDocuments write FAllSimpleDocuments; property AllObjectBindTypes: TObjectBindTypes read FAllObjectBindTypes write FAllObjectBindTypes; constructor Create; override; end; TMaterialCurveDataPoster = class(TImplementedDataPoster) private FAllSimpleDocuments: TSimpleDocuments; FAllCurveCategoryes: TCurveCategories; public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; property AllSimpleDocuments: TSimpleDocuments read FAllSimpleDocuments write FAllSimpleDocuments; property AllCurveCategoryes: TCurveCategories read FAllCurveCategoryes write FAllCurveCategoryes; constructor Create; override; end; TMaterialAuthorDataPoster = class(TImplementedDataPoster) private FAllSimpleDocuments: TSimpleDocuments; // FAllEmployees: TEmployees; public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; property AllSimpleDocuments: TSimpleDocuments read FAllSimpleDocuments write FAllSimpleDocuments; // property AllEmployees: TEmployees read FAllEmployees write FAllEmployees; constructor Create; override; end; TObjectBindMaterialTypeDataPoster = class(TImplementedDataPoster) private FAllObjectBindTypes: TObjectBindTypes; FAllDocumentTypes:TDocumentTypes; public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; property AllObjectBindTypes: TObjectBindTypes read FAllObjectBindTypes write FAllObjectBindTypes; property AllDocumentTypes: TDocumentTypes read FAllDocumentTypes write FAllDocumentTypes; constructor Create; override; end; implementation uses Facade,SysUtils,DateUtils, Variants; { TDocTypesCategoryDataPoster } constructor TDocTypeDataPoster.Create; begin inherited; Options := [soGetKeyValue]; DataSourceString := 'VW_MATERIAL_TYPES'; DataDeletionString := ''; DataPostString := 'SPD_ADD_MATERIAL_TYPE'; KeyFieldNames := 'MATERIAL_TYPE_ID'; FieldNames := 'MATERIAL_TYPE_ID, VCH_MATERIAL_TYPE_NAME, PARENTS_MATERIAL_TYPE_ID, BOOL_ARCHOV, LEVEL_ACCESS_ID'; AccessoryFieldNames := 'MATERIAL_TYPE_ID, VCH_MATERIAL_TYPE_NAME, PARENTS_MATERIAL_TYPE_ID, BOOL_ARCHOV, LEVEL_ACCESS_ID'; AutoFillDates := false; Sort := 'VCH_MATERIAL_TYPE_NAME'; end; function TDocTypeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TDocTypeDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TDocumentType; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TDocumentType; o.ID := ds.FieldByName('MATERIAL_TYPE_ID').AsInteger; o.Name := ds.FieldByName('VCH_MATERIAL_TYPE_NAME').AsString; //BOOL_ARCHOV, //LEVEL_ACCESS_ID ds.Next; end; ds.First; end; end; function TDocTypeDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; { TDocumentDataPoster } constructor TSimpleDocumentDataPoster.Create; begin inherited; Options := [soKeyInsert]; DataSourceString := 'VW_MATERIALS__NEW'; DataPostString:= 'SPD_ADD_MATERIAL_V3'; KeyFieldNames := 'MATERIAL_ID'; FieldNames := 'MATERIAL_ID, VCH_MATERIAL_NAME, MATERIAL_TYPE_ID, DTM_ENTERING_DATE, VCH_LOCATION,DTM_CREATION_DATE,NUM_INVENTORY_NUMBER,NUM_TGF_NUMBER,ORGANIZATION_ID,EMPLOYEE_ID,LOCATION_ID,VCH_COMMENTS,VCH_AUTHORS,VCH_BIND_ATTRIBUTES'; AccessoryFieldNames := 'MATERIAL_ID, VCH_MATERIAL_NAME, MATERIAL_TYPE_ID, DTM_ENTERING_DATE, VCH_LOCATION,DTM_CREATION_DATE,NUM_INVENTORY_NUMBER,NUM_TGF_NUMBER,ORGANIZATION_ID,EMPLOYEE_ID,LOCATION_ID,VCH_COMMENTS,VCH_AUTHORS,VCH_BIND_ATTRIBUTES'; AutoFillDates := false; Sort := 'NUM_INVENTORY_NUMBER, VCH_MATERIAL_NAME'; end; function TSimpleDocumentDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TSimpleDocumentDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TSimpleDocument; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TSimpleDocument; o.ID := ds.FieldByName('MATERIAL_ID').AsInteger; o.Name := o.StrToCorrect(ds.FieldByName('VCH_MATERIAL_NAME').AsString); o.LocationPath := ds.FieldByName('VCH_LOCATION').AsString; o.InventNumber:=ds.FieldByName('NUM_INVENTORY_NUMBER').AsInteger; o.TGFNumber:=ds.FieldByName('NUM_TGF_NUMBER').AsInteger; o.Authors:=ds.FieldByName('VCH_AUTHORS').AsString; o.Bindings:=ds.FieldByName('VCH_BIND_ATTRIBUTES').AsString; o.CreationDate:=ds.FieldByName('DTM_CREATION_DATE').AsDateTime; o.EnteringDate:=ds.FieldByName('DTM_ENTERING_DATE').AsDateTime; o.MaterialComment:=ds.FieldByName('VCH_COMMENTS').AsString; if Assigned(AllDocTypes) then o.DocType := AllDocTypes.ItemsByID[ds.FieldByName('MATERIAL_TYPE_ID').AsInteger] as TDocumentType; if Assigned(AllMaterialLocations) then o.MaterialLocation := AllMaterialLocations.ItemsByID[ds.FieldByName('LOCATION_ID').AsInteger] as TMaterialLocation; if Assigned(AllOrganizations) then o.Organization := AllOrganizations.ItemsByID[ds.FieldByName('ORGANIZATION_ID').AsInteger] as TOrganization; if Assigned(AllEmployees) then o.Employee := AllEmployees.ItemsByID[ds.FieldByName('EMPLOYEE_ID').AsInteger] as TEmployee; ds.Next; end; ds.First; end; end; function TSimpleDocumentDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; w: TSimpleDocument; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); w := AObject as TSimpleDocument; ds.FieldByName('MATERIAL_ID').AsInteger := w.ID; ds.FieldByName('VCH_MATERIAL_NAME').AsString:= w.Name; ds.FieldByName('DTM_CREATION_DATE').asDateTime:= DateOf(w.CreationDate); ds.FieldByName('DTM_ENTERING_DATE').asDateTime:= DateOf(w.EnteringDate); ds.FieldByName('NUM_INVENTORY_NUMBER').AsInteger:= w.InventNumber; ds.FieldByName('NUM_TGF_NUMBER').AsInteger:= w.TGFNumber; ds.FieldByName('VCH_LOCATION').AsString:= w.VCHLocation; ds.FieldByName('VCH_AUTHORS').AsString:= w.Authors; ds.FieldByName('VCH_BIND_ATTRIBUTES').AsString:= w.Bindings; ds.FieldByName('VCH_COMMENTS').AsString:= w.MaterialComment; ds.FieldByName('MATERIAL_TYPE_ID').AsInteger:= w.DocType.Id; ds.FieldByName('LOCATION_ID').AsInteger:= w.MaterialLocation.Id; ds.FieldByName('ORGANIZATION_ID').AsInteger:= w.Organization.Id; ds.FieldByName('EMPLOYEE_ID').AsInteger:= 775;//w.Employee.Id; // ds.FieldByName('STRUCTURE_ID').AsInteger:= w.Structure.ID; // ds.FieldByName('Version_ID').AsInteger:= w.Structure.Version; ds.Post; if w.ID = 0 then Result := ds.FieldByName('MATERIAL_ID').AsInteger; end; { TMaterialLocationDataPoster } constructor TMaterialLocationDataPoster.Create; begin inherited; Options := [soGetKeyValue]; DataSourceString := 'TBL_Location'; DataDeletionString := 'TBL_Location'; DataPostString := 'TBL_Location'; KeyFieldNames := 'Location_ID'; FieldNames := 'Location_ID, VCH_Location_NAME'; AccessoryFieldNames := 'Location_ID, VCH_Location_NAME'; AutoFillDates := false; Sort := 'VCH_Location_NAME'; end; function TMaterialLocationDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TMaterialLocationDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TMaterialLocation; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TMaterialLocation; o.ID := ds.FieldByName('Location_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_Location_NAME').AsString); ds.Next; end; ds.First; end; end; function TMaterialLocationDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; w: TMaterialLocation; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); w := AObject as TMaterialLocation; ds.FieldByName('Location_ID').AsInteger := w.ID; ds.FieldByName('VCH_Location_NAME').AsString := w.Name; ds.Post; if w.ID = 0 then Result := ds.FieldByName('Location_ID').AsInteger; end; { TTObjectBindTypeDataPoster } constructor TObjectBindTypeDataPoster.Create; begin inherited; Options := [soGetKeyValue]; DataSourceString := 'TBL_OBJECT_BIND_TYPES'; DataDeletionString := 'TBL_OBJECT_BIND_TYPES'; DataPostString := 'TBL_OBJECT_BIND_TYPES'; KeyFieldNames := 'OBJECT_BIND_TYPE_ID'; FieldNames := 'OBJECT_BIND_TYPE_ID,VCH_OBJECT_BIND_TYPE_NAME,table_id,attribute_id'; AccessoryFieldNames := 'OBJECT_BIND_TYPE_ID,VCH_OBJECT_BIND_TYPE_NAME,table_id,attribute_id'; AutoFillDates := false; Sort := 'VCH_OBJECT_BIND_TYPE_NAME'; end; function TObjectBindTypeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TObjectBindTypeDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TObjectBindType; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TObjectBindType; o.ID := ds.FieldByName('Object_Bind_Type_ID').AsInteger; o.Name:=ds.FieldByName('VCH_Object_Bind_Type_Name').AsString; if Assigned(AllRiccTables) then o.RiccTable := AllRiccTables.ItemsByID[ds.FieldByName('TABLE_ID').AsInteger] as TRiccTable; if Assigned(AllRiccAttributes) then o.RiccAttribute := AllRiccAttributes.ItemsByID[ds.FieldByName('ATTRIBUTE_ID').AsInteger] as TRiccAttribute; ds.Next; end; ds.First; end; end; function TObjectBindTypeDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result:=0; end; { TMaterialBindingDataPoster } constructor TMaterialBindingDataPoster.Create; begin inherited; Options := [soGetKeyValue]; DataSourceString := 'TBL_Material_Binding'; DataDeletionString := 'TBL_Material_Binding'; DataPostString := 'SPD_ADD_MATERIAL_BIND'; KeyFieldNames := 'MATERIAL_ID;OBJECT_BIND_TYPE_ID;OBJECT_BIND_ID'; FieldNames := 'MATERIAL_ID,OBJECT_BIND_TYPE_ID,OBJECT_BIND_ID'; AccessoryFieldNames := 'MATERIAL_ID,OBJECT_BIND_TYPE_ID,OBJECT_BIND_ID'; AutoFillDates := false; Sort := 'MATERIAL_ID'; end; function TMaterialBindingDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TCommonServerDataSet; mb: TMaterialBinding; begin Assert(DataDeletionString <> '', 'Не задан приемник данных ' + ClassName); Result := 0; ds := TMainFacade.GetInstance.DBGates.Add(Self); try // находим строку соответствующую ключу //ds.Refresh; mb := AObject as TMaterialBinding; ds.First; if ds.Locate(ds.KeyFieldNames, varArrayOf([mb.SimpleDocument.ID,mb.ObjectBindType.ID,AObject.ID]), []) then ds.Delete except Result := -1; end; end; function TMaterialBindingDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TMaterialBinding; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TMaterialBinding; if Assigned(AllSimpleDocuments) then o.SimpleDocument := AllSimpleDocuments.ItemsByID[ds.FieldByName('MATERIAL_ID').AsInteger] as TSimpleDocument; if Assigned(AllObjectBindTypes) then o.ObjectBindType := AllObjectBindTypes.ItemsByID[ds.FieldByName('OBJECT_BIND_TYPE_ID').AsInteger] as TObjectBindType; o.ID:=ds.FieldByName('OBJECT_BIND_ID').AsInteger; ds.Next; end; ds.First; end; end; function TMaterialBindingDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; w: TMaterialBinding; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); w := AObject as TMaterialBinding; ds.FieldByName('Material_id').AsInteger := w.SimpleDocument.id; ds.FieldByName('OBJECT_BIND_TYPE_ID').AsInteger := w.ObjectBindType.id; ds.FieldByName('OBJECT_BIND_ID').AsInteger := w.ID; ds.Post; //if w.ID = 0 then // Result := ds.FieldByName('Location_ID').AsInteger; end; { TMaterialCurveDataPoster } constructor TMaterialCurveDataPoster.Create; begin inherited; Options := [soGetKeyValue]; DataSourceString := 'TBL_MATERIAL_CURVE'; DataDeletionString := 'TBL_MATERIAL_CURVE'; DataPostString := 'TBL_MATERIAL_CURVE'; KeyFieldNames := 'MATERIAL_ID; CURVE_CATEGORY_ID'; FieldNames := 'MATERIAL_ID, CURVE_CATEGORY_ID'; AccessoryFieldNames := 'MATERIAL_ID, CURVE_CATEGORY_ID'; AutoFillDates := false; Sort := 'MATERIAL_ID'; end; function TMaterialCurveDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TCommonServerDataSet; mc: TMaterialCurve; begin Assert(DataDeletionString <> '', 'Не задан приемник данных ' + ClassName); Result := 0; ds := TMainFacade.GetInstance.DBGates.Add(Self); try // находим строку соответствующую ключу //ds.Refresh; mc := AObject as TMaterialCurve; ds.First; if ds.Locate(ds.KeyFieldNames, varArrayOf([mc.SimpleDocument.ID, mc.CurveCategory.ID]), []) then ds.Delete except Result := -1; end; end; function TMaterialCurveDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TMaterialCurve; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TMaterialCurve; if Assigned(AllSimpleDocuments) then o.SimpleDocument := AllSimpleDocuments.ItemsByID[ds.FieldByName('MATERIAL_ID').AsInteger] as TSimpleDocument; o.CurveCategory :=AllCurveCategoryes.ItemsByID[ds.FieldByName('CURVE_CATEGORY_ID').AsInteger] as TCurveCategory; end; ds.First; end; end; function TMaterialCurveDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; mc: TMaterialCurve; begin {Result := 0; mc := AObject as TMAterialCurve; try ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Active then ds.Open; if ds.Locate(KeyFieldNames, varArrayOf([mc.SimpleDocument.ID, mc.CurveCategory.ID]), []) then ds.Edit else ds.Append; except on E: Exception do begin raise; end; end; } Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); mc := AObject as TMaterialCurve; //if Assigned(o.Owner) then //ds.FieldByName('WELL_UIN').Value:= o.Owner.ID; ds.FieldByName('MATERIAL_ID').Value:= mc.SimpleDocument.ID; ds.FieldByName('CURVE_CATEGORY_ID').Value := mc.CurveCategory.ID; ds.Post; //ds.FieldByName('MATERIAL_ID').Value := mc.SimpleDocument.ID; //ds.FieldByName('CURVE_CATEGORY_ID').Value := mc.CurveCategory.ID; //ds.Post; end; { TMaterialAuthorDataPoster } constructor TMaterialAuthorDataPoster.Create; begin inherited; Options := [soGetKeyValue]; DataSourceString := 'TBL_AUTHOR'; DataDeletionString := 'TBL_AUTHOR'; DataPostString := 'SPD_ADD_AUTHOR'; KeyFieldNames := 'employee_id; MATERIAL_ID'; FieldNames := 'employee_id,MATERIAL_ID,role_ID'; AccessoryFieldNames := 'employee_id,MATERIAL_ID,role_ID'; AutoFillDates := false; Sort := 'MATERIAL_ID'; end; function TMaterialAuthorDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TCommonServerDataSet; ma: TMaterialAuthor; begin Assert(DataDeletionString <> '', 'Не задан приемник данных ' + ClassName); Result := 0; ds := TMainFacade.GetInstance.DBGates.Add(Self); try // находим строку соответствующую ключу //ds.Refresh; ma := AObject as TMaterialAuthor; ds.First; if ds.Locate(ds.KeyFieldNames, varArrayOf([AObject.ID, ma.SimpleDocument.ID]), []) then ds.Delete except Result := -1; end; end; function TMaterialAuthorDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TMaterialAuthor; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TMaterialAuthor; if Assigned(AllSimpleDocuments) then o.SimpleDocument := AllSimpleDocuments.ItemsByID[ds.FieldByName('MATERIAL_ID').AsInteger] as TSimpleDocument; o.ID :=ds.FieldByName('EMPLOYEE_ID').AsInteger; o.Role := TAuthorRole(ds.FieldByName('ROLE_ID').AsInteger); ds.Next; end; ds.First; end; end; function TMaterialAuthorDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; w: TMaterialAuthor; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); w := AObject as TMaterialAuthor; ds.FieldByName('EMPLOYEE_ID').AsInteger := w.ID; ds.FieldByName('Material_id').AsInteger := w.SimpleDocument.id; ds.FieldByName('Role_ID').AsInteger := ord(w.Role); ds.Post; end; { TObjectBindMaterialTypeDataPoster } constructor TObjectBindMaterialTypeDataPoster.Create; begin inherited; Options := [soGetKeyValue]; DataSourceString := 'TBL_OBJECT_BIND_MATERIAL_TYPE'; DataDeletionString := 'TBL_OBJECT_BIND_MATERIAL_TYPE'; DataPostString := 'TBL_OBJECT_BIND_MATERIAL_TYPE'; KeyFieldNames := 'OBJECT_BIND_TYPE_ID,MATERIAL_TYPE_ID'; FieldNames := 'OBJECT_BIND_TYPE_ID,MATERIAL_TYPE_ID'; AccessoryFieldNames := 'OBJECT_BIND_TYPE_ID,MATERIAL_TYPE_ID'; AutoFillDates := false; Sort := 'MATERIAL_TYPE_ID'; end; function TObjectBindMaterialTypeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TObjectBindMaterialTypeDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TObjectBindMaterialType; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TObjectBindMaterialType; if Assigned(AllObjectBindTypes) then o.ObjectBindType := AllObjectBindTypes.ItemsByID[ds.FieldByName('OBJECT_BIND_TYPE_ID').AsInteger] as TObjectBindType; if Assigned(AllDocumentTypes) then o.DocumentType := AllDocumentTypes.ItemsByID[ds.FieldByName('MATERIAL_TYPE_ID').AsInteger] as TDocumentType; ds.Next; end; ds.First; end; end; function TObjectBindMaterialTypeDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result:=0; end; end.
unit Matrices; {$mode objfpc}{$H+} interface uses Classes, SysUtils,Dialogs; type m_Matriz = array of array of real; type TMatrices = class public A: m_matriz; constructor Create(n,m: Integer); procedure setMatriz(); procedure printMatriz(); Function Suma(B: TMatrices) : TMatrices; Function Resta(B: TMatrices) : TMatrices; Function Multiplicacion( B: TMatrices) : TMatrices; Function Division(B: TMatrices) : TMatrices; Function MultEscalar(n:Real): TMatrices; Function Potencia(B:TMatrices;pot: Integer):TMatrices; Function Inversa(B:TMatrices):TMatrices; Function Transpuesta (): TMatrices; Function Determinante(B: TMatrices): Real; Function Traza():Real; Function SubMatriz(i,j:Integer):TMatrices; Function Adjunta (B:TMatrices): TMatrices; procedure Identidad(); end; implementation constructor TMatrices.Create(n,m: Integer); begin SetLength(A,n,m); end; Function TMatrices.Suma(B:TMatrices): TMatrices; var i,j,fil,col: integer; res: TMatrices; begin fil:=Length(A); col:=Length(A[0]); res:=TMatrices.create(fil,col); for i:=0 to fil-1 do for j:=0 to col-1 do res.A[i,j]:=A[i,j]+B.A[i,j]; Result:= res; end; Function TMatrices.Resta(B:TMatrices): TMatrices; var i,j,fil,col: integer; res: TMatrices; begin fil:=Length(A); col:=Length(A[0]); res:=TMatrices.create(fil,col); for i:=0 to fil-1 do for j:=0 to col-1 do res.A[i,j]:=A[i,j]-B.A[i,j]; Result:= res; end; Function TMatrices.Multiplicacion(B:TMatrices):TMatrices; var fila,cola,colb,i,j,k: integer; res: TMatrices; temporal: Real; begin fila := Length(A); cola:= Length(A[0]); colb:= Length(B.A[0]); res:=Tmatrices.create(fila,colb); for i:= 0 to fila-1 do //i para las filas de la matriz resultante for k := 0 to colb-1 do begin// k para las columnas de la matriz resultante temporal := 0 ; for j := 0 to cola-1 do begin//j para realizar la multiplicacion de los elementos de la matriz temporal := temporal + A[i][j] * B.A[j][k]; res.A[i][k] := temporal ; end; end; Result:=res; end; function TMatrices.Division(B: TMatrices) : TMatrices ; var fil,col:Integer; res,aux: TMatrices; begin fil:=Length(B.A); col:=Length(B.A[0]); aux:=TMatrices.Create(fil,col); fil:=Length(A); res:=TMatrices.create(fil,col); Aux:=B.Inversa(B); res:=Multiplicacion(aux); result:=res; end; Function TMatrices.MultEscalar(n:Real):TMatrices; var i,j,fil,col: Integer; res: TMatrices; begin fil:=Length(A); col:=Length(A[0]); res:=TMatrices.Create(fil,col); for i:=0 to fil-1 do for j:=0 to col-1 do begin res.A[i,j]:=A[i,j]*n; end; Result:=res; end; Function TMatrices.Potencia(B: TMatrices;pot:Integer):TMatrices; var fil,col,i: Integer; C: TMatrices; begin fil:=Length(B.A); col:=Length(B.A[0]); i:=1; C:=TMatrices.create(fil,col); C.A:=B.A; if pot=0 then identidad() else begin while(i<pot) do begin C:=C.Multiplicacion(B); i:=i+1; end; B.A:=C.A; end; Result:=B; end; Function TMatrices.Inversa(B:TMatrices): TMatrices; var fil,col: Integer; det: Real; adj,res: TMatrices; begin fil:=Length(B.A); col:=Length(B.A[0]); if (fil<>col) then exit; adj:=TMatrices.create(fil,col); res:=TMatrices.create(fil,col); adj:=Adjunta(B); det:=Determinante(B); if det=0 then begin ShowMessage('Matriz no invertible, determinante = 0'); result:=res; exit; end; adj:=adj.Transpuesta(); det:=1/det; res:=adj.MultEscalar(det); Result:=res; end; Function TMatrices.Transpuesta():TMatrices; var i,j,fil,col:integer; res: TMatrices; begin fil:=Length(A); col:=Length(A[0]); res:=TMatrices.create(col,fil); for i:=0 to fil -1 do for j:=0 to col -1 do res.A[j,i]:=A[i,j]; result:=res; end; Function TMatrices.Determinante(B:TMatrices):Real; var s,k,ma,na:integer ; begin result:=0.0; ma:=Length(B.A); if ma>1 then na:=Length(B.A[0]) else begin result:=B.A[0,0]; exit; end; if not (ma=na)then exit; if(ma=2) then result:=B.A[0,0]*B.A[1,1]-B.A[0,1]*B.A[1,0] else if ma=3 then result:=B.A[0,0]*B.A[1,1]*B.A[2,2]+B.A[2,0]*B.A[0,1]*B.A[1,2]+B.A[1,0]*B.A[2,1]*B.A[0,2]- B.A[2,0]*B.A[1,1]*B.A[0,2]-B.A[1,0]*B.A[0,1]*B.A[2,2]-B.A[0,0]*B.A[2,1]*B.A[1,2] else begin s:=1; for k:=0 to na-1 do begin result:=result+s*B.A[0,k]*Determinante(Submatriz(0,k)); s:=s*-1; end; end; end; Function TMatrices.Traza(): Real; var i,orden: Integer; temporal: Real; begin orden:=Length(A); temporal:=0; for i:=0 to orden-1 do temporal:= temporal + A[i][i]; Result:=temporal; end; Function TMatrices.SubMatriz(i:Integer;j:Integer):TMatrices; var w,x,y,z,fil,col:Integer; res: TMatrices; begin fil:=Length(A); col:=Length(A[0]); res:=TMatrices.create(fil-1,col-1); w:=0;z:=0; for x:=0 to fil-1 do begin if (x<>i) then begin for y:=0 to col-1 do if (y<>j) then begin res.A[w,z]:=A[x,y]; z:=z+1; end; w:=w+1; z:=0; end; end; Result:=res; end; Function TMatrices.Adjunta(B:TMatrices):TMatrices; var i,j,s,s1,fil,col: integer; res, temp: TMatrices; begin fil:=length(B.A); col:=length(B.A[0]); if(fil<>col) then exit; res:=TMatrices.create(fil,col); temp:=TMatrices.create(fil-1,col-1); s1:=1; for i:=0 to fil-1 do begin s:=s1; for j:=0 to col-1 do begin temp:=SubMatriz(i,j); res.A[i,j]:=s*Determinante(temp); s:=s*(-1); end; s1:=s1*(-1); end; Result:=res; end; procedure TMatrices.SetMatriz(); var m,n,i,j: Integer; numset: Real; begin m:=Length(A); n:=Length(A[0]); for j:=0 to m-1 do begin for i:=0 to n-1 do begin Write('[',i,',',j,']: '); Read (numSet); A[j,i]:=numSet; end; end; WriteLn(' '); end; procedure TMatrices.printMatriz(); Var m,n,j,i:Integer; begin m:=Length(A); n:=Length(A[0]); for j:=0 to m-1 do begin Write('[ '); for i:=0 to n-1 do begin Write(A[j,i]:0:2,' , '); end; WriteLn(' ]'); end; WriteLn(' '); end; procedure TMatrices.Identidad(); var fil,col,i,j: Integer; begin fil:=Length(A); col:=Length(A[0]); for i:=0 to fil-1 do for j:=0 to col-1 do begin if i=j then A[i,j]:=1 else A[i,j]:=0; end; end; end.
{* Guarda en la tabla DOCUMENT.DB una relación de todas las llamadas SQL generadas por los componentes UNIDAC. El campo descripción puede ser modificado mediante la utilidad DOCDM.EXE que se encuentra dentro de la carpeta SMTOOLS. También se puede obtener un informe con los datos de la tabla. @author Carlos Clavería @version 1.0 OCT-2011 } unit documentaDM; interface uses classes,VirtualTable,DB,SysUtils,Uni,Variants; procedure Documenta(DM : TDataModule); const /// Nombre del fichero generado por Documenta. DOCFILE = 'DOCUMENT.DB'; implementation {* Realiza la documentación del DataModule. Desde cualcuier parte de la aplicación que tenga declarada la unit del datamodule : DoocumentaDM.Documenta(DataMod); El fichero será generado en la carpeta del ejecutable. @param DM Nombre del DataModule } procedure Documenta(DM : TDataModule); var i : integer; t : TVirtualTable; begin try t := TVirtualTable.Create(nil); t.FieldDefs.Add('DATAMODULE',ftString,20,TRUE); t.FieldDefs.Add('NOMBRE',ftString,20,TRUE); t.FieldDefs.Add('CLASE',ftString,20,TRUE); t.FieldDefs.Add('SQLTEXT',ftMemo); t.FieldDefs.Add('DESCRIPCION',ftMemo); t.IndexFieldNames := 'DATAMODULE;NOMBRE'; if fileexists(DOCFILE) then t.LoadFromFile(DOCFILE); t.Open; t.Filter := format('DATAMODULE = ''%s''',[DM.Name]); t.Filtered := TRUE; // QUITO DE LA TABLA LOS ELIMINADOS if t.RecordCount > 0 then begin t.First; while not t.eof do begin if (dm.FindComponent(t.FieldByName('CLASE').AsString) = nil) then t.Delete; t.Next; end; end; for i := 0 to DM.ComponentCount-1 do if DM.Components[i] is TUniQuery then begin if t.Locate('DATAMODULE;NOMBRE',VarArrayOf([DM.Name,TUniQuery(DM.Components[i]).Name]),[]) then begin t.Edit; t.FieldByName('SQLTEXT').AsString := TUniQuery(DM.Components[i]).SQL.Text; end else begin t.Insert; t.FieldByName('DATAMODULE').AsString := DM.Name; t.FieldByName('NOMBRE').AsString := TUniQuery(DM.Components[i]).Name; t.FieldByName('CLASE').AsString := 'TUniQuery'; t.FieldByName('SQLTEXT').AsString := TUniQuery(DM.Components[i]).SQL.Text; end; t.Post; end else if DM.Components[i] is TUniSQL then begin if t.Locate('DATAMODULE;NOMBRE',VarArrayOf([DM.Name,TUniSQL(DM.Components[i]).Name]),[]) then begin t.Edit; t.FieldByName('SQLTEXT').AsString := TUniSQL(DM.Components[i]).SQL.Text; end else begin t.Insert; t.FieldByName('DATAMODULE').AsString := DM.Name; t.FieldByName('NOMBRE').AsString := TUniSQL(DM.Components[i]).Name; t.FieldByName('CLASE').AsString := 'TUniSQL'; t.FieldByName('SQLTEXT').AsString := TUniSQL(DM.Components[i]).SQL.Text; end; t.Post; end else if DM.Components[i] is TUniTable then begin if t.Locate('DATAMODULE;NOMBRE',VarArrayOf([DM.Name,TUniTable(DM.Components[i]).Name]),[]) then begin t.Edit; t.FieldByName('SQLTEXT').AsString := format('SELECT * FROM %s',[TUniTable(DM.Components[i]).TableName]); end else begin t.Insert; t.FieldByName('DATAMODULE').AsString := DM.Name; t.FieldByName('NOMBRE').AsString := TUniTable(DM.Components[i]).Name; t.FieldByName('CLASE').AsString := 'TUniTable'; t.FieldByName('SQLTEXT').AsString := format('SELECT * FROM %s',[TUniTable(DM.Components[i]).TableName]); end; t.Post; end finally t.Close; t.SaveToFile(DOCFILE); end; end; end.
(** * $Id: dco.transport.AbstractTransportImpl.pas 840 2014-05-24 06:04:58Z QXu $ * * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either * express or implied. See the License for the specific language governing rights and limitations under the License. *) unit dco.transport.AbstractTransportImpl; interface uses dutil.util.concurrent.BlockingQueue, dco.transport.Pdu, dco.transport.Transport; type /// <summary>The abstract class implements the basic behaviors of a transport resource. To maximize the throughput, /// it holds two threads for transmitting inbound and outbound messages. The messages will be stored in thread-safe /// blocking queues.</summary> TAbstractTransportImpl = class abstract(TInterfacedObject, ITransport) protected // Initially I plan to keep them private and expose IQueue in protected scope. However I cannot use `property` to // case a generic class to a generic interface. But if I use functions to expose them, I have to do extra locking // for the thread safety. FInboundQueue: TBlockingQueue<TPdu>; FOutboundQueue: TBlockingQueue<TPdu>; public constructor Create; destructor Destroy; override; /// <summary>Returns the identifier of the transport resource.</summary> function GetUri: string; virtual; abstract; /// <summary>Blocks until an inbound message is retrieved.</summary> function Read: TPdu; /// <summary>Sends an outbound message and waits for it is actually sent out.</summary> function WriteEnsured(const Pdu: TPdu): Boolean; virtual; abstract; /// <summary>Sends an outbound message and returns immediately.</summary> procedure Write(const Pdu: TPdu); /// <summary>Pushs an inbound message to the recipient.</summary> procedure ForceRead(const Pdu: TPdu); end; implementation constructor TAbstractTransportImpl.Create; begin inherited Create; FInboundQueue := TBlockingQueue<TPdu>.Create; FOutboundQueue := TBlockingQueue<TPdu>.Create; end; destructor TAbstractTransportImpl.Destroy; begin FOutboundQueue.Free; FInboundQueue.Free; inherited; end; procedure TAbstractTransportImpl.ForceRead(const Pdu: TPdu); begin // Usually the pdu is a poison pill to shut down gracefully to corresponding data reader. FInboundQueue.Put(Pdu); end; function TAbstractTransportImpl.Read: TPdu; begin Result := FInboundQueue.Take; end; procedure TAbstractTransportImpl.Write(const Pdu: TPdu); begin FOutboundQueue.Put(Pdu); end; end.
unit SubDividerComponentEditFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, SubDividerCommonObjects, CheckLst, ComCtrls, ImgList; type TfrmSubComponentEdit = class(TFrame) gbxProperties: TGroupBox; Label3: TLabel; edtDepth: TEdit; cmbxEdgeComment: TComboBox; pnlButtons: TPanel; btnOK: TButton; btnCancel: TButton; GroupBox1: TGroupBox; mmProperties: TMemo; imgLst: TImageList; pgctl: TPageControl; tshCommon: TTabSheet; tshPlus: TTabSheet; chlbxPlus: TCheckListBox; cmbxFilter: TComboBox; lblFilter: TLabel; chbxTemplateEdit: TCheckBox; Label5: TLabel; Label4: TLabel; cmbxComment: TComboBox; Label1: TLabel; cmbxStraton: TComboBox; Label2: TLabel; cmbxNextStraton: TComboBox; chbxChangeUndivided: TCheckBox; chbxVerified: TCheckBox; procedure btnOKClick(Sender: TObject); procedure cmbxFilterChange(Sender: TObject); procedure cmbxStratonChange(Sender: TObject); procedure edtDepthChange(Sender: TObject); procedure chlbxPlusClickCheck(Sender: TObject); procedure cmbxCommentChange(Sender: TObject); procedure edtDepthKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure pgctlChange(Sender: TObject); private { Private declarations } FWithButtons: boolean; FEditingComponent: TSubDivisionComponent; FAddTo: TSubDivision; FSearchString: string; FNearestComponent: TSubdivisionComponent; FUndividedChanged: integer; procedure SetSearchString(const Value: string); procedure SetAdditionalStratons(Value: TStratons); procedure ClearAll; procedure SetEditingComponent(Value: TSubDivisionComponent); procedure SetWithButtons(const Value: boolean); procedure Init; property SearchString: string read FSearchString write SetSearchString; function CheckedCount: integer; procedure EnableOK; public { Public declarations } property AddTo: TSubDivision read FAddTo write FAddTo; property AdditionalStratons: TStratons write SetAdditionalStratons; property EditingComponent: TSubDivisionComponent read FEditingComponent write SetEditingComponent; property NearestComponent: TSubdivisionComponent read FNearestComponent write FNearestComponent; property WithButtons: boolean read FWithButtons write SetWithButtons; property UndividedChanged: integer read FUndividedChanged; procedure ShowChanges; constructor Create(AOwner: TComponent); override; end; implementation uses SubDividerCommon, ClientCommon; {$R *.DFM} procedure TfrmSubComponentEdit.SetSearchString(const Value: string); var i, iPos: integer; sSearch, sStraton: string; ValidRanges: set of byte; begin if WithButtons or (pgctl.ActivePageIndex = 1) then begin iPos := DigitPos(Value); if (iPos > 1) and (iPos + 1= pos(' ', Value)) then Dec(iPos); sSearch := trim(copy(Value, 1, iPos)); // выбираем фильтр из списка ValidRanges := []; if WithButtons then begin if Assigned(FEditingComponent) then begin with FEditingComponent do for i := 0 to Stratons.Count - 1 do ValidRanges := ValidRanges + [0 .. Stratons[i].TaxRange]; end; end; //else sSearch := Value; if ValidRanges = [] then ValidRanges := [0 .. 255]; if (sSearch <> FSearchString) and (pos(FSearchString, sSearch) = 0) then begin if WithButtons then chlbxPlus.Items.Clear; with cmbxFilter do begin ItemIndex := -1; for i := 0 to Items.Count - 1 do if (sSearch = (Items.Objects[i] as TStraton).StratonIndex) then begin ItemIndex := i; break; end; end; FSearchString := sSearch; if sSearch = '' then begin with AllStratons do for i := 0 to Count - 1 do if Items[i].TaxRange in ValidRanges then chlbxPlus.Items.AddObject(Items[i].ListStraton(sloIndexName), Items[i]); exit; end else begin sSearch := RusTransLetter(AnsiUpperCase(sSearch)); with AllStratons do for i := 0 to Count - 1 do begin sStraton := RusTransLetter(Items[i].StratonIndex); if (pos(sSearch, sStraton) = 1) and (Items[i].TaxRange in ValidRanges) then chlbxPlus.Items.AddObject(Items[i].ListStraton(sloIndexName), Items[i]); end; end; end; end; end; procedure TfrmSubComponentEdit.SetAdditionalStratons(Value: TStratons); var i, iIndex: integer; begin if Assigned(Value) then begin cmbxStraton.ItemIndex := cmbxStraton.Items.IndexOf(Value[0].ListStraton(sloIndexName)); cmbxNextStraton.ItemIndex := -1; if Value.Count > 1 then cmbxNextStraton.ItemIndex := cmbxNextStraton.Items.IndexOf(Value[1].ListStraton(sloIndexName)); chlbxPlus.Items.BeginUpdate; iIndex := 0; for i := 1 to Value.Count - 1 do if Value[i].TaxRange < Value[iIndex].TaxRange then iIndex := i; SearchString := Value[iIndex].ListStraton(sloIndexName); for i := 0 to Value.Count - 1 do begin iIndex := chlbxPlus.Items.IndexOf(Value[i].ListStraton(sloIndexName)); if iIndex > -1 then begin chlbxPlus.Checked[iIndex] := true; chlbxPlus.ItemIndex := iIndex; end; end; chlbxPlus.Items.EndUpdate; end; end; procedure TfrmSubComponentEdit.ClearAll; begin cmbxStraton.ItemIndex := -1; cmbxNextStraton.ItemIndex := -1; edtDepth.Clear; edtDepth.Enabled := true; //cmbxComment.ItemIndex := -1; cmbxEdgeComment.ItemIndex := -1; end; {constructor TfrmSubComponentEdit.Create(AOwner: TComponent); begin FWithButtons := false; end;} procedure TfrmSubComponentEdit.SetEditingComponent(Value: TSubDivisionComponent); var Well: TWell; sD: TSubDivision; i, iIndex: integer; begin tshPlus.TabVisible := GatherComponents; chbxVerified.Checked := true; if FEditingComponent <> Value then begin FEditingComponent := Value; ClearAll; FSearchString := ' '; chlbxPlus.Clear; // загружаем стратоны чтобы показать плюсовик if Assigned(Value) then with FEditingComponent do begin chbxVerified.Checked := Verified; if GatherComponents then begin if (FEditingComponent.Stratons.Count > 1) and (FEditingComponent.Divider = '+') then pgctl.ActivePageIndex := 1 else pgctl.ActivePageIndex := 0; chlbxPlus.Items.BeginUpdate; iIndex := 0; for i := 1 to Stratons.Count - 1 do if Stratons[i].TaxRange < Stratons[iIndex].TaxRange then iIndex := i; SearchString := Stratons[iIndex].ListStraton(sloIndexName); for i := 0 to Stratons.Count - 1 do begin iIndex := chlbxPlus.Items.IndexOf(Stratons[i].ListStraton(sloIndexName)); if iIndex > -1 then begin chlbxPlus.Checked[iIndex] := true; chlbxPlus.ItemIndex := iIndex; end; end; if not WithButtons then for i := chlbxPlus.Items.Count - 1 downto 0 do if not chlbxPlus.Checked[i] then chlbxPlus.Items.Delete(i); chlbxPlus.Items.EndUpdate; end; cmbxStraton.ItemIndex := cmbxStraton.Items.IndexOf(Stratons[0].ListStraton(sloIndexName)); if Stratons.Count > 1 then cmbxNextStraton.ItemIndex := cmbxNextStraton.Items.IndexOf(Stratons[1].ListStraton(sloIndexName)); if Depth > 0 then edtDepth.Text := trim(Format('%6.2f',[Depth])) else edtDepth.Text := ''; cmbxComment.ItemIndex := cmbxComment.Items.IndexOfObject(TObject(SubdivisionCommentID)); edtDepth.Enabled := (cmbxComment.ItemIndex <> 1); Well := ((Collection as TSubDivisionComponents).SubDivision.Collection as TSubdivisions).Well; mmProperties.Clear; mmProperties.Lines.Add('скв. ' + Well.WellNum + ' - ' + Well.AreaName); mmProperties.Lines.Add('альт. ' + trim(Format('%6.2f', [Well.Altitude]))); mmProperties.Lines.Add('забой ' + trim(Format('%6.2f', [Well.Depth]))); sD := (Collection as TSubDivisionComponents).SubDivision; if sD.TectonicBlock <> '' then mmProperties.Lines.Add('тект. блок. ' + sD.TectonicBlock); end else SearchString := ''; end; EnableOk; end; procedure TfrmSubComponentEdit.ShowChanges; var C: TSubDivisionComponent; begin C := FEditingComponent; FEditingComponent := nil; EditingComponent := C; end; function TfrmSubComponentEdit.CheckedCount: integer; var i: integer; begin Result := 0; with chlbxPlus do for i := 0 to Items.Count - 1 do inc(Result, ord(Checked[i])); end; procedure TfrmSubComponentEdit.EnableOK; var S: String; procedure DecorateEdit(AColor: TColor); begin edtDepth.Font.Color := AColor; case AColor of clRed: edtDepth.Font.Style := [fsBold]; clBlack: edtDepth.Font.Style := []; end; end; begin if WithButtons then begin S := StringReplace(edtDepth.Text, '.', DecimalSeparator, [rfReplaceAll]); S := StringReplace(S, ',', DecimalSeparator, [rfReplaceAll]); try DecorateEdit(clBlack); btnOK.Enabled := true; StrToFloat(S) except if S <> '' then begin DecorateEdit(clRed); btnOK.Enabled := false end else if cmbxComment.ItemIndex > 1 then btnOK.Enabled := true else btnOk.Enabled := false; end; if btnOK.Enabled then case pgctl.ActivePageIndex of 0: btnOK.Enabled := cmbxStraton.ItemIndex > -1; 1: btnOK.Enabled := CheckedCount > 0; end; end; end; procedure TfrmSubComponentEdit.Init; var strlst: TStringList; i: integer; begin if Assigned(AllStratons) then begin strlst := TStringList.Create; strlst.Clear; AllDicts.MakeList(strlst, AllDicts.CommentDict); //cmbxComment.Items.AddStrings(strlst); {strlst.Clear; AllDicts.MakeList(strlst, AllDicts.EdgesDict); cmbxEdgeComment.Items.AddStrings(strlst);} cmbxNextStraton.Items.AddObject('<нет>', nil); if Assigned(AllStratons) then with AllStratons do for i := 0 to Count - 1 do begin cmbxStraton.Items.AddObject(Items[i].ListStraton(sloIndexName), Items[i]); cmbxNextStraton.Items.AddObject(Items[i].ListStraton(sloIndexName), Items[i]); if Items[i].TaxRange < 6 then cmbxFilter.Items.AddObject(Items[i].ListStraton(sloIndexName), Items[i]); end; strlst.Free; end; EnableOK; end; procedure TfrmSubComponentEdit.SetWithButtons(const Value: boolean); begin FWithButtons := Value; pnlButtons.Visible := FWithButtons; chbxTemplateEdit.Visible := FWithButtons; chbxChangeUndivided.Visible := FWithButtons; Height := Height - ord(not FWithButtons)* pnlButtons.Height + ord(FWithButtons)* pnlButtons.Height; Init; if not WithButtons then gbxProperties.Enabled := false; cmbxFilter.Visible := WithButtons; lblFilter.Visible := WithButtons; end; procedure TfrmSubComponentEdit.btnOKClick(Sender: TObject); var iCommentID, i: integer; Strs{, Strs2}: TStratons; sDivider: char; C, unDiv: TSubDivisionComponent; fDepth, fLastDepth: single; begin FUndividedChanged := 0; // C := EditingComponent; C := nil; //Strs2 := nil; Strs := TStratons.Create(false); if pgctl.ActivePageIndex = 0 then begin Strs.AddStratonRef(TStraton(cmbxStraton.Items.Objects[cmbxStraton.ItemIndex])); if cmbxNextStraton.ItemIndex > 0 then Strs.AddStratonRef(TStraton(cmbxNextStraton.Items.Objects[cmbxNextStraton.ItemIndex])); sDivider := '-'; C := EditingComponent; if not Assigned(C) then begin C := AddTo.Content.ComponentByID(Strs[0].StratonID); // если не удалось найти - добавляем if not Assigned(C) then if not Assigned(EditingComponent) then C := AddTo.Content.Add as TSubDivisionComponent else C := AddTo.Content.Insert(EditingComponent.Index + 1) as TSubDivisionComponent; C.Stratons.Assign(Strs); end else C.Stratons.Assign(Strs); if cmbxComment.ItemIndex > -1 then C.SubDivisionCommentID := Integer(cmbxComment.Items.Objects[cmbxComment.ItemIndex]) else C.SubDivisionCommentID := 0; C.Divider := '-'; end else begin for i := 0 to chlbxPlus.Items.Count - 1 do if chlbxPlus.Checked[i] then Strs.AddStratonRef(chlbxPlus.Items.Objects[i] as TStraton); {if (not chbxTemplateEdit.Checked) and not (Assigned(EditingComponent) and (Strs.Count = 1) and ((EditingComponent.Index > 0) and (Addto.Content[EditingComponent.Index - 1].SubDivisionCommentID = 0))) then begin Strs2 := TStratons.Create(false); Strs2.AddStratonRef(Strs[Strs.Count - 1]); Strs.Exclude(Strs2); end else Strs2 := nil;} sDivider := '+'; if not Assigned(C) then begin //if not Assigned(strs2) then C := EditingComponent; //else C := AddTo.Content.ComponentByStratons(Strs, '+'); // если не удалось найти - добавляем if not Assigned(C) then begin if not Assigned(EditingComponent) then C := AddTo.Content.Add as TSubDivisionComponent else C := AddTo.Content.Insert(EditingComponent.Index + 1) as TSubDivisionComponent; end; C.Stratons.Assign(Strs); C.SubDivisionCommentID := 1; C.Divider := '+'; { if Assigned(strs2) then begin C := EditingComponent; if not Assigned(C) then begin C := AddTo.Content.ComponentByID(Strs2[0].StratonID); if not Assigned(C) then C := AddTo.Content.Add as TSubDivisionComponent; end; C.Stratons.Assign(Strs2); C.SubDivisionCommentID := 0; C.Divider := '-'; chbxChangeUndivided.Checked := true; end;} end end; if Assigned(C) then with C do begin fLastDepth := Depth; if edtDepth.Text <> '' then Depth := StrToFloat(edtDepth.Text) else Depth := -2; //SubDivisionComment := cmbxComment.Text; Divider := sDivider; //if not Strs.EqualTo(Stratons) then C.Verified := chbxVerified.Checked; C.PostToDB; EditingComponent := C; // это потом { if chbxChangeUndivided.Checked then begin i := C.Index + 1; try unDiv := (C.Collection as TSubDivisionComponents).Items[i]; except undiv := nil; end; // пытаемся заменить все нерасчленненные, если меняется нижняя глубина while ((i < C.Collection.Count) and Assigned(unDiv) // and (unDiv.Depth = fLastDepth) and (unDiv.SubDivisionCommentID = 1)) do begin unDiv.Depth := C.Depth; unDiv.PostToDB; inc(FUndividedChanged); inc(i); try unDiv := (C.Collection as TSubDivisionComponents).Items[i]; except undiv := nil; end; end; end;} end else begin iCommentID := 0; if cmbxComment.ItemIndex > 0 then iCommentID := Integer(cmbxComment.Items.Objects[cmbxComment.ItemIndex]); if edtDepth.Text <> '' then fDepth := StrToFloat(edtDepth.Text) else fDepth := -2; //iCommentID := GetObjectID(AllDicts.CommentDict, cmbxComment.Text); EditingComponent := AddTo.AddComponent(Strs, sDivider, iCommentID, fDepth, chbxVerified.Checked); EditingComponent.PostToDB; end; Strs.Free; // Strs2.Free; end; procedure TfrmSubComponentEdit.cmbxFilterChange(Sender: TObject); begin FSearchString := ' '; with cmbxFilter do SearchString := (Items.Objects[ItemIndex] as TStraton).StratonIndex; end; procedure TfrmSubComponentEdit.cmbxStratonChange(Sender: TObject); begin EnableOK; end; procedure TfrmSubComponentEdit.edtDepthChange(Sender: TObject); begin EnableOK; if (cmbxComment.ItemIndex <> 1) then cmbxComment.ItemIndex := 0; end; procedure TfrmSubComponentEdit.chlbxPlusClickCheck(Sender: TObject); begin EnableOK; end; constructor TfrmSubComponentEdit.Create(AOwner: TComponent); var strlst: TStringList; begin inherited; if Assigned(AllDicts) then begin strlst := TStringList.Create; AllDicts.MakeList(strlst, AllDicts.CommentDict); strlst.InsertObject(0, '<нет>', TObject(0)); cmbxComment.Items.AddStrings(strlst); strlst.Free; end; end; procedure TfrmSubComponentEdit.cmbxCommentChange(Sender: TObject); var i: integer; unDiv: TSubDivisionComponent; begin EnableOk; // если не расчленено, то не можем редактировать глубину edtDepth.Enabled := (cmbxComment.ItemIndex <> 1); if cmbxComment.ItemIndex = 1 then begin unDiv := nil; for i := EditingComponent.Index - 1 downto 0 do if (EditingComponent.Collection as TSubDivisionComponents).Items[i].Depth > 0 then begin unDiv := (FEditingComponent.Collection as TSubDivisionComponents).Items[i]; break; end; try edtDepth.Text := trim(Format('%6.2f',[unDiv.Depth])); except try edtDepth.Text := trim(Format('%6.2f',[NearestComponent.Depth])); except // автоматически проставляется забой edtDepth.Text := trim(Format('%6.2f',[((FEditingComponent.Collection as TSubDivisionComponents).SubDivision.Collection as TSubDivisions).Well.Depth])); end; end; end; end; procedure TfrmSubComponentEdit.edtDepthKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin cmbxComment.ItemIndex := 0; end; procedure TfrmSubComponentEdit.pgctlChange(Sender: TObject); begin // chbxTemplateEdit.Checked := pgctl.ActivePageIndex = 0; end; end.
program GUIMusicPlayer; type Genre = (Pop, Classical, Rock); Album = record albumName: String; artistName: String; albumGenre: Genre; trackName: array of String; trackLoc: array of String; end; procedure DrawMainMenu(); begin OpenGraphicsWindow('Music Player GUI', 600, 400); end; procedure Main(); var menuSelection: Integer; begin DrawMainMenu(); end; begin Main(); end.
{ Arquivo criado automaticamente Gerador Multicamadas (Multitiers Generator VERSÃO 0.01) Data e Hora: 11/10/2016 - 23:04:17 } unit Marvin.AulaMulticamada.Cadastro.Cliente; interface uses Classes, { marvin } uMRVClasses, uMRVCadastroBase, uMRVClassesServidor, Marvin.AulaMulticamada.Classes.Cliente, Marvin.AulaMulticamada.Listas.Cliente, Marvin.AulaMulticamada.Repositorio.Cliente; type TMRVCadastroCliente = class(TMRVCadastroBase) private FCliente: IMRVRepositorioCliente; protected procedure DoAlterar(const AItem: TMRVDadosBase); override; procedure DoExcluir(const AItem: TMRVDadosBase); override; procedure DoInserir(const AItem: TMRVDadosBase); override; function DoProcurarItem(const ACriterio: TMRVDadosBase; const AResultado: TMRVDadosBase = nil): Boolean; override; function DoProcurarItems(const ACriterio: TMRVDadosBase; const AListaResultado: TMRVListaBase; const ASearchOption: TMRVSearchOption): Boolean; override; procedure FazerValidacoesDeRegras(AItem: TMRVDadosBase); override; public constructor Create(var ARepositorio: IMRVRepositorioCliente); reintroduce; virtual; destructor Destroy; override; property Cliente: IMRVRepositorioCliente read FCliente write FCliente; end; implementation uses uMRVConsts, Marvin.AulaMulticamada.Excecoes.Cliente, uMRVExcecoesFramework; { TMRVCadastroCliente } constructor TMRVCadastroCliente.Create(var ARepositorio: IMRVRepositorioCliente); begin inherited Create; { recebe a referência do objeto criado na Fachada } FCliente := ARepositorio; end; destructor TMRVCadastroCliente.Destroy; begin FCliente := nil; inherited; end; procedure TMRVCadastroCliente.DoAlterar(const AItem: TMRVDadosBase); begin Assert(AItem <> nil, 'O parâmetro AItem não pode ser NIL.'); { verifica se já foi o cadastro anteriormente } if not Self.ProcurarItem(AItem) then begin raise EMRVClienteNaoCadastrado.Create; end; { verificar regras de negócio } Self.FazerValidacoesDeRegras(AItem); { manda o Repositório alterar o objeto } FCliente.Alterar(AItem); end; procedure TMRVCadastroCliente.DoExcluir(const AItem: TMRVDadosBase); begin Assert(AItem <> nil, 'Parâmetro AItem não pode ser NIL.'); { verifica se já foi o cadastro anteriormente } if not Self.ProcurarItem(AItem) then begin raise EMRVClienteNaoCadastrado.Create; end; { valida as regras de negócio } //Self.FazerValidacoesDeRegras(AItem); { manda o Repositório excluir o objeto } FCliente.Excluir(AItem); end; procedure TMRVCadastroCliente.DoInserir(const AItem: TMRVDadosBase); var LCliente: TMRVCliente; procedure LPesquisar(AChave: array of string; AExcecaoClass: EMRVExceptionClass); var LSearchOption: TMRVSearchOption; LListaCliente: TMRVListaCliente; begin LSearchOption := TMRVSearchOption.Create(LCliente); try LSearchOption.SetSearchingFor(AChave); LListaCliente := TMRVListaCliente.Create; try if Self.ProcurarItems(LCliente, LListaCliente, LSearchOption) then begin { se encontrou } raise AExcecaoClass.Create; end; finally { libera a lista } LListaCliente.Free end; finally { libera o critério de procura } LSearchOption.Free; end; end; begin Assert(AItem <> nil, 'O parâmetro AItem não pode ser NIL.'); { realiza o typecast } LCliente := AItem as TMRVCliente; { Faz uma pesquisa pela chave do objeto a ser inserido } LPesquisar(['Nome', 'Numerodocumento'], EMRVClienteJaCadastrado); { não pode existir o mesmo número de documento mais de uma vez } LPesquisar(['Numerodocumento'], EMRVClienteNumerodocumentoJaCadastrado); { recupera o próximo id } LCliente.ClienteId := FCliente.GetNextId; { Faz as verificações das colunas que não podem ser nulas } Self.FazerValidacoesDeRegras(AItem); { manda o Repositório inserir o objeto } FCliente.Inserir(AItem); end; function TMRVCadastroCliente.DoProcurarItem(const ACriterio: TMRVDadosBase; const AResultado: TMRVDadosBase = nil): Boolean; begin { verifica se existe um objeto inicializado para ACriterio } Assert(ACriterio <> nil, 'O parâmetro ACriterio não pode ser NIL.'); { manda o repositório procurar o objeto } Result := FCliente.ProcurarItem(ACriterio, AResultado); end; function TMRVCadastroCliente.DoProcurarItems(const ACriterio: TMRVDadosBase; const AListaResultado: TMRVListaBase; const ASearchOption: TMRVSearchOption): Boolean; begin { verifica se existe um objeto inicializado para ACriterio } Assert(ACriterio <> nil, 'Parâmetro ACriterio não pode ser NIL.'); { verifica se existe um objeto inicializado para AListaResultado } Assert(AListaResultado <> nil, 'Parâmetro AListaResultado não pode ser NIL.'); { verifica se existe um objeto inicializado para ASearchOption } Assert(ASearchOption <> nil, 'O parâmetro ASearchOption não pode ser nil.'); { manda o repositório procurar } Result := FCliente.ProcurarItems(ACriterio, AListaResultado, ASearchOption); end; procedure TMRVCadastroCliente.FazerValidacoesDeRegras(AItem: TMRVDadosBase); var LCliente: TMRVCliente; begin { verifica se existe um objeto inicializado para AItem } Assert(AItem <> nil, 'O parâmetro AItem não pode ser NIL.'); LCliente := AItem as TMRVCliente; { Valida as regras de negócio } { checa se a propriedade é nula } if LCliente.Clienteid = C_INTEGER_NULL then begin raise EMRVClienteClienteidInvalido.Create; end; { checa se a propriedade é nula } if LCliente.TipoClienteId = C_INTEGER_NULL then begin raise EMRVClienteTipoClienteIdInvalido.Create; end; { checa se a propriedade é nula } if LCliente.Nome = C_STRING_NULL then begin raise EMRVClienteNomeInvalido.Create; end; { checa se não ultrapassa o tamanho máximo de caracteres } if Length(LCliente.Nome) > 100 then begin raise EMRVClienteNomeTamanhoInvalido.Create(100); end; { checa se a propriedade é nula } if LCliente.Numerodocumento = C_STRING_NULL then begin raise EMRVClienteNumerodocumentoInvalido.Create; end; { checa se não ultrapassa o tamanho máximo de caracteres } if Length(LCliente.Numerodocumento) > 50 then begin raise EMRVClienteNumerodocumentoTamanhoInvalido.Create(50); end; { checa se a propriedade é nula } if LCliente.Datahoracadastro = C_DATE_TIME_NULL then begin raise EMRVClienteDatahoracadastroInvalida.Create; end; end; end.
unit qsdk.wechat; interface uses system.classes, system.SysUtils, system.Generics.Collections, FMX.Graphics; type // Wechat Objects IWechatObject = IInterface; TMediaObjectType = (otUnknown, otText, otImage, otMusic, otVideo, otUrl, otFile, otAppData, otEmoji, otProduct, otEmotionGift, otDeviceAccess, otMailProduct, otOldTV, otEmotionShared, otCardShare, otLocationShare, otRecord, otTV, otDesignerShared); IWechatMediaMessage = interface ['{46D42E74-E148-4FC5-AFEC-706F4BA77B62}'] function getTitle: String; procedure setTitle(const Value: String); function getDescription: String; procedure setDescription(const Value: String); function getThumb: TBitmap; procedure setThumb(ABitmap: TBitmap); function getMediaObject: IWechatObject; procedure setMediaObject(AObject: IWechatObject); function getMediaTagName: String; procedure setMediaTagName(const AValue: String); function getMessageAction: String; procedure setMessageAction(const AValue: String); function getMessageExt: String; procedure setMessageExt(const AValue: String); property Title: String read getTitle write setTitle; property Description: String read getDescription write setDescription; property Thumb: TBitmap read getThumb write setThumb; property MediaObject: IWechatObject read getMediaObject write setMediaObject; property MediaTagName: String read getMediaTagName write setMediaTagName; property MessageAction: String read getMessageAction write setMessageAction; property MessageExt: String read getMessageExt write setMessageExt; end; IWechatAppExt = interface ['{93D6174A-8DE6-4B70-AD60-94FB1935B97D}'] function getExtInfo: String; procedure setExtInfo(const AValue: String); function getFilePath: String; procedure setFilePath(const AValue: String); function getFileData: TBytes; procedure setFileData(const AValue: TBytes); property ExtInfo: String read getExtInfo write setExtInfo; property FilePath: String read getFilePath write setFilePath; property FileData: TBytes read getFileData write setFileData; end; IWechatText = interface ['{01239E30-1D80-4155-BEB5-907226753781}'] function getText: String; procedure setText(const AValue: String); property Text: String read getText write setText; end; IWechatImage = interface ['{B015BE08-4F95-4C08-8F2A-11B1B9430B20}'] function getImagePath: String; procedure setImagePath(AValue: String); function getImage: TBitmap; procedure setImage(ABitmap: TBitmap); property ImagePath: String read getImagePath write setImagePath; property Imaget: TBitmap read getImage write setImage; end; IWechatMusic = interface ['{C4ED7560-E07B-43A2-AB17-2D287C17BAD4}'] function getMusicUrl: String; procedure setMusicUrl(const AValue: String); function getMusicLowBandUrl: String; procedure setMusicLowBandUrl(const AValue: String); function getMusicDataUrl: String; procedure setMusicDataUrl(const AValue: String); function getMusicLowBandDataUrl: String; procedure setMusicLowBandDataUrl(const AValue: String); property MusicUrl: String read getMusicUrl write setMusicUrl; property MusicLowBandUrl: String read getMusicLowBandUrl write setMusicLowBandUrl; property MusicDataUrl: String read getMusicDataUrl write setMusicDataUrl; property MusicLowBandDataUrl: String read getMusicLowBandDataUrl write setMusicLowBandDataUrl; end; IWechatVideo = interface ['{0C43F90E-02FF-4292-9485-2287F5CB4749}'] function getVideoUrl: String; procedure setVideoUrl(const AValue: String); function getVideoLowBandUrl: String; procedure setVideoLowBandUrl(const AValue: String); property VideoUrl: String read getVideoUrl write setVideoUrl; property VideoLowBandUrl: String read getVideoLowBandUrl write setVideoLowBandUrl; end; IWechatWebPage = interface ['{B7414EA8-AEDA-4DFD-9DC9-A167204D1E70}'] function getWebPageUrl: String; procedure setWebPageUrl(const AValue: String); function getExtInfo: String; procedure setExtInfo(const AValue: String); { Property } property WebPageUrl: String read getWebPageUrl write setWebPageUrl; property ExtInfo: String read getExtInfo write setExtInfo; end; IWechatEmoticon = interface ['{3CA5F5CB-38FF-4DDF-BBDF-EECC7C9F344F}'] function getEmoticonData: TBytes; procedure setEmoticonData(const AValue: TBytes); property EmoticonData: TBytes read getEmoticonData write setEmoticonData; end; IWechatFile = interface ['{C5FB3AC2-3D65-4A16-9F15-0943B7F4F819}'] function getFileExt: String; procedure setFileExt(const AValue: String); function getFileData: TBytes; procedure setFileData(const AValue: TBytes); property FileExt: String read getFileExt write setFileExt; property FileData: TBytes read getFileData write setFileData; end; IWechatLocation = interface ['{D0EA31ED-5972-4430-8720-DCEA91657862}'] function getLng: Double; procedure setLng(const AValue: Double); function getLat: Double; procedure setLat(const AValue: Double); property Lng: Double read getLng write setLng; property Lat: Double read getLat write setLat; end; IWechatRequest = interface ['{4FF6EC96-563B-4F66-9129-BD7ABF7416F1}'] function getOpenID: String; procedure setOpenID(const AValue: String); function getTansaction: String; procedure setTransaction(const AValue: String); property OpenID: String read getOpenID write setOpenID; property Transaction: String read getTansaction write setTransaction; end; IWechatResponse = interface ['{02FF62AF-5705-4047-947E-7F6019A9474E}'] function getErrorCode: Integer; procedure setErrorCode(const ACode: Integer); function getErrorMsg: String; procedure setErrorMsg(const AValue: String); function getRespType: Integer; property RespType: Integer read getRespType; property ErrorCode: Integer read getErrorCode write setErrorCode; property ErrorMsg: String read getErrorMsg write setErrorMsg; end; TWechatPayResult = (wprOk, wprCancel, wprError); IWechatPayResponse = interface(IWechatResponse) ['{0D062157-281E-40DB-A223-A74AB05D1C10}'] function getPrepayId: String; procedure setPrepayId(const AVal: String); function getReturnKey: String; procedure setReturnKey(const AVal: String); function getExtData: String; function getPayResult: TWechatPayResult; procedure setExtData(const AVal: String); property prepayId: String read getPrepayId write setPrepayId; property returnKey: String read getReturnKey write setReturnKey; property extData: String read getExtData write setExtData; property PayResult: TWechatPayResult read getPayResult; end; IWechatAddCardToPackageRequest = interface(IWechatRequest) end; TWechatOrderItem = record Id: String; // 商品ID WePayId: String; // 微信支付商品ID GoodsName: String; // 商品名称 Quantity: Integer; // 商品数量 Price: Currency; // 价格 CategoryId: String; // 分类编码 Comment: String; // 描述<1000字 end; TWechatOrderItems = array of TWechatOrderItem; TWechatOrder = record No: String; Description: String; // 商品描述(body:App名称-商品描述) Detail: TWechatOrderItems; // 商品详情(detail) extData: String; // 扩展数据(attach) TradeNo: String; // 商户订单号(out_trade_no) FeeType: String; // 货币类型(fee_type) Total: Currency; // 总金额(*100=total_fee) TTL: Integer; // 订单失效时间,单位为分钟,不小于5分钟(转换为time_expire,time_start直接取当前时间) Tag: String; // 商品标记,(goods_tag)如代金券 Limit: String; // 支付限制,no_credit 代表不接受信用卡支付 end; TWechatRequestEvent = procedure(ARequest: IWechatRequest) of object; TWechatResponseEvent = procedure(AResponse: IWechatResponse) of object; TWechatSession = (Session, Timeline, Favorite); IWechatSigner = interface ['{C06D210C-2DF7-413F-BFE6-E5CEAD764DA1}'] procedure Add(const AKey, AValue: String); procedure Clear; function GetSign: String; function GetKey: String; property Sign: String read GetSign; property Key: String read GetKey; end; IWechatService = interface ['{10370690-72BC-438C-8105-042D2029B895}'] procedure Unregister; function IsInstalled: Boolean; function getAppId: String; function getMchId: String; procedure setMchId(const AId: String); function getDevId: String; procedure setDevId(const AId: String); function getPayKey: String; procedure setPayKey(const AKey: String); function OpenWechat: Boolean; function IsAPISupported: Boolean; function SendRequest(ARequest: IWechatRequest): Boolean; function SendResponse(AResp: IWechatResponse): Boolean; function getOnRequest: TWechatRequestEvent; procedure setOnRequest(const AEvent: TWechatRequestEvent); function getOnResponse: TWechatResponseEvent; procedure setOnResponse(const AEvent: TWechatResponseEvent); procedure setAppId(const AId: String); function OpenUrl(const AUrl: String): Boolean; function SendText(const AText: String; ASession: TWechatSession = TWechatSession.Session): Boolean; function CreateObject(AObjId: TGuid): IWechatObject; function Pay(APrepayId, AnonceStr, ASign: String; ATimeStamp: Integer): Boolean; procedure EnableSignCheck(ASigner:IWechatSigner); function ShareText(ATarget: TWechatSession; const S: String): Boolean; function ShareWebPage(ATarget: TWechatSession; const ATitle, AContent, AUrl: String; APicture: TBitmap): Boolean; function ShareBitmap(ATarget: TWechatSession; ABitmap: TBitmap): Boolean; // function ShareVideo(const S:String):Boolean; property AppId: String read getAppId write setAppId; property Installed: Boolean read IsInstalled; property APISupported: Boolean read IsAPISupported; // 微信支付相关接口 property MchId: String read getMchId write setMchId; property DevId: String read getDevId write setDevId; // 支付终端设备号(device_info) property PayKey: String read getPayKey write setPayKey; property OnRequest: TWechatRequestEvent read getOnRequest write setOnRequest; property OnResponse: TWechatResponseEvent read getOnResponse write setOnResponse; end; TWechatObject = class(TInterfacedObject, IInterface) protected {$IFNDEF AUTOREFCOUNT} [Volatile] FRefCount: Integer; {$ENDIF} public function QueryInterface(const IID: TGuid; out Obj): HResult; virtual; stdcall; function _AddRef: Integer; virtual; stdcall; function _Release: Integer; virtual; stdcall; end; function WechatService: IWechatService; function WechatSigner(const AKey: String): IWechatSigner; implementation uses FMX.platform, qstring, qdigest{$IFDEF ANDROID}, qsdk.wechat.android{$ENDIF} {$IFDEF IOS}, qsdk.wechat.ios{$ENDIF}; {$I 'wxapp.inc'} type TWechatParam = class private FValue: String; public constructor Create(AValue: String); overload; property Value: String read FValue write FValue; end; TWechatSigner = class(TInterfacedObject, IWechatSigner) private FItems: TStringList; FKey: String; function GetSign: String; function GetKey: String; public constructor Create(const AKey: String); overload; destructor Destroy; override; procedure Add(const AName, AValue: String); procedure Clear; property Sign: String read GetSign; end; function WechatService: IWechatService; begin if not TPlatformServices.Current.SupportsPlatformService(IWechatService, Result) then begin RegisterWechatService; TPlatformServices.Current.SupportsPlatformService(IWechatService, Result); if Assigned(Result) then begin Result.AppId := SWechatAppId; Result.MchId := SWechatMchId; end; end; end; function WechatSigner(const AKey: String): IWechatSigner; begin Result := TWechatSigner.Create(AKey); end; { TWechatObject } function TWechatObject.QueryInterface(const IID: TGuid; out Obj): HResult; begin Result := inherited QueryInterface(IID, Obj); end; function TWechatObject._AddRef: Integer; begin Result := inherited _AddRef; end; function TWechatObject._Release: Integer; begin Result := inherited _Release; end; { TWechatSigner } procedure TWechatSigner.Add(const AName, AValue: String); begin // 空参数不参与签名 if Length(AValue) > 0 then FItems.AddObject(AName, TWechatParam.Create(AValue)); end; procedure TWechatSigner.Clear; var I: Integer; AObj: TObject; begin for I := 0 to FItems.Count - 1 do begin AObj := FItems.Objects[I]; FreeAndNilObject(AObj); end; FItems.Clear; end; constructor TWechatSigner.Create(const AKey: String); begin inherited Create; FKey := AKey; FItems := TStringList.Create; end; destructor TWechatSigner.Destroy; begin Clear; FreeAndNilObject(FItems); inherited; end; function TWechatSigner.GetKey: String; begin Result := FKey; end; function TWechatSigner.GetSign: String; var S: String; I: Integer; begin FItems.Sort; S:=''; for I := 0 to FItems.Count - 1 do S := S+FItems[I] + '=' + TWechatParam(FItems.Objects[I]).Value + '&'; S := S + 'key=' + FKey; Result := DigestToString(MD5Hash(S)); end; { TWechatParam } constructor TWechatParam.Create(AValue: String); begin inherited Create; FValue := AValue; end; end.
unit uPerfectNumbers; interface type NumberType = (Perfect, Abundant, Deficient); PerfectNumber = class public class function Classify(aNumber: integer): Numbertype; static; end; implementation class function PerfectNumber.Classify(aNumber: Integer): NumberType; var sumOfFactors: integer; i: integer; begin sumOfFactors := 0; for i := 1 to aNumber - 1 do if aNumber mod i = 0 then sumOfFactors := sumOfFactors + i; if sumOfFactors < aNumber then result := Deficient else if sumOfFactors = aNumber then result := Perfect else result := Abundant; end; end.
unit Helper.TWinControl; interface uses Vcl.Controls; type TWinControlHelper = class helper for TWinControl public procedure HideAllChildFrames; function SumHeightForChildrens( ControlsToExclude: TArray<TControl>): Integer; end; implementation uses Vcl.Forms; { TWinControlHelper } procedure TWinControlHelper.HideAllChildFrames; var i: Integer; begin for i := Self.ControlCount - 1 downto 0 do if Self.Controls[i] is TFrame then (Self.Controls[i] as TFrame).Visible := False; end; function TWinControlHelper.SumHeightForChildrens( ControlsToExclude: TArray<TControl>): Integer; var i: Integer; ctrl: Vcl.Controls.TControl; isExcluded: Boolean; j: Integer; sumHeight: Integer; ctrlHeight: Integer; begin sumHeight := 0; for i := 0 to Self.ControlCount - 1 do begin ctrl := Self.Controls[i]; isExcluded := False; for j := 0 to Length(ControlsToExclude) - 1 do if ControlsToExclude[j] = ctrl then isExcluded := True; if not isExcluded then begin if ctrl.AlignWithMargins then ctrlHeight := ctrl.Height + ctrl.Margins.Top + ctrl.Margins.Bottom else ctrlHeight := ctrl.Height; sumHeight := sumHeight + ctrlHeight; end; end; Result := sumHeight; end; end.
unit ideuimain; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LazIDEIntf, IDECommands; procedure Register; implementation type TPrevHandler = record OnMethod: TNotifyEvent; OnProc: TNotifyProcedure; end; var IDECloseAll: TPrevHandler; procedure InvokeHandler(const h: TPrevHandler; Sender: TObject); begin if Assigned(h.OnMethod) then h.OnMethod(Sender); if Assigned(h.OnProc) then h.OnProc(Sender); end; procedure MyCloseAll(Sender: Tobject); begin InvokeHandler(IDECloseAll, Sender); IDECommandList.FindIDECommand(ecCloseProject).Execute(Sender); end; procedure UpdateCloseAll; var idecmd : TIDECommand; begin idecmd := IDECommandList.FindIDECommand(ecCloseAll); if not Assigned(idecmd) then Exit; IDECloseAll.OnMethod := idecmd.OnExecute;; IDECloseAll.OnProc := idecmd.OnExecuteProc; idecmd.OnExecuteProc := @MyCloseAll; idecmd.OnExecute := nil; end; procedure Register; begin UpdateCloseAll; end; end.