Neural-Style output flag - bash

I'm messing around with jcjohnson/neural-style. I have it up and running just fine. However, I cannot for the life of me make the -output_image or -init flags work. My gut says it's some very simple misunderstanding on my part.
-output_image is driving me especially nuts because it should just be a string to use as the filename, the script even appends the file formate in function that takes -output_image as an argument. I've tried single, double, and no quotes, as well as changing the order of the flags. My gut says it's something trivially simple because nobody is complaining about this on-line anywhere,but I'm a little in over my head because I'm not especially proficient with either bash, torch, or lua.
I'm using this simple script I hacked together that works just fine if I leave off both of the troublesome flags
#!/bin/bash
echo "#### Starting Job B ####"
th neural_style.lua \
-gpu -1 \
-print_iter 1 \
-save_iter 10 \
-num_iterations 3000 \
-style_image a_style.jpg \
-content_image a_content.jpg \
-style_scale 0.15 \
-style_weight 25 \
-content_weight 1e3 \
-output_image a \
-init a_460.png \
The above throws "Invalid argument: "
if it helps, in the script 'neural_style.lua'
the flags are defined as
cmd:option('-init', 'random', 'random|image')
...
cmd:option('-output_image', 'out.png')
and used as
local function maybe_save(t)
local should_save = params.save_iter > 0 and t % params.save_iter == 0
should_save = should_save or t == params.num_iterations
if should_save then
local disp = deprocess(img:double())
disp = image.minmax{tensor=disp, min=0, max=1}
local filename = build_filename(params.output_image, t)
if t == params.num_iterations then
filename = params.output_image -- ## LOOK HERE ##
end
-- Maybe perform postprocessing for color-independent style transfer
if params.original_colors == 1 then
disp = original_colors(content_image, disp)
end
image.save(filename, disp) -- ## LOOK HERE ##
end
end
as well as
if params.init == 'random' then
img = torch.randn(content_image:size()):float():mul(0.001)
elseif params.init == 'image' then
img = content_image_caffe:clone():float()
else
error('Invalid init type') -- ## NOT THE ERROR THROWN #
end
if params.gpu >= 0 then

Related

What is the meaning of "-" in getopts template?

What is the meaning of the following template in getopts?
while getopts ':x:y-:' val;
I know that it expects two options -x or -y but what is the meaning of the symbol - at the end of the template ?
Empirical approach
I was unable to find any documentation about this "-" in the option string. So, I tried an empirical approach to see how it influences the behavior of getopts. I found that passing "--something" to the script (without spaces after "--") makes it accept "--" as an option and report "something" in OPTARG:
#!/bin/bash
xopt=
yopt=
mopt=
while getopts ':x:y-:' val
do
case $val in
x) xopt=1
xval="$OPTARG";;
y) yopt=1;;
-) mopt=1
mval="$OPTARG";;
?) echo "Usage: $0: [-x value] [-y] [--long_opt_name] args" >&2
exit 2;;
esac
done
[ ! -z "$xopt" ] && echo "Option -x specified with parameter '$xval'"
[ ! -z "$yopt" ] && echo "Option -y specified"
[ ! -z "$mopt" ] && echo "Option -- specified with optname '$mval'"
shift $(($OPTIND - 1))
echo "Remaining arguments are: $*"
Examples of executions:
$ t.sh --v
Option -- specified with optname 'v'
Remaining arguments are:
$ t.sh --vv other1 other2
Option -- specified with optname 'vv'
Remaining arguments are: other1 other2
$ t.sh --help -x 123 -y others
Option -x specified with parameter '123'
Option -y specified
Option -- specified with optname 'help'
Remaining arguments are: others
$ t.sh --help -x 123 -- -y others
Option -x specified with parameter '123'
Option -- specified with optname 'help'
Remaining arguments are: -y others
$ t.sh -y -x val --x -- param1 -h -j -x -y
Option -x specified with parameter 'val'
Option -y specified
Option -- specified with optname 'x'
Remaining arguments are: param1 -h -j -x -y
Would it be a "hidden" feature to manage gnu-like long options but without parameters (i.e. only the "--long_opt_name") or am I promoting the side effect of a bug? Anyway, using such undocumented behavior is not advised as this may change after some future fixes or evolution of the command.
Nevertheless, if spaces are put after the double "-", the latter continues to play its usual documented role separating options from additional parameters:
$ t.sh --help -y -x val -- param1 -h -j -x -y
Option -x specified with parameter 'val'
Option -y specified
Option -- specified with optname 'help'
Remaining arguments are: param1 -h -j -x -y
$ t.sh -- -v
Remaining arguments are: -v
Verification in the source code
As getopts is a builtin of bash, I downloaded its source code (version 5.0) from here. The builtins are located in the eponym sub-directory. getopts source code is: builtins/getopts.def. For each argument on the command line, it calls sh_getopt(argc, argv, optstr). This function is defined in builtins/getopt.c:
[...]
int
sh_getopt (argc, argv, optstring)
int argc;
char *const *argv;
const char *optstring;
{
[...]
/* Look at and handle the next option-character. */
c = *nextchar++; sh_charindex++;
temp = strchr (optstring, c);
sh_optopt = c;
/* Increment `sh_optind' when we start to process its last character. */
if (nextchar == 0 || *nextchar == '\0')
{
sh_optind++;
nextchar = (char *)NULL;
}
if (sh_badopt = (temp == NULL || c == ':'))
{
if (sh_opterr)
BADOPT (c);
return '?';
}
if (temp[1] == ':')
{
if (nextchar && *nextchar)
{
/* This is an option that requires an argument. */
sh_optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
sh_optind++;
}
else if (sh_optind == argc)
{
if (sh_opterr)
NEEDARG (c);
sh_optopt = c;
sh_optarg = ""; /* Needed by getopts. */
c = (optstring[0] == ':') ? ':' : '?';
}
else
/* We already incremented `sh_optind' once;
increment it again when taking next ARGV-elt as argument. */
sh_optarg = argv[sh_optind++];
nextchar = (char *)NULL;
}
return c;
}
In the previous source lines, nextchar points on the option character (i.e. the one located right after '-') in argv[] and temp points on the option character in the optstring (which is '-'). We can see when temp[1] == ':' (i.e. the optstring specifies "-:"), sh_optarg is set with the incremented value of nextchar which is the first letter of the option name located behind "--".
In our example, where optstring is ":x:y-:" and we pass to the script "--name", the above code does:
optstring = ":x:y-:"
^
|
temp
argv[x] = "--name"
^^
/ \
c nextchar (+ 1)
temp[1] == ':' ==> sh_optarg=nextchar="name"
Hence, with the above algorithm in bash, when ":-" is specified in the option string, any "--name" option on the command line reports "name" in OPTARG variable.
This is merely the output of the code path when the parameter is concatenated to the option name (e.g. -xfoo = option "x" and parameter "foo", --foo = option "-" and parameter "foo").

Makefile Open externally managed shell and run command

I am trying to open and externally managed shell and trying to run some command in makefile. How can I do that?
For example, if I want to run the following sequence in my make file:
> python
> a = 6
> b = 5
> c = a + b
> print(c)
>exit()
This is a sample of externally managed shell that I am trying.
There are various ways, none of them super-simple. Here's the most basic one:
runcommand:
( echo 'a = 6'; \
echo 'b = 5'; \
echo 'c = a + b'; \
echo 'print(c)'; \
echo 'exit()'; \
) | python
Basically, if you can write the command in a single shell command line, then you can transpose that command line into your makefile recipe.

sed: no input files

I have a script where I read in columns of data from an "input file", then use those to change some variables in another file.
Here is my script, titled FA_grid_changer.sh
#!/bin/bash
# before runnning, please ensure your inlist has the following parameters: RSP_mass, RSP_Teff, RSP_L, RSP_X, RSP_Z,
# log_directory, photo_directory, RSP_alfa, photo_interval, profile_interval, history_interval, terminal_interval,
# max_num_profile_models, RSP_max_num_periods
export OMP_NUM_THREADS=8
# get current directory
dir=$PWD
data_file="$dir"/input.dat
mesa_inlist="$dir"/inlist_rsp_RR_Lyrae
# set STR to 1 for saving history and profile files BEFORE the model has reached full-amplitude pulsations
# set STR to 2 for saving history and profile files AFTER the model has reached full-amplitude pulsations
STR=1
max_num_periods=4000
max_num_periods_2=$(($max_num_periods + 4))
if [[ "$STR" = 1 ]]
then
echo Configuring inlist to save settings before full-amplitude pulsations...
sed -i \
-e "s/^\([[:blank:]]*photo_interval\).*/\1 = 1000/i" \
-e "s/^\([[:blank:]]*profile_interval\).*/\1 = 1000/i" \
-e "s/^\([[:blank:]]*history_interval\).*/\1 = 1000/i" \
-e "s/^\([[:blank:]]*terminal_interval\).*/\1 = 4000/i" \
-e "s/^\([[:blank:]]*max_num_profile_models\).*/\1 = 100/i" \
-e "s/^\([[:blank:]]*RSP_max_num_periods\).*/\1 = $max_num_periods/i" \
"$mesa_inlist"
sleep 1.5
while read -ra fields; do
echo Changing model parameters...
sleep 0.5
sed -i \
-e "s/^\([[:blank:]]*RSP_mass\).*/\1 = ${fields[3]}/i" \
-e "s/^\([[:blank:]]*RSP_Teff\).*/\1 = ${fields[5]}/i" \
-e "s/^\([[:blank:]]*RSP_L\).*/\1 = ${fields[4]}/i" \
-e "s/^\([[:blank:]]*RSP_X\).*/\1 = ${fields[2]}/i" \
-e "s/^\([[:blank:]]*RSP_Z\).*/\1 = ${fields[1]}/i" \
-e "s/^\([[:blank:]]*log_directory\).*/\1 = 'LOGS\/LOGS_${fields[0]}'/i" \
-e "s/^\([[:blank:]]*photo_directory\).*/\1 = 'photos\/photos_${fields[0]}'/i" \
#-e "s/^\([[:blank:]]*RSP_alfa\).*/\1 = ${fields[6]}/i" \
"$mesa_inlist"
echo Compiling MESA...
sleep 0.5
./mk
echo Running MESA...
sleep 0.5
./rn
done < "$data_file"
elif [[ "$STR" = 2 ]]
then
echo Configuring inlist to save settings after full-amplitude pulsations...
sed -i \
-e "s/^\([[:blank:]]*photo_interval\).*/\1 = 1000/i" \
-e "s/^\([[:blank:]]*profile_interval\).*/\1 = 1/i" \
-e "s/^\([[:blank:]]*history_interval\).*/\1 = 1/i" \
-e "s/^\([[:blank:]]*terminal_interval\).*/\1 = 4000/i" \
-e "s/^\([[:blank:]]*max_num_profile_models\).*/\1 = -1/i" \
-e "s/^\([[:blank:]]*RSP_max_num_periods\).*/\1 = $max_num_periods_2/i" \
"$mesa_inlist"
sleep 1.5
else
echo STR\: Not an acceptable option. Please \set STR to 1 or 2.
fi
Here is my input file input.dat, which I am keeping in the same directory.
RRL1 0.001 0.749 0.61036165206037 48.3930329458203 6795.10018238295
RRL2 0.001 0.749 0.60627327846453 59.8125833648911 6793.11236483182
RRL3 0.001 0.749 0.606272337551755 56.5141274900899 7059.10474568471
And here is the file I am trying to change inlist_rsp_RR_Lyrae
! long-period RR Lyrae star: M=0.65Ms, L=60Ls, Teff=6500K, X=0.75, Z=0.0004
! original test case contributed by Radek Smolec.
&star_job
!pgstar_flag = .true.
/ ! end of star_job namelist
&controls
! check for retries and backups as part of test_suite
!max_number_retries = -1
!max_number_backups = 0
!max_model_number = 15000
! RSP controls
! x_integer_ctrl(1) = 10 ! which period to check
x_ctrl(1) = 0.71262d0 ! expected period (in days)
RSP_mass = 0.606272337551755
RSP_Teff = 7059.10474568471
!RSP_L = 59.3141274900899
RSP_L = 56.5141274900899
RSP_X = 0.749
RSP_Z = 0.001
RSP_max_num_periods = 4000
RSP_nmodes = 10 ! number of modes LINA will calculate for initial model
RSP_nz = 150 ! number of zones of model
log_directory = 'LOGS/LOGS_M081_second'
photo_directory = 'photos/photos_M081_second'
! output controls
!num_trace_history_values = 2
trace_history_value_name(1) = 'rel_E_err'
trace_history_value_name(2) = 'log_rel_run_E_err'
! for cases in which you have a run that has reached steady pulses
! and you want to look at plots of just a few periods to see the details,
! i suggest the following method. interrupt the run soon after
! it makes a photo. remove or delete LOGS/history.data to force
! creation of a new one when restart. edit the inlist to set
! history_interval to 1 to get maximum time resolution.
! restart the run and let it go for as many periods as desired.
do_history_file = .true.
photo_interval = 1000
profile_interval = 1000
history_interval = 1000
terminal_interval = 4000
max_num_profile_models = 100
!photo_interval = 1
!profile_interval = 1
!history_interval = 1
!terminal_interval = 1
! FOR DEBUGGING
!RSP_report_undercorrections = .true.
!report_hydro_solver_progress = .true. ! set true to see info about newton iterations
!report_ierr = .true. ! if true, produce terminal output when have some internal error
!stop_for_bad_nums = .true.
!trace_evolve = .true.
! hydro debugging
!hydro_check_everything = .true.
!hydro_inspectB_flag = .true.
!hydro_sizequ_flag = .true.
! for making logs, uncomment hydro_dump_call_number plus the following
! to make residual logs, uncomment hydro_sizequ_flag
! to make correction logs, uncomment hydro_inspectB_flag
! to make jacobian logs, uncomment hydro_numerical_jacobian, hydro_save_numjac_plot_data
! to do dfridr test, uncomment hydro_get_a_numerical_partial, hydro_test_partials_k,
! hydro_numerical_jacobian, hydro_save_numjac_plot_data, hydro_dump_iter_number
!hydro_get_a_numerical_partial = 1d-7
!hydro_test_partials_k = 190
!hydro_numerical_jacobian = .true.
!hydro_save_numjac_plot_data = .true.
!hydro_dump_call_number = 1
!hydro_dump_iter_number = 6
!hydro_epsder_struct = 1d-6
!hydro_epsder_chem = 1d-6
!hydro_save_photo = .true. ! Saves a photo when hydro_call_number = hydro_dump_call_number -1
!fill_arrays_with_NaNs = .true.
!report_why_dt_limits = .true.
!report_all_dt_limits = .true.
!report_hydro_dt_info = .true.
!report_dX_nuc_drop_dt_limits = .true.
!report_bad_negative_xa = .true.
!show_mesh_changes = .true.
!mesh_dump_call_number = 95
!trace_newton_bcyclic_solve_input = .true. ! input is "B" j k iter B(j,k)
!trace_newton_bcyclic_solve_output = .true. ! output is "X" j k iter X(j,k)
!trace_newton_bcyclic_matrix_input = .true.
!trace_newton_bcyclic_matrix_output = .true.
!trace_newton_bcyclic_steplo = 1 ! 1st model number to trace
!trace_newton_bcyclic_stephi = 1 ! last model number to trace
!trace_newton_bcyclic_iterlo = 2 ! 1st newton iter to trace
!trace_newton_bcyclic_iterhi = 2 ! last newton iter to trace
!trace_newton_bcyclic_nzlo = 1 ! 1st cell to trace
!trace_newton_bcyclic_nzhi = 10000 ! last cell to trace; if < 0, then use nz as nzhi
!trace_newton_bcyclic_jlo = 1 ! 1st var to trace
!trace_newton_bcyclic_jhi = 100 ! last var to trace; if < 0, then use nvar as jhi
!trace_k = 0
/ ! end of controls namelist
&pgstar
!pause = .true.
pgstar_interval = 6
Grid2_win_flag = .true.
Grid2_title = '4.165 M\d\(2281)\u Z=0.007 Classical Cepheid'
History_Panels1_xaxis_name='star_age_day'
History_Panels1_max_width = 365 ! only used if > 0. causes xmin to move with xmax.
! Grid2_file_flag = .true.
file_digits = 7
Grid2_file_dir = 'png'
Grid2_file_prefix = 'grid'
Grid2_file_interval = 5 ! output when mod(model_number,Grid2_file_interval)==0
!Profile_Panels1_show_grid = .true.
Profile_Panels1_xaxis_name = 'logtau'
Profile_Panels1_xaxis_reversed = .true.
Profile_Panels1_xmin = -101D0
Profile_Panels1_xmax = -101D0
Profile_Panels1_dymin(4) = 0.02
Profile_Panels1_yaxis_name(2) = 'avg_charge_He'
/ ! end of pgstar namelist
Yet, when I try to run the shell script in bash, inlist_rsp_RR_Lyrae remains unchanged. Instead, this occurs:
Configuring inlist to save settings before full-amplitude pulsations...
Changing model parameters...
sed: no input files
/home/nick/mesa-r11701/star/test_suite/rsp_RR_Lyrae_grid/inlist_rsp_RR_Lyrae: line 1: long-period: command not found
/home/nick/mesa-r11701/star/test_suite/rsp_RR_Lyrae_grid/inlist_rsp_RR_Lyrae: line 3: original: command not found
/home/nick/mesa-r11701/star/test_suite/rsp_RR_Lyrae_grid/inlist_rsp_RR_Lyrae: line 5: syntax error near unexpected token `&'
/home/nick/mesa-r11701/star/test_suite/rsp_RR_Lyrae_grid/inlist_rsp_RR_Lyrae: line 5: `&star_job'
Compiling MESA...
As you can see, it is mistaking the first few lines of comments in inlist_rsp_RR_Lyrae as commands. Is there something I am missing here?
The problem is
sed -i \
...
-e "s/^\([[:blank:]]*photo_directory\).*/\1 = 'photos\/photos_${fields[0]}'/i" \
#-e "s/^\([[:blank:]]*RSP_alfa\).*/\1 = ${fields[6]}/i" \
"$mesa_inlist"
Here the comment before $mesa_inlist also comments out the \ at the end of the line. Therefore the command ends at that comment and sed -i complains that there is no file given. Afterwards bash tries to execute "$mesa_inlist" (that is inlist_rsp_RR_Lyrae) as a command, which fails.
To fix the problem, simply remove the comment line.
Bye the way: With this function you can drastically improve the readability of your script.
sedi() {
mapfile -t args < <(printf -- '-e\ns/^\([[:blank:]]*%s\).*/\\1 = %s/i\n' "$#")
sed -i "${args[#]}" "$mesa_inlist"
}
Now you can replace ...
sed -i \
-e "s/^\([[:blank:]]*photo_interval\).*/\1 = 1000/i" \
-e "s/^\([[:blank:]]*profile_interval\).*/\1 = 1/i" \
-e "s/^\([[:blank:]]*history_interval\).*/\1 = 1/i" \
-e "s/^\([[:blank:]]*terminal_interval\).*/\1 = 4000/i" \
-e "s/^\([[:blank:]]*max_num_profile_models\).*/\1 = -1/i" \
-e "s/^\([[:blank:]]*RSP_max_num_periods\).*/\1 = $max_num_periods_2/i" \
"$mesa_inlist"
... by ...
sedi \
photo_interval 1000 \
profile_interval 1 \
history_interval 1 \
terminal_interval 4000 \
max_num_profile_models -1 \
RSP_max_num_periods "$max_num_periods_2"
... and so on for the other sed commands.

Change back DPI settings in a bash script

I would like to run a program that does not properly support my desired resolution+DPI settings.
Also I want to change my default GTK theme to a lighter one.
What I currently have:
#!/bin/bash
xfconf-query -c xsettings -p /Xft/DPI -s 0
GTK_THEME=/usr/share/themes/Adwaita/gtk-2.0/gtkrc /home/unknown/scripts/ch_resolution.py --output DP-0 --resolution 2560x1440 beersmith3
This sets my DPI settings to 0, changes the gtk-theme, runs a python script that changes my resolution and runs the program, and on program exit changes it back. This is working properly.
Now I want to change back my DPI settings to 136 on program exit
xfconf-query -c xsettings -p /Xft/DPI -s 136
My guess is I need to use a while loop but have no idea how to do it.
ch_resolution.py
#!/usr/bin/env python3
import argparse
import re
import subprocess
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--output', required=True)
parser.add_argument('--resolution', required=True)
parser.add_argument('APP')
args = parser.parse_args()
device_context = '' # track what device's modes we are looking at
modes = [] # keep track of all the devices and modes discovered
current_modes = [] # remember the user's current settings
# Run xrandr and ask it what devices and modes are supported
xrandrinfo = subprocess.Popen('xrandr -q', shell=True, stdout=subprocess.PIPE)
output = xrandrinfo.communicate()[0].decode().split('\n')
for line in output:
# luckily the various data from xrandr are separated by whitespace...
foo = line.split()
# Check to see if the second word in the line indicates a new context
# -- if so, keep track of the context of the device we're seeing
if len(foo) >= 2: # throw out any weirdly formatted lines
if foo[1] == 'disconnected':
# we have a new context, but it should be ignored
device_context = ''
if foo[1] == 'connected':
# we have a new context that we want to test
device_context = foo[0]
elif device_context != '': # we've previously seen a 'connected' dev
# mode names seem to always be of the format [horiz]x[vert]
# (there can be non-mode information inside of a device context!)
if foo[0].find('x') != -1:
modes.append((device_context, foo[0]))
# we also want to remember what the current mode is, which xrandr
# marks with a '*' character, so we can set things back the way
# we found them at the end:
if line.find('*') != -1:
current_modes.append((device_context, foo[0]))
for mode in modes:
if args.output == mode[0] and args.resolution == mode[1]:
cmd = 'xrandr --output ' + mode[0] + ' --mode ' + mode[1]
subprocess.call(cmd, shell=True)
break
else:
print('Unable to set mode ' + args.resolution + ' for output ' + args.output)
sys.exit(1)
subprocess.call(args.APP, shell=True)
# Put things back the way we found them
for mode in current_modes:
cmd = 'xrandr --output ' + mode[0] + ' --mode ' + mode[1]
subprocess.call(cmd, shell=True)
edit:
Thanks #AndreLDM for pointing out that I do not need a separate python script to change the resolution, I don't know why I didn't think of that.
I changed it so I don't need the python script and it is working properly now. If I can improve this script please tell me!
#!/bin/bash
xrandr --output DP-0 --mode 2560x1440
xfconf-query -c xsettings -p /Xft/DPI -s 0
GTK_THEME=/usr/share/themes/Adwaita/gtk-2.0/gtkrc beersmith3
if [ $? == 0 ]
then
xrandr --output DP-0 --mode 3840x2160
xfconf-query -c xsettings -p /Xft/DPI -s 136
exit 0
else
xrandr --output DP-0 --mode 3840x2160
xfconf-query -c xsettings -p /Xft/DPI -s 136
exit 1
fi

Is it possible to use EPS file (created with eps2write) in EndPage procedure?

For testing purposes, let's draw some meaningless rectangles:
gswin32c -q -o f.pdf -sDEVICE=pdfwrite -c "<</PageSize[595 842]>>setpagedevice 0 0 595 842 rectfill showpage"
+
gswin32c -q -o f.eps -sDEVICE=eps2write -f f.pdf
And ps.ps file:
<<
/EndPage {
exch pop
2 ne dup {
1 dict begin
/showpage {} def
(f.eps) run
end
} if
}
>> setpagedevice
And then
gswin32c -q -o out.pdf -sDEVICE=pdfwrite -f ps.ps -f f.pdf
produces an error:
%%[ Error handled by opdfread.ps : GPL Ghostscript 9.15: Unrecoverable
error, exit code 1 Unrecoverable error: typecheck in if Operand stack:
typecheck ebuf false false --nostringval--
On the other hand, if I create EPS with another tool, e.g. xpdf's pdftops:
pdftops -eps f.pdf f.eps
... then EPS can be placed as e.g. watermark or logo with above command:
gswin32c -q -o out.pdf -sDEVICE=pdfwrite -f ps.ps -f f.pdf
So the question is, is it possible to use Ghostscript's eps2write for the purpose, maybe I'm missing something.
I tried to bracket (f.eps) run with calls to BeginEPSF and EndEPSF as defined in Adobe's EPSF Format Specification, but it didn't help. And after decoding prologue which eps2write creates (which, itself, gives same error if run from EndPage), it looks to me that it violates section on Illegal and Restricted Operators of mentioned Specification.
Edit:
I think there's an issue with the Immediately Evaluated Names if code is run from EndPage. In prologue, which eps2write creates, there's a fragment not very far from the beginning:
//SetPageSize{
//RotatePages//FitPages or//CenterPages or{
mark(/RotatePages, /FitPages and CenterPages are not allowed with /SetPageSize)//error exec
}if
}
{
//FitPages//CenterPages and{
mark(CenterPages is not allowed with /FitPages)//error exec
}if
}
ifelse
If I frame it like this:
SetPageSize ==
//SetPageSize ==
{
//SetPageSize{
//RotatePages//FitPages or//CenterPages or{
mark(/RotatePages, /FitPages and CenterPages are not allowed with /SetPageSize)//error exec
}if
}
{
//FitPages//CenterPages and{
mark(CenterPages is not allowed with /FitPages)//error exec
}if
}
ifelse
} stopped { (***\n) print } if
And modify ps.ps slightly:
<<
/EndPage {
exch pop
2 ne dup {
1 dict begin
/showpage {} def
(prologue.ps) run
end
} if
}
>> setpagedevice
Then this command:
gswin32c -q -o out.pdf -sDEVICE=pdfwrite -f ps.ps -f f.pdf
...gives this output:
false
/SetPageSize
***
%%[ Error handled by opdfread.ps : GPL Ghostscript 9.14: Unrecoverable error, exit code 1
I.e. it fails in above fragment (and for obvious reason, I think) and then fails somewhere else further down within prologue.ps.
OK so I did something similar to your expereience. I started with a simple PostScript file (testeps.ps):
%!
0 1 0 setrgbcolor
0 0 100 100 rectfill
showpage
I then ran that through Ghostscript using the eps2write device:
./gs -sDEVICE=eps2write -sOutputFile=out.eps -dCompressPages=false testeps.ps
I then constructed another test file (test.ps):
%!
<<
/EndPage {
exch pop
2 ne dup {
1 dict begin
/showpage {} def
(/temp/out.eps) run
end
} if
}
>> setpagedevice
1 0 0 setrgbcolor
0 100 100 100 rectfill
showpage
and ran that through GS:
./gs test.ps
The file ran to completion, and contained appropriately coloured rectangles at the correct positions on the page.
Its possible this is something which has been fixed (you don't say what version of Ghostscript you are using). The next release (9.16) is due very shortly, or you can build iot yourself from source, I'd suggest you try it when its available.

Resources