-
MY PROJECTS
-
Recent Posts
- ChromeDevTools.Watch all failed requests
- SQL.What are domain types (or constraints on data types), and how do they help enforce data correctness?
- SQL.How does SQL handle comparisons between different data types (for example, string vs number), and why is this dangerous?
- SQL.What is the difference between DATE, TIME, TIMESTAMP, and TIMESTAMPTZ, and which one should be used for business events?
- SQL.How do numeric types like INTEGER, BIGINT, DECIMAL, and FLOAT differ in terms of precision and use cases?
- SQL.What problems can arise from implicit type casting in SQL, and how can it affect indexes?
- SQL.How does NULL differ from 0, an empty string, or FALSE in SQL?
- SQL.What is the difference between CHAR, VARCHAR, and TEXT, and when would you choose each?
- SQL.What is MVCC ?
- SQL.What is AutoVacuum Postgres ?
- SQL.What is eventual consistency ?
- SQL.What is CDC (Change Data Capture)? ?
- SQL.If i should write a little operations of income and outome of client from kafka and then show them big reports, what should i do ? Shouldnt it be the one db to not to write to both OLTP and OLAP databases ?
- SQL.What is OLTP, OLAP ?
- SQL.What is full scan / index scan ?
- SQL.How DBMS chooses the plan ?
- SQL.JoinExamples
- SQL.What are join algos ?
- SQL.What is the problem in using null in in operator ?
- SQL.How does the relational model differ from object-oriented models, and why does this matter for backend development?
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
DesignPatterns. TemplateMethod
Шаблонный метод позволяет объявить в базовом классе некоторый метод, который может быть группой других методов и переопределить его в классах наследниках. Посмотрим на примере. Разработка ПО может быть разделена на несколько стадий. -Идея -Проектирование -Дизайн -Тестирование Вот как мы можем … Continue reading
Posted in Delphi
Comments Off on DesignPatterns. TemplateMethod
DesignPatterns. Strategy
Пример с отпуском Мы можем поехать в отпуск на самолете, поезде или машине. Это будут разные стратегии. Посмотрим, как это реализовать, с помощью соответствующего паттерна. Main
|
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 |
program Strategy; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, uStrategyVacation in 'uStrategyVacation.pas'; var v: TVacation; begin try v := TVacation.Create(); try v.Transport := TStrategyAirplane.Create(); v.Move(); // v.Transport := TStrategyTrain.Create(); v.Move(); // v.Transport := TStrategyCar.Create(); v.Move(); Readln; finally v.Free(); end; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end. |
Интерфейсы и классы стратегий
Posted in Delphi
Comments Off on DesignPatterns. Strategy
DesignPatterns. Command
Когда использовать? Когда необходимо ответить действием на действие, callback Когда нужно вести очередь действий с возможностью Undo / Redo Когда нужно последовательное логгирование Про этот паттерн говорят следующее. Client – посетитель кафе, Invoker – официантка, Command – листочек с заказом … Continue reading
Posted in Delphi
Comments Off on DesignPatterns. Command
DesignPatterns. AbstractFactory
Абстрактная фабрика порождает абстрактные продукты. При применении, вызове клиентом, конкретная фабрика порождает конкретные продукты, опираясь на абстракцию. Канонический пример На примере супер героев Delphi Main
|
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 |
program AbstractFactory; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, uAbstractFactory in 'uAbstractFactory.pas'; var f: TAbstractSuperHeroesFactory; c: TClient; begin try f := TDisneyFactory.Create(); c := TClient.Create(f); c.SaveMePlease(); Readln; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end. |
Фабрика и клиент
|
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 |
unit uAbstractFactory; interface uses System.SysUtils; type TAbstractFlyingSuperHero = class public procedure SaveTheWorld; virtual; abstract; end; TSuperMan = class(TAbstractFlyingSuperHero) public procedure SaveTheWorld; override; end; TAbstractSuperHeroesFactory = class public function CreateFlyingSuperHero: TAbstractFlyingSuperHero; virtual; abstract; end; TDisneyFactory = class(TAbstractSuperHeroesFactory) public function CreateFlyingSuperHero: TAbstractFlyingSuperHero; override; end; TClient = class private FAbstractFlyingSuperHero: TAbstractFlyingSuperHero; public constructor Create(aFactory: TAbstractSuperHeroesFactory); procedure SaveMePlease(); end; implementation { TDisneyFactory } function TDisneyFactory.CreateFlyingSuperHero: TAbstractFlyingSuperHero; begin Result := TSuperMan.Create(); end; { TClient } constructor TClient.Create(aFactory: TAbstractSuperHeroesFactory); begin FAbstractFlyingSuperHero := aFactory.CreateFlyingSuperHero(); end; procedure TClient.SaveMePlease; begin FAbstractFlyingSuperHero.SaveTheWorld(); Writeln('SuperMan saved me!'); end; { TSuperMan } procedure TSuperMan.SaveTheWorld; begin Writeln('I''m flying to save you... ! '); end; end. |
C#
Delphi. TStream. Сохранение строки в TStream и чтение строки из TStream
Пример
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
procedure SaveStringToStream(aStr: string; aStream: TStream); var l: integer; begin l := length(aStr); aStream.WriteBuffer(l, SizeOf(l)); if l > 0 then aStream.WriteBuffer(PChar(aStr)^, l); end; function LoadStringFromStream(aStream: TStream): string; var l: integer; begin aStream.ReadBuffer(l, SizeOf(l)); if l > 0 then begin SetLength(Result, l); aStream.ReadBuffer(PChar(Result)^, l) end else Result := ''; end; |
Posted in Delphi
Comments Off on Delphi. TStream. Сохранение строки в TStream и чтение строки из TStream
Delphi. Hex метаморфозы с байтовой строкой или функции для перевода в Hex и Hex представление и обратно
Вспомогательные функции, из проектов Пусть на входе есть строка
|
1 |
#50#54#51#171#56#53#173#65#55#52#172#64#57#58#59#60#61#62#63#175#176#177#178#179#180#165#166#167#168#169#170#181 |
Строка – > массив байт
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
type ArrayOfByte = array of byte; function Str2Hex(s: string): ArrayOfByte; var i: Integer; sLength: Integer; begin sLength := Length(s); if (sLength > 0) then begin SetLength(Result, sLength); for i := 0 to High(Result) do Result[i] := Ord(S[i + 1]); end; end; |
Получили массив байт
|
1 |
(50, 54, 51, 171, 56, 53, 173, 65, 55, 52, 172, 64, 57, 58, 59, 60, 61, 62, 63, 175, 176, 177, 178, 179, 180, 165, 166, 167, 168, 169, 170, 181) |
Байт -> StrHex (Шестнадцатеричное представление)
|
1 2 3 4 5 6 |
function ByteToHex(InByte: byte): shortstring; const Digits: array[0..15] of char = '0123456789ABCDEF'; begin result := digits[InByte shr 4] + digits[InByte and $0F]; end; |
|
1 2 3 4 5 6 7 8 |
function Hex2StrHex(aBuf: ArrayOfByte): string; var i: Integer; begin Result := ''; for i := Low(aBuf) to High(aBuf) do Result := Result + ByteToHex(aBuf[i]); // Format('%x', [aBuf[i]]) работает не совсем корректно в данном случае, 7 переводит в 7, а не 07 end; |
Шестнадцатеричное представление
|
1 |
'323633AB3835AD413734AC40393A3B3C3D3E3FAFB0B1B2B3B4A5A6A7A8A9AAB5' |
Или, расставив пробелы, получим
|
1 |
32 36 33 AB 38 35 AD 41 37 34 AC 40 39 3A 3B 3C 3D 3E 3F AF B0 B1 B2 B3 B4 A5 A6 A7 A8 A9 AA B5 |
Шестнадцатеричное представление -> байты
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function StrHex2Hex(sHex: string): ArrayOfByte; var i: Integer; sHexLength: Integer; sHexWithoutSpaces: string; begin sHexWithoutSpaces := ''; for i := 1 to Length(SHex) do if SHex[i] <> ' ' then sHexWithoutSpaces := sHexWithoutSpaces + SHex[i]; sHexLength := Length(sHexWithoutSpaces); if (sHexLength > 0) and (sHexLength mod 2 = 0) then begin SetLength(Result, sHexLength div 2); for i := 0 to High(Result) do Result[i] := StrToInt('$' + Copy(sHexWithoutSpaces, i * 2 + 1, 2)); end; end; |
Posted in Delphi
Comments Off on Delphi. Hex метаморфозы с байтовой строкой или функции для перевода в Hex и Hex представление и обратно
Delphi. UniGUi. Синхронный и асинхронный режимы модальных окон
Все мы привыкли писать что-то такое для модальных окон
|
1 2 |
if LoginForm.ShowModal = mrOk then ShowMessage('authorized'); |
Но в UniGUI, для того, чтобы это срабатывало так как мы привыкли, надо подключать синхронный режим.
|
1 |
MainModule - > EnableSynchronousOperations |
По умолчанию эта галчонка отключена. Я сначала думал, что это баг, оказалось фича … Continue reading
Delphi. UniGUI. Веб / Мобильное приложение в стиле Hybrid
Продолжаем исследовать космический UniGUi. Оказывается, есть режим Hybrid, когда мы можем в одном проекте одновременно разрабатывать веб-десктоп и веб-мобильное приложение. Для этого, в проект нужно добавить мобильную форму, то есть так… Теперь, по одному адресу в сети, в зависимости от … Continue reading
Posted in Delphi
Comments Off on Delphi. UniGUI. Веб / Мобильное приложение в стиле Hybrid
Delphi.MD5
Через Indy
|
1 2 3 4 5 6 7 8 |
uses IdHashMessageDigest ... with TIdHashMessageDigest5.Create do try Result := AnsiLowerCase(HashStringAsHex(aString)); finally Free; end; |
Posted in Delphi
Comments Off on Delphi.MD5
Представление положительных и отрицательных чисел в памяти компьютера. Прямой и дополнительный код числа
Прямой код Прямой код – это представление числа в двоичной системе счисления, при котором первый (старший) разряд отводится под знак числа. Если число положительное, то в левый разряд записывается 0; если число отрицательное, то в левый разряд записывается 1. Таким образом, … Continue reading
Posted in Delphi
Comments Off on Представление положительных и отрицательных чисел в памяти компьютера. Прямой и дополнительный код числа