How to use a variable in the format specifier statement? - formatting

I can use:
write (*, FMT = "(/, X, 17('-'), /, 2X, A, /, X, 17('-'))") "My Program Name"
to display the following lines on the console window:
-----------------
My Program Name
-----------------
Now, I want to show a pre-defined character instead of - in the above format. I tried this code with no success:
character, parameter :: Chr = Achar(6)
write (*, FMT = "(/, X, 17(<Chr>), /, 2X, A, /, X, 17(<Chr>))") "My Program Name"
Obviously, there are another ways to display what I am trying to show by means of a variable in the format specifier statement. For instance:
character, parameter :: Chr = Achar(6)
integer :: i, iMax = 17
write (*, FMT = "(/, X, <iMax>A1, /, 2X, A, /, X, <iMax>A1)") (Chr, i = 1, iMax), &
"My Program Name", &
(Chr, i = 1, iMax)
However, I would like to know if there is any way to use a variable or invoke a function in the format specifier statement.

The code you are trying to use (<>) is not standard Fortran. It is an extension accepted by some compilers. Just build the format string as a string.
"(/, X, 17(" // Chr // "), /, 2X, A, /, X, 17(" // Chr // "))"
For the the numeric case you have to prepare a string with the value
write(chMax, *) iMax
"(/, X, " // chMax // "A1, /, 2X, A, /, X, " // chMax // "A1)"
or you can use some function, if you have it
"(/, X, " // itoa(iMax) // "A1, /, 2X, A, /, X, " // itoa(iMax) // "A1)"
but it may still be preferable to call it beforehand, to avoid multiple calls.
The function can look like:
function itoa(i) result(res)
character(:),allocatable :: res
integer,intent(in) :: i
character(range(i)+2) :: tmp
write(tmp,'(i0)') i
res = trim(tmp)
end function

Related

z3py: Symbolic expressions cannot be cast to concrete Boolean values

I'm having troubles to define the objective fucntion in a SMT problem with z3py.
Long story, short, I have to optimize the placing of smaller blocks inside a board that has fixed width but variable heigth.
I have an array of coordinates (represented by an array of integers of length 2) and a list of integers (representing the heigth of the block to place).
# [x,y] list of integer variables
P = [[Int("x_%s" % (i + 1)), Int("y_%s" % (i + 1))]
for i in range(blocks)]
y = [int(b) for a, b in data[2:]]
I defined the objective function like this:
obj= Int(max([P[i][1] + y[i] for i in range(blocks)]))
It calculates the max height of the board given the starting coordinate of the blocks and their heights.
I know it could be better, but I think the problem would be the same even with a different definition.
Anyway, if I run my code, the following error occurs on the line of the objective function:
" raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.") "
While debugging I've seen that is P[i][1] that gives an error and I think it's because the program reads "y_i + 3" (for example) and they can't be added togheter.
Point is: it's obvious that the objective function depends on the variables of the problem, so how can I get rid of this error? Is there another place where I should define the objective function so it waits to have the P array instantiated before doing anything?
Full code:
from z3 import *
from math import ceil
width = 8
blocks = 4
x = [3,3,5,5]
y = [3,5,3,5]
height = ceil(sum([x[i] * y[i] for i in range(blocks)]) / width) + 1
# [blocks x 2] list of integer variables
P = [[Int("x_%s" % (i + 1)), Int("y_%s" % (i + 1))]
for i in range(blocks)]
# value/ domain constraint
values = [And(0 <= P[i][0], P[i][0] <= width - 1, 0 <= P[i][1], P[i][1] <= height - 1)
for i in range(blocks)]
obj = Int(max([P[i][1] + y[i] for i in range(blocks)]))
board_problem = values # other constraints I've not included for brevity
o = Optimize()
o.add(board_problem)
o.minimize(obj)
if (o.check == 'unsat'):
print("The problem is unsatisfiable")
else:
print("Solved")
The problem here is that you're calling Python's max on symbolic values, which is not designed to work for symbolic expressions. Instead, define a symbolic version of max and use that:
# Return maximum of a vector; error if empty
def symMax(vs):
m = vs[0]
for v in vs[1:]:
m = If(v > m, v, m)
return m
obj = symMax([P[i][1] + y[i] for i in range(blocks)])
With this change your program will go through and print Solved when run.

Changing a mutable field in OCaml

When I run the following code I get a syntax error, although as far as I can tell the syntax is correct. This attempts to implement a queue structure, where the function from_list converts a list to a queue with the corresponding values. I wrote str_of_int_q to print the contents of a queue. x and y are supposed to be two nodes, with x at the head and y at the tail.
;; open Assert
type 'a qnode = {v: 'a;
mutable next: 'a qnode option}
type 'a queue = {mutable head: 'a qnode option;
mutable tail: 'a qnode option}
let from_list (l: 'a list) : 'a queue =
let rec loop (l2: 'a list) (qu: 'a queue) =
begin match l2 with
| [] -> qu
| [x] -> let y = {v = x; next = None} in
qu.head <- Some y; qu.tail <- Some y;
qu
| h1::h2::t -> let y = qu.head in
let z = {v = h1; next = y} in
qu.head <- Some z;
qu
end
in loop l {head = None; tail = None}
let str_of_int_q (q: int queue) : string =
let rec loop (r: int qnode option) (s: string) : string =
begin match r with
| None -> s
| Some n -> loop n.next (s ^ (string_of_int n.v))
end
in loop q.head ""
let x = {v = 1; next = None}
let y = {v = 2; next = None}
x.next <- Some y;
let z = {head = Some x; tail = Some y}
;; print_endline (str_of_int_q z)
My error:
line 32, characters 7-9:
Error: Syntax error
Line 32 is the line x.next <- Some y; and characters 7-9 indicate the <-. But I'm storing into a mutable field an object of the appropriate type, so I don't see what's going wrong.
Top-level statements are separated by ;; in OCaml. However, ;; is optional before several keywords, such as let, open, type, etc. This is why you don't need ;; most of the time.
In your case, ;; is needed to disambiguate between let y = {v = 2; next = None} and x.next <- Some y. The latter is an expression and doesn't start with a special keyword, so OCaml doesn't know to insert an implicit ;; here.
See also http://ocaml.org/learn/tutorials/structure_of_ocaml_programs.html#The-disappearance-of.
As explained there, you can either do
let y = {v = 2; next = None}
;; x.next <- Some y
or
let y = {v = 2; next = None}
let () = x.next <- Some y
This latter solution works because by introducing a dummy binding we're starting our statement with let, which disambiguates again.
Note: I've also removed the trailing ; from your code. ; is actually an infix operator that combines two expressions (by throwing the result of the first one away and returning the result of the second one). This is not what you want here.

Weird syntax error

data A = B | C Int
implementation Semigroup A where
B <+> x = x
x <+> B = x
C m <+> C n = C (m + n)
gives me a syntax error of
./Nodes/Test.idr:3:1: error: expected: ";",
"|", declaration, end of input
implementation Semigroup A where
^
Type checking ./Nodes/Test.idr
in Idris 0.11.2. Removing implementation gives instead this message:
./Nodes/Test.idr:3:13: error: expected: "#",
"with", argument expression,
constraint argument,
function right hand side,
implicit function argument,
with pattern
Semigroup A where
^
Type checking ./Nodes/Test.idr
Should I get an error message? I can't see anything wrong with the syntax.
Thanks.
You cannot use infix operators in implementations (for now, I guess). Instead, wrap them to prefixes:
data A = B | C Int
implementation Semigroup A where
(<+>) B x = x
(<+>) x B = x
(<+>) (C m) (C n) = C (m + n)

WoW LUA: MSP, combining GTAL?

While I understand it's best to start from the basics, I like to dabble. This is killing me though. In WoW, I use ElvUI and MyRolePlay (MRP) and the result is an issue with the enhanced tooltip. I've done quite a bit of editing to the code and the only thing left is trying to get this last line formatting properly - the entirety (3 variables) on one line. I don't understand what gtal is (or the "L"), but it seems to create a new line. Is there a way to combine the gtal lines, while retaining the RGB colors for both respectively? I've tried to stay within the code style (since I'm having trouble bringing in new code) but due to how the author calls for colors on the variables, I couldn't manage to get the final %s its own color value without making a brand new line.
local dC = GetQuestDifficultyColor(level);
local cC = RAID_CLASS_COLORS[ classunloc ];
Best I could come up with,
gtal( format( L["|r%s|cffffffff %s"], e, emptynil( mrp.DisplayTooltip.RA( f.RA ) ) or race, class), dC.r, dC.g, dC.b )
gtal( format( L["|r%s"], class), cC.r, cC.g, cC.b )
There's no information on gtal in the mod or anywhere else that I could find. I hear the author is impossible to approach. But I was hoping someone got the idea here.
Result of the two gtal lines Perfect, if only the last word was on the line above it!
If it helps, the block all this is in is
local dC = GetQuestDifficultyColor(level);
local cC = RAID_CLASS_COLORS[ classunloc ];
if level ~= nil and level < 0 then
e = L["|cffffffff(Boss)"]
else
e = format( L["|r%d|cffffffff"], level )
end
if mspsupported then
gtal( format( L["|r%s|cffffffff %s"], e, emptynil( mrp.DisplayTooltip.RA( f.RA ) ) or race, class), dC.r, dC.g, dC.b )
gtal( format( L["|r%s"], class), cC.r, cC.g, cC.b )
n = nil
t = nil
if f.FR and f.FR ~= "" and f.FR ~= "0" then
n = mrp.DisplayTooltip.FR( f.FR ) .. " "
end
and finally, this is what the original gtal looked like
gtal( format( L["%s %s |r%s|cffffffff (Player)"], e, emptynil( mrp.DisplayTooltip.RA( f.RA ) ) or race, class), r, g, b )
r, g, b = 1.0, 1.0, 1.0
Update - this is what works here, since if this were ever helpful to anyone else:
local dC = GetQuestDifficultyColor(level);
local cC = RAID_CLASS_COLORS[ classunloc ];
if level ~= nil and level < 0 then
e = L["|cffffffff(Boss)"]
else
e = format( L["|r%d|cffffffff"], level )
end
if mspsupported then
local classStr = format("|cff%02x%02x%02x%s|r", cC.r * 255, cC.g * 255, cC.b * 255, class)
local str = format( L["|r%s |cffffffff%s|r %s"], e, emptynil( mrp.DisplayTooltip.RA( f.RA ) ) or race, classStr)
gtal(str, dC.r, dC.g, dC.b)
gtal is defined in UI_Tooltip.lua:
--[[
EPIC KLUDGE!
Special local functions to overwrite and add the current tooltip.
]]
-- Single string
local function gtal( n, r, g, b )
local l = GameTooltip.mrpLines + 1
GameTooltip.mrpLines = l
r, g, b = (r or 1.0), (g or 1.0), (b or 1.0)
--if GameTooltip.mrpLines <= GameTooltip.orgLines then
-- Replace original line with ours, or add a new one if not there
if _G["GameTooltipTextLeft"..tostring(l)] then
if _G["GameTooltipTextLeft"..tostring(l)]:IsVisible() then
if _G["GameTooltipTextRight"..tostring(l)] then
_G["GameTooltipTextRight"..tostring(l)]:Hide()
end
_G["GameTooltipTextLeft"..tostring(l)]:SetText( n )
_G["GameTooltipTextLeft"..tostring(l)]:SetTextColor( r, g, b )
else
GameTooltip:AddLine( n, r, g, b )
end
else
GameTooltip:AddLine( n, r, g, b )
end
end
L is conventionally your localization table lookup, used here in case you want a different format string for a different language.
In this case, it looks like gtal always adds a line, so you need to do your work all in the same line. Fortunately, WoW gives you inline color overrides that you can use! See UI Escape Sequences - that's what's going on with |cxxxxxxxx and whatnot in the strings. You probably want something like:
-- Build a color-formatted class string
local classStr = format("|c%02x%02x%02x%s|r", cC.r, cC.g, cC.b, class)
-- Build your tooltip line, which consists of `$e $race $class`
local str = format( L["|r%s |cffffffff%s|r %s"], e, emptynil( mrp.DisplayTooltip.RA( f.RA ) ) or race, classStr)
-- Add the line to the tooltip
gtal(str, dC.r, dC.g, dC.b)

How to format a number with padding in Erlang

I need to pad the output of an integer to a given length.
For example, with a length of 4 digits, the output of the integer 4 is "0004" instead of "4". How can I do this in Erlang?
adding a bit of explanation to Zed's answer:
Erlang Format specification is: ~F.P.PadModC.
"~4..0B~n" translates to:
~F. = ~4. (Field width of 4)
P. = . (no Precision specified)
Pad = 0 (Pad with zeroes)
Mod = (no control sequence Modifier specified)
C = B (Control sequence B = integer in default base 10)
and ~n is new line.
io:format("~4..0B~n", [Num]).
string:right(integer_to_list(4), 4, $0).
The problem with io:format is that if your integer doesn't fit, you get asterisks:
> io:format("~4..0B~n", [1234]).
1234
> io:format("~4..0B~n", [12345]).
****
The problem with string:right is that it throws away the characters that don't fit:
> string:right(integer_to_list(1234), 4, $0).
"1234"
> string:right(integer_to_list(12345), 4, $0).
"2345"
I haven't found a library module that behaves as I would expect (i.e. print my number even if it doesn't fit into the padding), so I wrote my own formatting function:
%%------------------------------------------------------------------------------
%% #doc Format an integer with a padding of zeroes
%% #end
%%------------------------------------------------------------------------------
-spec format_with_padding(Number :: integer(),
Padding :: integer()) -> iodata().
format_with_padding(Number, Padding) when Number < 0 ->
[$- | format_with_padding(-Number, Padding - 1)];
format_with_padding(Number, Padding) ->
NumberStr = integer_to_list(Number),
ZeroesNeeded = max(Padding - length(NumberStr), 0),
[lists:duplicate(ZeroesNeeded, $0), NumberStr].
(You can use iolist_to_binary/1 to convert the result to binary, or you can use lists:flatten(io_lib:format("~s", [Result])) to convert it to a list.)
Eshell V12.0.3 (abort with ^G)
1> F = fun(Max, I)-> case Max - length(integer_to_list(I)) of X when X > 0 -> string:chars($0, X) ++ integer_to_list(I); _ -> I end end.
#Fun<erl_eval.43.40011524>
2> F(10, 22).
"0000000022"
3> F(3, 22345).
22345