How fix bug in delphi 7 with scale dpi? - winforms
Please help fix bug in delphi 7 with scale dpi.
In this sample, I use TButton with Anchor:=[akRight] and as you can see button text overflow if window setting 125 dpi scale mode.
I prepared example for demonstration:
1) Default scale
2) Large scale ( as you see button2 is gone )
Source code:
Unit1.pas
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Button1: TButton;
Button2: TButton;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
end.
Unit1.dfm
object Form1: TForm1
Left = 488
Top = 196
Width = 720
Height = 511
Caption = 'Form1'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object Panel1: TPanel
Left = 0
Top = 432
Width = 704
Height = 41
Align = alBottom
Caption = 'Panel1'
TabOrder = 0
DesignSize = (
704
41)
object Button1: TButton
Left = 12
Top = 8
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 0
end
object Button2: TButton
Left = 616
Top = 8
Width = 75
Height = 25
Anchors = [akTop, akRight]
Caption = 'Button2'
TabOrder = 1
end
end
object Panel2: TPanel
Left = 0
Top = 0
Width = 704
Height = 432
Align = alClient
Caption = 'Panel2'
TabOrder = 1
end
end
To work properly with scaling, you must use an environment prepared for this.
there is nothing complicated and the letters will not shrink and everything will work fine.
I have a demo application that shows how to work with scaling
if the global scale of the system differs from the scale on the development aspiration also
depending on the overall scale, it is possible to adjust the scale of only the application itself.
EXE APP DEMO
screen
unit AmUserScale;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs;
//type
type
AmScale = class
private
class procedure SetScaleAppCustom(New,Old:integer);
public
//хранит значение маштаба по умолчанию
// AppScaleDesing рекомедую выстовить в 100 при создании формы а не здесь
// WinScaleDPIDesing рекомедую выстовить в 96 при создании формы что равно WinApi.Windows.USER_DEFAULT_SCREEN_DPI а не здесь
//если вы разрабатываете прогу и у вас на компе глобальный маштаб 120 то его и установите по умолчанию в WinScaleDPIDesing
// если у вас всегда глобальный маштаб 96 то ничего устанавливать не нужно см initialization
class var AppScaleDesing:Integer; // какой маштаб был на этапе разработки
class var AppScaleNow:Integer; //какой маштаб сейчас в приложении
class var WinScaleDPIDesing:Integer; //какой глобальный маштаб системы был на этапе разработки
class var WinScaleDPINow:Integer; //какой глобальный маштаб системы сейчас в приложении
class var IsShow:boolean;
// при создании главной формы запустить Init
// можно передать параметр сохраненного маштаба приложения например с какой то базы данных
// это процент от 30 до 200 обычно это 100 процентов от размера приложения на этапе разработки
class procedure Init(ASavedProcent:Integer=100);
// в собыитии FormShow запустить Show
class procedure Show;
// запустить в событии главной формы FormAfterMonitorDpiChanged
// проиходит когда в системе глобально меняется маштаб
class procedure ChangeDPI(NewDPI,OldDPI:integer);
// получить новое значение размера для числа val смотрите ниже описание
// если кратко то P:=Tpanel.create(self); P.height:= AmScale.Value(88);
class function Value(val:integer):integer; static;
// если хотим поменять мастаб всего приложения SetScaleApp(120,100) увеличится на 20%
class procedure SetScaleApp(New,Old:integer);
// получить список для юзера возможных маштабов приложения
class procedure GetAppToList(L:TStrings);
// у вас есть значение но не знаете индек его в списке = найдите
class function GetIndexFromList(L:TStrings;value:integer=0):integer;
// получить значение с строки которая была получена в GetAppToList
class function GetValueFromStr(S:String):integer;
// изменить маштаб когда юзер выбрал новое значение из списка
class procedure SetAppFromListInt(New:Integer);
//передать одну линию со списка полученного в GetAppToList
class procedure SetAppFromList(S:String);
end;
function UserMainScale(val:integer):integer;
{
ЭТО СТАРОЕ ОПИСАНИЕ СМЫСЛ ТОТ ЖЕ просто имена процедур изменены
получает маштаб экрана у пользователя на форм create занести значение в UserMainScaleGetConst
где
Width_now это ширина формы когда програ запускается
Width_debag это ширина формы на этапе разработки
в ответ приходит процент изменения , т.е маштаб
USER_MAIN_SCALE_CREATE:= UserMainScaleGetConst(MyForm.Width,500);
USER_MAIN_SCALE_CREATE хранит текуший маштаб наример 125.67 но обычно 100
далее если создаем компоненты диначимичеки то указываем ширину и высоту и отступы как
P:=Tpanel.create(self);
P.parent:=self;
P.height:= UserMainScale(88); //хотя раньше бы писали как P.height:= 88;
P.font.size:= UserMainScale(10);
небольшое замечание по динамическому созданию котролов
после TWinControl.Create
и до уставновки Parent
нужно ставить значения высот обычно т.е
P.height:= 88;
P.parent:=self;
после установки Parent
P.height:= UserMainScale(88);
}
implementation
{ AmScale }
function UserMainScale(val:integer):integer;
begin
Result:=AmScale.Value(val);
end;
class procedure AmScale.GetAppToList(L: TStrings);
begin
L.Clear;
L.Add('70 %');
L.Add('80 %');
L.Add('90 %');
L.Add('95 %');
L.Add('100 % (рекомедуется)');
L.Add('110 %');
L.Add('120 %');
L.Add('130 %');
L.Add('140 %');
L.Add('150 %');
L.Add('175 %');
L.Add('200 %');
end;
class function AmScale.GetIndexFromList(L: TStrings; value: integer=0): integer;
begin
if value<30 then
value:= AppScaleNow;
for Result := 0 to L.Count-1 do
if GetValueFromStr(L[Result]) = value then exit;
Result:=-1;
end;
class function AmScale.GetValueFromStr(S: String): integer;
var tok:integer;
begin
Result:=0;
tok:= pos(' ',S);
if (tok<>1) and (tok<>0) then
begin
S:=s.Split([' '])[0];
TryStrToInt(S,Result);
end;
end;
class procedure AmScale.SetAppFromList(S: String);
begin
SetAppFromListInt(GetValueFromStr(S));
end;
class procedure AmScale.SetAppFromListInt(New: Integer);
begin
SetScaleApp(New,AppScaleNow);
end;
class procedure AmScale.SetScaleApp(New,Old:integer);
begin
if New<30 then exit;
if Old<30 then
Old:= AppScaleNow;
if Old<30 then exit;
if New<>AppScaleNow then
begin
SetScaleAppCustom(New,AppScaleNow);
AppScaleNow:= New;
end;
end;
class procedure AmScale.SetScaleAppCustom(New, Old: integer);
var i:integer;
begin
for I := 0 to Screen.FormCount-1 do
Screen.Forms[i].ScaleBy(New,Old);
end;
class procedure AmScale.Show;
begin
SetScaleAppCustom(AppScaleNow,AppScaleDesing);
IsShow:=true;
end;
class procedure AmScale.ChangeDPI(NewDPI,OldDPI:integer);
begin
WinScaleDPINow:= NewDPI;
end;
class procedure AmScale.Init(ASavedProcent:Integer=100);
var LMonitor:TMonitor;
LForm: TForm;
LPlacement: TWindowPlacement;
begin
if ASavedProcent<=0 then
ASavedProcent:=100;
if ASavedProcent<30 then ASavedProcent:=30;
if ASavedProcent>300 then ASavedProcent:=300;
AppScaleDesing:=100;
AppScaleNow:=ASavedProcent;
WinScaleDPINow:=USER_DEFAULT_SCREEN_DPI;
WinScaleDPIDesing:=USER_DEFAULT_SCREEN_DPI;
if (Application<>nil) and (Screen<>nil) then
begin
LMonitor := Screen.MonitorFromWindow(Application.Handle);
if LMonitor <> nil then
WinScaleDPINow := LMonitor.PixelsPerInch
else
WinScaleDPINow := Screen.PixelsPerInch;
LForm := Application.MainForm;
if (LForm <> nil) then
WinScaleDPIDesing := LForm.PixelsPerInch;
end
else if (Screen<>nil) and (Mouse<>nil) then
begin
LMonitor := Screen.MonitorFromPoint(Mouse.CursorPos);
if LMonitor <> nil then
WinScaleDPINow := LMonitor.PixelsPerInch
else
WinScaleDPINow := Screen.PixelsPerInch;
LForm := Application.MainForm;
if (LForm <> nil) then
WinScaleDPIDesing := LForm.PixelsPerInch;
end;
//ScaleForPPI(GetParentCurrentDpi);
end;
class function AmScale.Value(val: integer): integer;
begin
// result:=Round( Value(Real(val)) );
// сначало маштаб системы потом маштаб приложения
result:=MulDiv(val, WinScaleDPINow, WinScaleDPIDesing);
if IsShow then
result:=MulDiv(result, AppScaleNow, AppScaleDesing);
end;
{
class procedure AmScale.Start(Width_now, Width_debag: real);
begin
USER_SCALE:=100;
if Width_debag=0 then exit;
USER_SCALE:=(Width_now/Width_debag)*100;
c:=TMonitor.Create;
c.PixelsPerInch
end;}
initialization
begin
AmScale.IsShow:=false;
AmScale.AppScaleDesing:=100;
AmScale.AppScaleNow:=100;
AmScale.WinScaleDPIDesing:= WinApi.Windows.USER_DEFAULT_SCREEN_DPI;
AmScale.WinScaleDPINow:= WinApi.Windows.USER_DEFAULT_SCREEN_DPI;
end;
end.
I've found a solution: detect all TControl's and reposition them.
const
DEFAULT_DPI = 97;
function TFMain.ScaleDPI(Value: Integer) : Integer;
begin
Result:=Ceil(Value*Screen.PixelsPerInch/DEFAULT_DPI);
end;
var i, n : integer;
CompFix : array of TAnchors;
with IsForm do begin
SetLength(CompFix, ComponentCount);
if ( Screen.PixelsPerInch > DEFAULT_DPI ) and Scaled then
if ( (BorderStyle = bsSizeable) or (BorderStyle = bsSizeToolWin) ) then begin
for i:=0 to ComponentCount-1 do
if Components[i] is TControl then
if ( akRight in (Components[i] as TControl).Anchors ) or
( akBottom in (Components[i] as TControl).Anchors ) then begin
CompFix[i]:=(Components[i] as TControl).Anchors;
(Components[i] as TControl).Anchors:=(Components[i] as TControl).Anchors - [akRight] - [akBottom] + [akLeft] + [akTop];
end else CompFix[i]:=[];
ClientWidth:=ScaleDPI(ClientWidth);
ClientHeight:=ScaleDPI(ClientHeight);
for i:=0 to ComponentCount-1 do
if CompFix[i] <> [] then begin
(Components[i] as TControl).Anchors:=CompFix[i];
end;
end;
end;
Related
table array security request Bollinger Pine script
I am attempting to create a scanner for higher time frame Bollingers to place in a table. I have the code working partially using variable. But have been unable to successfully add the data to a table array. My goal is to create a table array that list assets and color codes then in table when conditions are met i.e. price is above or below my signal bollinger deviation. I have added the assets into arrays but have not been successful in getting them to plot as an array. as a variable using table cell i get a single asset that plot. `//#version=5 indicator('Matrix Radar test', overlay=true) custom_tf = input.timeframe('', title='Timeframe for Screening') lbl_col = color.new(color.gray, 100) len3= input.int(50, minval=1, title="Ma Length 1") len4= input.int(100, minval=1, title="Ma Length 2") len5= input.int(200, minval=1, title="Ma Length 3") BB_sdev25 = input.float(2.5, minval=0.001, maxval = 2.8, title="Signal") //dev for signal 100 dev37 = BB_sdev25 * ta.stdev(close, len4) //dev for signal 200 dev38 = BB_sdev25 * ta.stdev(close, len5) //dev for signal 50 dev39 = BB_sdev25 * ta.stdev(close, len3) //50 1h signals dma50_up1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len3) + dev39) dma50_dwn1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len3) - dev39) //50 4hr signals dma50_up4hs=request.security(syminfo.tickerid, "240", ta.sma(close, len3) + dev39) dma50_dwn4hs=request.security(syminfo.tickerid, "240", ta.sma(close, len3) - dev39) //50 day signals dma50_upDs=request.security(syminfo.tickerid, "D", ta.sma(close, len3) + dev39) dma50_dwnDs=request.security(syminfo.tickerid, "D", ta.sma(close, len3) - dev39) // 100 1 hr signals dma100_up1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len4) + dev37) dma100_dwn1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len4) - dev37) //100 4 hr signal 4hr dma100s_up4=request.security(syminfo.tickerid, "240", ta.sma(close, len4) + dev37) dma100s_dwn4=request.security(syminfo.tickerid, "240", ta.sma(close, len4) - dev37) //100 day signals dma100_upDs=request.security(syminfo.tickerid, "D", ta.sma(close, len4) + dev37) dma100_dwnDs=request.security(syminfo.tickerid, "D", ta.sma(close, len4) - dev37) //200 1h signal dma200_up1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len5) + dev38) dma200_dwn1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len5) - dev38) // 200 4hr signal dma200_up4s=request.security(syminfo.tickerid, "240", ta.sma(close, len5) + dev38) dma200_dwn4s=request.security(syminfo.tickerid, "240", ta.sma(close, len5) - dev38) //200 day signals dma200_upDs=request.security(syminfo.tickerid, "D", ta.sma(close, len5) + dev38) dma200_dwnDs=request.security(syminfo.tickerid, "D", ta.sma(close, len5) - dev38) // plot for visual to check if working upper10s = ta.sma(close, len4) + dev37 lower10s = ta.sma(close, len4) - dev37 var sma1label9Us = label.new(x = bar_index, y = dma100_up1hs, style = label.style_label_left, color=lbl_col, textcolor = color.yellow, text = "---- --1HUSignal-") label.set_xy(sma1label9Us, x = bar_index, y = dma100_up1hs) var sma1label9Ls = label.new(x = bar_index, y = dma100_dwn1hs, style = label.style_label_left, color=lbl_col, textcolor = color.yellow, text = "---- --1HLSignal-") label.set_xy(sma1label9Ls, x = bar_index, y = dma100_dwn1hs) // plot for visual to check if working end indiSet = input(false, '═════════ MRC Parameter ════════') screenSet = input(false, '═════════ Screening Setting ════════') screenList = input(false, '═════════ Asset for Screening ════════') asset_01 = input.symbol(title='Asset 01', defval='') asset_02 = input.symbol(title='Asset 02', defval='') asset_03 = input.symbol(title='Asset 03', defval='') asset_04 = input.symbol(title='Asset 04', defval='') asset_05 = input.symbol(title='Asset 05', defval='') asset_06 = input.symbol(title='Asset 06', defval='') asset_07 = input.symbol(title='Asset 07', defval='') asset_08 = input.symbol(title='Asset 08', defval='') asset_09 = input.symbol(title='Asset 09', defval='') asset_10 = input.symbol(title='Asset 10', defval='') asset_11 = input.symbol(title='Asset 11', defval='') asset_12 = input.symbol(title='Asset 12', defval='') asset_13 = input.symbol(title='Asset 13', defval='') asset_14 = input.symbol(title='Asset 14', defval='') asset_15 = input.symbol(title='Asset 15', defval='') asset_16 = input.symbol(title='Asset 16', defval='') asset_17 = input.symbol(title='Asset 17', defval='') asset_18 = input.symbol(title='Asset 18', defval='') asset_19 = input.symbol(title='Asset 19', defval='') asset_20 = input.symbol(title='Asset 20', defval='') asset_21 = input.symbol(title='Asset 21', defval='') asset_22 = input.symbol(title='Asset 22', defval='') screen_mrc() => int condition = 0 // if low < dma50_dwn1hs or low < dma50_dwn4hs or low < dma50_dwnDs //condition := 1 //if high > dma50_up1hs or high > dma50_up4hs or high > dma50_upDs //condition := 1 /// this line below the greater than and less than reversed to force signal for testing if low > dma100_dwn1hs or high < dma100_up1hs ///////////////////////////////////////// condition := 1 ///////////////////////////////////////// /// this code above the greater than and less than reversed to force signal for testing //if low < dma100s_dwn4 or high > dma100s_up4 //condition := 3 //if low < dma100_dwnDs or high > dma100_upDs // condition := 4 //if low < dma200_dwn1hs or high > dma200_up1hs // condition := 5 // if low < dma200_dwn4s or high > dma200_up4s // condition := 6 // if low < dma200_dwnDs or high > dma200_upDs //condition := 7 // Retrieves the names of the ticker //************************************************************************************************** ********** // Screener Logic //************************************************************************************************************ // set asset status { asset_01_status = asset_01 == '' ? 0 : request.security(asset_01, custom_tf, screen_mrc()) asset_02_status = asset_02 == '' ? 0 : request.security(asset_02, custom_tf, screen_mrc()) asset_03_status = asset_03 == '' ? 0 : request.security(asset_03, custom_tf, screen_mrc()) asset_04_status = asset_04 == '' ? 0 : request.security(asset_04, custom_tf, screen_mrc()) asset_05_status = asset_05 == '' ? 0 : request.security(asset_05, custom_tf, screen_mrc()) asset_06_status = asset_06 == '' ? 0 : request.security(asset_06, custom_tf, screen_mrc()) asset_07_status = asset_07 == '' ? 0 : request.security(asset_07, custom_tf, screen_mrc()) asset_08_status = asset_08 == '' ? 0 : request.security(asset_08, custom_tf, screen_mrc()) asset_09_status = asset_09 == '' ? 0 : request.security(asset_09, custom_tf, screen_mrc()) asset_10_status = asset_10 == '' ? 0 : request.security(asset_10, custom_tf, screen_mrc()) asset_11_status = asset_11 == '' ? 0 : request.security(asset_11, custom_tf, screen_mrc()) asset_12_status = asset_12 == '' ? 0 : request.security(asset_12, custom_tf, screen_mrc()) asset_13_status = asset_13 == '' ? 0 : request.security(asset_13, custom_tf, screen_mrc()) asset_14_status = asset_14 == '' ? 0 : request.security(asset_14, custom_tf, screen_mrc()) asset_15_status = asset_15 == '' ? 0 : request.security(asset_15, custom_tf, screen_mrc()) asset_16_status = asset_16 == '' ? 0 : request.security(asset_16, custom_tf, screen_mrc()) asset_17_status = asset_17 == '' ? 0 : request.security(asset_17, custom_tf, screen_mrc()) asset_18_status = asset_18 == '' ? 0 : request.security(asset_18, custom_tf, screen_mrc()) asset_19_status = asset_19 == '' ? 0 : request.security(asset_19, custom_tf, screen_mrc()) asset_20_status = asset_20 == '' ? 0 : request.security(asset_20, custom_tf, screen_mrc()) asset_21_status = asset_21 == '' ? 0 : request.security(asset_21, custom_tf, screen_mrc()) asset_22_status = asset_22 == '' ? 0 : request.security(asset_22, custom_tf, screen_mrc()) //} end //symbol name s_arr = array.new_string(0) array.push(s_arr, asset_01) array.push(s_arr, asset_02) array.push(s_arr, asset_03) array.push(s_arr, asset_04) array.push(s_arr, asset_05) array.push(s_arr, asset_06) array.push(s_arr, asset_07) array.push(s_arr, asset_08) array.push(s_arr, asset_09) array.push(s_arr, asset_10) array.push(s_arr, asset_11) array.push(s_arr, asset_12) array.push(s_arr, asset_13) array.push(s_arr, asset_14) array.push(s_arr, asset_15) array.push(s_arr, asset_16) array.push(s_arr, asset_17) array.push(s_arr, asset_18) array.push(s_arr, asset_19) array.push(s_arr, asset_20) array.push(s_arr, asset_21) array.push(s_arr, asset_22) //asset condition state asset_condition = array.new_bool() array.push(asset_condition, asset_01_status) array.push(asset_condition, asset_02_status) array.push(asset_condition, asset_03_status) array.push(asset_condition, asset_04_status) array.push(asset_condition, asset_05_status) array.push(asset_condition, asset_06_status) array.push(asset_condition, asset_07_status) array.push(asset_condition, asset_08_status) array.push(asset_condition, asset_09_status) array.push(asset_condition, asset_10_status) array.push(asset_condition, asset_11_status) array.push(asset_condition, asset_12_status) array.push(asset_condition, asset_13_status) array.push(asset_condition, asset_14_status) array.push(asset_condition, asset_15_status) array.push(asset_condition, asset_16_status) array.push(asset_condition, asset_17_status) array.push(asset_condition, asset_18_status) array.push(asset_condition, asset_19_status) array.push(asset_condition, asset_20_status) array.push(asset_condition, asset_21_status) array.push(asset_condition, asset_22_status) // set lower 1001h signal lower_100hsignal = '' lower_100hsignal := asset_01 != '' and asset_01_status == 1 ? lower_100hsignal + asset_01 + ' (100 Lower Signal) \n ' : lower_100hsignal // set upper 1001h signal upper_100hsignal = '' upper_100hsignal := asset_01 != '' and asset_01_status == 1 ? upper_100hsignal + asset_01 + ' (100 Upper Signal) \n ' : upper_100hsignal // Prep Label Value //-------------- var assetcount = asset_01 == '' and asset_02 == '' and asset_03 == '' and asset_04 == '' and asset_05 == '' and asset_06 == '' and asset_07 == '' and asset_08 == '' and asset_09 == '' and asset_10 == '' and asset_11 == '' and asset_12 == '' and asset_13 == '' and asset_14 == '' and asset_15 == '' and asset_16 == '' and asset_17 == '' and asset_18 == '' and asset_19 == '' and asset_20 == '' and asset_21 == '' and asset_22 == '' ? 0 : 1 var tf = custom_tf == '' ? timeframe.period : custom_tf var brl = '\n-----------------------\n' title = 'Bollinger Band Signals:\nTimeframe = ' + tf + brl var lowertable = table.new(position = position.bottom_left, columns = 1, rows = 40, bgcolor = color.blue, border_width = 3 ) if assetcount > 0 if lower_100hsignal + lower_100hsignal != '' lower_100hsignal := '\lower100' + lower_100hsignal lower_100hsignal if barstate.islast table.cell(lowertable, column = 0, row = 0, text=title + lower_100hsignal) var upperTable = table.new(position = position.middle_left, columns = 1, rows = 40, bgcolor = color.red, border_width = 1) if assetcount > 0 if upper_100hsignal + upper_100hsignal != '' upper_100hsignal := '\upper100' + upper_100hsignal upper_100hsignal if barstate.islast table.cell(table_id = upperTable, column = 0, row = 0, text=title + upper_100hsignal)`
Convert Pine-Script version 2.0 to version 4.0
I need to convert this PineScript Study from v2.0 to v4.0 //#version=2 study("trendFilter",overlay=true) // Pd=input(200) Factor=input(0.9) // P = pow(Pd,2) a = 2/(P+1) d = abs(close - nz(Tsl[0],hl2)) t = a*d+(1-a)*nz(t[1],d) src = Factor*nz(Tsl[0],hl2) + (1-Factor)*close Up=nz(Tsl[0],hl2)-t Dn=nz(Tsl[0],hl2)+t // TrendUp=src[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up TrendDown=src[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn // Trend = src > TrendDown[1] ? 1: src< TrendUp[1]? -1: nz(Trend[1],1) Tsl = Trend==1? TrendDown : TrendUp css = Tsl > Tsl[1] ? #0080FF : Tsl < Tsl[1] ? #FF0040 : na plot(Tsl,color=fixnan(css),transp=0) In TradingView's Pine-Script latest version (4.0) it's required remove Forward-referenced variables.
//#version=4 study("trendFilter", "TF", overlay=true) // Pd=input(200) Factor=input(0.9) // var float Tsl = na var float t = na var float TrendUp = na var float TrendDown = na var float Trend = na P = pow(Pd,2) a = 2/(P+1) d = abs(close - nz(Tsl[0],hl2)) t := a*d+(1-a)*nz(t[1],d) src = Factor*nz(Tsl[0],hl2) + (1-Factor)*close Up=nz(Tsl[0],hl2)-t Dn=nz(Tsl[0],hl2)+t // TrendUp := src[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up TrendDown := src[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn // Trend := src > TrendDown[1] ? 1: src< TrendUp[1]? -1: nz(Trend[1],1) Tsl := Trend==1? TrendDown : TrendUp css = Tsl > Tsl[1] ? #0080FF : Tsl < Tsl[1] ? #FF0040 : na plot(Tsl,color=fixnan(css),transp=0)
I think it's better. //#version=4 study("trendFilter", "TF", overlay=true) // Pd=input(200) Factor=input(0.9) // var float Tsl = na var float t = na P = pow(Pd,2) a = 2/(P+1) d = abs(close - nz(Tsl[0],hl2)) t := a*d+(1-a)*nz(t[1],d) src = Factor*nz(Tsl[0],hl2) + (1-Factor)*close Up=nz(Tsl[0],hl2)-t Dn=nz(Tsl[0],hl2)+t // TrendUp = Up TrendUp := src[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up TrendDown = Dn TrendDown := src[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn // Trend = int(na) Trend := src > TrendDown[1] ? 1: src< TrendUp[1]? -1: nz(Trend[1],1) Tsl := Trend==1? TrendDown : TrendUp css = Tsl > Tsl[1] ? #0080FF : Tsl < Tsl[1] ? #FF0040 : na plot(Tsl,color=fixnan(css),transp=0)
How would i go about filling a TDBEdit from MS Access table field in Delphi on button click
I tried doing it two ways First i tried just using the ADOTable1.Fieldbyname thing to fill a tedit from First_Class field in ms access db but that didnt display anything procedure TForm5.btnzaprosClick(Sender: TObject); var vremia: string; sysTime: tdatetime; begin dbeTime.text:=vremia; dbeClass1.Text:=ADOTable1.FieldByName('First_Class').AsString; end; I also tried doing it through this complicated code procedure TForm1.btnzaprosClick(Sender: TObject); // Процедура определения количества билетов по выбранному рейсу var vremia: string; sysTime: tdatetime; begin if edDate.Text = datamodule2.ADOTable1DSDesigner.Text then begin { showmessage ('Нашел дату'); } datamodule2.ADOTable1.First; while datamodule2.ADOTable1.Eof <> true do begin if cmbNumber.Text = datamodule2.ADOTable1_.Text then begin { showmessage ('Нашел рейс'); } vremia: = datamodule2.ADOTable1_2.Text; delete(vremia, 1, 11); sysTime: = time; { showmessage (timetostr (sysTime)); } if sysTime < strtotime(vremia) then begin dbeTime.Text: = vremia; dbeClass1.Text: = datamodule2.ADOTable1_3.Text; dbeClass2.Text: = datamodule2.ADOTable1_4.Text; exit; end else showmessage('Данный рейс уже улетел в ' + vremia); dbeTime.Text: = ''; dbeClass1.Text: = ''; dbeClass2.Text: = ''; exit; end else datamodule2.ADOTable1.Next; end; end else if edDate.Text = datamodule2.ADOTable2DSDesigner.Text then begin datamodule2.ADOTable2.First; while datamodule2.ADOTable2.Eof <> true do begin if cmbNumber.Text = datamodule2.ADOTable2_.Text then begin vremia: = datamodule2.ADOTable2_2.Text; delete(vremia, 1, 11); dbeTime.Text: = vremia; dbeClass1.Text: = datamodule2.ADOTable2_3.Text; dbeClass2.Text: = datamodule2.ADOTable2_4.Text; exit; end else datamodule2.ADOTable2.Next; end; end else if edDate.Text = datamodule2.ADOTable3DSDesigner.Text then begin datamodule2.ADOTable3.First; while datamodule2.ADOTable3.Eof <> true do begin if cmbNumber.Text = datamodule2.ADOTable3_.Text then begin vremia: = datamodule2.ADOTable3_2.Text; delete(vremia, 1, 11); dbeTime.Text: = vremia; dbeClass1.Text: = datamodule2.ADOTable3_3.Text; dbeClass2.Text: = datamodule2.ADOTable3_4.Text; exit; end else datamodule2.ADOTable3.Next; end; end else begin showmessage('Билетов на данный рейс нет'); dbeTime.Text: = ''; dbeClass1.Text: = ''; dbeClass2.Text: = ''; end; end; but that instantly spit loads of errors so i opted to not use it So how exactly would i go about filling a tdbedit on clicking a button?
Import many files .txt in SAS
I built a code to import multiple data simultaneously into SAS, but I want to improve it does anyone have any suggestions? filename indata pipe 'dir E:\Desafio_SAS\Dados /B'; data file_list; length arquivos$20.; infile indata truncover ; input arquivos $20.; call symput('num_files',_n_); arquivos=compress(arquivos,',.txt'); run; CRIANDO UMA MACRO POR PROC SQL PARA GUARDAR O NOME DOS ARQUIVOS proc sql; select arquivos into :lista separated by ' ' from file_list; quit; %let &lista; %macro importar(arquivo=); filename data "E:\Desafio_SAS\Dados\&arquivo..txt"; data &arquivo; infile data dlm=" " missover dsd firstobs=2; input v0 (v1 - v8) ($); format v0 F16.; run; %mend importar; %macro fileout; %do i=1 %to &num_files; %importar(arquivo=df&i); data df&i; set var_names df&i; run; %end; %mend fileout; %fileout; %macro excluiv0; %do i=1 %to &num_files; data _null_; data df&i(drop = v0); set df&i; run; %end; run; %mend excluiv0; %excluiv0; It's just part of the code.
You can use a wildcard in the infile file-specification. As long as all the files meeting the wildcard are the same layout, you can use a single input to read all the files. Example * create three text files having same fields; data _null_; file '%temp%\1.txt'; put '1 2 3 abc'; put '3 4 5 def'; file '%temp%\2.txt'; put '6 7 8 ghi'; put '9 10 11 jkl'; file '%temp%\3.txt'; put '12 13 14 xyz'; put '15 16 17 tuv'; run; * read all three using wildcard in infile. Save name of file whence * data cometh frometh; data want; length _filename_ $250; infile '%temp%\?.txt' filename=_filename_; length source $250; length a b c 8 s $20; source = _filename_; input a b c s; run; Wildcards are ?, 0 or 1 of any character *, any number of any character
t1 <- ttheme_default(core=list( fg_params=list(fontface=c("bold.italic")), bg_params = list(fill=c("green", "grey90","blue","red")))) grid.arrange(g1, tableGrob(iris[1:5, 1:4], theme = t1,, rows=NULL), g1, g1, nrow = 2)
--- title: "Column Orientation" output: flexdashboard::flex_dashboard --- ```{r setup, include=FALSE} library(ggplot2);library(knitr);library(kableExtra) library(flexdashboard);library(gridExtra);library(grid) ``` <style> .colored { background-color: #002080;} </style> Column{data-width=200} ------------------------------------- ### Chart 1{.colored} ```{r} gauge(10, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080")) gauge(50, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080")) gauge(20, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080")) gauge(15, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080")) gauge(5 , min = 0, max = 100, sectors = gaugeSectors(colors = "#002080")) ``` Column ------------------------------------- ### Chart 2 ```{r, include=FALSE} tt1 <- ttheme_default() tt2 <- ttheme_minimal() tt3 <- ttheme_minimal( core=list(bg_params = list(fill = blues9[1:4], col=NA), fg_params=list(fontface=3)), colhead=list(fg_params=list(col="navyblue", fontface=4L)), rowhead=list(fg_params=list(col="orange", fontface=3L))) tab <- grid.arrange(tableGrob(iris[c(1:4,1:2), c(1:3,1:2)], theme=tt3), nrow=1) graf <- ggplot(data=mtcars, aes(x=drat, y=disp, group=vs)) + geom_line() + ylab("") + geom_point() gg.gauge <- function(pos,breaks=c(0,10,25,100)) { get.poly <- function(a,b,r1=0.5,r2=1.0) { th.start <- pi*(1-a/100) th.end <- pi*(1-b/100) th <- seq(th.start,th.end,length=1000) x <- c(r1*cos(th),rev(r2*cos(th))) y <- c(r1*sin(th),rev(r2*sin(th))) return(data.frame(x,y)) } ggplot()+ geom_polygon(data=get.poly(breaks[1],breaks[2]),aes(x,y),fill="forestgreen", colour = "white", size = 1.2, alpha = 0.7) + geom_polygon(data=get.poly(breaks[2],breaks[3]),aes(x,y),fill="gold", colour = "white", size = 1.2, alpha = 0.7) + geom_polygon(data=get.poly(breaks[3],breaks[4]),aes(x,y),fill="red", colour = "white", size = 1.2, alpha = 0.7) + geom_polygon(data=get.poly(pos-1,pos+1,0.2),aes(x,y), colour = "white")+ annotate("text",x=0,y=0,label=pos,vjust=0,size=8,fontface="bold")+ coord_fixed()+ theme_bw()+ theme(axis.text=element_blank(), axis.title=element_blank(), axis.ticks=element_blank(), panel.grid=element_blank(), panel.border=element_blank()) } gg1 <- gg.gauge(2,breaks=c(0,10,25,100)) gg2 <- gg.gauge(5,breaks=c(0,10,25,100)) gg3 <- gg.gauge(7,breaks=c(0,10,25,100)) ``` ```{r, fig.width=9.5, fig.height=7} for (i in 1:5){ title1=textGrob("Test title TESTE", gp=gpar(fontface="bold", fontsize = 15)) lay <- rbind(c(3,3,4,4,5,5), c(1,1,1,1,1,1), c(1,1,1,1,1,1), c(2,2,2,2,2,2), c(2,2,2,2,2,2)) grid.arrange(graf, tab, gg1, gg2, gg3, top=title1, layout_matrix= lay) grid.rect(width = 1, height = 1, gp = gpar(lwd = 2, col = "black", fill = NA)) cat("\n") } ```
--- title: "BRADESCO" output: flexdashboard::flex_dashboard: orientation: rows --- ```{r setup, include=FALSE} library(ggplot2);library(knitr);library(kableExtra) library(flexdashboard); library(gridExtra);library(grid) ``` Geral {data-icon="fa-signal"} ===================================== ### Chat 1 ```{r} p1 <- qplot(mpg, wt, data = mtcars, colour = cyl) p2 <- qplot(mpg, data = mtcars) p3 <- qplot(mpg, data = mtcars, geom = "dotplot") lay <- rbind(c(1,1,1,2,2,2), c(3,3,3,3,3,3)) grid.arrange(p2, p3, p1, nrow = 2, layout_matrix= lay) ``` ### Table 1 ```{r} kable(mtcars[1:10, c(1:6,1:4)], caption = "Group Rows") %>% kable_styling("striped", full_width = F) %>% group_rows("Group 1", 4, 7) %>% group_rows("Group 2", 8, 10) ``` Por segmento {data-icon="fa-signal"} ===================================== <style> .colored { background-color: #002080;} </style> Row{data-height=200} ------------------------------------- ### Chart 1{.colored} ```{r, fig.width=55} dat = data.frame(count=rep(c(10, 60, 30),10), category=rep(c("A", "B", "C"),10), fator=c(1,2,3,4,5)) # Add addition columns, needed for drawing with geom_rect. dat$fraction = dat$count / sum(dat$count) dat = dat[order(dat$fraction), ] dat$ymax = cumsum(dat$fraction) dat$ymin = c(0, head(dat$ymax, n=-1)) p <- ggplot(dat, aes(x=2, y=fraction, fill=category))+ geom_bar(stat="identity", colour = "white", size = 2) + xlim(0, 2.5) + scale_fill_manual(values=c("#002080", "#002080", "white")) + coord_polar(theta = "y")+ labs(x=NULL, y=NULL)+ guides(fill=FALSE) + ylab("fsfagafs") + facet_wrap(~ fator,nrow = 1) + annotate("text", x = 0, y = 0, label = "WW", size = 20, colour = "white") + theme( plot.margin = margin(-1.1, 3.6, -1.1, 3.6, "cm"), panel.spacing = unit(30, "lines"), axis.ticks=element_blank(), axis.text=element_blank(), axis.title=element_blank(), panel.grid=element_blank(), plot.background = element_rect(fill = "#002080", colour="#002080"), panel.background = element_rect(fill = "#002080", colour="#002080"), strip.background = element_blank(), strip.text.x = element_blank()) p ``` Row ------------------------------------- ### Chart 2 {data-wight=900} ```{r, include=FALSE} tt1 <- ttheme_default() tt2 <- ttheme_minimal() tt3 <- ttheme_minimal( core=list(bg_params = list(fill = blues9[1:4], col=NA), fg_params=list(fontface=3)), colhead=list(fg_params=list(col="navyblue", fontface=4L)), rowhead=list(fg_params=list(col="orange", fontface=3L))) tab <- grid.arrange(tableGrob(iris[c(1:4,1:2), c(1:3,1:2)], theme=tt3), nrow=1) graf <- ggplot(data=mtcars, aes(x=drat, y=disp, group=vs)) + geom_line() + ylab("") + geom_point() gg.gauge <- function(pos,breaks=c(0,10,25,100)) { get.poly <- function(a,b,r1=0.5,r2=1.0) { th.start <- pi*(1-a/100) th.end <- pi*(1-b/100) th <- seq(th.start,th.end,length=1000) x <- c(r1*cos(th),rev(r2*cos(th))) y <- c(r1*sin(th),rev(r2*sin(th))) return(data.frame(x,y)) } ggplot()+ geom_polygon(data=get.poly(breaks[1],breaks[2]),aes(x,y),fill="forestgreen", colour = "white", size = 1.2, alpha = 0.7) + geom_polygon(data=get.poly(breaks[2],breaks[3]),aes(x,y),fill="gold", colour = "white", size = 1.2, alpha = 0.7) + geom_polygon(data=get.poly(breaks[3],breaks[4]),aes(x,y),fill="red", colour = "white", size = 1.2, alpha = 0.7) + geom_polygon(data=get.poly(pos-1,pos+1,0.2),aes(x,y), colour = "white")+ annotate("text",x=0,y=0,label=pos,vjust=0,size=8,fontface="bold")+ coord_fixed()+ theme_bw()+ theme(axis.text=element_blank(), axis.title=element_blank(), axis.ticks=element_blank(), panel.grid=element_blank(), panel.border=element_blank()) } gg1 <- gg.gauge(2,breaks=c(0,10,25,100)) gg2 <- gg.gauge(5,breaks=c(0,10,25,100)) gg3 <- gg.gauge(7,breaks=c(0,10,25,100)) ``` ```{r, fig.width=7.2, fig.height=7} for (i in 1:5){ title1=textGrob("Test title TESTE", gp=gpar(fontface="bold", fontsize = 15)) lay <- rbind(c(3,3,4,4,5,5), c(1,1,1,1,1,1), c(1,1,1,1,1,1), c(2,2,2,2,2,2), c(2,2,2,2,2,2)) grid.arrange(graf, tab, gg1, gg2, gg3, top=title1, layout_matrix= lay) grid.rect(width = 1, height = 1, gp = gpar(lwd = 2, col = "black", fill = NA)) cat("\n") } ``` ### Chart 2 ```{r} mydata = data.frame(x1 = c(1,2,3), x2 = c(9,8,7), label = c("description a", "description b", "description c")) ht = 5 wd1 = 5 wd2 = 12 gap = 0.1 nc = ncol(mydata) nr = nrow(mydata) x = rep(c(seq(0,(nc-2)*(wd1+gap), wd1+gap), (nc-2)*(wd1+gap) + gap + 0.5*(wd2+wd1)), nr) y = rep(seq(0,(nr-1)*(ht+gap), ht+gap), nc) %>% sort() h = rep(ht, nr * nc) w = rep(c(rep(wd1, nc-1), wd2), nr) info = as.vector(t(as.matrix(mydata[nr:1,]))) df = data.frame(x = x, y = y, h = h, w = w, info = info) ggplot(df, aes(x, y, height = h, width = w, label = info)) + geom_tile() + geom_text(color = "white", fontface = "bold") + coord_fixed() + scale_fill_brewer(type = "qual",palette = "Dark2") + theme_void() + guides(fill = F) ``` teste
how to make an iron python drop down menu
I've got this program made up But i want to change bacon to a drop down list instead of a text box. But i don't know what a drop down menu would be like in Iron python. I'm open to suggestions. import clr clr.AddReference('System.Drawing') clr.AddReference('System.Windows.Forms') from System.Drawing import * from System.Windows.Forms import * class SimpleTextBoxForm(Form): def __init__(self): self.Text = "Production Plan Pull" self.Width = 300 self.Height = 250 self.label = Label() self.label.Text = "bacon" self.label.Location = Point(25, 25) self.label.Height = 25 self.label.Width = 75 self.textbox = TextBox() self.textbox.Text = "Please Insert The bacon" self.textbox.Location = Point(100, 25) self.textbox.Width = 150 self.label2 = Label() self.label2.Text = "soup" self.label2.Location = Point(25, 50) self.label2.Height = 25 self.label2.Width = 75 self.textbox2 = TextBox() self.textbox2.Text = "Please Insert The Soup" self.textbox2.Location = Point(100, 50) self.textbox2.Width = 150 self.label3 = Label() self.label3.Text = "dork" self.label3.Location = Point(25, 75) self.label3.Height = 25 self.label3.Width = 75 self.textbox3 = TextBox() self.textbox3.Text = "Please Insert The dork" self.textbox3.Location = Point(100, 75) self.textbox3.Width = 150 self.button1 = Button() self.button1.Text = 'Submit' self.button1.Location = Point(50, 125) self.button1.Click += self.update self.button2 = Button() self.button2.Text = 'Reset' self.button2.Location = Point(150, 125) self.button2.Click += self.reset self.AcceptButton = self.button1 self.CancelButton = self.button2 self.Controls.Add(self.label) self.Controls.Add(self.textbox) self.Controls.Add(self.label2) self.Controls.Add(self.textbox2) self.Controls.Add(self.label3) self.Controls.Add(self.textbox3) self.Controls.Add(self.button1) self.Controls.Add(self.button2) def update(self, sender, event): self.label.Text = self.textbox.Text def reset(self, sender, event): self.label.Text = "Nothing So Far" self.textbox.Text = "The Default Text" form = SimpleTextBoxForm() Application.Run(form)
IronPython is the programming language you're using, text boxes or drop down menus are a product of the UI library you're using. They're not the same at all. You're using Windows Forms for your UI. Get acquainted with the available controls or build one yourself. What you're looking for is the ComboBox. Change your "bacon" control to use that instead.