-
MY PROJECTS
-
Recent Posts
- SpringBoot.Making our first starter and autoconfiguration
- Spring. Creating main annotation to start business logic
- Spring.Reading from properties file
- Spring.How to define spring version inside springBoot ?
- SpringBoot App inside Docker
- Kafka.FirstExperience
- Docker.MySql and Lost connection to MySQL server at ‘reading initial communication packet’, system error: 0
- Gradle.Tips
- Spring.AppConfig
- Leetcode.Best-time-to-buy-and-sell-stock
- LeetCode.ClimbStairs.Fibbonacci
- Leetcode.Roman-to-integer
- LeetCode.Palindrome-number
- Java.DesignPatterns.Lightweight
- Java.DesignPatterns.Proxy
- Java.DesignPatterns.Facade
- Java.DesignPatterns.Composite
- Java.DesignPatterns.Bridge
- Java. Strange OOP thing
- Java.Classpath
Categories
- Aptana
- Azure
- C#
- DataSnap
- DBExpress
- Delphi
- Delphi и сети
- Delphi. Язык программирования
- ExtJS
- FastReport
- FireDAC
- FireMonkey
- GIT
- ICS
- IDE
- IIS
- Indy
- InnoSetup
- javascript
- jQuery
- JSON
- LiveBindings
- MSHTML
- MySQL
- PHP
- REST
- Ribbons
- SMS
- SQL инструкции
- SVN
- TRichView
- UniGui
- WebBroker
- WinAPI
- Windows
- Алгоритмы
- Без рубрики
- Деревья
- Ищу ответ
- Компонентостроение
- Мои компоненты
- Начальный уровень
- Обработка исключений
- Парсинг
- Потоки(Threads)
- Регулярные выражения
- Тестирование приложений
Category Archives: Delphi
Delphi. Запуск анонимного потока
Увидел в блоге следующий пример, по-моему оч. удобно для каких-то простых случаев….
1 2 3 4 5 |
TThread.CreateAnonymousThread( procedure begin // do smth... end).Start; |
Немного модифицировал
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Если нужно настраивать какие-то параметры проекта после его запуска t := TThread.CreateAnonymousThread( procedure var i: Integer; begin for i := 0 to 10 do Sleep(15); end).Start; t.FreeOnTerminate := true; // Если нужно настраивать какие-то параметры потока до его запуска... with TThread.CreateAnonymousThread( procedure var i: Integer; begin for i := 0 to 10 do Sleep(15); end) do begin FreeOnTerminate := true; Start; end; e |
Со StackOverflow, в тему, запуск анонимного потока процедуры с параметрами
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
procedure DoSomething(const aWebAddress: String); begin end; procedure BuildThread; var myThread: TThread; fetchURL: string; begin fetchURL := 'http://stackoverflow.com'; // Create an anonymous thread that calls a method and passes in // the fetchURL to that method. myThread := TThread.CreateAnonymousThread( procedure begin DoSomething(fetchURL); end); ... end; |
Posted in Delphi
Comments Off on Delphi. Запуск анонимного потока
Delphi. “Nullable” Post by Allen Bauer
В Delphi вроде как нет Nullable типов, но если нет, но очень хочется, то они могут появиться ))) Читал книгу Delphi Memory Management, и там наткнулся на раздел про Nullable, автор книги ссылался на MVP Allen Bauer. Идея проста… To implement … Continue reading
Posted in Delphi
Comments Off on Delphi. “Nullable” Post by Allen Bauer
Delphi. SmartPointers – меньше кода больше дела
Читая Delphi Memory Management, открыл для себя SmartPointers. Подход, основанный на ARC, позволяет, применяя данный класс писать меньше кода, заниматься больше делом, сосредоточиться на бизнес-задаче.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
unit uSmartPointer; interface type ISmartPointer<T> = reference to function: T; TSmartPointer<T: class, constructor> = class(TInterfacedObject, ISmartPointer<T>) private FValue: T; function Invoke: T; procedure SetValue(const Value: T); public constructor Create; overload; constructor Create(AValue: T); overload; destructor Destroy; override; function Extract: T; property Value: T read FValue write SetValue; end; implementation constructor TSmartPointer<T>.Create; begin inherited Create; FValue := T.Create; end; constructor TSmartPointer<T>.Create(AValue: T); begin inherited Create; FValue := AValue; end; destructor TSmartPointer<T>.Destroy; begin FValue.Free; inherited; end; function TSmartPointer<T>.Invoke: T; begin Result := FValue; end; procedure TSmartPointer<T>.SetValue(const Value: T); begin FValue := Value; end; function TSmartPointer<T>.Extract: T; begin Result := FValue; FValue := nil; end; end. |
Теперь можно писать так…
1 2 3 4 5 6 |
var sl: ISmartPointer<TStringList>; begin sl := TSmartPointer<TStringList>.Create(); sl.Add('I am inside automanaged StringList'); end; |
Вместо…
Posted in Delphi
Comments Off on Delphi. SmartPointers – меньше кода больше дела
Delphi. Memory Management. Book
Купил сегодня книгу по управлению памятью в Delphi. Понравилось содержание, хочу углубить свои знания в этом вопросе. А вот и содержание на английском…
Posted in Delphi
Comments Off on Delphi. Memory Management. Book
Delphi. GarbageCollector
Понравилось, на одном из форумов, а ля сборщик мусора, теоретически должно сократиться количество кода… Но надо потестить….
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
unit uGC; interface uses System.Generics.Collections, Rtti, System.Classes; ///<summary> Класс позволяющий упростить освобождение памяти.</summary> type TGarbageCollector = class(TComponent) public const DEFAULT_TAG = 'DEFAULT_TAG'; private items: TDictionary<TObject, string>; public //constructor Create(); destructor Destroy; override; // constructor Create(AOwner: TComponent); override; constructor Create(AOwner: TComponent); override; ///<summary> Добавить элемент в список и вернуть свежедобавленный элемент.</summary> function Add<T>(item: T): T; overload; ///<summary> Добавить помеченый элемент в список и вернуть свежедобавленный элемент.</summary> function Add<T>(item: T; const tag: string): T; overload; /// <summary> Произвести сборку мусора с указанной меткой. </summary> procedure Collect(const tag: string); end; var GC: TGarbageCollector; implementation uses System.Types, System.SysUtils; { constructor TGarbageCollector.Create(); begin items := TObjectDictionary<TObject, string>.Create([doOwnsKeys]); end; } constructor TGarbageCollector.Create(AOwner: TComponent); begin inherited; items := TObjectDictionary<TObject, string>.Create([doOwnsKeys]); end; destructor TGarbageCollector.Destroy; begin items.free(); inherited Destroy; end; function TGarbageCollector.Add<T>(item: T): T; begin result := Add(item, DEFAULT_TAG); end; function TGarbageCollector.Add<T>(item: T; const tag: string): T; var obj: TObject; v: TValue; begin v := TValue.From<T>(item); if v.IsObject then begin items.add(v.AsObject, tag); result := item; end else raise Exception.Create('not an Object'); end; procedure TGarbageCollector.Collect(const tag: string); var key: TObject; item: TPair<TObject, string>; gcList: TList<TObject>; begin gcList := TList<TObject>.Create(); try for item in items do begin if (item.Value = tag) then gcList.add(item.Key); end; for key in gcList do items.remove(key); finally gcList.free(); end; end; end. |
Пример использования
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
program GarbageCollector; uses Vcl.Forms, uMain in 'uMain.pas' {Main}, uGC in 'uGC.pas', uSomeClass in 'uSomeClass.pas'; {$R *.res} begin Application.Initialize; Application.MainFormOnTaskbar := True; GC := TGarbageCollector.Create(Application); // <<< Application.CreateForm(TMain, Main); Application.Run; end. |
В любом месте проекта делаем что-то подобное…
1 2 3 4 5 6 7 8 |
someInstance := GC.Add(TSomeClass.Create(nil), 'TSomeClassTag'); // do smth with someInstance //now destroy GC.Collect('TSomeClassTag'); // anotherInstance := GC.Add(TSomeClass.Create(nil), 'TSomeClassTag'); // do smth with anotherInstance // not destroying here - will be destroyed on app destroy... |
Врубил
1 |
ReportMemoryLeaksOnShutdown := true; |
При закрытии приложения – тишина, и это радует. Прошелся … Continue reading
Posted in Delphi
Comments Off on Delphi. GarbageCollector
Delphi. Тестовое задание. Проект квартира
Ссылка на описание тестового задания Проект сделан на Delphi Berlin+MySQL; Реализация на VCL Forms Application Проект на Delphi Berlin (скачать) Код на gitHub База данных Для автоматического проставления даты в момент добавления записей использованы триггеры, например
1 2 3 4 |
CREATE DEFINER = CURRENT_USER TRIGGER `flat_db`.`counterData_BEFORE_INSERT` BEFORE INSERT ON `counterData` FOR EACH ROW BEGIN SET NEW.MeasureDateTime = Now(); END |
Полный код … Continue reading
Posted in Delphi
Comments Off on Delphi. Тестовое задание. Проект квартира
Delphi. Firemonkey. Fatal error
Embarcadero Rad Studio 10.1.2 Delphi Linker error code 1 ($00000001) [DCC Error] E2597 C:\Users\Public\Documents\Embarcadero\Studio\18.0\PlatformSDKs\android-ndk-r9c\toolchains\arm-linux-androideabi-4.6\prebuilt\windows\bin\arm-linux-androideabi-ld.exe: fatal error: .AndroidDebuglibAlamcenistaImpo.so: mmap: failed to allocate 202548716 bytes for output file: Not enough space http://support.embarcadero.com/article/44279
Posted in Delphi
Comments Off on Delphi. Firemonkey. Fatal error
Delphi. Firemonkey. Делаем круглое изображение наложением маски
Нам нужно 2 изображения – то, которое нужно сделать круглым и сама маска в виде круга. В процессе этого кода размеры этих изображений выравниваются, чтобы маска могла наложиться корректно, иначе это будет невозможно. Помог вот это код с официального сайта … Continue reading
Posted in Delphi
Comments Off on Delphi. Firemonkey. Делаем круглое изображение наложением маски
Delphi. Json. Получение всей структуры ключей-значений
Писал сервер, и понадобилось обработать application/json запрос, очень помог код со stackOverflow для получения всей структуры json, делается это вот так… Для своей задачи сделал так…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
procedure TDecodePostRequest.ParseJson(const aAsObject: TSuperTableString; var postParams: TStringList); var names: ISuperObject; name: string; items: ISuperObject; item: ISuperObject; idx: Integer; value: string; begin if Assigned(aAsObject) then begin names := aAsObject.GetNames; items := aAsObject.GetValues; for idx := 0 to items.AsArray.Length - 1 do begin name := names.AsArray[idx].AsString; item := items.AsArray[idx]; if item.DataType = stObject then value := '<Object>' else if item.DataType = stArray then value := '<Array>' else value := item.AsString; postParams.Add(name + '=' + value); // if SameText(Name, 'id') then // WriteLn(Format('%s: %s', [aPrefix + Name, Value])); // // if Item.DataType = stArray then // for ArrayItem in Item do // ProcessObject(ArrayItem.AsObject, aPrefix + Name + '.'); // // if Item.DataType = stObject then // ProcessObject(Item.AsObject, aPrefix + Name + '.'); end; end; end; |
Posted in Delphi
Comments Off on Delphi. Json. Получение всей структуры ключей-значений
Delphi. FireMonkey. Модальные окна
В Android нет модальных окон, в Windows они есть. Обойти это можно так.
1 2 3 4 5 6 7 8 9 10 11 |
procedure TfrmParent.TestModalWindowClick(Sender: TObject); var f: TForm1; begin f := TForm1.Create(Self); f.ShowModal(procedure(ModalResult : TModalResult) begin if ModalResult = mrOK then // do something here end); end; |
Уничтожить форму можно в момент закрытия
1 2 3 4 |
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := TCloseAction.caFree; end; |
Гениально и просто !) Взял отсюда
Posted in Delphi, FireMonkey
Comments Off on Delphi. FireMonkey. Модальные окна