title: Tools for finding minimal or almost-minimal graph vertex colorations in Mathematica v9?

text: I'm looking to compute minimum vertex colorations (s.t. no two vertices of the same color share an edge: http://en.wikipedia.org/wiki/Graph_coloring) for graphs in Mathematica v9 with potentially up to a few hundred vertices. I noticed that there are some old functions for this in the Combinatorica package (`MinimumVertexColoring` and `VertexColoring`), however these seem to no longer work with Mathematica v9 graph data structures. Unfortunately, I couldn't find anything newer in the function directory. How does one find a graph coloring in Mathematica v9, or at least the chromatic number of the graph? Is there anything that will guarantee a minimal coloring conditioned on a result being returned? Sage has the following functionalities: http://www.sagemath.org/doc/reference/graphs/sage/graphs/graph_coloring.html, but I can't seem to find anything in Mathematica v9 for this. Update - Let's take belisarius' suggestion to use `ToCombinatoricaGraph` (and Szabolcs code from Generating a graph where vertices correspond to points in an integer lattice and edges connect points less than a threshold distance apart, which doesn't clash with Combinatorica package definitions):               Needs["Combinatorica`"]     Needs["GraphUtilities`"]          pts = Tuples[Range[10], 2];     threshold = 2;          distances = With[{tr = N@Transpose[pts]}, Function[point, Sqrt[Total[(point - tr)^2]]] /@ pts];     G = SimpleGraph[AdjacencyGraph@UnitStep[threshold - distances], VertexCoordinates -> pts]          MinimumVertexColoring[ToCombinatoricaGraph[G]]      The output (for `threshold = 2`) is:               {1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3}      So this seems to work. I suppose the obvious questions would be: Is it known what algorithm `MinimumVertexColoring` is actually using? The help directory says that it returns a minimum vertex coloring, but is it actually guaranteed to be minimal? In other words, what algorithm is being employed? (Partial answer: the algorithm is based on [Mehrotra, A. and Trick, M. A. "A Column Generation Approach for Graph Coloring." INFORMS J. on Computing 8, 344-354, 1996.] http://mathworld.wolfram.com/ChromaticNumber.html. I need to read the paper to determine if there are any caveats to obtaining an exact minimum coloring. Also, can we place markers on the vertices in the Mathematica v9 graph structure indicating their color? It's not clear to me if `ToCombinatoricaGraph` is preserving vertex orderings when reporting a coloring?


title: Convert an expression from one form to another

text: I have this expression               -0.433284-0.758719 x+0.00289158 x^2-0.443672 y+0.00149027 y^2      I want to express it in terms of $$\frac{(x-h)^2}{b^2}+\frac{(y-k)^2}{a^2}$$. Using Solve gave me a big mess:               Solve[-0.433284-0.758719 xP+0.00289158 xP^2-0.443672 yP+0.00149027 yP^2==(xP-h)^2/b^2+(yP-k)^2/a^2,{a,b,h,k}]      ![Solve](http://i.stack.imgur.com/s4VFs.png) What can I do to get it in the form I wanted?


title: Programmatically move the cursor to a desired location on the screen

text: Is it possible to set/move the mouse pointer's location directly from _Mathematica_ without using external tools like `Run["xdotool mousemove x y"]`?


title: Finding lags of time series with `Do`

text: I have generated two time series, `S[t]` and `P[t]` as follows:               In[2990]:= Table[S[t], {t, 1, 50}]          Out[2990]= {0.5, 0.5, 2.253, 2.7614, 2.87762, 4.05318, 5.03183, 5.42801, 6.32663,     7.43033, 8.14412, 8.98434, 10.0983, 11.0536, 11.9744, 13.0988, 14.2194, 15.2811,     16.4588, 17.7028, 18.9201, 20.1964, 21.5544, 22.9261, 24.3338, 25.8165, 27.3415,     28.9023, 30.5282, 32.2123, 33.9413, 35.7309, 37.5859, 39.4971, 41.4699, 43.5124,     45.6209, 47.7963, 50.0454, 52.3689, 54.7668, 57.2436, 59.8024, 62.4438, 65.1712,     67.988, 70.8963, 73.8987, 76.9988, 80.1996}          In[3057]:= Table[P[t], {t, 1, 50}]          Out[3057]= {0.75, 0.75, 0.75, 0.75, 2.22, 2.26635, 2.31409, 4.72832, 5.47929, 5.71359,     7.38173, 8.77145, 9.38649, 10.687, 12.2584, 13.3072, 14.5348, 16.1313, 17.5145,     18.8577, 20.4782, 22.0947, 23.6365, 25.3391, 27.1332, 28.8952, 30.7413, 32.7011,     34.6829, 36.7181, 38.8585, 41.0603, 43.3149, 45.6623, 48.0927, 50.5888, 53.1718,     55.8482, 58.6059, 61.4525, 64.3987, 67.44, 70.5779, 73.8214, 77.1718, 80.6293,     84.2004, 87.8892, 91.6969, 95.6281}      Now, these two time series are related to each other by a lag, `L[t]`. Thus, `S[t]==P[t-L[t]]`. Time series of `L[t]` is not known and I have to find it from given `S[t]` and `P[t]`. My code for this is:               Do[{Do[If[S[t] > P[i], k = i], {i, 1, t}],Print[t-k]},{t,5,50}]      The list of numbers printed out, i.e. `t-k`, is exactly what I expected. So I would like to define `L[t_] := t - k`. But if I substitute this for `Print[t-k]` in the code and `Print` the resulting list of numbers, I get a different result. Is there any way to define this function?


title: Image compose coordinate problem

text: Am I missing something or this is a bug? Why I get different results by just adding a bracket?               g1 = Graphics[{}, ImageSize -> {200, Automatic}, AspectRatio -> 2];     g2 = Graphics[Rectangle[], ImageSize -> {200, Automatic}, AspectRatio -> 1];     g3 = Graphics[Rectangle[], {ImageSize -> {200, Automatic}, AspectRatio -> 1}];          Row[{     ImageCompose[g1, g2, {0, 0}, {0, 0}],     ImageCompose[g1, g3, {0, 0}, {0, 0}],     ImageCompose[g1, Show[g2], {0, 0}, {0, 0}]}]      ![enter image description here](http://i.stack.imgur.com/OXzI1.png)


title: Display functions without dependence?

text: I'm solving systems of equations with a few different functions of time, t, and so I'm getting output with lots of [t] running around. Is there a way to display these functions without the dependences, e.g., to display               a[t] b'[t]      as               a b'      ? I can use a series of replacement rules to do this, e.g.,               /.{a[t]->a,b[t]->b}      but this is pretty cumbersome, and doesn't generalize well (e.g., when more functions are added in).


title: Is equation numbering in exported HTML considered deprecated for built in stylesheets?

text:
So I've been tinkering around with the built in stylesheets and the `Export` command and I've noticed that in principle equation numbering _should_ work. When you look at PublicationDefault.nb or Notebook.nb stylesheets you'll notice the use of the `IncludeCount` function, which looks like it should print a number into EquationNumberedLabel class of html code. Here's what I'm talking about:               Cell[StyleData["EquationNumbered", StyleDefinitions -> StyleData["Equation"]],      ConversionRules:>{       "HTML" -> {{"", ""}, {"

", Automatic,        IncludeCount[           "	(`1`)

",             "EquationNumbered"]}}},...]      I've tried exporting it with commands: `Export["test.html", SelectedNotebook[], "HTML"]` `Export["test.html", SelectedNotebook[], "HTML", "MathOutput" -> "TeX"]` both don't seem to give me the equation numbers. Is this functionality really not intended to work?


title: FindDistributionParameters of a sum of a mixture distribution

text: I have this Mixture Distribution of two Normal Distributions:                mix[p_, μ1_, μ2_, σ_] :=       MixtureDistribution[{p,       1 - p}, {NormalDistribution[μ1, σ],       NormalDistribution[μ2, σ]}];      Say $x_1, x_2$ are samples from this mixture. Set $y=x_1+x_2$, so that $y$ is the sum of two samples from the mixture. I now generate 100 $y's$ (with arbitrary p, mu and sigma, each is a sum of two $x$:               mixdat = RandomVariate[mix[0.75, 0.5, -1.5, 0.2], 1000];     mixdatSum =      Total[RandomVariate[mix[0.75, 0.5, -1.5, 0.2], 2]] & /@ Range[100];      mixdatSum contains these 100 values. Now given the data in mixdatSum I want to estimate the Distribution Parameters. So a natural way to solve this would be:               FindDistributionParameters[mixdatSum,      TransformedDistribution[x1 + x2,      Thread[Distributed[{x1, x2},      MixtureDistribution[{p,        1 - p}, {NormalDistribution[μ1, σ],        NormalDistribution[μ2, σ]}]]]]]      Problem is, the sum of a mixture does not follow the mixture distribution, so this does not work and I get lots of errors. However I want to treat the sum of a mixture AS IF IT WERE following the same mixture, for approximation purposes. Is there a way to do this?


title: Intersection of lists of disjoint intervals

text: Here is my problem: I have two very large lists of intervals (stored as many couples in the form `{{"start point", "end point"}, ..., {"start point", "end point"}`), and I want the result of the intersection of those lists. Here is an example :               intervalsA = {{1, 2}, {3, 4}, {5, 7}, {8, 8.5}};     intervalsB = {{1.5, 3.5}, {4.1, 6}, {9, 10}};      The expected result is: `overlap = {{1.5, 2}, {3, 3.5}, {5, 6}};` I tried using `Interval`, `IntervalUnion` and `IntervalIntersection`, but nothing worked. The only working method that I found uses `Piecewise` functions where each interval is set as 1. By multiplying the two piecewise functions, I have something similar to the intersection, but the solution is very inefficient. I hope I am clear and precise enough.


title: Why is SparseArray and InterpolationFunction always grayed out?

text: In the front end of _Mathematica_ version 10, a new feature was implemented which dims output cells that no longer correspond to its input cells. So when you type               1 + 1     (* 2 *)      and go into the input and add another `+1`, the `2` is slightly gray to indicate that `1+1+1` is not `2`. `SparseArray` seem to be always grey, as if they are never up-to-date > ![Mathematica graphics](http://i.stack.imgur.com/yckik.png) The same is true for `InterpolatingFunction` but not for `CompiledFunction`. > ![Mathematica graphics](http://i.stack.imgur.com/DdgBY.png) Any clues why this is?


title: Key->Value or Value when returning (multiple) parts of an Association

text: There seems to be an idiom whereby multiple parts generates Key->Value forms whereas for single part specifications, only a Value is returned. This however, can lead to inconsistencies as follows:                     assoc = <|"a" -> 7, b -> 8, "c" -> 9|>;           {Query[{1, 2}][assoc], Query[1][assoc], Query[2][assoc]}      (* -> {<|"a" -> 7, b -> 8|>, 7, 8} *)      but doesn't this contradict the documentation on multiple queries?                Query::Docs] {op_1, op_2, ...} apply multiple operators at once to the result, yielding a list      firstly, a list is not "yielded" (returned) and secondly, each application of the operator ordinarily returns a value. A more consistent usage would therefore appear to be?               Query[{1, 2}][assoc]     (* -> {7, 8}  *)          (* not valid existing input/output - suggestive only *)      In addition, the mere presence of a range (e.g. `1 ;; 2`) seems to induce individually specified parts to now return Values?               Query[{1, 2, 1 ;; 2}][assoc]     (*->  {7, 8, <|"a" -> 7, b -> 8|>} *)


title: Exporting plots

text: I want to export a plot which includes curve fitted to a multiple data set. shortly ( I use autolegend function Here )               datpl = ListPlot[{Er[1], Er[2], Er[3], Er[4], Er[5], Er[6], Er[7],          Er[8], Er[9], Er[10], Er[11], Er[12], Er[13]},         PlotStyle -> {Black, Red, Blue, Green, Pink, Yellow, Brown, Orange,           Magenta, Gray, Cyan, Purple, Darker[Blue] }];     datap2 = ListPlot[{{Er[1][[#, 1]], U[#, 1] /. solmd[[2]]} & /@           Ei[1][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Black}, Axes -> False];     datap3 = ListPlot[{{Er[2][[#, 1]], U[#, 2] /. solmd[[2]]} & /@           Ei[2][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Red}, Axes -> False];     datap4 = ListPlot[{{Er[3][[#, 1]], U[#, 3] /. solmd[[2]]} & /@           Ei[3][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Blue}, Axes -> False];     datap5 = ListPlot[{{Er[4][[#, 1]], U[#, 4] /. solmd[[2]]} & /@           Ei[4][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Green}, Axes -> False];     datap6 = ListPlot[{{Er[5][[#, 1]], U[#, 5] /. solmd[[2]]} & /@           Ei[5][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Pink}, Axes -> False];     datap7 = ListPlot[{{Er[6][[#, 1]], U[#, 6] /. solmd[[2]]} & /@           Ei[6][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Yellow}, Axes -> False];     datap8 = ListPlot[{{Er[7][[#, 1]], U[#, 7] /. solmd[[2]]} & /@           Ei[7][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Brown}, Axes -> False];     datap9 = ListPlot[{{Er[8][[#, 1]], U[#, 8] /. solmd[[2]]} & /@           Ei[8][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Orange}, Axes -> False];     datap10 =        ListPlot[{{Er[9][[#, 1]], U[#, 9] /. solmd[[2]]} & /@           Ei[9][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Magenta}, Axes -> False];     datap11 =        ListPlot[{{Er[10][[#, 1]], U[#, 10] /. solmd[[2]]} & /@           Ei[10][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Gray}, Axes -> False];     datap12 =        ListPlot[{{Er[11][[#, 1]], U[#, 11] /. solmd[[2]]} & /@           Ei[11][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Cyan}, Axes -> False];     datap13 =        ListPlot[{{Er[12][[#, 1]], U[#, 12] /. solmd[[2]]} & /@           Ei[12][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Purple}, Axes -> False];     datap14 =        ListPlot[{{Er[13][[#, 1]], U[#, 13] /. solmd[[2]]} & /@           Ei[13][[All, 1]]}, Joined -> True, PlotRange -> {{2, 6}, All},         Frame -> True, PlotStyle -> {Darker[Blue]}, Axes -> False];     p = Show[datpl, datap2, datap3, datap4, datap5, datap6, datap6,         datap7, datap8, datap9, datap10, datap11, datap12, datap13,         datap14];     plot = autoLegend[       p, {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",         "M"}, Background -> Directive[LightOrange, Opacity[.5]],        Alignment -> {Right, Top}]     Export["/Users/nazanin/Documents/thesis/results/plot.bmp", plot,       ImageSize -> 900]      but when I get my plot it looks pixelated, and also if I try to export as jpg it compress the picture hugely and my version of mathematica(8.04) seems not to understand the command "CompressionLevel" though it gives me no error. ![my plot](http://i.stack.imgur.com/lgFuf.png)


title: The plot of roots of polynomials

text: I have polynomial equation like Tribonacci Polynomials for example: $T_3(x)=x^4+x$. After finding the roots of this polynomial, I want to show these roots in the complex plane. I have tried lots of methods as follows but I haven't found one that worked:               f[x_] := x^4 + x;     ListPlot[x /. Solve[f[x] == 0, {x}]]


title: How to create internally optimized expression for computing with high WorkingPrecision?

text: I have large dataset and need to fit rather complicated function on it with different values of one of its parameters (this parameter must be fixed in every fit). I use the `"LevenbergMarquardt"` algorithm of `FindMinimum` as described here (with the only difference that my function is not a "black- box"). I notice that if I set               Method -> {"LevenbergMarquardt",         "Residual" -> Sqrt[2] residualVector[optimVariables],         "Jacobian" -> {"Symbolic", EvaluationMonitor :> ++steps}}      then `FindMinimum` takes 5 minutes to create an optimized form of symbolic jacobian and after this every evaluation of the jacobian takes only 2 seconds. I need to fit my function with many different values of the parameter and to spend 5 minutes for making the jacobian that is identical for all the fits (with exception for the value of only one parameter) is a waste of time. I tried to compute symbolic form of the jacobian by myself and got identical results with automatic symbolic jacobian. I used the code:               jacobianMatrix[_List?(VectorQ[#, NumberQ] &)] =          D[Sqrt[2] residualVector[optimVariables], {optimVariables}]      and               Method -> {"LevenbergMarquardt",         "Residual" -> Sqrt[2] residualVector[optimVariables],         "Jacobian" -> {jacobianMatrix[optimVariables], EvaluationMonitor :> ++steps}}      The problem is that each evaluation of this symbolic jacobian with numerical values of parameters takes 4 minutes! Obviously `FindMinimum` optimizes its internal representation in some way and it gives huge speedup. But `FindMinimum` creates the jacobian for every fit again. Is it possible to optimize the internal representation manually? **I should stress that I compute with`WorkingPrecision` higher than `MachinePrecision`. So probably compilation is not an option.**


title: Sorting a large file

text: I have some huge logs, which are text files, containing up to a million rows each, and I need them sorted. Because trying to import one obviously makes _Mathematica_ run out of memory, we must rule out approaches like this               data=Sort/@Import[fileIn,"Lines"];     Export[fileOut,data,"Lines"];      At the present moment I use a childish method, splitting the file to be ordered in ten files 0.txt ... 9.txt, where k.txt contains only lines starting with the figure k; ordering each (as above) and, finally, gathering them. It works fine in some respects but it's deadly slow, even on a solid state hard disk. Does _Mathematica_ ( 8.0 or 9.0 ) provide any built-in support or package for sorting files? Any suggestion is highly welcome! ADDENDUM : 2014 03 21 Firstly I apologize for my poor English and I thank for you adjusting: I will attend english.stackexchange.com, promise. I'm good enough in "from English to Italian" but I still walk backward on a finely greased, splippery, floor. I have put a piece of my code here: https://www.dropbox.com/s/i9l4atcfwhcmg5q/fileSorter%20ver.%204.2%20unformatted.%20.zip It operates splitting a file over and over again, up to pieces loadable in RAM, sorting them and sticking all togheter. It works as intended but deadly slowly: sorting a file containing 10^7 records, a string of length 10^3 each, takes around two hours on my pc (P4 1,8 GHz, 2 Gb RAM, SSD) because of a wasteful cutting method. At present moment I'm improving it to a single pass knife. I'm thoroughly studying the Stream[] based hint you provided, also The dabaase to be sorted is precisely structured; it' a tab delimited list of files, located on external hard disks : file size, unit serial number, unit label, file date, file hash (crc32), file hash (crcmd5), filedate, folder, file base name, file extension


title: Integral not being evaluated

text: I'm trying to do the following integral, but Mathematica won't evaluate it - it just spits out the actual symbollic integral (sorry I'm not sure how to copy the output into this post so it appears as it does in the notebook!).               a = 1;     b = 1;     c = 0;     d = 0.0001;          Integrate[((2*Pi*a^2)^(-1/4)*          Exp[-(k - d)^2/(4*a^2)])^2 * (Abs[           1 + ((k - d + (I*c/2) - (I*b/2))/ (k - d + (I*c/2) + (I*b/2)))]/          2)^2, {k, 0, Infinity} ]      Can anyone tell me what I'm doing wrong? Thanks


title: Nested NDSolve with WhenEvent: setting up new equations and discarding old ones

text: I am checking a complex situation where a function `x1[t1]` only exit in a finite time span, and after this a new function `x2[t2]` will be set up according to the final value of `x1`, and then repeat the same procedure to build `x3[t3]`, ..., `xn[tn]`. A most simple 3-nest toy code can be rawly formatted like this               d0 = 1;     {c1, c2, c3} = {1, 2, 3};     end=20;          res1 = NDSolve[{        x1'[t1] == c1, x1[0] == 0,        WhenEvent[x1[t1] == d0,         res2 = NDSolve[{            x2'[t2] == c2, x2[t1] == x1[t1],            WhenEvent[x2[t2] == 2*d0,             res3 = NDSolve[{                x3'[t3] == c3, x3[t2] == x2[t2]                }, x3, {t3, t2, end}, MaxSteps -> 1000000];             "StopIntegration"             ]}, x2, {t2, t1, end}, MaxSteps -> 1000000];         "StopIntegration"         ]}, x1, {t1, 0, end}, MaxSteps -> 1000000];      We can now check `res1`, `res2` and `res3`, and they work. But I hope that this code can be more concise than its current state, like how we discard the previous functions and code the remaining inner-nest part, especially for multiple-nest cases, ie. a 100-nest case. I think the most proper way would be to go meta-programming together with recursion... am I right? * * * **Update** Based on Albert Retey's answer, we can furthe treat x[t] as a vector function, like this               cVals = {{1, 1/2}, {1/3, 1/4}, {1/5, 1/10}};     tvals = {5, 10, 20};     tstart = 0;     xsol = Quiet[        NDSolveValue[{          x'[t] == cVals[[n[t]]], x[tstart] == {0, 0}, n[tstart] == 1,          WhenEvent[t == tvals[[n[t]]],           If[TrueQ[n[t] < Length[cVals]], n[t] -> n[t] + 1, "RemoveEvent"]]          }, x, {t, tstart, 20},         DiscreteVariables -> {Element[n, Integers]}, MaxSteps -> 1000000         ], Part::pspec];          Plot[xsol[t], {t, ##}] &[Sequence @@ xsol["Domain"][[1]]]      ![enter image description here](http://i.stack.imgur.com/ZQa8d.png) Where we used `cVals = {{1, 1/2}, {1/3, 1/4}, {1/5, 1/10}}`. I think the code can be more general if we can use something like `cVals = {1, {1/2, 1/3}, {1/4, 1/5, 1/6}}` so that the `x[t]` can have variable dimensions at different time scopes. I wonder if this idea is feasible? * * * **Update 2** Here is a first try, which shows the idea, but the code does not work yet...               cVals = {1, {1/2, 1/3}};     tvals = {5, 10};     tstart = 0;     xsol = Quiet[        NDSolveValue[{          x'[t] == cVals[[n[t]]], x[tstart] == 0, n[tstart] == 1,          WhenEvent[t > tvals[[n[t]]],           If[TrueQ[n[t] < Length[cVals]],            xv = x[t];            n[t] -> n[t] + 1;            x[t] -> {xv, xv},            "RemoveEvent"]]          }, x, {t, tstart, 20},         DiscreteVariables -> {Element[n, Integers]}, MaxSteps -> 1000000         ], Part::pspec];          Plot[xsol[t], {t, ##}] &[Sequence @@ xsol["Domain"][[1]]]


title: A design of abstract data structures: How robust is the presented design?

text: EDIT: An envisioned answer to this post should be in the form of a mathematica code that can demonstrate how the internal checks discussed below can be bypassed. Everything goes... On my part, I think the system should be relatively safe, but I would like to be sure. See it as a challenge. I know that this question has been asked many times. This is my take at it. Ideas are not mine, they are borrowed from many posts on this site. Below is the core of the best setup that I came up with (that I think will work for me). I designed it to be very robust and lightweight. I've spent quite some time testing different possibilities. I realized that the issue was how to design a system that flows well with _Mathematica_ and at the end it was all about evaluation control, the standard, versus non-standard (i.e. the use versus an assignment), and an interplay between general and specific definitions. I departed from the `OBJ[id_]@f1 := f1[id]` design by keeping the `OBJ` and the field `f1` tightly together. The challenge was to control the evaluation and detect incorrect use (more below). The question is whether the setup is indeed robust/safe. I would encourage everyone to find a way to abuse the system below. This will help me get an idea of how robust/safe the system is. AN ADS SYSTEM BEGIN:               objectExistsQ[___] := False;     registerObject[___] :=       Print["cannot register object: invalid id structure."]     registerObject[id_] := (objectExistsQ[id] = True);     isFieldQ[___] := False;          neo = "attempt to use non-existing object";     nef = "use of non-existing field";     nif = "attempt to use non-initialized field";          OBJ[id_] := Print[neo] /; ! objectExistsQ[id];     OBJ /: HoldPattern[_[___, OBJ[id_]@fm_, ___]] :=        Print[nef] /; ! isFieldQ[fm];     Protect[f1]; isFieldQ[f1] = True;     HoldPattern[OBJ[id_]@f1] := Print[nif];      AN ADS SYSTEM END: Assume that the code above cannot be changed. Is it possible to bypass all the checks while using it (i.e. while constructing expressions that involve `OBJ[id]@f1`)? (NOTE: naturally, the print statements are to be implemented as interrupts.) EDIT: Imagine that there is a package that, once invoked, prepares the definitions above and seals definitions of OBJ etc. Alternativelly, OBJ is defined in the Private scope of the package and cannot be directly accessed. The specifications are like this: obj not initialized, has to fail already on object               OBJ[$1]@f1     (* attempt to use non-existing object *)      and even if non-existing field is used               OBJ[$1]@f4     (* attempt to use non-existing object *)      when the object is initialized it has to fail on non-initialized field               registerObject[$2];         OBJ[$2]@f1      (* attempt to use non-initialized field *)      if the field does not exist it has to say that               OBJ[$2]@f4     (* use of non-existing field *)      assignment on non-existing object has to fail               OBJ[$3]@f1 = 1     (* attempt to use non-existing object *)      ibid if used on non existing field               OBJ[$3]@f4 = 1     (* use of non-existing field *)      assignment on registered (created) object has to work               registerObject[$4]         OBJ[$4]@f1 = 1      but fail if the field does not exist               OBJ[$4]@f4 = 1     (* use of non-existing field *)      Is it possible to construct a piece of _Mathematica_ code ... `OBJ[id]@f1`... so that, e.g., the following erroneous assignment is being made               registerObject[$1];         ...         OBJ[$1]@f2 = 3      ...      Note that in the code above a non-existing field is being used. EDIT 2: More specifically, I am working on a phraser that will (1) prepare the THE ADS system described in the beginning of the post (2) convert "source" code, for example, THIS@instanceMethod[args_]:= ( ... THIS@f1 = 1; THIS@f2 = THIS@f1 + args; ... ) into OBJ[id_]@instanceMethod[args_] := ( ... OBJ[id]@f1 = 1; OBJ[id]@f2 = OBJ[id]@f1 + args; ... ) I am asking, very, very specifically: is the design I have present good from the safety of use point of view? Is it possible to find an example of the source code which will "cheat" all the safety rules implemented into the ADS system? For example, I worry that one might use AppendTo or simmilar constructs to perform wrong initializations. For example, the outcome of AppendTo[OBJ[1]@f4, value], depends on how AppendTo internally behaves (e.g. if it holds the first argument or not, how it behaves when it encounters a non-initialized List as the first argument etc). Of course, one can try the command and see, but I cannot possibly try all such commands. I would like to form a general opinion, thus the question. Regards, Zoran


title: Specifying Table/grid dimensions in version 7

text: The result of my calculations is quite large list (nested list to be precise). I would like to improve its visualization, to make it more legible, by setting the number of columns to let's say 5. Documentation Center suggests an option `AllowedDimensions`, but it is new in ver 9. How can I make it happen in version 7? Thanks for any hints. **Edit:** The list has two sublists of equal length, simple example would be:               list={{45.1,73.5,12.9,56.4,114.6,87.1,90.5,263.8,99.3,104.6},          {0.34,0.12,0.56,0.95,0.25,0.57,1.03,0.73,0.92,1.02}};      **Edit 1:** After setting the number of columns to 5 it should look more or less like this:               {{45.1,73.5,12.9,56.4,114.6,       87.1,90.5,263.8,99.3,104.6},      {0.34,0.12,0.56,0.95,0.25,       0.57,1.03,0.73,0.92,1.02}};


title: How to return escaped characters from MathLink?

text: I'd like to return Greek symbols through MathLink from a C function. However, returning the usual escape sequence (such as \[Alpha]) does not seem to work. Here's a minimal example .tm file (myalpha.tm) which creates a function that should simply return \[Alpha] :               void myAlpha P(( ));          :Begin:              :Function:          myAlpha     :Pattern:           myAlpha[ ]     :Arguments:         { }     :ArgumentTypes:     { }     :ReturnType:        Manual     :End:          #include "mathlink.h"     void myAlpha() { MLPutSymbol( stdlink, "\\[Alpha]" ); }     int main(int argc, char *argv[]) { return MLMain(argc, argv); }      To compile it (on OSX) I use :               /Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/CompilerAdditions/mprep myalpha.tm -o myalphatm.c     /usr/bin/clang -c -I/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/CompilerAdditions myalphatm.c     /usr/bin/clang++ myalphatm.o -L/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/CompilerAdditions -lMLi3 -lstdc++ -framework Foundation -o myalpha      And to run it I execute this little script :               link = Install["<fullpath>/myalpha"];     myAlpha[];     Print[%]     Uninstall[link]      Inside a Mathematica notebook this produces some binary symbol, and if I run it with MathKernel from the commandline then I get :               $IterationLimit::itlim: Iteration limit of 4096 exceeded.         Hold[Out[$Line - 1]]      My guess is that I haven't escaped everything correctly in the C string, but I'm not sure what the right escape sequence is. Since \ is the escape character in C I have escaped that, so the C-string reads "\\[Alpha]" and I've tried a variety of other options but to no avail.


title: Properly applying BandstopFilter

text: In the documentation about BandstopFilter it says that the cutoff-frequencies `w1` and `w2` in `BandstopFilter[data,{w1,w2}]` should be values between 0 and Pi. I am certain that this is helpful information for someone more knowledgeable than me, but I cannot figure out how to apply it to my specific problem. I have time-series data acquired at fixed sampling rate (1 kHz) of a certain duration (let's say 20.000 data points). The data is contaminated with 50Hz line noise. How do I properly set up `w1`and `w2`, as a function of the sampling rate and the length of the data, to properly reduce the 50Hz contamination? Incidentally, it would be nice to have an appropriate example in the documentation.


title: Pattern matching in nested lists

text: I'm sure this has been asked before, but I can't find the right combination of search keywords to find it. Apologies. I want to do a `ReplaceAll` on a list of lists, for example, I would like:               {{a, b}, {c, d}} /. {i_, j_} -> {i, j, 0}      What I want is to turn this list into `{{a,b,0}, {c,d,0}}`, but I can't figure out a way to tell Mathematica to only look at lists that are one level "below". Running the above returns `{{a, b}, {c, d}, 0}`, as `i` matched `{a,b}` and `j` matched `{c,d}`. How do I pattern match lists that nested?


title: Need help with solving a second order differential equation

text: I need help with solving this differential equation.               DSolve[       {D[x[r], {r, 2}] + (1/r) D[x[r], r] + (1 - 1/r^2) x[r] - x[r]^3 == 0,         x[0] == 0, x[Infinity] == 1}, x[r], r]      I tried to solve this with `DSolve`, but no success. Any suggestion is highly appreciated.


title: Maximization of a function within a unit square

text: I work in a unit square. I have some conditions under which areas within the unit square are defined. Say for simplicity that there are two conditions which define two areas. For example, if y > 1/2 or if y > ax + b , we are in area 1 and otherwise, in area 2. I have represented two possible situations in the figures (Case 1 Case 2) I want to find a and b (which are strictly positive) such that a*(area 1) + b*(area 2) is maximized. I think this is an easy problem to solve by hand, except if you have 7 different conditions. I am wondering if there is a way to automate that in Mathematica. The problem I have is that as conditions change, the shapes of the areas also change, which makes it difficult to compute them automatically (see the figures). I would already be very happy if I could find all possible shapes given my seven conditions. Anyone has an idea ?


title: Power::infy: error using FindFit

text: I have a 2D data to fit (the Airy type pattern from diffraction of Gaussian beam on the circular aperture). Please see the attached picture. I was going to use a function like `BesselJ[1, x]*BesselJ[1, y]/x/y` for that. But there is an error about infinity at zero. > Power::infy: "Infinite expression 1/0.^2 encountered. The problem related to the FindFit (or NonlinearModelFit) procedure trying to calculate Jacobian at this point and finding infinity there. I tried to use some tricks such as specify the method (`Method -> "PrincipalAxis"` or `"Gradient"`), but these do not help. Will appreciate any suggestions! ![enter image description here](http://i.stack.imgur.com/eUcG8.png) My code:               (* Write images as numerical 2D array, find max and min (=background) \     values for each image *)     For[k = 0, k < dim0, k++;       data02[k] = ImageData[data01[k]];       min02[k] = Min[data02[k]];       max02[k] = Max[data02[k]];       ];          (* substrack the backgound and normilize to the max value *)     (*Read each 5-th pixel on the image to speed up the program, later \     multiply by that number to get      correct value for the beam size*)     ReducPix = 5;     For[k = 0, k < dim0, k++;       data03[k] =         Table[ (data02[k][[i]][[j]][[1]] - min02[k] + 0.0001)/max02[k], {i,           1, dim01b, ReducPix}, {j, 1, dim01a, ReducPix}];            ];          Bessel3D =        a0 (BesselJ[1, a2 (x0 - a1)]*          BesselJ[1, b2 (y0 - b1)]/(a2 (x0 - a1))/(b2 (y0 - b1)))^2;          data3D[13] =       Flatten[MapIndexed[{#2[[1]], #2[[2]], #1} &, data03[13], {2}],        1]; found it here \     http://mathematica.stackexchange.com/questions/27642/fitting-a-two-\     dimensional-gaussian-to-a-set-of-2d-pixels/27643#27643?newreg=\     2edd44e8d4d0498aa9afc19085d228f8*)          (*fit=NonlinearModelFit[data3D[13],Bessel3D,{{a0,1},{a1,75},{a2,20},{\     b1,50},{b2,20}},{x0,y0},Gradient\[Rule]"FiniteDifference"];  *)


title: Plotting Network with LayeredGraphPlot with specific order

text: I have a network and want to plot it. I use `LayeredGraphPlot`, and the network is described as:               NetList={"A1" -> "a1", "A1" -> "b1", "b1" -> "A2", "a1" -> "a2", "A2" -> "b2",     "A2" -> "c2", "a2" -> "B3", "b2" -> "B3", "c2" -> "c3", "B3" -> "a3",     "B3" -> "b3", "a3" -> "A4", "b3" -> "A4", "c3" -> "c4", "A4" -> "a4",     "A4" -> "b4"};     LayeredGraphPlot[NetList, Bottom, VertexLabeling -> True]      Result: ![GraphPlot](http://i.imgur.com/CK4jsPu.png) I have two question: _1) Main question:_ How can I tell `LayeredGraphPlot` to put all `a1, a2, a3, a4` in one vertical line, and `b1, b2, b3, b4` in one line, and `c2, c3, c4` in one vertical line? (the `c`-elements are already in a vertical line coincidencely for this network). _2) Minor question:_ If I only want to have labeling for certain elements (such as the upper-case Elements `A1, A2, B3, A4`), how can I modify the LayeredGraphPlot-instruction? **Update** ad1) One methode to do this is `VertexCoordinateRules` - i'm afraid it doesnt get much easier than that. **Update2** With the nice solution of hftf (below), the example above works perfectly. However, there is a problem with different networks. When I have:               NetList={"A1" -> "a1", "A1" -> "b1", "b1" -> "A2", "a1" -> "a2", "A2" -> "b2",         "A2" -> "c2", "a2" -> "B3", "c2" -> "B3", "b2" -> "b3", "B3" -> "a3",         "B3" -> "c3", "a3" -> "A4", "c3" -> "A4", "b3" -> "b4", "A4" -> "a4",         "A4" -> "c4"};     GraphPlot[NetList, VertexLabeling -> True, VertexCoordinateRules -> coords,          DirectedEdges -> True]      I get the following: ![GraphPlot2](http://i.imgur.com/UzNjasL.png) The problem is, that `b2` -> `B3` and `b3` -> `A4`, even though there is no rule in `NetList` for that. It happens because `B3` and `A4` are somehow _in the way_ of b. In the documentary of `LayeredGraphPlot`, there are several examples how edges _go around_ vertices that are in the way. But I could not get that work for my example. The error it tells me is > LayeredGraphPlot::vprmtd: Warning: the VertexCoordinateRules option with > rule list value is only supported for the SpringElectricalEmbedding method. > Switching to the SpringElectricalEmbedding method. If I try using `SpringElectricalEmbedding`, it complains about the `VertexCoordinateRules`. Is there a simple way around these hurdles? On solution would be to define the positions of As and Bs at some fractional position. But maybe there is some nicer way, where the edges go around the vertices in the way?


title: Export CSV from tables

text: I am reading my csv which looks like: float,float,float,integer,boolean I read it with:               table = Take[Import["~/myfile.csv"]];     x = table[[All, 1]];     y = table[[All, 2]];     z = table[[All, 3]];     time = table[[All, 4]];     bool = table[[All, 5]];      Then I do some job with x,y,z and I need to export it back to csv. But I dont know how to get the table to export.


title: Creating nested matrix using random integers

text: How do i create 15x2 matrix with 2x2 random integer elements? My code only returned identical 2x2 elements: ![This is what i get when i tried to do that.](http://i.stack.imgur.com/zAJmd.png)


title: Square root of a value defined in a finite field?

text: I am trying to find the right way to compute the square root of a number defined in a finite field. For example,               << FiniteFields`     In[18]:= Sqrt[GF[17][{8}]]     Out[18]= Sqrt[Subscript[{8}, 17]]      Results in an incorrect answer. The correct answer is `5`.


title: Random variation inside NMaximize

text: I am using `NMaximize` as following code.               NMinimize[{x[1] + x[1]^RandomVariate[NormalDistribution[1, 30]] +      x[2] + x[3] + x[4] + x[5] +      RandomVariate[NormalDistribution[5, 3]] x[5],      RandomVariate[NormalDistribution[5, 3]]*x[1] + x[2] > 3 &&      x[3] > 1 && x[4] > 0 && x[5] > 0 && x[1] <= 1 && x[2] <= 8 &&      x[3] <= 1 && x[4] <= 1 && x[5] <= 2}, {x[1], x[2], x[3], x[4],      x[5]}]      I want to variate random variables for 100 times and capture the optimized data including the maximized function values and all variables for each time.What will be the best way to capture them? of course the situation there is no answer and also unboundedness have to be taken into the account.


title: Insert a linebreak and character repeatedly into a very long string

text: Suppose I have a very long string `x=2*g*o*p*s*v-2*B*g*o*p*s*v*w+2*a*c*g*m*o*p*s*v+2*c*g*m*o*p*s*v*B-2*a*c*g*m*o*p*s*v*B+3*g*m*o*p*s*v*B-3*B*g*m*o*p*s*v*w*B+m*w**2*B +5*a*c*g*m**2 +o*p*s*v*B -a*c*m**2*w**2*B +c*g*m**2*o*p*s*v*B* - 3*a*c*g*m*o*p*s*v*+c*m**2-w**2*B-a*c*m**2-w**2*B....)` etc that goes on for almost 1000 lines. When exported to a .txt file, the file is >100MB. I want to use the expression in Fortan and Fortan will not accept lines greater than 100 characters or so. To the string `x`, is it possible to insert a linebreak every 100 characters and insert `&&` at the end of each line and at the beginning of the next line?


title: Why is the new PositionIndex horribly slow?

text: Disconcertingly I have discovered that the new (v10) `PositionIndex` is horribly slow. Using Szabolcs's clever `GatherBy` inversion we can implement our own function for comparison:               myPosIdx[x_] :=       <|Thread[x[[ #[[All, 1]] ]] -> #]|> & @ GatherBy[Range @ Length @ x, x[[#]] &]      * * * **_Edit:_** I should have used `AssociationThread` in defining my function as it performs better:               myPosIdx2[x_] :=        x[[ #[[All, 1]] ]] ~AssociationThread~ # & @ GatherBy[Range @ Length @ x, x[[#]] &]      Timings below and Taliesin Beynon's analysis refer to the original version; changes would be minor. * * * Check that its output matches:               RandomChoice[{"a", "b", "c"}, 50];          myPosIdx[%] === PositionIndex[%]      > >     True >   Check performance in version 10.0.0 under Windows:               a = RandomInteger[99999, 5*^5];     myPosIdx[a]      // Timing // First     PositionIndex[a] // Timing // First      > >     0.140401 >   >     0.920406 >   Not a good start for the `System`` function, is it? It gets worse:               a = RandomInteger[999, 5*^5];     myPosIdx[a]      // Timing // First     PositionIndex[a] // Timing // First      > >     0.031200 >   >     2.230814 >   With fewer unique elements `PositionIndex` actually gets _slower!_ Does the trend continue?               a = RandomInteger[99, 5*^5];     myPosIdx[a]      // Timing // First     PositionIndex[a] // Timing // First      > >     0.015600 >   >     15.958902 >   Somewhere someone should be doing a face-palm right about now. Just how bad does it get?               a = RandomInteger[9, 5*^5];     myPosIdx[a]      // Timing // First     PositionIndex[a] // Timing // First      > >     0.015600 >   >     157.295808 >   Ouch. This has to be a new record for poor computational complexity in a System function. :o


title: What leads to Mathlink connection lost when running

text: My C program called Mathematica several times during the execution. However, after 4 or 5 times Mathematica stopped and then I got this message. > /home/sec/.Mathematica/Licensing/mathpass:3: The Mathematica license you are > using has expired. Please contact Wolfram Research or an authorized > Mathematica distributor to extend your license and obtain a new password. > Error detected by MathLink: MathLink connection was lost.. Is this the licence problem or technical problem? I am using Mathematica 9 Student right now. Thanks,


title: Is there any way to allow a message to appear more than three times before General::stop shuts it off?

text: I have some Mathematica code that analyzes data in a database and uses `Message` to report when expected data is missing. By default, Mathematica will allow this message to appear only three times before it gets shut off, but I'd like this message to appear as often as the errors do. The solutions I can think of are               Off[General::stop];      but this kills limits for all error messages, not just this one, or just to switch to `Print`, which seems inelegant. Is there some way to allow this one message to appear more than three times, while leaving behavior unchanged for the rest?


title: Generate a Unit Circle Trigonometry

text: Struggling often with Trigonometry I would like to have some code to generate this Unit Circle Trigonometry. Would be of great help when I need to transform some data : ![enter image description here](http://i.stack.imgur.com/r8uHr.gif)


title: kernel Local crashes during the course of a For loop

text: I want to find the minimum of the function `r[x,p]` subject to the constraint `w[x,p,t]==0` (`t` is a fixed parameter). To find the minimum I use the function `NMinimize`. The constraint `w[x,p,t]==0` is a rather complicated numerical function. It depends on the function `evolve[x,p,t]` which is the numerical solution of some ordinary differential equation. I use a `For` loop to find the minima for different values of the constraint parameter `t`. My problem is the following: At certain instants of time, the kernel Local quits without errors or warnings before the loop is finished. The error message is "The kernel Local has quit (exited) during the course of an evaluation". The time when the kernel quits is always different, sometimes it happens very early, sometimes rather late. When I evaluate `NMinimize` for the parameter `t` where the kernel crashed (and also for parameters beyond that point), it works well without any error. First I thought the reason for the crash could be a lack of memory, but if I monitor the memory during the calculation, everything looks fine. Here is the code of a simplified version of my problem.               (*definition of the constraint*)     h[x_, p_] := -x^2 + p^2 + x^4;          evolve[ xini_, pini_, time_] :=       Module[{x, p, t},        Hold[{x[time], p[time]} /.         NDSolve[{x'[t] == p[t], p'[t] == -x[t], x[0] == xini, p[0] == pini}, {x, p},                 {t, 0, time}, MaxSteps -> Infinity][[1]]      ]];          w[x_?NumericQ, p_?NumericQ, t_?NumericQ] := h @@ ReleaseHold[evolve[x, p, t]] - h[x, p];          (*definition of the function which should be minimized*)     r[x_, p_] := {x - 1, p}.{{0.1, 0}, {0, 0.1}}.{x - 1, p};          fct = First[{Print[#];       NMinimize[{r[x, p], w[x, p, #] == 0}, {x, p},        Method -> "NelderMead", MaxIterations -> 10^3]}] &;          (*loop over different parameters t*)     dt := 0.05;     tmin := 0;     tmax := 40;     maxt := Floor[(tmax - tmin)/dt];     times = Table[tmin + dt*n, {n, 0, maxt}];          positions = Table[0, {Length[times]}];     values = Table[0, {Length[times]}];          For[n = 1, n <= Length[times], n++,       tmp = fct@times[[n]];       positions[[n]] = {x, p} /. (tmp[[2]]);       values[[n]] = tmp[[1]];     ];      When I replace the loop over `t` by               fct/@times;      I get the same error. I am using _Mathematica_ 9.0.1.0


title: How to impose custom style to the edges of a graph

text: We construct a graph as the following.               node = {11, 12, 13, 14, 15, 16};     edges = {11 -> 14, 11 -> 16, 12 -> 16, 12 -> 15, 13 -> 15, 13 -> 16,               14 -> 16, 14 -> 15, 15 -> 16, 15 -> 13, 16 -> 15, 16 -> 14};     vertexposition = {{6.51493919050084`, 44.04756585632944`},          {75.59445680043342`, 50.47455242214042`},          {87.32825501506514`, 13.395648943951699`},          {28.795707353492418`, 3.420138063734413`},          {60.729164933330765`, 16.915777496473908`},          {51.85158892659126`, 25.803692768150313`}};     Show[         Graph[node, edges, VertexCoordinates -> vertexposition,                VertexSize -> {"Scaled", .02},VertexLabels -> "Name"],         Frame -> True, FrameTicks -> True, ImageSize -> 600]      ![enter image description here](http://i.stack.imgur.com/o7hDI.png)   1. Now in the above graph how can I can control the size of the `Arrowheads` and thickness/color/opacity of the lines?   2. Is there any options that I can use to make the graph aesthetically more eye catching (sorry for using a qualitative term!)?   3. Without using `Show` can I display the frame and the axes values directly in a `Graph`?


title: Why does Export drop namespace prefixes in the exported XML file?

text: I am trying to generate an Excel-compatible XML file from _Mathematica_. First, I created a test XML file by saving a Microsoft Excel workbook as "XML Table". Then I `Import`ed this file:               XMLdata = Import["test.xml", "IncludeNamespaces" -> True]      Now I am `Export`ing this back to XML:               Export["test_exported.xml", XMLdata, "AttributeQuoting" -> "\""]      The generated file cannot be opened by Excel. Comparing it with the original file shows that most of namespace prefixes are dropped although they were present in `XMLdata`. Why does this happen? How can I correctly `Export` an XML file which will be compatible with Excel?


title: Having problems compiling Mathematica Cuda code

text: Ok I am trying to follow the examples of Cuda Code in the docummentation Run the `CUDAQ[]` and get back a `True` and run some of the first examples of Cuda code in the documentation and they also work but when I try               doubleFun = CUDAFunctionLoad["       __global__ void doubleVec(mint * in,  mint length) {           mint index = threadIdx.x + blockIdx.x * blockDim.x;               if (index < length)               in[index] = 2*in[index];         }", "doubleVec", {{_Integer}, _Integer}, 256]      This example is to multiply a vector by 2 I get the following error code               CUDAFunctionLoad::noxcomp: A C compiler was not found in specified directory `1`.      Set"XCompilerInstallation" to the directory containing a supported C compiler.         Supported C compilers are detailed in the NVCCCompiler documentation page. >>      It looks like mathematica does not know where my C compiler is at and needs to be define I look in the documentation and I do not see how to do that. I am using OS X for Mac and from the above error message they are asking me to set XCompilerInstallation to the directory containing the C compiler, I also have installed XCode. What should I do next?


title: Inserting a jpeg image at a specified point in the XY-plane

text: I know how to import an image into Mathematica using the `Import` command. The original image can come from anywhere, but call this image "myimage" after importing into Mathematica Now my problem is how to insert this image at the point with coordinates (2,3) in the XY-plane. I know how to insert certain text at a prescribed place, but with imported images, I am not sure how to do it. Any help will be greatly appreciated!


title: How to calculate the distance between UTM-projected coordinates?

text: My coordinates are projected using the following projection:               proj= {"UTMZone32", {"GridOrigin" -> {500000, 0}, "CentralScaleFactor" -> 0.9996}};      Now I wish to calculate the distance between two points (ignoring elevation), e.g.               p1= GeoGridPosition[{359577, 5.51291*10^6,0}, proj]     p2= GeoGridPosition[{509108, 5.972*10^6,0}, proj]      When I try `GeoDistance`               GeoDistance[p1,p2]      it fails with the error message > >     GeoDistance::invparam: "Invalid parameters > \!\(\"GeoGridPosition[{359577, 5.51291*^6, 0}, >     {\\\"UTMZone32\\\", {\\\"GridOrigin\\\" -> {500000, 0}, >      \\\"CentralScaleFactor\\\" -> 0.9996}}]\"\). " >   Also, the `GeoPositionXYZ` function, as in               GeoPositionXYZ[p1]      fails with the error messages > >     ToString::nonopt: Options expected (instead of InputForm) beyond > position 2 in > > ToString[None,{GridOrigin->{500000,0},CentralScaleFactor->0.9996},InputForm]. >     An option must be a rule or a list of rules. >> >   >     GeoGridPosition::invparam: "Invalid parameters ToString[\!\(None, { >      \"GridOrigin\" -> {500000, 0}, \"CentralScaleFactor\" -> 0.9996`}, > InputForm\)]." >   >     GeoPositionXYZ::invcoord: "\!\(\"GeoPosition[GeoGridPosition[{359577, > 5.51291*^6, 0}, >     {\\\"UTMZone32\\\", {\\\"GridOrigin\\\" -> {500000, 0}, > \\\"CentralScaleFactor\\\" -> >     0.9996}}]]\"\) is not a valid coordinate specification." >   Both functions work, however, when I switch `proj` to the string `UTMZone32`. Do I need to get the full projection specification to work? _EDIT_ : After some further googling, I realized that in UTM coordinates the distance between two points is simply               Norm[{p1[[1,1;;2]]-p2[[1,1;;2]]}]      so I would answer my own question with no.


title: How to access off-cell mouse position inside an EventHandler?

text: Consider the following example. First, I print the dynamically updated value of the actual position of the mouse, then I print `pt`, which is the same but is only updated when the `EventHandler` object (a grey rectangle) is clicked and dragged.               Dynamic@MousePosition@"ScreenScaled"     Dynamic@pt     Deploy@EventHandler[       Graphics[{Gray, Rectangle[]}, ImageSize -> 50, AspectRatio -> 2],       {"MouseDragged" :> (pt = MousePosition@"ScreenScaled")}]      This has two issues:   1. While `Dynamic@MousePosition@"ScreenScaled"` updates correctly when the mouse moves anywhere on the screen, `pt` is constrained to be updated only in the cell where the `EventHandler` is when the rectangle is dragged. The `EventHandler` **DOES** register and display movement outside the gray `Rectangle` (and thus outside the `EventHandler`), though it **DOES NOT** register movement outside of the cell. Whenever the dragged mouse leaves the cell where the `EventHandler` resides, the updating stops. Whenever the dragged mouse enters the cell, the updating continues.   2. When the rectangle is dragged, not even `Dynamic@MousePosition@"ScreenScaled"` gets updated outside of the cell, though it has nothing to do with the `EventHandler`, and it is updated correctly on its own (i.e. when EventHandler is not triggered). The problem is more general: the mouse coordinates over the full screen cannot be accessed in any construction I've tried, not just in `EventHandler`s. Note that `MousePosition["coords"]` is equivalent to `CurrentValue[{"MousePosition","coords"}]`, and as such, the latter fails as well. **Question: How to access global mouse coordinates in a dynamic structure such as an EventHandler?** **EDIT:** What I want is to create an object (e.g. a button) that accepts/processes/displays the global mousecoordinates **only when** the mouse is dragged.


title: Reflect a Plot Object

text: I have a relatively simple operation I'd like to perform on a plot: I would like to reflect the plot across the x-axis. I do not have any tick labels, so making sure that the labels are not themselves reflected is not a concern. Rotating the plot works as expected:               Rotate[ListPlot[{{0,0},{1,1}},Joined->True],90\[Degree]]      ...but there does not appear to be a "Reflect" command or equivalent that performs a reflection operation. I've tried using GeometricTransformation and Scale, but both of those don't seem to work on plot objects. How should I go about doing this?


title: Processing all files in a folder automatically

text: I have a lot of files in a folder that needs to be process through a function that I have written in Mathematica. I need help writing a code that would process all the files automatically.               TestData = Import["file.xls"];          function[input_] :=       Module[{CellsKey, Datalist, Lastcap, Pdata, filename},       Datalist = {};       CellsKey = TestData[[1]][[1]][[1]];       a = Last[TestData[[1]]];       Lastcap = a[[4]];       (*Print[Lastcap]*)       Pdata = Append[CellsKey, Lastcap]         (*Print[CellsKey]*)         Print[Pdata]     ]      This is what I have so far. With this code, I could only import one file at a time.


title: How to partition a list of numbers in two lists of numbers such that each lists elements sums up to the same number?

text: I have the following list of squares.               {1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256}      Their sum is $1496$, I want to make two partitions with the given numbers and each partition should have a sum of $748$, does Mathematica have a built-in function for that?


title: Notebook vs. DocumentNotebook; display a Notebook inline, like a DocumentNotebook

text: If you evaluate a `DocumentNotebook[]` expression in the front-end, it nicely displays inline, inside of an output cell in the current notebook: ![DocumentNotebook displayed](http://i.stack.imgur.com/pjdQb.png) For my purposes, `TextCell` and `ExpressionCell` expressions are insufficiently flexible. So (as in the question Combination of CellPrint and PrintTemporary, or DisplayForm for Cells), I'm programmatically generating some formatted output that generates raw `Cell[]` box expressions. For instance, the output might be               cell = Cell[TextData[{"Function ",         Cell[BoxData[FormBox[RowBox[{"f","(","x",")"}],             TraditionalForm]], FormatType->"TraditionalForm"]}],        "Subsection"];      (where $f(x)$ will actually be some complicated expression). Unfortunately, `DocumentNotebook[]` seems to require `TextCell`/`ExpressionCell` and doesn't work when given `Cell[]`s: ![DocumentNotebook with Cell](http://i.stack.imgur.com/6acGn.png) So I tried using `Notebook[]` instead, which does work with `Cell[]`s. However, evaluating a `Notebook` expression doesn't display in the front-end: ![Notebook](http://i.stack.imgur.com/YKO1U.png) It displays correctly when I run `NotebookPut@Notebook@{cell}`, but in a new window. **How can I get it to display inline in the current notebook, like how`DocumentNotebook` displays?** I tried wrapping it in `CellPrint` and in `DisplayForm`, but those don't work for `Notebook[]`s. Relatedly, what's the difference between `DocumentNotebook` (and friends) and `Notebook`? Both appear to be intended to represent a notebook as an expression, but as I discovered they behave slightly differently.


title: Showing AlgebraicNumber[1/2 (1 + Sqrt[5]), {-3, 2}] in human-readable way

text: Is there a function to show algebraic numbers in Mathematica more conveniently? I am looking for something similar to MatrixForm for matrices. For example, I would like to view `AlgebraicNumber[1/2 (1 + Sqrt[5]), {-3, 2}]` as `-3 + 2*q`, where `q` is the generator of the number field my algebraic number comes from, i. e. `1/2 (1 + Sqrt[5])` in this case. I searched the documentation concerning algebraic numbers with no success. Something along the lines of `Extract[AlgebraicNumber[...], {2}].{1, x}` works, but it requires tweaking for different fields.


title: How to work with 3D images of STL format

text: After importing a 3D image of STL format, my possibilities in regard to "3D Volumetric Image Processing" seems rather limited. All examples are given with TIFF files. Is there a way to convert from STL to TIFF or work with STL image in some other way?


title: Why are some equal expressions more equal than others?

text: n1 = 1/3 (2 + (-Sqrt[3] + 2 Sin[(2 π)/9])/(Sqrt[3] Cos[π/9] - Sin[π/9]));     n2 = 1/2 + Sin[π/18]/(3 Cos[(2 π)/9] + Sqrt[3] Sin[(2 π)/9]);     n3 = 2/3 (1 - Cos[4 π/9]);      These three expressions are numerically equivalent. How can I coax _Mathematica_ to simplify the first two into the third? `FullSimplify` only returns the original forms.


title: Sort lists of vertices {indegrees, outdegrees} by indegree

text: in = VertexInDegree[F];     out = VertexOutDegree[F];      I want both in and out to be ordered by in. Example: graph has nodes a,b,c with indegrees 1,2,0 and outdegrees 0,1,2. I want lists in = {0,1,2} and out = {2,0,1}. How do I do this? I tried               in = Sort[VertexInDegree[F]];     out = VertexOutDegree[F][[Ordering@in]];      , but this didn't give the expected result.


title: Authorizing use of proprietary code in the cloud?

text: As I continue to refine my working approach to deploying proprietary Mathematica code (see: Prevent package from being opened in a notebook interface and Run encoded package code through .NET/Link?). I've gotten to wondering about a next step. I currently create a pair of compiled Mathematica Libraries. One with my proprietary code and a second which supplies authorizations of machines or users designated to use the libraries. The first calls the second and if the user or the machine does not have permission it closes down the kernel. This works ok, except since I don't develop in a Windows environment I have to do the compilation on a Windows machine in my client's offices. Not the best situation for code security. I started wondering how Wolfram identifies authorized users. I further wondered if one could overload the Wolfram authorization functions for a specific authorized machine or user to use a specific compiled library. Can one access this or use it in this way? Alternatively, does any means exist where I could maintain authorizations in the "cloud"? I could readily update authorizations and I could then simply give the client read only access to the authorization list. This would work great as it could operate independently of platform and any specific libraries or code. It would also make for very easy license maintenance. Mathematica Online, looks promising for this: ![enter image description here](http://i.stack.imgur.com/8tf0E.png) but I don't know when Wolfram will release it. Can anyone suggest a currently viable way to do this?


title: Is there an option to change the space/distance between tick labels and axes labels for plots?

text: In an attempt to squeeze more plots and controls into the limited space for a demo UI, I am trying to remove any extra white spaces I see. I am not sure what options to use to reduce the amount of space between the ticks labels and the actual text that represent the labels on the axes. Here is a small `Plot` example using `Frame->True` (I put an outside `Frame` as well, just for illustration, it is not part of the problem here)               Framed[           Plot[Sin[x], {x, -Pi, Pi},       Frame -> True,       FrameLabel -> {{Sin[x], None}, {x,           Row[{"This is a plot of ", Sin[x]}]}},       ImagePadding -> {{55, 10}, {35, 20}},       ImageMargins -> 0,       FrameTicksStyle -> 10,       RotateLabel -> False       ],           FrameMargins -> 0      ]      ![Mathematica graphics](http://i.stack.imgur.com/JRzf3.png) Is there an option or method to control this distance? Notice that `ImagePadding` affects distance below the frame label, and not between the frame label and the ticks. Hence changing `ImagePadding` will not help here. Depending on the plot and other things, this space can be more than it should be. The above is just a small example I made up. Here is a small part of a UI, and I think the space between the `t(sec)` and the ticks is too large. I'd like to reduce it by few pixels. I also might like to push the top label down closer to the plot by few pixels also. ![Mathematica graphics](http://i.stack.imgur.com/jruyf.png) I am Using V9 on windows. **update 12/22/12** Using Labeld solution by @kguler below is a good solution, one just need to be little careful with the type-sitting for the labels. `Plot` automatically typeset things as `Text` in `TraditionalFormat`, which is a nice feature. To do the same when using `Labeled` one must do this manually using `TraditionalForm` and `Text` as well. Here is example to show the difference **1)** Labeled used just with `TraditionalForm`. The left one uses `Plot` and the right one uses `Labeled` with `TraditionalForm`. Notice the difference in how labels look.               Grid[{       {             Plot[Sin[x], {x, -Pi, Pi}, Frame -> True,          FrameLabel -> {{Sin[x], None}, {x, E Tan[x] Sin[x]}},          ImageSize -> 300, FrameTicksStyle -> 10, FrameStyle -> 16,RotateLabel -> False],             Labeled[         Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, ImageSize -> 300],          TraditionalForm /@ {Sin[x], x, E Tan[x] Sin[x]}, {Left, Bottom, Top},          Spacings -> {0, 0, 0}, LabelStyle -> "Panel"]        }             }, Frame -> All]      ![Mathematica graphics](http://i.stack.imgur.com/MXRlR.png) **2)** Now we do the same, just need to add `Text` to get the same result as `Plot`.               Grid[{       {        Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, FrameTicksStyle -> 10,          FrameStyle -> 16,          FrameLabel -> {{Sin[x], None}, {x, E Tan[x] Sin[x]}},          ImageSize -> 300, RotateLabel -> False],             Labeled[         Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, ImageSize -> 300],          Text /@ TraditionalForm /@ {Sin[x], x, E Tan[x] Sin[x]}, {Left,           Bottom, Top}, Spacings -> {0, 0, 0}, LabelStyle -> "Panel"]        }             }, Frame -> All]      ![Mathematica graphics](http://i.stack.imgur.com/CHhZF.png) **Update 12/22/12 (2)** There is a big problem with controlling the spacing. `Labeled` spacing only seem to work for horizontal and vertical spacing, taken togother. i.e. One can't control spacing on each side of the plot separately? Here is an example, where I tried to move the bottom axes label up, this ended with moving the top label down as well. Which is not what I want.               Labeled[Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, ImageSize -> 300],       Text /@ TraditionalForm /@ {Sin[x], x, E Tan[x] Sin[x]}, {Left,        Bottom, Top}, Spacings -> {-.2, -0.7}]      ![Mathematica graphics](http://i.stack.imgur.com/q0Wdo.png) Will see if there is a way to control each side spacing on its own. Trying `Spacing->{-0.2,{-0.7,0}}` does not work, it seems to take the zero in this case and ignored the `-0.7` This gives the same result as above:               Labeled[Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, ImageSize -> 300],       Text /@ TraditionalForm /@ {Sin[x], x, E Tan[x] Sin[x]}, {Left,        Bottom, Top}, Spacings -> {-.2, -0.7, .0}]      ![Mathematica graphics](http://i.stack.imgur.com/6JCgC.png) ps. there might be a way to specify the spacing for each side with some tricky syntax. I have not figured it out yet. Still trying thing.... http://reference.wolfram.com/mathematica/ref/Spacings.html **update 12/22/12 (3)** Using combination of `ImagePadding` and `Spacing` should have worked, but for some reason, the top label now is cut off. Please see screen shot. Using V9 on windows ![enter image description here](http://i.stack.imgur.com/kbT3G.png) Note: The above seems to be related to the issue reported here: some Graphics output do not fully render on the screen until an extra click is made into the notebook Need an extra click inside the notebook. Then label become un-chopped !


title: NDSolve problems of convergence

text: I have a big function that I have to maximize, so I have to evaluate some equation with thousands of different values of the parameter. But the FindMaximum returns me many errors. I have traced the cause down to a differential equation that is part of the calculation. This differential equation has to be solved as function of the parameter (called "sup" in this case) and even though it is a seemingly "easy" function and I don't need a very high precision, in many points it does not converge and reaches the maximum number of steps. The following is a simplified sample code to view the problem with a Manipulate: as you slide the cursor with the Sup variable the NDsolve produces errors.                    Manipulate[      Module[{pend, tmax}, tmax = 30;        pend = NDSolve[{1.1089 \[Alpha]''[t] + 1.2936 Sin[\[Alpha][t]] +             210*sup*             (0.33 Sin[\[Alpha][t]] + (               0.33^2 Cos[\[Alpha][t]] Sin[\[Alpha][t]])/Sqrt[               1 - 0.33^2 Sin[\[Alpha][t]]^2]) *             UnitStep[Sin[\[Alpha][t] + Pi*UnitStep[-\[Alpha]'[t]]]] ==            0, \[Alpha][0] == -Pi/3, \[Alpha]'[0] == 0}, \[Alpha], {t, 0,           tmax}, MaxSteps -> 10^5, PrecisionGoal -> 8,          AccuracyGoal -> acc];        Plot[\[Alpha][x] /. pend, {x, 0, tmax}]], {{sup, 0.01, "Sup"}, 0.01,        0.1, Appearance -> "Labeled"}, {{acc, 8, "Acc"}, 6, 10, 1,        Appearance -> "Labeled"}, Bookmarks -> {        "Error1" :> {sup = 0.0577, acc = 7},         "Error2" :> {sup = 0.0413, acc = 8},         "Error3" :> {sup = 0.0351, acc = 6}}]      I have tried with increasing the MaxSteps and reducing the AccuracyGoal/PrecisionGoal, but it seems that there are always points in which the NDSolve does not return a good solution. And thus I cannot execute the FindMaximum to maximize my function. Any hint on how to avoid this kind of problem and get NDSolve to return a correct result? Is there a way to trace down why NDSolve has this problems of convergence with this function? Thanks for any help, JBB PD: Code update to define tmax. In the manipulate Bookmarks I have placed some examples of errors.


title: How do I find the amount of free space on disk?

text: I know a workaround, where one calculates sizes of all files and then you subtract this from your default space, but is there any direct way to do it? Simplicity and speed are important. There's the way to calculate free RAM with external call               ReadList["!typeperf \"\\Memory\\Available Bytes\" -sc 1", Word,     RecordLists -> True, WordSeparators -> {","}] //      ToExpression@Part[#, 2, 2] &      Is there any way to do the same but for disk space? SOLVED               StringJoin[     ReadList["!dir c:\ ", Word, RecordLists -> True,      WordSeparators -> {" ", ","}][[-1, 3 ;; -3]]] // ToExpression      gives the amount of free memory on disk C in bytes)


title: How to produce functions

text: I want to produce `n` functions. For example, assume that by giving `n=3`, 3 definite integrals will be created, like the following:               In[1]:= n=3;          (The algorithm and Processing )          Out[1]:={ Integrate[f1,{x,x1,x2}], Integrate[f2,{x,x3,x4}], Integrate[f3,{x,x5,x6}]}      OR:               Out[1]:=  Integrate[f1,{x,x1,x2}]+ Integrate[f2,{x,x3,x4}]+ Integrate[f3,{x,x5,x6}]      What is the elegant way to do this calculation and produce different functions ?!


title: How to execute a function in the package from java?

text: I use Wolfram Workbench 2.0. I can get a `KernelLink` object and evaluate some simple expressions like "2+2". But I don't know how to export a package and execute any functions from Java code. Please, show me any example.


title: How to extract the bin width from a Histogram made with an automatic binning method?

text: I am using the Scott binning method with `Histogram` and `Histogram3D` to plot some data. How could I find out the bin width chosen by _Mathematica_? I am using version 7 and thus I cannot use `HistogramList`.


title: Image of input and output cells is not exported correctly

text: Wolfram Blog uses PNG images to display input and output cells in a notebook. For example, the following is an image from Samuel Chen's post: ![enter image description here](http://i.stack.imgur.com/xGAgz.png) I should be able to produce a similar image by selecting a group of cells and selecting File -> Save Selection from the pull-down menu. When I tried that on the cell               In[1]:= Series[Log[1+x],{x,0,6}]     Out[1]= x-x^2/2+x^3/3-x^4/4+x^5/5-x^6/6+O[x]^7      I get the garbled image ![enter image description here](http://i.stack.imgur.com/QKYi0.png) This does not happen when I save selection to PDF or BMP. In the case of BMP, the `In[1]` and `Out[1]` goes missing: ![enter image description here](http://i.stack.imgur.com/GthCm.png) Do you know of a way to fix the problem with PNG export and/or include the `In[1]` in BMP export? I am running Mathematica 8.0.4.0 on Linux x86 (64-bit), which I think is part of the problem.


title: How to take part (and then sum over) of specific level of an array?

text: Specifically, I want to take some elements of the lowest level of an array, and then sum over these elements while holding the higher level. Sorry for my vague expression, maybe an example would make it clear: An array of 3 levels:                try = {{0,{a,b,c}},{{d,e,f,g},{h,i,j}}}      I want to obtain `{{0,{a,b}},{{d,e},{h,i}}}`, and then sum over to obtain `{{0,a+b},{d+e,h+i}}`. Following illustration of Mathematica, i tried:               try[[All,All,1;;2]]      but it could not work. As to summation,               Total[try,{-1}]      could sum over all elements of the last level, however I have no idea how to sum over part of the last level. Solution?


title: How to solve a quadratic integer programming problem?

text: I want to solve a quadratic integer programming problem in Mathematica. My first attempt looks like this:               Minimize[{0.21 (2 x/40)^2 + 0.15 (10 y/40)^2 - 2*(2 x/40)*(10 y/40)*0.05,      2 x + 10 y == 40 && x > 0 && y > 0 && Element[x | y, Integers]}, {x,y}]      The output is:               NMinimize::cvmit: Failed to converge to the requested accuracy or precision within 100 iterations. >>      And:               {0.07875, {x -> 5, y -> 3}}      But it seems not very optimal (e.g. for x=10 and y=2 we get 0.065). I know that integer programming can be tough, but I think this kind of problems should be somehow solvable in Mathematica. Probably I just use wrong commands to achieve this. How can I go about it?


title: How to highlight various parts of a plot

text: I'd like to show students a graph of a function, say $(x,y)\mapsto\sqrt[3]{x^3+y^3}$, and then highlight its various properties connected with (non)differentiability at certain points etc. Having some lines included in the graph seems a good idea. Now I'd like to be able to highlight (by using different colors and/or thicker lines) some of these lines. It would be best if I could press or click something so that one or another line gets "selected" (highlighted). How to achieve something like this? Note: I'll be fully satisfied with one-line, RTFM-style answers, if someone could provide me a hint where to look for the FM; I'm new to Mathematica and feel a bit overwhelmed by the multitude of documentation in various formats...


title: Does a running evaluation continue after the PC wakes from sleep mode?

text: I was wondering if there are any issues with running a process on Mathematica, putting the computer to sleep, and then waking it up sometime later? It seems to work just fine on my test process (appending data to a list), but I wanted to know if there may be complications with doing this that I can't predict.


title: Tweaking Prime[n] to return 1 when n==0

text: I manually evaluate this cell to set Prime[0]               Unprotect[Prime]     Prime[0] = 1     Protect[Prime]         I manually evaluate this cell to reset Prime[0]               Unprotect[Prime]     Prime[0] =.     Protect[Prime]        In case I forget to do it, is there a way to automatically evaluate the second cell when I close the nb? **Motivation** I'm working with bags of primes and want to use $p_0$ as the bag for all prime greater than the square-root of some $n$. Displayed as: $\left\{p_0^1,p_1^5,p_2^2,p_3^1,p_4^1\right\}$ With counts as: $\left\{1,5,2,1,1\right\}$


title: Take screenshot of the entire desktop using Mathematica

text: Is it possible to get a screenshot of the entire desktop directly in _Mathematica_? I am on Ubuntu running _Mathematica_ 8. For some reason `GUIScreenShot[]` fails. But something like `GUIScreenShot[{{0, 500}, {0, 500}}]` works It is strange that in the reference               GUIScreenShot[]      is given as an example (last one), with the caption **Capture the entire screen:**. But when I copy it and paste it in a notebook, it expects a parameter! (I have included the code `Needs["GUIKit`"]`) I get the error as shown in this image ![Screenshot of the image](http://i.stack.imgur.com/h78MS.png)


title: How do you insert more columns into Table cells?

text: **How do you insert more columns into Table cells as shown below?** To get to this table, go to _File -> New -> Styled Notebook -> Textbook -> New -> Scroll down to the Table Cells_. ![http://img145.imageshack.us/img145/9009/db931ede98ce459db69ca94.png](http://i.stack.imgur.com/KBgPf.png)


title: Issue with Mouseover within Geographics

text: When using Graphics, I can change the color of the object with the use of Mouseover.                   Graphics[{Opacity[0.9], {Mouseover[{Red, #}, {Green, #}]}} & /@ {Disk[{0, 0}],          Text["Moi", {1.5, 0}], Disk[{3, 0}]}]         (*Objects change color *)      When trying the same approach with Geographics               countries = {"Spain", "Belgium", "Romania"};     GeoGraphics[{GeoStyling[Opacity[0.5]],        Mouseover[{Red,        Tooltip[Polygon[{Entity["Country", #]}], #]}, {Green,        Tooltip[Polygon[{Entity["Country", #]}], #]}]} & /@ countries]      Graphics are displayed but when mouse hovers on top of a country polygon, then an error message will toggle on the screen stating that "Coordinate Entity["Country","Spain"] should be a pair of numbers..... What is the correct approach to make the polygon representing the country change colors when selected?


title: How to make a drop-down selector?

text: How to make a drop-down selector UI component? Something that looks like this


title: Problems with images caused by which stylesheet is used

text: **Update** > This looks now like it was a bug in Mathematica version 8, because > everything works as expected - at least for this minimal example - in > version 9. (As an aside, I couldn't seem to find the Creative stylesheets > using the menu interface, although they're still installed at > "/Applications/Mathematica.app/SystemFiles/FrontEnd/StyleSheets/Creative/" > (on Mac OS X). Perhaps I accidentally did something to hide them... I finally tracked down a weird problem I was having with Export and other image-related operations to the type of stylesheet I was using. Consider the same expression evaluated in three different notebooks:               ImageDimensions[Rasterize["Mathematica"]]      ![enter image description here](http://i.stack.imgur.com/TsH0j.png) You can see that, with the fancier stylesheets, the graphics of the notebook have interacted with the graphics produced by the Mathematica expression. Is there a work round for this? Here's another example - exporting a video using the Creative/PrimaryColor stylesheet.               grafik = Manipulate[        Graphics3D[{Blue, Cuboid[{0, 0, 0}, {1, 1, 1}]}, Boxed -> False,         SphericalRegion -> True,         ViewPoint -> {12 Cos[t],  12 Sin[t], 6 Sin[t]}],  {t, 0 , 2 Pi,         Pi/24}]     Export["/tmp/grafix.mov", grafik]      ![stylesheet problems 2](http://i.stack.imgur.com/oYiIc.png) When the resulting movie is viewed in a movie player, you can see the orange outline and the original graphical frame: ![stylesheet problems 3](http://i.stack.imgur.com/ASM6a.png)


title: Unexpected behavior of rule-replacing with string concatenation

text: Here's the code.               Clear[x,y,z];     {x,y,z} /. x_ :> ("^_^" <> ToString[x])      I get the result `^_^{x, y, z}`, which is not what I intended. However, I want to have `{^_^x, ^_^y, ^_^z}`. I found the problem occurred was related to the appearance of `<>` or `ToString`. The problem seems so basic, but I've been debugging for a long while, still having not got the right answer.


title: Amount of k-sized not-duplicated subsets of subsets of pair with disitinct sorted integers

text: I have a list, L, of this kind ($n\in \mathbb{N}$):               L=Sort[RandomSample[Subsets[Range[n],{2}],RandomInteger[{1,Binomial[n,2]}]]]      S contains any k-sized subset with no duplicating integers:               S=Select[Subsets[L,{k}],Length[Gather[Flatten[#]]]===2k&] (*k>1*)     (*What I need is Length[S]*)      But when $n$ and $k$ are too big, I think there must be a simpler way to get the length than generating S. Which obtainable properties of L determines Length[S]?


title: StreamPlot,StreamPoints and the Fisher's equation

text: I'm trying to reproduce a `StreamPlot` from a vector field encoundered while analyzing the Fisher's equation (http://en.wikipedia.org/wiki/Fisher%27s_equation), for a variable parameter `c` (the speed of the progressive wave). I have two-three problems. 1A) I wish to draw the stream lines entering the stable node `P` along the directions of the eigenvectors `hP` and exiting from the unstable point `Q` along the directions of the eigenvectors `hQ`, particularly the orbit from `Q` to `P`. I'm unable to do this and to get a single continuous line from `Q` to `P` no matter how I set `StreamPoints`. 1B) If possible I wish to put arrow heads in the middle of a continuos stream lines and not at the end to get a cleaner look. 2) In the right pane of `Manipulate` I wish to get the numeric evaluation of eigenvectors `hP` and `hQ` along with the symbolic expression. The numeric evaluation depends on `c` and `c` is a variable in `Manipulate`. Basically I wish to reproduce a plot like this: ![1](http://imagizer.imageshack.us/v2/280x200q90/674/11f5e5.png) This is my code (sorry for the bad code indentation, but copying from a Mathematica apparently do not preserve indentation):               Module[{A,J,P={0,0},Q={1,0},hP,hQ},     A=c\[Function]({U,V}\[Function]{V,-c V-U+U^2});     J=c\[Function]Evaluate[{U,V}\[Function]Evaluate[Grad[A[c][U,V],{U,V}]]];     hP=c\[Function]Evaluate@Eigenvectors[J[c]@@P];     hQ=c\[Function]Evaluate@Eigenvectors[J[c]@@Q];     Manipulate[     With[{A=A[c],J=J[c],hP=Normalize/@hP[c],hQ=Normalize/@hQ[c]},     StreamPlot[A[U,V],{U,-.5,1.5},{V,-.5,.5},     PlotRangePadding->0.01,AspectRatio->Automatic,     Axes->True,AxesStyle->Directive[Dashed,LightGray],ImageSize->Large,     StreamScale->Full,StreamStyle->Arrowheads[.02],StreamPoints->Fine,StreamColorFunction->"Rainbow",     Prolog->{     PointSize[.02],Darker[Green],Point[P],Text["P",Offset[{10,10},P]],     Gray,If[c>=2,Line[{P-.25#,P+.25#}&/@hP]],          Darker[Red],Point[Q],Text["Q",Offset[{10,10},Q]],     Gray,Line[{Q-.25#,Q+.25#}&/@hQ]     }]     ],          {{c,3},0,10,1/4,Appearance->"Labeled"},          Delimiter,     Row[{"A"," = ",MatrixForm[A["c"]["U","V"]]}],     Row[{"J", " = ", MatrixForm[J["c"]["U","V"]],"  Subscript[J, P] = ",MatrixForm[J["c"]@@P],"  Subscript[J, Q] = ",MatrixForm[J["c"]@@Q]}],     Row[{"Subscript[H, P]\[Transpose]", " = ", MatrixForm[hP["c"]]," = ",MatrixForm[hP[c]]}],     Row[{"Subscript[H, Q]\[Transpose]", " = ", MatrixForm[hQ["c"]]," = ",MatrixForm[hQ[c]]}],          ControlPlacement->Right     ]     ]      But I get this: ![2](http://i.stack.imgur.com/U9Frq.png) # UPDATE This is another code where I try to use `NDSolve` to draw the stable/unstable mainfold near P and Q. Works only for the curve between Q and P.               Module[{A, J, P = {0, 0}, Q = {1, 0}, hP, hQ},      A = c \[Function] ({U, V} \[Function] {V, -c V - U + U^2});      J = c \[Function]         Evaluate[{U, V} \[Function] Evaluate[Grad[A[c][U, V], {U, V}]]];      hP = c \[Function] Evaluate[2*Eigenvectors[J[c] @@ P]];      hQ = c \[Function] Evaluate[2*Eigenvectors[J[c] @@ Q]];           Manipulate[       With[{A = A[c], J = J[c], hP = Normalize /@ N@hP[c],          hQ = Normalize /@ N@hQ[c], \[Epsilon] = 0.01,          t1 = -20*Max[1, c/3], t2 = 20*Max[1, c/3]},        Module[{g1, g2},              g1 = Quiet@             NDSolveValue[{U''[z] + c U'[z] + U[z] (1 - U[z]) == 0, #},               U, {z, t1, t2}] & /@ {            (*{U[t2],U'[            t2]}\[Equal]P+\[Epsilon] hP\[LeftDoubleBracket]1\     \[RightDoubleBracket],            {U[t2],U'[            t2]}\[Equal]P-\[Epsilon] hP\[LeftDoubleBracket]1\     \[RightDoubleBracket],            {U[t2],U'[            t2]}\[Equal]P+\[Epsilon] hP\[LeftDoubleBracket]2\     \[RightDoubleBracket],            {U[t2],U'[            t2]}\[Equal]Q+\[Epsilon] hQ\[LeftDoubleBracket]1\     \[RightDoubleBracket],            {U[t2],U'[            t2]}\[Equal]Q-\[Epsilon] hQ\[LeftDoubleBracket]1\     \[RightDoubleBracket],            {U[t1],U'[            t1]}\[Equal]Q+\[Epsilon] hQ\[LeftDoubleBracket]2\     \[RightDoubleBracket],*)            {U[t1], U'[t1]} == Q - \[Epsilon] hQ[[2]]            };              g1 = Quiet@           ParametricPlot[            Evaluate[{#[t], Derivative[1][#][t]} & /@ g1], {t, t1, t2},            PlotRange -> {{-.5, 1.5}, {-.5, .5}},            Epilog -> {              PointSize[.02], Darker[Green], Point[P],               Text["P", Offset[{10, 10}, P]],              Gray, If[c >= 2, Line[{P - .1 #, P + .1 #} & /@ hP]],                   Darker[Red], Point[Q], Text["Q", Offset[{10, 10}, Q]],              Gray, Line[{Q - .1 #, Q + .1 #} & /@ hQ]              }];              g2 = StreamPlot[A[U, V], {U, -.5, 1.5}, {V, -.5, .5},           StreamScale -> Full, StreamStyle -> Arrowheads[.02],            StreamPoints -> Fine, StreamColorFunction -> "Rainbow"           ];              Show[g1, g2, Frame -> True, PlotRange -> {{-.5, 1.5}, {-.5, .5}},           PlotRangePadding -> 0.01,          AspectRatio -> Automatic, ImageSize -> Large,          Axes -> True, AxesStyle -> Directive[Dashed, LightGray]]         ]        ],            {{c, 3}, 0, 10, 1/4, Appearance -> "Labeled"},            Delimiter,       Column[{         Row[{"A", " = ", MatrixForm[A["c"]["U", "V"]]}],         Row[{"J", " = ", MatrixForm[J["c"]["U", "V"]],            "  \!\(\*SubscriptBox[\(J\), \(P\)]\) = ",            MatrixForm[J["c"] @@ P],            "  \!\(\*SubscriptBox[\(J\), \(Q\)]\) = ",            MatrixForm[J["c"] @@ Q]}],         Row[{"\!\(\*SubscriptBox[\(H\), \(P\)]\)\[Transpose]", " = ",            MatrixForm[hP["c"]]}],         Row[{"\!\(\*SubscriptBox[\(H\), \(Q\)]\)\[Transpose]", " = ",            MatrixForm[hQ["c"]]}],         }, Center, 1.5],            ControlPlacement -> Right       ]      ]


title: Arguments for ChartElementFunction

text: I was reading the documentation for `BubbleChart` and I saw this example               DataDrilldownBubble[{{xmin_, xmax_}, {ymin_, ymax_}}, v_, {meta_}, style___] := PopupWindow[       Polygon[{{xmin, ymin}, {xmax, ymax}, {xmin, ymax}, {xmax, ymin}}], PieChart[meta]]          DataDrilldownBubble[{{xmin_, xmax_}, {ymin_, ymax_}}, y_, ___] := Rectangle[      {xmin, ymin}, {xmax, ymax}]          BubbleChart[{{1, 0, 1} -> Range[5], {0, 1, 2}, {1, 2, 3} -> RandomReal[1, 10]},                  ChartElementFunction -> DataDrilldownBubble]      How exactly the `ChartElementFunction` works? Which arguments are passed to it? In this answer the claim is that the arguments are [`region`, `values`, `metadata`]. The use of `style___` in the documentation may suggest that there is another optional argument. Is there an official documentation for that? How are exactly the metadata defined? The Mathematica help for `ChartElementFunction` is not very helpful here. In the above examples metadata are given by the lists `Range[5]` and `RandomReal[1, 10]` respectively


title: Thick polygons in Graphics3D

text: I have a polygon that I want to thicken with thickness `h`. How do I do this? `FaceForm` is evil and says: > The directive Thickness was encountered in a context where it is not > allowed.


title: Import numeric values from XML

text: I am trying to import data from an XML file and then perform calculations on those numeric values. When I import the data the values seem to be stored as strings. I tried using a ToExpression function on the different fields in a Cases function but the values seem to stay as strings. So first off here is a sample of my XML file:               <ArrayOfXMLHexNode>       <XMLHexNode>         <ID>1</ID>         <X>-1.000000000000000e+003</X>         <Y>0.000000000000000e+000</Y>         <Radius>1.000000000000000e+003</Radius>         <Angle>3.141592653589793e+000</Angle>         <RingIndex>0.000000000000000e+000</RingIndex>         <RingSuborder>1.000000000000000e+000</RingSuborder>         <DisplayOrder>1</DisplayOrder>       </XMLHexNode>       <XMLHexNode>         <ID>2</ID>         <X>1.000000000000000e+003</X>         <Y>0.000000000000000e+000</Y>         <Radius>1.000000000000000e+003</Radius>         <Angle>0.000000000000000e+000</Angle>         <RingIndex>0.000000000000000e+000</RingIndex>         <RingSuborder>1.000000000000000e+000</RingSuborder>         <DisplayOrder>2</DisplayOrder>       </XMLHexNode>       <XMLHexNode>         <ID>3</ID>         <X>-5.000000000000000e+002</X>         <Y>-8.660000000000000e+002</Y>         <Radius>1.000000000000000e+003</Radius>         <Angle>4.188790204786391e+000</Angle>         <RingIndex>0.000000000000000e+000</RingIndex>         <RingSuborder>1.000000000000000e+000</RingSuborder>         <DisplayOrder>3</DisplayOrder>       </XMLHexNode>     </ArrayOfXMLHexNode>      And an example of how I am importing the data follows:               hexNodeData =  Import["HexNodes.xml"]          myHexNodes :=        Cases[hexNodeData, XMLElement["XMLHexNode", _, _], Infinity];          pointsWithDisplayOrder =       Cases[myHexNodes,        XMLElement[         "XMLHexNode", _, {___, XMLElement["X", {}, {x_}], ___,           XMLElement["Y", {}, {y_}], ___,           XMLElement["RingSuborder", {}, {subOrder_}], ___,           XMLElement[           "DisplayOrder", {}, {displayOrder_}], ___}] -> {ToExpression[x],          ToExpression[y], ToExpression[subOrder],          ToExpression[displayOrder]}, Infinity]      And then a few lines to try out the data I imported:               In[53]:= tempDO1 = pointsWithDisplayOrder[[3]][[3]]          Out[53]= "1.000000000000000e+000"          In[54]:= tempDO1 \[Element] Reals          Out[54]= "1.000000000000000e+000" \[Element] Reals          In[55]:= StringMatchQ[tempDO1, "1.000000000000000e+000"]          Out[55]= True          In[56]:= ToExpression[tempDO1, InputForm]          Out[56]= 1. e          In[57]:= tempDO = ToExpression[pointsWithDisplayOrder[[3]][[4]]]          Out[57]= 3          In[58]:= tempDO \[Element] Reals          Out[58]= True      So a couple questions come out of this.   1. Why does the ToExpression's used in the Cases call not convert my data to Reals or Integers as appropiate when I store the data in the pointsWithDisplayOrder List? And to be clear I mean in the first code block where I have a line like this: ...-> {ToExpression[x], ToExpression[y], ToExpression[subOrder], ToExpression[displayOrder]}...   2. How can I convert values in sql scientific notation like 5.0000e+000 into a Real Number in Mathematica? Mathematica wants to treat e is an unknown variable. Thanks in advance. Brian


title: Summing Over a Variable Number of Indices

text: I am trying to figure out the best way to include a variable number of indexes of summation in a program. For example: Suppose I want to define a function $g[n,s]$ that returns the sum $$\sum_{a_1+...+a_s=n}\hbox{Multinomial}[a_1,\ldots, a_s]$$ I can do this with the following code:               vv[n_,s_,0]:=Multinomial @@ Flatten[{Array[p,s],n-Sum[p[k],{k,1,s}]}];          vv[n_,s_,k_]:=Sum[Evaluate[vv[n,s,k-1]],{p[s-k+1],1,n-Sum[p[j],{j,1,s-k-1}]}];          g[n_,s_]:=First[{Clear[p];vv[n,s,s]}]      But this runs very slowly, presumably because it spends a lot of time computing big symbolic expressions. (That is, the value of vv[n,s,k] is a big symbolic expression, not a number, at least as long as $k\neq s$.) I feel like there must be a more efficient way to do this. If $s$ were fixed I wouldn't have to form the big expression; I'd just keep a running total of the summands as I iterated through their values. But in this case, I don't know in advance how many iterating indices I need, so I've resorted to the above. Is there some standard and/or obvious trick for handling this? In case it's relevant for efficiency issues, the function I'm actually interested in is not Multinomial but a function that takes on real numbers as values.


title: Generalization of a rule to N arguments

text: I am trying to apply a series expansion on a function `x[t1,t2,...tn]`, with an expansion parameter `a`. For `n=2`, the function is `x[t1,t2]`, and this is my series expansion:               solRule2 = x -> (Sum[a^i Subscript[x, i][#1, #2], {i, 0, 2}] &);     x[t1, t2] /. solRule2      The result is given correctly as > Subscript[x, 0][t1, t2] + a Subscript[x, 1][t1, t2] + a^2 Subscript[x, > 2][t1, t2] This works also with derivatives, and this matters to me:               (x^(2,0))[t1,t2]/.solRule2      > (Subscript[x, 0]^(2, 0))[t1, t2] + a (Subscript[x, 1]^(2,0))[t1, t2] + a^2 > (Subscript[x, 2]^(2, 0))[t1, t2] Now, I can manually extend the rule to `n = 3`,               solRule3 = x -> (Sum[a^i Subscript[x, i][#1, #2, #3], {i, 0, 3}] &);      but what I want to do is to extend it to the generic n. I tried this               solRuleN = x -> (Sum[a^i Subscript[x, i][##], {i, 0, Length[{##}]}] &);      This works well with the function `x[t1,t2]` and in general with `x[t1,t2, ..., tn]`, but it fails with the derivatives:               (x^(1, 1))[Subscript[t, 1], Subscript[t, 2]]/.solRuleN      gives output `0`. I don't understand why this happens.


title: Plot cross sections of a function

text: I have been learning how to use _Mathematica_ for the past few weeks, and recently I have been trying to recreate something along the lines of this. ![enter image description here](http://i.stack.imgur.com/pTySV.png) Given a function, I want to create a 3d plot of an object as if the bounded regions of the function were to be extruded upwards in a certain shape. From this I hope to find a basic volume, instead of integrating. How would I do this? I have seen `ParametricPlot3D`, but I haven't been able to create what I want with it.


title: Is this a bug in NIntegrate?

text: Is this a bug or I missed something? `NIntegrate` seems to give a different answer for the same integrand when the option `Method -> {Automatic, "SymbolicProcessing" -> 0}` is given.               $Version     (* "10.0 for Mac OS X x86 (64-bit) (June 29, 2014)" *)          $Assumptions = w ∈ Reals;     FEx[w_] = (I E^(-25 + 5 I w - w^2/4) Sinh[5 w])/Sqrt[2];     NIntegrate[Conjugate[FEx[w]]*FEx[w], {w, -∞, ∞}]     NIntegrate[Conjugate[FEx[w]]*FEx[w], {w, -∞, ∞},       Method -> {Automatic, "SymbolicProcessing" -> 0}]     (* 0.313329 + 0. I *)     (* 0.626657 + 0. I *)      version 10 ![enter image description here](http://i.stack.imgur.com/knug2.png) version 9 ![enter image description here](http://i.stack.imgur.com/FyOAX.png) version 8 ![enter image description here](http://i.stack.imgur.com/q6pM5.png) It seems to have worked in version 7. version 7 ![enter image description here](http://i.stack.imgur.com/biIqH.png)


title: Solving for a variable within a definite integral using FindRoot

text: I want to solve for P in this equation:               Integrate[1/((P/(M*V)) - r*g - c*A*(V^2)*p/(2 M)), {V, 0, 26.82}] = s      , where all constants are given except P. I've tried:               FindRoot [Integrate[1/((P/(M*V)) - r*g - c*A*(V^2)*p/(2 M)), {V, 0, 26.82}] == s, {P, 0}]      but I get this error: > FindRoot::nlnum: "The function value {Undefined} is not a list of numbers > with dimensions {1} at {P} = {0.`}." Any ideas on what I should try? I appreciate the help!


title: Symbolic representation of bessel series derivative

text: I want to get symbolic expression for BesselJ derivative, where BesselJ is represented as series:               D[Sum[((-1)^k/(Gamma[k + ν + 1] k!)) (z/2)^(2 k + ν), {k, 0, Infinity}], z]      but I get following:               1/2 (BesselJ[-1 + ν, z] - BesselJ[1 + ν, z])      How to get derivative of this series in explicit form?`


title: Coulomb/kepler potential dynamics. NDSolve breaks

text: I've been trying to do a simple dynamics in coulomb potential (electron(s) around a nucleus). My equations break down. I think it's because of `1/0`. is there a way to make it work? this is what I have so far:               Needs["DifferentialEquations`NDSolveUtilities`"];     eqs = {{Derivative[1][q][T] == p[T],          Derivative[1][p][T] == -q[T]/(4 Pi Abs[ q[T]]^3)}, {q[0] == 2,          p[0] == 0.1}};     vars = {q[T], p[T]};     time = {T, 0, 20};     step = 1/25;     solee = NDSolve[eqs, vars, time, Method -> "ExplicitEuler",         StartingStepSize -> step, MaxSteps -> Infinity];     ParametricPlot[Evaluate[vars /. First[solee]], Evaluate[time],       PlotPoints -> 100]     Plot[Evaluate[vars /. First[solee]], Evaluate[time]]      I've used the documentation in `tutorial/NDSolveSPRK` **Update (1)** In the second plot, you can see that the trajectories start to jump. It's an unphysical behavior. A correct solution would be periodic or pseudo-periodic orbits.               Plot[Evaluate[{p[T]^2/2 - 1/(4 Pi q[T]), p[T]^2/2, -(1/(4 Pi q[T]))} /. First[solee]], Evaluate[time]]      Plots total, kinetic and potential energy. the total energy (blue line) should be a straight horizontal line. **Update (2)** if I comment out `4 Pi`, I get the correct result               Needs["DifferentialEquations`NDSolveUtilities`"];     eqs = {{Derivative[1][q][T] == p[T],          Derivative[1][p][T] == -q[T]/(*4 Pi *) (          Norm[q[T]]^3)}, {q[0] == {1, 0.1, 0.1}, p[0] == {0.1, 1, 0.1}}};     vars = {q[T], p[T]};     time = {T, 0, 20};     step = 0.01;     solee = NDSolve[eqs, vars, time(*, Method->"ExplicitEuler",         StartingStepSize->step,MaxSteps->Infinity*)];     ParametricPlot[Evaluate[{{p[T], q[T]}} /. First[solee]],       Evaluate[time], PlotPoints -> 100]     Plot[Evaluate[{vars} /. First[solee]], Evaluate[time]]     Plot[Evaluate[{Norm[q[T]], q[T]} /. First[solee]], Evaluate[time]]     Plot[Evaluate[{Norm[p[T]]^2/2 - 1/(*4 Pi*) Norm[q[T]], Norm[p[T]]^2/         2, -(1/(*4 Pi*) Norm[q[T]])} /. First[solee]], Evaluate[time]]      So it seems that the problem might be with initial conditions.


title: GraphicsGrid Format Problem with SpanFromAbove

text: I believe this is a bug in GraphicsGrid.               x = Graphics[Circle[]];     g1=GraphicsGrid[{{x, x, x}, {Item[x, Background -> Red], SpanFromLeft, x}, {x, x, x}}, Frame -> All];     g2=GraphicsGrid[{{x, Item[x, Background -> Red], x}, {x, SpanFromAbove, x}, {x, x, x}}, Frame -> All];     g3=GraphicsGrid[{{x, Item[x, Background -> Red], x}, {x, SpanFromAbove, x}, {x, SpanFromAbove, x}}, Frame -> All];     Row[{g1,g2,g3},"   "]      ![enter image description here](http://i.stack.imgur.com/fKeMO.png) SpanFromAbove do not works like expected, formats are not respected. Changing GraphicsGrid into Grid we get: ![enter image description here](http://i.stack.imgur.com/0Knx6.png) I tested this in V9 for Win and in V10 for Mac and Win.