Printing system symbol definitions without context prepended
The contextFreeDefinition[]
function below will attempt to print the definition of a symbol without the most common context prepended. The definition then can be copied to Workbench and formatted for readability (select it, right click, Source -> Format)
Clear[commonestContexts, contextFreeDefinition]
commonestContexts[sym_Symbol, n_: 1] := Quiet[
Commonest[
Cases[Level[DownValues[sym], {-1}, HoldComplete],
s_Symbol /; FreeQ[$ContextPath, Context[s]] :> Context[s]], n],
Commonest::dstlms]
contextFreeDefinition::contexts = "Not showing the following contexts: `1`";
contextFreeDefinition[sym_Symbol, contexts_List] :=
(If[contexts =!= {}, Message[contextFreeDefinition::contexts, contexts]];
Internal`InheritedBlock[{sym}, ClearAttributes[sym, ReadProtected];
Block[{$ContextPath = Join[$ContextPath, contexts]},
Print@InputForm[FullDefinition[sym]]]])
contextFreeDefinition[sym_Symbol, context_String] :=
contextFreeDefinition[sym, {context}]
contextFreeDefinition[sym_Symbol] :=
contextFreeDefinition[sym, commonestContexts[sym]]
withRules[]
Caveat: This function does not localize variables the same way With
and Module
do, which means that nested localization constructs won't work as expected. withRules[{a -> 1, b -> 2}, With[{a=3}, b_ :> b]]
will replace a
and b
in the nested With
and Rule
, while With
doesn't do this.
This is a variant of With
that uses rules instead of =
and :=
:
ClearAll[withRules]
SetAttributes[withRules, HoldAll]
withRules[rules_, expr_] :=
Internal`InheritedBlock[
{Rule, RuleDelayed},
SetAttributes[{Rule, RuleDelayed}, HoldFirst];
Unevaluated[expr] /. rules
]
I found this useful while cleaning up code written during experimentation and localizing variables. Occasionally I end up with parameter lists in the form of {par1 -> 1.1, par2 -> 2.2}
. With withRules
parameter values are easy to inject into code previously written using global variables.
Usage is just like With
:
withRules[
{a -> 1, b -> 2},
a+b
]
Antialiasing 3D graphics
This is a very simple technique to antialias 3D graphics even if your graphics hardware doesn't support it natively.
antialias[g_, n_: 3] :=
ImageResize[Rasterize[g, "Image", ImageResolution -> n 72], Scaled[1/n]]
Here's an example:
Note that a large value for n
or a large image size tends to expose graphics driver bugs or introduce artefacts.
Notebook diff functionality
Notebook diff functionality is available in the < package, and (at least in version 8) in the undocumented NotebookTools`
context. This is a little GUI to diff two notebooks that are currently open:
PaletteNotebook@DynamicModule[
{nb1, nb2},
Dynamic@Column[
{PopupMenu[Dynamic[nb1],
Thread[Notebooks[] -> NotebookTools`NotebookName /@ Notebooks[]]],
PopupMenu[Dynamic[nb2],
Thread[Notebooks[] -> NotebookTools`NotebookName /@ Notebooks[]]],
Button["Show differences",
CreateDocument@NotebookTools`NotebookDiff[nb1, nb2]]}]
]