Conditionally modifying multiple strings with For - visual-foxpro

So I have 13 binary values, which I call b_1... b_13, and based off these values I'd like to either set something I call indic_j to a previously defined string called inf_j, or nothing at all. Is it possible to do this without using 13 "If..." statements? What I have tried is below:
inf_1 = "aaaaa"
inf_2 = "bbbbb"
... and so on defining 13 infs, where aaaaa, bbbbb etc are names of columns in a table that I want to select.
FOR j = 1 to 13
IF b_j = 1 THEN "indic_"+j = inf_j + ",";
ELSE "indic_"+j = ""
ENDIF
ENDFOR
Also, before this I haven't introduced anything called indic_1, indic_2, etc. Is this needed?
My end goal is to transfer selected columns over to Excel. I've no problems doing this with predetermined columns, but I'm not sure how to allow for selected columns only.
I've tried using 13 IF statements, but I'm getting operator/operand type mismatch errors. My code currently is
IIF(b_1 = 1, indic_1 = inf_1 + ",",indic_1 = "")
IIF(b_2 = 1, indic_1 = inf_2 + ",",indic_1 = "")
IIF(b_3 = 1, indic_1 = inf_3 + ",",indic_1 = "")
and so on for 13 times, and then
SELECTIONRANG = indic_1 + indic_2 + indic_3 + indic_4 + indic_5 + indic_6 +indic_7 + indic_8 + indic_9 + indic_10 + indic_11 + indic_12 + indic_13
SELECTIONRANGE = LEFT(SELECTIONRANG,LEN(Selectionrang)-1)

You could create te variable name as a string and use it with &
As:
ind = 13
Var = "inf_" + ind
&Var ** inf_13

Related

Is there a way to simply replace string elements containing escape characters

From a file i import lines. In this line an (escaped) string is part of the line:
DP,0,"021",257
DP,1,"022",257
DP,2,"023",513
DP,3,"024",513
DP,4,"025",1025
DP,5,"026",1025
DP,6,"081",257
DP,7,"082",257
DP,8,"083",513
DP,9,"084",513
DP,10,"085",1025
DP,11,"086",1025
DP,12,"087",1025
DP,13,"091",257
DP,14,"092",513
DP,15,"093",1025
IS,0,"FIX",0
IS,1,"KARIN02",0
IS,2,"KARUIT02",0
IS,3,"KARIN02HOV",0
IS,4,"KARUIT02HOV",0
IS,5,"KARIN08",0
IS,6,"KARUIT08",0
IS,7,"KARIN08HOV",0
IS,8,"KARUIT08HOV",0
IS,9,"KARIN09",0
IS,10,"KARUIT09",0
IS,11,"KARIN09HOV",0
IS,12,"KARUIT09HOV",0
IS,13,"KARIN10",0
IS,14,"KARUIT10",0
IS,15,"KARIN10HOV",0
I get the following Objects (if DP) :
index - parts1 (int)
name - parts2 (string)
ref - parts3 (int)
I tried using REGEX to replace the excape-sequence from the lines but to no effect
#name_to_ID = {}
kruising = 2007
File.open(cfgFile).each{|line|
parts = line.split(",")
if parts[0]=="DP"
index = parts[1].to_i
hex = index.to_s(16).upcase.rjust(2, '0')
cname = parts[2].to_s
tname = cname.gsub('\\"','')
p "cname= #{cname} (#{cname.length})"
p "tname= #{tname} (#{tname.length})"
p cname == tname
#name_to_ID[tname] = kruising.to_s + "-" + hex.to_s
end
}
teststring = "021"
p #name_to_ID[teststring]
> "021" (5)
> "021" (5)
> true
> nil
The problem came to light when calling from another string reference (length3)
hash[key] isnt equal as string "021" ( length 5) is not string 021 ( length 3)
any method that actually replaces the chars i need?
EDIT: I used
cname.each_char{|c|
p c
}
> "\""
> "0"
> "2"
> "1"
> "\""
EDIT: requested outcome update:
# Current output:
#name_to_ID["021"] = 2007-00 "021".length = 5
#name_to_ID["022"] = 2007-01 "022".length = 5
#name_to_ID["081"] = 2007-06 "081".length = 5
#name_to_ID["082"] = 2007-07 "082".length = 5
#name_to_ID["091"] = 2007-0D "091".length = 5
#name_to_ID["101"] = 2007-10 "101".length = 5
# -------------
# Expected output:
#name_to_ID["021"] = 2007-00 "021".length = 3
#name_to_ID["022"] = 2007-01 "022".length = 3
#name_to_ID["081"] = 2007-06 "081".length = 3
#name_to_ID["082"] = 2007-07 "082".length = 3
#name_to_ID["091"] = 2007-0D "091".length = 3
#name_to_ID["101"] = 2007-10 "101".length = 3
Your problem is you don't know the correct character in your string. It might not be the same character when printing it.
Try parts[2].to_s.bytes to check exactly what is the character code of that unexpected character. For example:
> "͸asd".bytes
=> [205, 184, 97, 115, 100]
Alternatively, you can delete the first and the last characters, if you are sure that every part of the string has the same format:
cname = parts[2].to_s[1..-2]
Or you can remove all special characters in the string if you know that the string will not contain any special character
cname = parts[2].to_s.gsub(/[^0-9A-Za-z]/, '')

update_cells not working as expected

I have written this function:
def duplicate_sheet1(wb, title=None):
if title is None:
title = wb.sheet1.title + ' DUPLICATE'
wb._sheet_list = [wb.sheet1]
wb.add_worksheet(title, wb.sheet1.row_count, wb.sheet1.col_count)
wb._sheet_list = wb._sheet_list[::-1]
wb._sheet_list[0].update_cells(wb._sheet_list[1]._fetch_cells())
...everything works as expected upon inspection with a debugger except update_cells, when I _fetch_cells for worksheet 0 after running the code, the sheet is empty.
Apparently the list returned by _fetch_cells is not the same as what is expected by update_cells. This may be because _fetch_cells does not include empty cells in the returned list, update_cells may only work with a 1 or 2-D grid--I am unsure.
Here is the work-around I found, apologies as the code could could probably be improved:
def duplicate_sheet1(wb, title=None):
if title is None:
title = wb.sheet1.title + ' DUPLICATE'
wb._sheet_list = [wb.sheet1]
wb.add_worksheet(title, wb.sheet1.row_count, wb.sheet1.col_count)
wb._sheet_list = wb._sheet_list[::-1]
cell_list = build_cell_list(wb._sheet_list[0], wb._sheet_list[1])
wb._sheet_list[0].update_cells(cell_list)
def build_cell_list(new_worksheet, old_worksheet):
fetched = old_worksheet._fetch_cells()
max_row = fetched[-1].row
max_col = max([cell.col for cell in fetched])
cell_list = new_worksheet.range('A1:' + chr(max_col + 64) + str(max_row))
for cell in cell_list:
cell.value = next(
(
f.value for f in fetched
if f.col == cell.col and f.row == cell.row
),
'',
)
return cell_list

VB6 MSFlexGrid - Unable to set columns and rows count at runtime

I have a Visual Basic 6 form with a MSFlexGrid control inside, which takes data from a record set(ADODB) and displays them.
Before starting the copy of data to the FlexGrid, I'm trying to set the rows count, depending on records count. Also I have a collection which contains columns' names, then I can get the number of columns from here.
The following is a code snippet:
v_colsCount = UBound(aCols) + 2 // aCols = array with columns' names
v_regCount = rs.RecordCount // rs = my ADODB record set
myFlexGrid.Rows = 0 // for cleaning rows from a previous display
myFlexGrid.Rows = IIf(v_regCount > 0, v_regCount + 1, 2)
myFlexGrid.Cols = v_colsCount
myFlexGrid.FixedRows = 1
myFlexGrid.FixedCols = 0
There are 7532 rows and 52 columns. The problem comes when I run the application and try to execute this part of the code (fill the FlexGrid with data from the record set):
For iRow = 1 To v_regCount
For iCol = 0 To v_colsCount -2
sAux = ConvStr(rs.Fields(aCols(iCol)).Value)
myFlexGrid.TextMatrix(iRow, iCol) = sAux
I notice that
v_regCount = 7532 but v_colsCount = 2 ,
and I get an error ("Substring out of range"). If I swap the settings order (i.e. if I set myFlexGrid.Cols after set myFlexGrid.Rows), then
v_regCount = 0 and v_colsCount = 52
I don't understand why I can't set rows and columns count at the same time.
Any ideas?
Thanks in advance

While debugging the function breakpoint is not hit

I am using powerbuilder 11.2 and I have a pbl that creates a main screen. The user enters an order number in the textbox and hit enter and it fills in data in the bottom of the screen. I am trying to get debugging to hit a breakpoint in my function but it seems to ignore the breakpoint. Is there a way to break into the function? I have a variable I need to evaluate and I can't seem to get into the function while running. Here is the code:
Decimal{2} ld_total_hrs,ld_load_hrs,ld_unload_hrs
long ll_stops_rowcount, ll_row, ll_type, ll_ord_number, ll_rd_rowcount
datetime ldt_1st_stop, ldt_last_stop, ldt_start_time, ldt_end_time, ldt_deliver_time
string ls_dest_id, ls_type, ls_pay_id, ls_ref_number, ls_pay_leg_config
boolean lb_first_drop = TRUE
ld_load_hrs = 0
ld_unload_hrs = 0
SetNull(ldt_deliver_time)
ll_stops_rowcount = dw_trip.RowCount()
If ll_stops_rowcount < 1 then Return 0
For ll_row = 1 to ll_stops_rowcount
If ll_row = 1 then
ldt_1st_stop = dw_trip.GetItemDateTime ( 1, "stops_stp_arrivaldate" )
End if
If dw_trip.GetItemString(ll_row,"stops_stp_type") = "PUP" then
ldt_start_time = dw_trip.GetItemDateTime(ll_row,"stops_stp_arrivaldate")
ldt_end_time = dw_trip.GetItemDateTime(ll_row,"stops_stp_departuredate")
ld_load_hrs = ld_load_hrs + (f_datetimediff(ldt_start_time,ldt_end_time)/60)/60
End if
If dw_trip.GetItemString(ll_row,"stops_stp_type") = "DRP" then
ldt_start_time = dw_trip.GetItemDateTime(ll_row,"stops_stp_arrivaldate")
ldt_end_time = dw_trip.GetItemDateTime(ll_row,"stops_stp_departuredate")
ld_unload_hrs = ld_unload_hrs + (f_datetimediff(ldt_start_time,ldt_end_time)/60)/60
// get the first drops info for the report if paylegaslane is true else get last drop
ls_pay_leg_config = is_PayLegConfig
If is_CompanyOverride=true then
ls_pay_leg_config = "ByLeg"
End if
//TGRIFFIT - PayLegConfig = 'ByLeg' in TMW is equivalent to 'PayLegAsLane = 'Y' in FSS
if Upper(ls_pay_leg_config) = 'BYLEG' then
If lb_first_drop Then
ldt_deliver_time = ldt_end_time
ls_dest_id = dw_trip.GetItemString(ll_row,"stops_cmp_id")
ls_ref_number = dw_trip.GetItemString(ll_row,"stops_stp_refnum")
lb_first_drop = FALSE
End if
else
ldt_deliver_time = ldt_end_time
ls_dest_id = dw_trip.GetItemString(ll_row,"stops_cmp_id")
ls_ref_number = dw_trip.GetItemString(ll_row,"stops_stp_refnum")
end if
End if
Next
ldt_last_stop = dw_trip.GetItemDateTime ( ll_stops_rowcount, "stops_stp_departuredate" )
ld_total_hrs = (f_datetimediff(ldt_1st_stop,ldt_last_stop)/60)/60
ll_ord_number = long(dw_triptab.GetItemString(1,"ord_number"))
//If g_messlevel% < 1 Then
if gnv_app.ii_MessLevel < 1 Then
ids_revdist.Reset()
End if
//Load the datastore that stores all the revenue distribution values
ll_rd_rowcount = ids_revdist.RowCount()
ids_revdist.InsertRow(0)
ll_rd_rowcount ++
ids_revdist.SetItem(ll_rd_rowcount,"mov_number",i_movenum%)
ids_revdist.SetItem(ll_rd_rowcount,"lgh_number",dw_trip.GetItemNumber(1,"stops_lgh_number"))
ids_revdist.SetItem(ll_rd_rowcount,"total_hours",ld_total_hrs)
ids_revdist.SetItem(ll_rd_rowcount,"load_hours",ld_load_hrs)
ids_revdist.SetItem(ll_rd_rowcount,"unload_hours",ld_unload_hrs)
ids_revdist.SetItem(ll_rd_rowcount,"deliver_date",ldt_deliver_time)
ids_revdist.SetItem(ll_rd_rowcount,"dest_code",ls_dest_id)
ids_revdist.SetItem(ll_rd_rowcount,"ref_number",ls_ref_number)
Return ids_revdist.RowCount()
I need to evaluate this line specifically and I set a breakpoint at this line:
ls_pay_leg_config = "ByLeg"
as well as the following lines. It does not break. I am rusty at PowerBuilder and can figure this out.
Put the breakpoint at the start of the loop.

Fixing sql length error in progress 4gl 10.2B

I'm trying to use the openedge jdbc connector to pull data from an existing progress db but im running into column width issues.
Here is the error that is holding me up.
[DataDirect][OpenEdge JDBC Driver][OpenEdge] Column TabDisplayName in table PUB.Menu has value exceeding its max length or precision.
I've looked at many posts, each offering different advice, and here's what I've given a go this far:
Manually modify the SQL width via the data dictionary.
I ran a quick check on PUB.Menu.TabDisplayName to find a max value of 44 Characters
Set the width to x(50) to no avail and then x(100) out of a fix of irrational rage, again with no luck.
Use the SUBSTR() SQL Function to truncate the field -not optimum but better than nothing
I get weird results with this. It works fine in sqlexp but in a java environment its like the column is never selected.
Use the dbtool to automatically fix width problems with option #2
After selecting all tables and "areas" (not sure what those are...) and submitting the final option I am returned to the proenv cmdline as if nothing ever happened.
Modify the sql width programmatically via 4gl
This is the only option I found that I have yet to try.
I am a little reluctant to try this only because a manual modification failed. Also this is a live development environment(for me only) and Im trying to mess it up too terribly, although i am taking snaps regularly.
Running progress 10.2B on a unix machine.
Any comments and suggestions would be appreciated.
-Thanks
The dbtool option is the best. It is designed for this. From proenv you should see something like this:
proenv> dbtool s2k
DATABASE TOOLS MENU - 10.2B
---------------------------
1. SQL Width & Date Scan w/Report Option
2. SQL Width Scan w/Fix Option
3. Record Validation
4. Record Version Validation
5. Read or Validate Database Block(s)
6. Record Fixup
7. Schema Validation
9. Enable/Disable File Logging
Q. Quit
Choice: 2
: (0=single-user 1=self-service >1=#threads)? 1
Padding % above current max: 100
: (Table number or all)? all
: (Area number or all)? all
: (verbose level 0-3)? 0
Total records read: 31357
SQLWidth errors found: 0, Date errors found: 0
SQLWidth errors fixed: 0
If your db has a server up & running choose "1" at the connect: prompt. If not, choose "0".
Pick 100 for padding to double the width of fields.
Try it on a copy of the "sports" database if you are unsure. Use a higher level of verboseness if you want some insight into what it is doing.
It does not take very long to run on a small development database. (It is basically instantaneous on "sports".)
It is possible to create views with substring (field.name,1,maxlength) option and use PUB2.viewname instead pub.tablename
DROP VIEW PUB2."accounts";
CREATE VIEW PUB2."accounts" (
"ACC-TYPE",
"ACCOUNT-NAME",
ANALITIC,
ARCH,
COUNT1,
CURRENCY,
PLAN,
QUANTITY,
"RID-ANOBJECT",
"RID-APP",
TRANSIT )
AS select "acc-type",
SUBSTRING("account-name", 1, 130),
"analitic",
"arch",
"count1",
"currency",
"plan",
"quantity",
"rid-anobject",
"rid-app",
"transit"
FROM PUB."accounts";
COMMIT;
use sqlexp for automatic creation:
sqlexp account -H localhost -S ' + db-port + ' -user sysprogress -password sysprogress -infile recreateSQLviews.sql -outfile recreateSQLviews.log
here is code:
def var num-port as integer.
for first _Servers where _Servers._Server-Type = "Login" no-lock:
num-port = _Servers._Server-PortNum.
end.
if num-port < 0 then num-port = num-port + 65536.
if num-port = 0 then do:
message "Define -S parameter for Database" view-as alert-box.
RETURN.
end.
message num-port.
/* ttSQLWidth table: SQL WIDTH for all tables */
def var execstr as char.
def var rez-str as char.
def var db-port as char. /* -S port */
db-port = STRING(num-port).
DEFINE TEMP-TABLE ttSQLWidth NO-UNDO
FIELD tableName AS CHARACTER
FIELD tableNum AS INTEGER
FIELD fieldName AS CHARACTER
FIELD sqlWidth AS INTEGER
FIELD requireFix AS LOGICAL INIT FALSE
FIELD actualWidth AS INTEGER
FIELD newWidth AS INTEGER
INDEX tableNum tableNum
INDEX tableName tableName.
FOR EACH _File NO-LOCK WHERE _Tbl-Type = "T":
FOR EACH _Field OF _File WHERE _Field._Data-type = "character":
if _field._extent > 0 then next.
CREATE ttSQLWidth.
ASSIGN tableName = _File._File-name
tableNum = _File._File-num
fieldName = _Field._Field-name
sqlWidth = _Field._Width.
RELEASE ttSQLWidth.
END. /* FOR EACH _Field */
END. /* FOR EACH _File */
DEFINE VARIABLE bTab AS HANDLE NO-UNDO.
DEFINE VARIABLE hQuery AS HANDLE NO-UNDO.
DEFINE VARIABLE queryString AS CHARACTER NO-UNDO.
FOR EACH ttSQLWidth:
CREATE BUFFER bTab FOR TABLE tableName.
CREATE QUERY hQuery.
hQuery:ADD-BUFFER(bTab).
message tablename.
queryString = "FOR EACH " + tableName + " WHERE LENGTH(" + fieldName + ") >= " + STRING(sqlWidth) + " BY LENGTH(" + fieldName + ") DESC".
hQuery:QUERY-PREPARE(queryString).
hQuery:QUERY-OPEN().
IF hQuery:GET-NEXT() THEN DO:
ASSIGN actualWidth = LENGTH(bTab:BUFFER-FIELD(fieldName):BUFFER-VALUE)
requireFix = TRUE.
END. /* IF .. THEN DO */
hQuery:QUERY-CLOSE.
DELETE OBJECT hQuery.
bTab:BUFFER-RELEASE().
DELETE OBJECT bTab.
END. /* FOR EACH ttSQLWidth */
def var add-pr as integer initial 10. /* % from max */
def var maxWidth as integer initial 249. /* maxwidth */
FOR EACH ttSQLWidth WHERE ttSQLWidth.requireFix = TRUE:
ttSQLWidth.newWidth = TRUNCATE ( (ttSQLWidth.actualWidth + add-pr) / add-pr, 0 ) * add-pr.
ttSQLWidth.newWidth = INTEGER( ttSQLWidth.newWidth).
if ttSQLWidth.newWidth > maxWidth then ttSQLWidth.newWidth = maxWidth.
END.
/* sql script generation */
OUTPUT TO value("recreateSQLviews.sql").
def var lst-field as char.
FOR EACH ttSQLWidth WHERE BREAK BY ttSQLWidth.tableName:
IF FIRST-OF(ttSQLWidth.tableName)
THEN run MakeSQLViews(ttSQLWidth.tableName).
END.
OUTPUT CLOSE.
/* sql script execution */
execstr = 'sqlexp account -H localhost -S ' + db-port + ' -user sysprogress -password sysprogress -infile recreateSQLviews.sql -outfile recreateSQLviews.log'.
input through value(execstr).
repeat:
IMPORT UNFORMAT rez-str.
message rez-str.
end.
INPUT CLOSE.
RETURN.
PROCEDURE MakeSQLViews:
define input parameter tableName as character.
def var str_tmp as char.
def var str_tmp1 as char.
def var str as char initial "count,sum,double,row,date,level,area,number,primary".
def var fieldName as char.
def var fieldName1 as char.
FOR EACH _file WHERE _file._file-name = tableName AND
_file._file-num GT 0 AND _file._file-num LT 32000 NO-LOCK:
fieldName = "".
FOR EACH _Field OF _File NO-LOCK:
str_tmp = '"' + _Field._Field-name + '"'.
FOR FIRST ttSQLWidth where ttSQLWidth.tableName = _file._file-name and
ttSQLWidth.fieldName = _Field._Field-name and
ttSQLWidth.requireFix = TRUE:
str_tmp = 'SUBSTRING("' + _Field._Field-name + '", 1, ' + STRING(ttSQLWidth.newWidth) + ')'.
END.
fieldName = fieldName + (IF(fieldName = "") THEN ("") ELSE ("," + chr(10) + chr(9))) + str_tmp.
str_tmp1 = ( IF ( INDEX ( _Field._Field-name, "-" ) = 0 )
THEN ( _Field._Field-name )
ELSE ( '"' + _Field._Field-name + '"' )).
if LOOKUP ( _Field._Field-name, str, "," ) > 0 then str_tmp1 = '"' + _Field._Field-name + '"'.
fieldName1 = fieldName1 + (IF(fieldName1 = "") THEN ("") ELSE ("," + chr(10) + chr(9))) + UPPER(str_tmp1).
END. /* FOR EACH _Field */
PUT UNFORMATTED 'DROP VIEW PUB2."' + _file._file-name + '";' SKIP.
PUT UNFORMATTED 'CREATE VIEW PUB2."' + _file._file-name + '" ( ' + chr(10) chr(9) + fieldName1 + ' ) ' + chr(10) +
'AS select ' + fieldName + chr(10) +
'FROM PUB."' + _file._file-name + '";' SKIP.
PUT UNFORMATTED 'COMMIT;' SKIP(1).
END.
END.

Resources