2022_Q1 MakeOverChallenge: acción al hacer clic con el mouse de varias manerasEste es el Makeover Challenge Q1 2022.
El objetivo es generar un ejemplo, script o guía para cumplir con una de las tres tareas (todas tienen que ver con iniciar alguna acción después de hacer clic en algo en JMP):
- Desafío A: (imágenes y secuencia de comandos para crear la tabla de datos inicial para abrir las imágenes adjuntas: 2022Q1_ChallengeA.zip)
- Tiene: Una columna de tabla de datos con imágenes o enlaces a un sitio web o un archivo (también conocido como expresiones)
- Desea: hacer clic en una celda de esta columna y abrir el enlace o la imagen fuera de JMP
- El objetivo general: hacer clic en una celda de la tabla de datos debería iniciar algo
- Desafío B : (script para abrir la tabla de datos y crear el informe adjunto: 2022Q1_ChallengeB_starterScript.jsl)
- Tienes: Big Class y un informe Graph Builder de peso por altura (ver script)
- Desea: Al cerrar el informe Graph Builder debería abrir un informe de distribución de "edad", guardar este informe como una imagen y cerrar el informe de distribución.
- El objetivo general: cerrar una ventana debería desencadenar alguna acción
- Reto C: (script para abrir la tabla de datos y crear el informe adjunto: 2022Q1_ChallengeC_starterScript.jsl)
- Tiene: Un informe de Graph Builder sobre datos de muestra de medidas de crecimiento.
- Desea: Al hacer clic en una línea o seleccionar varias líneas (o categorías en la leyenda), desea generar un subconjunto de las filas seleccionadas.
- El objetivo general: hacer clic en un gráfico o informe debería desencadenar alguna acción
Puedes trabajar en tantos desafíos como quieras. Puede/debe enviar sus respuestas directamente como respuesta a este hilo.
!!! Al enviar, comience en la primera línea con el desafío al que se refiere su respuesta, por ejemplo
RETO A:
Esta es mi respuesta...
// this is my code
...
En la próxima reunión (18 de mayo de 2022) presentaremos algunas de las respuestas y marcaré las mejores respuestas como solución a este hilo.
Espero sus envíos 
Re: 2022_Q1 MakeOverChallenge: Acción al hacer clic con el mouse de varias manerasRETO C
Esta es mi respuesta, vea el guión completo a continuación.
La parte inferior agrega un controlador de estado de fila a la tabla, que desencadena la acción (ver ejemplo en Índice de secuencias de comandos).
Names Default To Here( 1 );
// Open Data Table
dt = Open( "$SAMPLE_DATA/Growth Measurements.jmp", invisible );
// Report snapshot: Growth Measurements - Graph Builder
gb = dt << Graph Builder(
Size( 522, 452 ),
Show Control Panel( 0 ),
Legend Position( "Bottom" ),
Graph Spacing( 8 ),
Variables( X( :Age ), Y( :Growth ), Overlay( :Subject ) ),
Elements( Line( X, Y, Legend( 13 ) ) )
);
// This is my code (Georg)
// (see Scripting Index "Make Row State Handler")
// Define a function, that does the action
f = Function( {a},
Current Data Table() << Subset( Selected Rows( 1 ), Selected columns only( 0 ) )
);
// Set up a row state handler, that triggers the execution of a function on any change of row states,
// a change on row selection by clicking on a line in Graph Builder is a change of row states in the table
rs = dt << make row state handler( f );Re: 2022_Q1 MakeOverChallenge: Acción al hacer clic con el mouse de varias manerasRETO C
Con un cuadro de mouse no era posible seleccionar algo, así que cambié a un controlador de estado de fila
Names Default To Here( 1 );
// Open Data Table
dt = Open( "$SAMPLE_DATA/Growth Measurements.jmp", invisible );
// Report snapshot: Growth Measurements - Graph Builder
gb = dt << Graph Builder(
Size( 522, 452 ),
Show Control Panel( 0 ),
Legend Position( "Bottom" ),
Graph Spacing( 8 ),
Variables( X( :Age ), Y( :Growth ), Overlay( :Subject ) ),
Elements( Line( X, Y, Legend( 13 ) ) )
);
active_subset = "";
first_subset = "false";
rsh = dt << make row state handler(
Function( {a},
subtbl = dt << Subset( Selected Rows( 1 ) );
gb << Bring Window To Front;
if(
first_subset == "true",
close(active_subset, no save)
);
active_subset = subtbl;
first_subset = "true";
)
);
Re: 2022_Q1 MakeOverChallenge: Acción al hacer clic con el mouse de varias manerasRETO A:
NOTA: Mantuve esta versión anterior porque algunas personas ya la habían visto, pero publiqué una solución más limpia como Respuesta a este
No es en absoluto una solución bonita, pero hace el trabajo... ¡Esperando que aparezca uno más elegante!
Esto se agregará después del starterScript:
// Defining the file name for an image placeholder for displaying on the OS when clicking:
pictFileName = Get Default Directory() || "verylonganduselessname.png"; //name for the temp image file (to be deleted at the end)
dtx:Picture << Set Property("tmpFileName", pictFileName); //saving the name so it can be retrieved from within the table
dtx << On Close( Delete File(pictFileName) ); //make sure we erase the temp image file at the end.
// Setting a Click event handler for the column of interest:
dtx:Picture << Set Property(
"Event Handler",
Event Handler(
Click(JSL Quote( Function(
{thisTable, thisColumn, iRow},
pictFileName = thisTable:thisColumn<< Get Property("tmpFileName"); //recover the path for a temp file
thisTable:thisColumn[iRow] << Save Image( pictFileName ); //save cell contents to temp file
Web( "file://" || pictFileName ) // open the image file
)
)
),
Tip(JSL Quote( Function(
{thisTable, thisColumn, iRow},
"click to open";
)
)
)
)
);
Re: 2022_Q1 MakeOverChallenge: Acción al hacer clic con el mouse de varias manerasRETO A
Perdón por adelantarme con mi solución inicial... Aquí hay uno más limpio.
Names Default to Here ( 1 );
//path = <YOUR full="" path="" to="" where="" the="" images="" have="" been="" saved="">;
// eg.
// path = "C:\EventHandlerImages\";
path = "$DOCUMENTS\Scripting\2022Q1\ChallengeA\2022Q1_ChallengeA\";
//==========================================================================
//Multiple File Import is new in JMP 14
{dtx} = Multiple File Import(
<<SET folder=""></SET></YOUR>Re: 2022_Q1 MakeOverChallenge: Acción al hacer clic con el mouse de varias manerasReto C
Desafortunadamente, había poco más que hacer en lo que respecta a los desafíos A y B. Las soluciones proporcionadas parecían impecables. Por el contrario, sentí que aún era posible alguna mejora para el desafío C. Algunas palabras sobre mi respuesta.
- Básicamente he robado el código necesario. de aquí ( @txnelson es, como muchos otros guionistas, una estrella de rock para mí)
- Modifiqué ligeramente el gráfico al incluir puntos de datos visibles, por lo que es más fácil seleccionar filas individuales
- Después de seleccionar los puntos en el gráfico, la tabla de datos con el subconjunto no se abre inmediatamente. Esto se hace a través del botón agregado debajo del gráfico.
Vea a continuación el script completo, incluido el gráfico modificado.
// Open Data Table
dt = Open( "$SAMPLE_DATA/Growth Measurements.jmp",invisible );
// Report snapshot: Growth Measurements - Graph Builder
gb = dt << Graph Builder(
Size( 522, 452 ),
Show Control Panel( 0 ),
Legend Position( "Bottom" ),
Graph Spacing( 8 ),
Variables( X( :Age ), Y( :Growth ), Overlay( :Subject ) ),
Elements(
Points( X, Y, Legend( 17 ), Jitter Limit( 0 ) ), // added markers
Line( X, Y, Legend( 13 ) ) ),
SendToReport( // increased markers to decent size
Dispatch(
{},
"Graph Builder",
FrameBox,
{Marker Size( 6 ), Marker Drawing Mode( "Normal" )}
)
)
);
// my solution (stolen from here: https://community.jmp.com/t5/Discussions/Creating-a-Subset-from-an-Interactive-Graph/td-p/114459)
subsetButton = Button Box( "Dear user, Please press here to create a Subset of the Selected Points immediately",
If( N Rows( dt << get selected rows ) > 0,
dt << subset( selected rows( 1 ), selected columns( 0 ) )
)
);
Report( gb )["Graph Builder"] << append( subsetButton );
Re: 2022_Q1 MakeOverChallenge: Acción al hacer clic con el mouse de varias manerasDesafío A:
Principalmente código escrito JMP con Agregar propiedades de columna. También se agregó un ejemplo de cómo agregar y abrir URL
Ver más...
Names Default To Here(1);
// Challenge A
path = "2022Q1_ChallengeA"; // path to images
{dtx} = Multiple File Import(
<<SET folder=""></SET>
Re: 2022_Q1 MakeOverChallenge: Acción al hacer clic con el mouse de varias manerasRETO B
Agregue esto al final del script:
gb << On Close(
dist = dt << Distribution( Nominal Distribution( Column( :age ) ) );
image = dist << Get Picture;
path = "$temp/age_dist.png";
image << Save Picture( path, "png" );
dist << Close Window();
Open( path );
);
Re: 2022_Q1 MakeOverChallenge: Acción al hacer clic con el mouse de varias manerasReto B:
Ver más...
Names Default To Here(1);
// 2022_Q1 MakeOverChallenge: Action on mouse click in various ways
// Challenge B
dt = Open("$SAMPLE_DATA/Big Class.jmp");
//Use expression to make script a bit more clean IF this were to be expanded
create_dist = Expr(
dist = dt << Distribution(Nominal Distribution(Column(:age)), Histograms Only);
wait(1); // add wait so we can see that distribution is created
dist << Save Picture("$TEMP/Big_Class_age_dist.png", png);
dist << Close Window;
);
gb = dt << Graph Builder(
Size(528, 454),
Show Control Panel(0),
Variables(X(:height), Y(:weight)),
Elements(Points(X, Y, Legend(3)), Line Of Fit(X, Y, Legend(5)))
);
gb << On Close(create_dist);
// Open("$TEMP/Big_Class_age_dist.png"); // un-comment to open the image
Re: 2022_Q1 MakeOverChallenge: Acción al hacer clic con el mouse de varias manerasReto C:
Definitivamente sugiero hacer cosas como esta con botones, ya que evita la creación de demasiados subconjuntos. Pero aquí seguí el desafío dado y agregué una verificación simple de que al menos no crearemos el mismo subconjunto dos veces.
Ver más...
Names Default To Here(1);
// Open Data Table
dt = Open("$SAMPLE_DATA/Growth Measurements.jmp", invisible);
gb = dt << Graph Builder(
Size(522, 452),
Show Control Panel(0),
Legend Position("Bottom"),
Graph Spacing(8),
Variables(X(:Age), Y(:Growth), Overlay(:Subject)),
Elements(Line(X, Y, Legend(13)))
);
//initialize some variables
prev_rows = [];
dt_list = {};
f = Function({rows_changed},
//Rowstate 1 is selected row
cur_rows = Loc(dt << Get Row States, 1);
//if no rows are selected, don't try to create subsets
If(N Items(cur_rows) == 0,
return()
);
//compare to previous to prevent opening extensive abmount of subsets
If(N Items(cur_rows) == N Items(prev_rows),
If(All(cur_rows == prev_rows),
return();
);
);
dt_subset = dt << Subset(Output table("selected_rows"), Rows(cur_rows), invisible);
Insert Into(dt_list, dt_subset); //keep list to make closing easier
//attempt to bring gb to front, this won't work perfectly without wait
gb << Bring Window To Front;
dt_subset << Show Window(1);
//it is enough if we update prev_rows only when subset was created
prev_rows = cur_rows;
);
rs = dt << make row state handler(f);
/* run this to close all data tables
For Each({dt_ref}, dt_list,
Try(Close(dt_ref, no save), Show(exception_msg));
);
Close(dt, no save);
*/
Con Row State Handler no podemos acceder al evento de liberación del mouse, por lo que aún crearemos muchos subconjuntos si el usuario selecciona varias líneas una por una del gráfico (podría haber una manera de hacer esto con Mouse Box(), pero creo que usar el botón sería sea mucho más simple y fácil).