Skip to main content

front end - Getting the Box of a Button


I have a useful snippet of code that I use for anything in my notebook that takes a while to execute and doesn't need to be executed for subsequent cells:


buttonEvaluate[expr_] := Module[{cell}, 
Button["Evaluate",
cell = Cell[BoxData[ToBoxes[ expr ]], "Output"];
SelectionMove[ButtonNotebook[], All, ButtonCell];
NotebookWrite[ButtonNotebook[], cell]

,
Method -> "Queued"
]
];

SetAttributes[buttonEvaluate, HoldFirst];

buttonEvaluate::usage = "Returns a button, that when pressed, replaces itself with the evaluation of the passed in expression. Useful for things you don't necessarily care to recalculate when the notebook is evaluated.";

I usually use it like this:



some[expression,that,takes] + a * long / time // buttonEvaluate

...and when that cell is executed, the output is a button labelled Evaluate, which, when pressed, replaces the output cell with the result. This means I can use Evaluation->Evaluate Notebook, and it effectively skips over some cells until I explicitly choose to evaluate them.


However, I've run into an issue when I try to use it inside an expression, because the perfectionist in me wants to be able to do something like:


Row[{slowThing[] // buttonEvaluate, fastThing[]}]

However, the Button's action is to replace the ButtonCell with the results, which inadvertently replaces everything, not just the Button's Box. So, two questions:



  1. Is there any way to select the Box of the Button?

  2. Will replacing that selection using NotebookWrite work how I want it to? I can imagine it might play havoc with Mathematica's formatting.




Answer



V10 edit


As of V10 it is easier to do that with a help of EvaluationBox[]. Your second concern is solved by temporarily changing DefaultDuplicateCellStyle. 78417


ButtonHold ~ SetAttributes ~ HoldFirst;

ButtonHold[expr_] := Button[
Tooltip["Evaluate", HoldForm[expr]]
,
Module[{nb = EvaluationNotebook[], pre, opt = DefaultDuplicateCellStyle},

pre = Options[nb, opt];
SetOptions[nb, opt -> "Output"];
NotebookWrite[EvaluationBox[], ToBoxes @ expr];
SetOptions[nb, pre]
]
,
Method -> "Queued"
];

Grid[{{1, Button[1]}, {ButtonHold[Plot[Sin[x], {x, 0, 1}]],

4}, {ButtonHold[Plot[Cos[x], {x, 0, 1}]], 10}}]

enter image description here




Old solution


Not pretty but works. The trick is to inject Unique string to the box so it can be found later in whatever you wish to have in that cell.


Cell expression with replaced BouttonBox is then overwritting button's parent cell.


buttonEvaluate2 = Function[expr,

Button["Evaluate",

#;
SelectionMove[EvaluationCell[], All, Cell];
NotebookWrite[ EvaluationNotebook[],
NotebookRead[EvaluationCell[]
] /. b_ButtonBox /; MemberQ[b, #, {3}] :> ToBoxes@expr
];
, Method -> "Queued"
] &[ ToString @ Unique["x"] ]
,
HoldFirst];




test


Grid[{
{1, Button[1]},
{buttonEvaluate2[Plot[Sin[x], {x, 0, 1}]], 4},
{buttonEvaluate2[Plot[Cos[x], {x, 0, 1}]], 10}
}]

Comments

Popular posts from this blog

mathematical optimization - Minimizing using indices, error: Part::pkspec1: The expression cannot be used as a part specification

I want to use Minimize where the variables to minimize are indices pointing into an array. Here a MWE that hopefully shows what my problem is. vars = u@# & /@ Range[3]; cons = Flatten@ { Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1, 3 - 1}], 1 vec1 = {1, 2, 3}; vec2 = {1, 2, 3}; Minimize[{Total@((vec1[[#]] - vec2[[u[#]]])^2 & /@ Range[1, 3]), cons}, vars, Integers] The error I get: Part::pkspec1: The expression u[1] cannot be used as a part specification. >> Answer Ok, it seems that one can get around Mathematica trying to evaluate vec2[[u[1]]] too early by using the function Indexed[vec2,u[1]] . The working MWE would then look like the following: vars = u@# & /@ Range[3]; cons = Flatten@{ Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1, 3 - 1}], 1 vec1 = {1, 2, 3}; vec2 = {1, 2, 3}; NMinimize[ {Total@((vec1[[#]] - Indexed[vec2, u[#]])^2 & /@ R...

functions - Get leading series expansion term?

Given a function f[x] , I would like to have a function leadingSeries that returns just the leading term in the series around x=0 . For example: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x)] x and leadingSeries[(1/x + 2 + (1 - 1/x^3)/4)/(4 + x)] -(1/(16 x^3)) Is there such a function in Mathematica? Or maybe one can implement it efficiently? EDIT I finally went with the following implementation, based on Carl Woll 's answer: lds[ex_,x_]:=( (ex/.x->(x+O[x]^2))/.SeriesData[U_,Z_,L_List,Mi_,Ma_,De_]:>SeriesData[U,Z,{L[[1]]},Mi,Mi+1,De]//Quiet//Normal) The advantage is, that this one also properly works with functions whose leading term is a constant: lds[Exp[x],x] 1 Answer Update 1 Updated to eliminate SeriesData and to not return additional terms Perhaps you could use: leadingSeries[expr_, x_] := Normal[expr /. x->(x+O[x]^2) /. a_List :> Take[a, 1]] Then for your examples: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x), x] leadingSeries[Exp[x], x] leadingSeries[(1/x + 2 + (1 - 1/x...

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]