Dangerous symbol names that begin with a lowercase letter - wolfram-mathematica

I am looking for a full list of dangerous symbol names that begin with a lowercase letter in Mathematica.
At this moment I know three such names: min, max and lim. These names appear in the LimitsPositioningTokens list and are being treated as operators at least when they are entered in the FrontEnd with a superscript:
In[3]:= Options[$FrontEnd,LimitsPositioningTokens]
Out[3]= {LimitsPositioningTokens->{\[Sum],\[Product],\[Intersection],
\[Union],\[UnionPlus],\[Wedge],\[Vee],lim,max,min,\[CirclePlus],
\[CircleMinus],\[CircleTimes],\[CircleDot]}}
For example, type in the FrontEnd the following (use Ctrl+^ for making superscript - it is important!):
In[1]:= max^n+4
(max^n+4)//HoldComplete//FullForm
Out[1]= 4 max^n
Out[2]//FullForm= HoldComplete[Times[Power[max,n],Plus[4]]]
You see that max^n+4 is interpreted as 4*max^n in this case.
Can anyone explain what LimitsPositioningTokens option really does?
Are there other dangerous symbols that begin with a lowercase letter in Mathematica?

I cannot confirm the problem you report. Besides, the tokens you've found seem to be strings rather than symbols.
This is on win7-64/M8.0.1, my wife's mac lion/M8 doesn't show it either.
The fact that they are strings seems to be consistent with the description on the doc page of LimitsPositioning
LimitsPositioningTokens is a Cell option which can be set to a list of
forms for which LimitsPositioning->True should be used.
All examples given there use strings.
Update to illustrate the point made in the comments below
This is with the standard LimitsPositioningTokens setting in $FrontEnd:
and this is with SetOptions[$FrontEnd, LimitsPositioningTokens -> {}]:
Please note that the $FrontEnd setting with SetOptions is sticky. It is likely that yours isn't at default anymore. Use the option inspector to return LimitsPositioningTokens to its default value (search for LimitsPositioningTokens with Global Settings on and remove the cross next to the variable if there is any).

Related

Referencing Two-Word Variables in Applescript?

I'm attempting to get some data from an app called "Timing", which is local to my computer, and post it to a URL to notify a webhook, from which some process automation will occur.
According to the Applescript integration with Timing,
There is a time summary object that's returned from a command which I've successfully executed. When displayed as an alert, that data looks like this:
Can't get |times per project| of {id:5C6CD8C8-357F-4EE7-890C-5946DC03BBB9", overall total:1.18092493622303E+4, times per project:{Maintenance:81.091759443283, Youtube:4820.38001298904, |self improvement effors|:876.930474758148, Homework:2383.20326805115, |(no project)|:3647.64384698868}, overall total without tasks:1.18092493622303E+4, productivity score:0.388005592511, times per project without tasks:{Maintenance:81.091759443283, Youtube:4820.38001298904, |self improvement efforts|:876.930474758148, Homework:2383.20326805115, |(no project)|:3647.64384698868}, class:time summary}.
As you can see, (above), there is a property called productivity score, which is two words.
When attempting to get this datapoint from the object (which I will use to notify the webhook:)
set newnewVar to productivity score of newvar
display alert newvar
Obviously this wont work, because the variable name is two words. I've tried surrounding the name in quotes and surround it with other characters, but nothing seems to work, and the documentation for getting specific properties only has examples with variables with one word.
What's the solution to this problem?
In AppleScript, user-defined variables cannot generally have spaces. Typically they start with a letter or underscore, and then can contain only letters, numbers, or underscores. A user-defined variable can only contain spaces if it is contained within vertical pipes. So all of the following are valid variable forms: alphaUnit, slideRow3, _tempItem, |my variable|, left_hand_vector
However, any application or script that creates and uses a scripting definition can create commands and classes and properties that have multi-word names. For instance, if you look at the System Events app, you'll see that the Disk-Folder-File Suite has a class named disk item with properties like creation date. The reason this works is that these multi-word names are actually represented by a numeric (four-char) code: disk item is actually 'ditm' and creation date is 'ascd'. You often see these codes pop up in error strings like so:
"cannot make class ≪ditm≫ into..."
Make sure you have the scope right to invoke the dictionary — i.e. be within a tell block for the app or script that invokes the scripting dictionary — and the multi-word names should 'just work'. After compiling, you'll see them highlighted in a purple color that's just a bit different from the red of uncompiled text. You do not need to enclose dictionary terms in vertical pipes; if you do, they will be treated as user-defined variables and lose their special scripting purposes.

Mathematica output formatting

How does Mathematica decide when to round numbers in its output? For example,
giving the input
250000.5
gives the output
2500001
While
25000.5
is indeed printed as
25000.5
N[] isn't helpful here either, I need to use NumberForm[] to get it to actually print 250000.5 as 250000.5
I'm a Mathematica newbie, and I'm sure its ridiculously easy to control this threshold for when it starts ignoring decimals in its output, but could somebody please point me in the right direction?
another option for you to try, you can go to options and change the default PrintPrecision from 6 to say 16, and now you will see that it will print what you typed above
after I changed that to 16 (click on the field itself, and type 16 into the field to replace the 6, and hit return), then
Nasser is correct that PrintPrecision is the right setting.
You have a number of options for its use. You can set it Globally or for the specific Notebook using the Options Inspector. You can also use it directly with Style:
Style[250000.5, PrintPrecision -> 10]
250000.5
You can set it temporarily for one session like this:
SetOptions[$FrontEndSession, PrintPrecision -> 10]
Finally you can set it using Style Sheets (select cell type Output).
In the default TraditionalForm and StandardForm output modes Mathematica only shows a certain number of most significant digits. You can use InputForm to get the full precision number.

How to generate new unique name for context?

What is the best way to generate a name for some temporary context which is guaranteed to be unique (context with this name must not exist in the system)?
The following expression will generate a context name that is guaranteed not to conflict with any loaded context:
First#Contexts[] //.
c_ /; MemberQ[Contexts[], c] :>
"Context"~~ToString[RandomInteger[1000000]]~~"`"
It makes no attempt to account for contexts that are not yet loaded. As written, this expression could be used up to 1,000,000 times before running out of names. Adjust the fixed string ("Context") and name count (1000000) to suit your taste.
Update
As #Leonid points out in a comment, empty contexts will not be listed in Contexts[]. Therefore, it is strictly speaking possible that this expression could return the name of an existing empty context.
UUIDs
For all practical purposes, generating a name from a number randomly selected from a large enough range would work, e.g.
"Context"~~ToString[RandomInteger[2^128]]~~"`"
In a similar vein, one could use a UUID. UUIDs are routinely used as identifiers that are phenomenally likely to be unique across all network nodes as well:
Needs["JLink`"]
LoadJavaClass["java.util.UUID"]
"Context"~~
StringReplace[JavaBlock#java`util`UUID`randomUUID[]#toString[], "-" -> ""]~~
"`"
I can suggest a function I used here:
Clear[unique];
unique[sym_] :=
ToExpression[
ToString[Unique[sym]] <>
StringReplace[StringJoin[ToString /# Date[]], "." :> ""]];
You can replace the ToExpression by StringJoin[...,"`"] to tailor it to your needs.
Another option would be to look at all starting contexts (before the first backquote), find their string length and then generate a string (maybe random, but that isn't necessary) that is at least one character longer than the others. This is guaranteed to be unique, and there isn't even a theoretical possibility of a collision as in some of the other solutions.
sl = (StringSplit[#, "`"][[1]] & /# Contexts[] // StringLength // Max )
Out[349]= 30
In[353]:= "c" ~~ ToString[10^sl] ~~ "`"
Out[353]= "c1000000000000000000000000000000`"
A disadvantage of this method would be that the context names get longer after each repeated application of this method. ;-) If that's a problem we could create a unique name based on the set of longest context names using Cantor's diagonal procedure.
Is Unique perhaps what you're looking for?
This is really an example illustrating Alexey's response to Sjoerd's answer/question. From a fresh kernel on my machine, the following code
Begin["myContext3`"];
Unique["myContext"]
Yields "myContext3". Thus, clearly, Unique (the first thing I thought of) does not work.
Incidentally, I would have just added a comment to Sjoerd's response, but I don't know how to include the accent symbol used to denote a context inline. Does anyone here know how to do this?

Formatting usage messages

If you take a look at the Combinatorica package in Mathematica8 in (mathematicapath)/AddOns/LegacyPackages/DiscreteMath/Combinatorica.m you will find the definitions of functions. What I'm interested to know is how Mathematica knows how to format the usage messages. Something tells me that I'm not looking at the right file. In any case, lets try the following:
Cofactor::usage = "Cofactor[m, {i, j}] calculates the (i, j)th cofactor of matrix m."
This line is the 682 line in the file mentioned above. Now if we run it in a mathematica notebook and we use ?Cofactor we will see the exact same message. But if we get the package then the message is formatted. Here is a screenshot:
Notice how the m, i and j inside the function changed and a double arrow was added to the message. I think the arrow was added to the message because there exists documentation for it. Can someone explain this behavior?
EDIT:
This is a screenshot of my notebook file that autosaves to an m file.
As you can see, the L and M are in italic times new roman. Now I will load the package and see the usage.
So far so good. Now lets look at the Documentation center. I will look for the function LineDistance.
As you can see, it shows a weird message. In this case we only want to display the message without any styles. I still can't figure out how the Combinatorica package does this.
I followed this to make the index so that the doc center can display the summary. The summary is essentially the usage display. Let me know if I need to be more specific.
OK, here's the explanation.
Digging in the Combinatorica source reveals this:
(* get formatted Combinatorica messages, except for special cases *)
If[FileType[ToFileName[{System`Private`$MessagesDir,$Language},"Usage.m"]]===File,
Select[FindList[ToFileName[{System`Private`$MessagesDir,$Language},"Usage.m"],"Combinatorica`"],
StringMatchQ[#,StartOfString~~"Combinatorica`*"]&&
!StringMatchQ[#,"Combinatorica`"~~("EdgeColor"|"Path"|"Thin"|"Thick"|"Star"|"RandomInteger")~~__]&]//ToExpression;
]
It is loading messages from ToFileName[{System`Private`$MessagesDir,$Language},"Usage.m"], which on my machine is SystemFiles\Kernel\TextResources\English\Usage.m. This is why all usage messages are created conditionally in Combinatorica.m (only if they don't exist yet). If you look in Usage.m you'll see it has all the ugly boxes stuff that #ragfield mentioned.
I guess the simplest way to have formatted messages is to edit them in the front end in a notebook, and create an auto-save package. This way you can use all the front end's formatting tools, and won't need to deal with boxes.
I will answer on how the link in the Message is generated. Tracing Message printing shows a call to undocumented Documentation`CreateMessageLink function which returns the URL to the corresponding Documentation page if this page exists:
Trace[Information[Sin], Documentation`CreateMessageLink]
In[32]:= Documentation`CreateMessageLink["System", "Sin", "argx", "English"]
Out[32]= "paclet:ref/message/General/argx"
In some cases we can also see calls to Internal`MessageButtonHandler which further calls Documentation`CreateMessageLink:
Trace[Message[Sin::argx, 1, 1],
Internal`MessageButtonHandler | Documentation`CreateMessageLink,
TraceInternal -> True]
The way to embed style information in a String expression is to use linear syntax. For a box expression such as:
StyleBox["foo", FontSlant->Italic]
You can embed this inside of a String by adding \* to the front of it and escaping any special characters such as quotes:
"blah \*StyleBox[\"foo\", FontSlant->Italic] blah"
This should work for any box expression, no matter how complicated:
"blah \*RowBox[{SubsuperscriptBox[\"\[Integral]\",\"0\",\"1\"],RowBox[{FractionBox[\"1\",RowBox[{\"x\",\"+\",\"1\"}]],RowBox[{\"\[DifferentialD]\",\"x\"}]}]}] blah"
I am currently working on rewriting your ApplicationMaker for newer Mathematica-Versions with added functionalities and came to the exact same question here.
My answer is simple: Mathematica dont allowes you to use formated summaries for your symbols (or even build in symbols), so we have to unformate the usage-strings for the summaries. The usagestring itself can still have formatting, but one needs to have a function that removes all the formatingboxes from a string.
i have a solution that uses the UndocumentedTestFEParserPacket as described by John Fultz! in this question.
This funny named Tool parses a String Input into the real unchanged Mathematica BoxForm.
This is my example code:
str0 = Sum::usage
str1=StringJoin[ToString[StringReplace[#, "\\\"" -> "\""]]& /#
(Riffle[MathLink`CallFrontEnd[
FrontEnd`UndocumentedTestFEParserPacket[str0, True]]〚1〛
//. RowBox[{seq___}] :> seq /. BoxData -> List, " "]
/. SubscriptBox[a_, b_] :> a<>"_"<>b
/. Except[List, _Symbol][args__] :> Sequence##Riffle[{args}, " "])];
str2 = Fold[StringReplace, str1,
{((WhitespaceCharacter...)~~br:("["|"("|"=") ~~ (WhitespaceCharacter ...)) :> br,
((WhitespaceCharacter ...) ~~ br:("]"|"}"|","|".")) :> br,
(br:("{") ~~ (WhitespaceCharacter ...)) :> br,
". " ~~ Except[EndOfString] -> ". \n"}]
and this is how the Output looks like (first Output formatted fancy str0, second simple flat str2)
Code Explanation:
str0 is the formatted usagestring with all the StyleBoxes and other formatting boxes.
str1:
UndocumentedTestFEParserPacket[str0, True] gives Boxes and strips off all StyleBoxes, thats because the second argument is True.
First Replacement removes all RowBoxes. The outer BoxForm changed to a List of strings. Whitespaces are inserted between these strings the by Riffle. SubscriptBox gets a special treatment. The last line replaces every remaining FormatBox such as UnderoverscriptBox and it does that by adding Whitespaces between the arguments, and returning the arguments as a flat Sequence.
ToString[StringReplace[#, "\\\"" -> "\""]]& /#
was added to include more cases such as StringReplace::usage. This cases include string representations "" with Styles inside of a the usage-string, when "args" has to be given as strings.
str2:
In this block of code i only remove unwanted WhitespaceCharacter from the string str1 and i add linebreaks "/n" after the ".", because they got lost during the Parsing. There are 3 different cases where WhitespaceCharacter can be removed.
1 removing left-and right sided WithespaceCharacter from a character like "[".
2. and 3. removing WithespaceCharacter from left(2) or right(3) side.
Summary
Istead of summary-> mySymbol::usage, use summary -> unformatString[mySymbol::usage] with unformatString being an appropriate function that performes the unformating like descriped above.
Alternatively you can define another usage message manually like
f::usage = "fancy string with formating";
f::usage2 = "flat string without formating";
than use summary -> mySymbol::usage2

Syntax Coloring In Mathematica

How could user-defined function symbol such as f in
f[x_] = 2 x
or variable symbols such as lotto in
lotto = Table[2, {10}];
be colored automatically ?
In Syntax coloring on M8 no option is offered for this.
Only Local Variables or Global symbols that have no values assigned.
This is not exactly what you asked for, but it may be useful to you.
You can highlight symbols by context, using this method:
SetOptions[$FrontEndSession,
AutoStyleOptions -> {"SymbolContextStyles" -> {"highlight`" -> Green}}
]
AppendTo[$ContextPath, "highlight`"];
Now, when you create a symbol in the context highlight` it will automatically be colored green:
highlight`lotto ;
and since highlight` was appended to $ContextPath, after that the symbol can be used plainly:
lotto
Highlighting all symbols (variables)
If you want all the symbols you create to automatically be highlighted, then set:
$Context = "highlight`"
After that, all new symbols you create will belong to the context highlight` and will receive the color.
New means ones that have not been previously used in the session, or have been Removed.
It occurs to me that a better way to accomplish this, that avoids a possible "shadowing" problem, may be to set highlighting for the Global` context itself. I have not considered the ramifications of this, but it can be done with this alone:
SetOptions[$FrontEndSession,
AutoStyleOptions -> {"SymbolContextStyles" -> {"Global`" -> Green}}
]
Tips on usage
The context highlight` is completely arbitrary, and you can have multiple contexts highlighted with different colors.
You can color the contexts of packages such as Units` to distinguish which symbols belong to that package.
Such variables are automatically colored after you assign a value to them. Under the default Mathematica settings, lotto changes color from blue to black as soon as you assign the value. Strictly speaking, it is the unassigned variables that get colored according to the setting you will find under Preferences / Appearance / Syntax Coloring / Other / Global symbols that have no value assigned.
If what you are looking for is a way to assign a distinct color to global symbols whose only definitions are own-values, then I believe that you are out of luck. As far as I know, the syntax coloring machinery does not distinguish between own-values ("variable assignments"), down-values ("function definitions") and up-values ("expression part definitions").
As I said in my comment above, I think that this would be hard to completely automate. You'd have to wrap Set and SetDelayed to automatically move variables into the right context depending on whether they're creating an OwnValue or a DownValue.
To do this manually just requires a simple edit of Mr.Wizard's previous work...
SetOptions[$FrontEndSession,
AutoStyleOptions -> {"SymbolContextStyles" ->
{"functions`" -> Green, "variables`" -> Pink}}]
$ContextPath = Join[$ContextPath, {"functions`", "variables`"}]//DeleteDuplicates;
variables`x;
functions`f;
Is this what you want?

Resources