How to write to the cloud quickly?

I am wondering how to most quickly log data during cloud execution. I do not need anything fancy: all I want to do is persist certain information for later analysis, with minimal blocking for the end user. A solution that involves dumping data and then periodically cleaning it up with a `ScheduledTask` would be acceptable. All of the code will run in the cloud. The `Permissions` need to be private. For example, say I want to track which users call certain functions I have deployed. `CloudSymbol` is faster in the cloud than in Mathematica, but it is still slow.               CloudSymbol@"list1" = {};     AppendTo[CloudSymbol@"list1", $RequesterWolframUUID] // AbsoluteTiming      > {4.070239, $RequesterWolframUUID} Before we compare timings, briefly note this behavior:               CloudSymbol@"list1"      > {$RequesterWolframUUID}               CloudEvaluate[CloudSymbol@"list1"]      > {"0e2497dc-9281-48f3-8e84-14b5e2587446"}               CloudSymbol@"list1"      > {$RequesterWolframUUID} Returning to timings,               CloudEvaluate[AppendTo[CloudSymbol@"list1",$RequesterWolframUUID]//AbsoluteTiming]       //AbsoluteTiming      > {2.866184, {1.723062, > {0e2497dc-9281-48f3-8e84-14b5e2587446,0e2497dc-9281-48f3-8e84-14b5e2587446}}} It is worth pointing out that the assignment in the cloud caused `$RequesterWolframUUID` to be resolved at that time. Compare this result to the behavior above.               CloudSymbol@"list1"      > {0e2497dc-9281-48f3-8e84-14b5e2587446,0e2497dc-9281-48f3-8e84-14b5e2587446} `URLFetch` is marginally faster than `CloudEvaluate`.               logUser=CloudDeploy@APIFunction[{},AppendTo[CloudSymbol@"list1",$RequesterWolframUUID]&];     URLFetch@logUser // AbsoluteTiming      > {2.500356,{"0e2497dc-9281-48f3-8e84-14b5e2587446", > "0e2497dc-9281-48f3-8e84-14b5e2587446", > "0e2497dc-9281-48f3-8e84-14b5e2587446"} However, this doesn't work when running in the cloud.               CloudEvaluate[URLFetch@logUser // AbsoluteTiming] // AbsoluteTiming      > (* errors, because the page was a login prompt *) I tried `CloudEvaluate`-ing `CloudConnect` first, with no luck. Also, `URLFetch` and `URLFetchAsynchronous` are inconsistent.               URLFetchAsynchronous[logUser,#&]      > > URLFetchAsynchronous[CloudObject["https://www.wolframcloud.com/objects/b2305e35-a643-4a52-a94d-575e0019b0d2"],#1&]               URLFetchAsynchronous[URLBuild@logUser,#&]      > > AsynchronousTaskObject["https://www.wolframcloud.com/objects/b2305e35-a643-4a52-a94d-575e0019b0d2", > 5, 15817848933037716543] But even putting the syntax aside, handling the `"data"` event revealed that `URLFetchAsynchronous` is getting the login prompt, as in the cloud, so the function was not evaluated. Lastly, the documentation says `PutAppend` has been updated to work with cloud objects, but I don't know how to use it.               list2 = CloudPut[$RequesterWolframUUID, "list2"];     $RequesterWolframUUID >>> list2 (* fast, no errors *)     CloudGet@"list2"      > $RequesterWolframUUID               PutAppend[$RequesterWolframUUID, URLBuild@list2]      > OpenAppend::noopen: Cannot open > https://www.wolframcloud.com/objects/user-0e2497dc-9281-48f3-8e84-14b5e2587446/list2. Ideas?


How can I change the position of my plot legends?

As the title indicates, I want to change the current position of the legends in a combined plot. The _Mathematica_ code I used is               dataRG00 = {{2.5, 15.15}, {2.75, 13.73}, {3, 12.64}, {3.25,      11.56}, {3.5, 10.68}, {3.75, 9.65}, {4, 9.31}, {4.25, 9.27}, {4.5,      8.88}, {4.75, 8.21}, {5, 8.0}};     dataRG11 = {{2.5, 2.07}, {2.75, 3.0}, {3, 3.84}, {3.25, 4.58}, {3.5,      5.56}, {3.75, 6.32}, {4, 6.73}, {4.25, 7.10}, {4.5, 7.06}, {4.75,      7.07}, {5, 7.29}};     dataRG21 = {{2.5, 20.56}, {2.75, 19.50}, {3, 18.51}, {3.25,      17.51}, {3.5, 16.52}, {3.75, 15.63}, {4, 14.75}, {4.25,      13.85}, {4.5, 13.00}, {4.75, 12.26}, {5, 11.6}};     dataRG32 = {{2.5, 5.24}, {2.75, 5.14}, {3, 5.00}, {3.25, 4.51}, {3.5,      4.25}, {3.75, 3.62}, {4, 2.56}, {4.25, 1.66}, {4.5, 1.42}, {4.75,      1.29}, {5, 1.25}};     dataRG43 = {{2.5, 10.31}, {2.75, 10.41}, {3, 10.56}, {3.25,      10.46}, {3.5, 10.25}, {3.75, 10.33}, {4, 10.67}, {4.25,      10.23}, {4.5, 9.21}, {4.75, 9.60}, {5, 10.5}};     dataRG85 = {{2.5, 4.62}, {2.75, 4.64}, {3, 4.72}, {3.25, 4.67}, {3.5,      4.46}, {3.75, 4.49}, {4, 4.37}, {4.25, 4.22}, {4.5, 4.25}, {4.75,      4.06}, {5, 3.8}};     dataRG99 = {{2.5, 1.05}, {2.75, 0.77}, {3, 0.66}, {3.25, 0.74}, {3.5,      0.86}, {3.75, 0.81}, {4, 0.90}, {4.25, 0.76}, {4.5, 0.90}, {4.75,      0.90}, {5, 1.08}};     dataCH = {{2.5, 41.0}, {2.75, 42.81}, {3, 44.05}, {3.25, 45.96}, {3.5,      47.42}, {3.75, 49.18}, {4, 50.68}, {4.25, 52.90}, {4.5,      55.27}, {4.75, 56.60}, {5, 56.48}};          col = {Darker[Green], Red, Blue, Yellow, Orange, Cyan, Magenta,      Darker[Gray]};     ley = {"Box", "1:1 linear", "2:1 boxlet", "3:2 boxlet", "4:3 boxlet",      "8:5 boxlet", "Other resonances", "Chaotic"};     plrange = {{2.4, 5.1}, {-2, 60}};          legendPlot[xl_List] :=      ListPlot[xl, Frame -> True,      PlotStyle -> Table[{Thickness[0.003], col[[i]]}, {i, 1, 8}],      Joined -> True, PlotMarkers -> {Automatic, 15},      FrameLabel -> {"α", "Percentage %"},      FrameStyle -> Directive[FontSize -> 17, FontFamily -> "Helvetica"],      PlotRange -> plrange, Axes -> False, ImageSize -> 600,      Epilog ->       Inset[Grid[      MapIndexed[{Graphics[{col[[First[#2]]],            Inset[Style[{\[FilledCircle], \[FilledSquare], \      \[FilledDiamond], \[FilledUpTriangle], \[FilledDownTriangle], \      \[EmptyCircle], \[EmptySquare], \[EmptyDiamond]}[[First[#2]]], 15]],            Thickness[0.08], Line[{{0, 0}, {1, 0}}]},           AspectRatio -> 0.5, ImageSize -> 20],          Style[ley[[First[#2]]], Bold, FontSize -> 10,           FontFamily -> "Helvetica"]} &, xl]],      Offset[{-2, -2}, Scaled[{1, 1}]], {Right, Top}]]          P0 = legendPlot[{dataRG00, dataRG11, dataRG21, dataRG32, dataRG43,      dataRG85, dataRG99, dataCH}]      which produces the following plot ![enter image description here](http://i.stack.imgur.com/ybPtx.jpg) Obviously, the position of the legends is wrong since they overlap part of the plot. What I want, is to move the legends outside the frame of the plot and particularly at the right hand side of it and adjust it at the middle of the y range. I "played" a lot with `Offset` and `Scaled` but I without success. Any ideas?


Removing a ProgessIndicator when no longer needed

I have a progress indicator in my _Mathematica_ notebook that I update as various calculations are performed:               indicator = ProgressIndicator[Dynamic[progress]];      I would like to figure out how to remove the indicator when the calculations are complete or in the case above when               progress == 1      I’ve looked through the documentation and can’t seem to find a good way to do this.


Differentiating a Dot Product

I apologize if this type of question has been asked before, but a preliminary search turned up nothing. I would like to differentiate dot products. For example, consider taking a derivative with respect to the $i$-th component of $P$ in the dot product $P \cdot X$. How do I teach Mathematica that is given by $\frac{\partial (P\cdot X)}{\partial P_i} = \frac{\partial }{\partial P_i}(P_a X^a) = \delta^i_a X^a = X^i$ ? Ideally, I would like to implement/generalize this rule to dot products of vectors in special relativity where the dot product is given by $a \cdot b = \eta_{\mu\nu} a^\mu b^\nu$. Thanks!


How can I factor my trigonometric equation?

The equation $$3\sin^2 x - 3\cos x -6\sin x + 2\sin 2x + 3=0$$ has a solution $x = 0$. That means it has a factor of $\cos x - 1$. I tried to write the given equation has the form $$(\cos x - 1)P(x)=0.$$ I am looking for the factor $P(x)$. How can I get _Mathematica_ to find it?


Why don't I see all the grid lines in my combined contour plots?

I am trying to display four continuous functions, but when I try to combine them withe a single `Show`, I can't see the second vertical line. I suppose the problem is with the `GridLines`. The code is:               j = -1;     a2 = 3.968342707518218;     a1 = 3.275794729726671;     NalfaF = -0.749964;     alfaF1 = 0.749964;     mu = 10^-3;     Ntot = NalfaF*mu;     tot1 = alfaF1*mu;     alfaF2 = 1.54553;     tot2 = alfaF2*mu;     k =       Show[ContourPlot[(Sqrt[(16 tot1 y)/3 (1 + tot1/(27 y^3))] - (            2 tot1)/(9 j y)) (x - 0.95 a1) == 0.002, {x, -10, 10}, {y,          0, .3}, PlotRange -> {{2.50, 4.5}, {0., 0.3}},         ContourShading -> None, PlotPoints -> 100,         Epilog -> {AbsolutePointSize[8], Text["2:1", {a1 + 0.1, 0.01}],           Black, Point[{a1, 0.}]}, GridLines -> {{a1}, {}}],       ContourPlot[(-Sqrt[(16 tot1*y)/3 (1 + tot1/(27 y^3))] - (2 tot1)/(            9 j y)) (x - 1.17 a1) == 0.004, {x, -10, 10}, {y, 0, .3},         PlotRange -> {{2.50, 4.5}, {0., 0.3}}, ContourShading -> None,         GridLines -> {{a1}, {}}, PlotPoints -> 100,         Epilog -> {AbsolutePointSize[8], Text["2:1", {a1 + 0.1, 0.01}],           Black, Point[{a1, 0.}]}],        ContourPlot[(Sqrt[(16 tot2 y)/3 (1 + tot2/(27 y^3))] - (2 tot2)/(            9 j y)) (x - 0.95 a2) == 0.002, {x, -10, 10}, {y, 0, .3},         PlotRange -> {{2.50, 4.5}, {0., 0.3}}, ContourShading -> None,         PlotPoints -> 100,         Epilog -> {AbsolutePointSize[8], Text["3:2", {a2 + 0.1, 0.01}],           Black, Point[{a2, 0.}]}, GridLines -> {{a2}, {}}],       ContourPlot[(-Sqrt[(16 tot2*y)/3 (1 + tot2/(27 y^3))] - (2 tot2)/(            9 j y)) (x - 1.1 a2) == 0.004, {x, -10, 10}, {y, 0, .3},         PlotRange -> {{2.50, 4.5}, {0., 0.3}}, ContourShading -> None,         GridLines -> {{a2}, {}}, PlotPoints -> 100,         Epilog -> {AbsolutePointSize[8], Text["3:2", {a2 + 0.1, 0.01}],           Black, Point[{a2, 0.}]}]]      How can I make sure both vertical lines show?


What is the inverse of CoefficientList?

I have numbers in vector notation. I need to get polynomial notation from them. My numbers are `{0, 1, 23, 5, 15, 0, 0, 0}`. I want to get x + 23x^2 + 5x^3 + 15x^4 from this list. How can I get that polynomial?


Can one optimize AutomaticNumbering feature?

If one wants to use the automatic numbering feature of Mathematica, he has to make tags for cells of the type he wants to be referenced to. Then, as soon as he needs to make a reference to the tagged cell, he goes to Menu/Insert/Automatic Numbering. This brings up the dialog "Create Automatic Numbering Object". There one finds three fields: one is entitled "Counter", the two others enable one to select the tag of the cell to be numbered. In the field "Counter" one finds a number of cell types, and one MUST select the type he needs. In some StyleSheets, such as JournalArticle, the number of cell types is really impressive. In this case the stage of choosing the cell type from the Counter field of the "Create Automatic Numbering Object" dialog considerably brakes the writing process and becomes a head ache. I heavily use the JournalArticle StyleSheet along with the automatic numeration. However, I only make numeration and refer to two types of Cells: (i) DisplayFormulaNumbered and (ii) Figure. Here comes my question: Is it possible to customize the "Create Automatic Numbering Object" dialog such, that only two types of cells: (i) DisplayFormulaNumbered and (ii) Figure would show up there? (my data PC WindowsXP, Mathematica 9.0.1.0)


Manipulate for probability distribution with multiple parameters, kernel smoothing

I'm looking to use the `Manipulate` command to take a distribution with multiple parameters (e.g., mean and sigma for the normal), generate some variates, then plot the density with kernel smoothing. Ideally I'd like to have sliders for all parameters, the number of variates used, and the bandwidth for smoothing. Here's what I've got:               Manipulate[       Plot[         SmoothKernelDistribution[RandomVariate[NormalDistribution[μ, σ], numbVars], bw],         {x, -5, 5}],       {μ, -1, 1},       {σ, 0, 5},       {numVars, 10, 1000, 10},       {bw, .1, 5}]      But it looks like I'm not indicating things correctly, getting errors for the `RandomVariate` parameters and for `SmoothKernelDistribution` and perhaps others that are supressed.


How do I generate a set of n-tuples containing integral solutions to a linear equation provided certain constraints?

Let $m,k,p$ be fixed positive integers. I want to create a table of k-tuples $(x_1,x_2,\ldots,x_k)$ comprised of solutions in positive integers to the equation below: $$x_1+x_2+\cdots+x_k=m\quad\text{where }1\leq{}x_1,x_2,\ldots,x_k\leq{}p$$ For example, if I set $m=16,k=3$, and $p=6$. How can I make mathematica generate the set (table) of integer triples $(x_1,x_2,x_3)$ such that $$x_1+x_2+x_3=16$$ where $1\leq{}x_1,x_2,x_3\leq{}6$. Also, how would I seperately generate a table of positive integral triples $(x_1,x_2,x_3)$ for which $$x_1+x_2+x_3\geq{}16 \quad \text{and } 1\leq{}x_1,x_2,x_3\leq{}6.$$


Why does Installing small caps fonts in OS X cause notebook Text cells to use that font?

I installed Adobe Type 1 Times Roman SC (small caps) and Times Roman Bold SC fonts on my Mac OS X system. Now every old or newly-created `Text` style cell in every Mathematica notebook appears in small caps! This is with the `Default.nb` style sheet. Why? And how to fix. Uninstalling the two fonts did cure the problem, but it makes no sense to me that this should have happened. Note that the Options Inspector shows the font settings for the `Text` style as being Times, 12, Plain.


Why does Mathematica choose the second function definition?

While working on a solution to this question I've come across a case where I simply don't understand Mathematica's behaviour. I've got the following definitions:               PatternImplies[(x:(Verbatim[Blank]                       |Verbatim[BlankSequence]                       |Verbatim[BlankNullSequence]))[h_],x[]]:=True          (*CatchAll rule*)     PatternImplies[_,_]:=Maybe;      Now I try this:               PatternImplies[_Integer,_]     (*     ==> Maybe     *)      I would have expected `True`. My first thought was that I probably got the pattern wrong, so I tested:               MatchQ[PatternImplies[_Integer,_],            PatternImplies[(x:(Verbatim[Blank]                              |Verbatim[BlankSequence]                              |Verbatim[BlankNullSequence]))[h_],x[]]]     (*     ==> True     *)      In other words, the pattern matches. Moreover, looking at `Downvalues` I see that the special rule is indeed stored before the catch-all rule. So why does Mathematica chose the second definition (and more importantly, what can I do about it?)


How can I completely ban usage of some functions in output and mandate use of others?

For example, I hate that Mathematica uses `Pochhammer` symbol in outputs and prefer all the expressions in `Gamma` function. How can I ban usage of `Pochhammer`? I also want all outputs to use `HurwitzZeta` rather than `Zeta`. In another instance I want the results to use my own variant of Polygamma function (modified). How can I mandate its usage when possible?


What default theoretical distribution does Mathematica use in PearsonChiSquareTest?

I used Mathematica's function PearsonChiSquareTest to test whether the data were drawn from a normal distribution. As in the reference, I expected Mathematica to compare the result to a normal distribution, by running: `PearsonChiSquareTest[data]`. As I wanted to extract the test statistics from properties, I was "forced" to name the distribution I wanted to compare it to, namely the normal distribution: `PearsonChiSquareTest[data, NormalDistribution[],"PValue"]`.   What is surprising is that the _PValue_ for the first case is _different_ from the second case where I use the Normal Distribution explicitly. Anyone knows what's the difference here?               data = RandomVariate[NormalDistribution[], 10^4];          PearsonChiSquareTest[data]          (*     ==> 0.3248593157     *)          PearsonChiSquareTest[data, NormalDistribution[]]          (*     ==> 0.4704917701     *)


How can I create facetted histograms?

I love _Mathematica_ , and I would love to be able to use it for all of my data analysis tasks, but there is one type of analysis which I find almost trivial in R, and I have no idea how to approach in _Mathematica_. Say I have a CSV file containing a few hundred thousand people's ranked preferences for items, in a format like this:               Gender,X29234,X30310,X28908,...     Male,1,2,3,...     Female,1,3,2,...     ...      (in this case the female liked item X28908 more than item X30310) 10000 rows of sample data can be found here. I want to plot histograms of the ranks each gender assigned to each item. In R I can use `reshape2` and `ggplot2` to do something like this:               library(reshape2)     library(ggplot2)     merged_data <- read.csv("merged_data.csv")     melted = melt(merged_data, id=1)     ggplot(melted)      + geom_histogram(aes(x=value,y = ..density..,fill=factor(Gender)),binwidth=1, position="identity",alpha=.5)      + facet_wrap(~variable)      + theme(legend.position="bottom")      + scale_fill_discrete(name="Gender: ")      to get a nice graph like this: ![histograms](http://i.stack.imgur.com/qeR0z.jpg) The key thing for me here are that the individual plots all end up having the same axis bounds, even though the bounds of the data in each plot aren't the same, which makes comparisons really easy. How would I go about doing something like this in _Mathematica_ so I can get rid of R in my workflow? **Edit:** I should clarify that this example with Gender is to simplify the problem to something easier to explain, and I'm looking for a solution which is as automatic as possible: doesn't involve enumerating in the source the possible values of the Gender field, doesn't involve hard-coding in the source the bounds of the plot etc. ggplot2 does all of these out of the box, so I'm looking for a reusable approach to do something similar.


Table with some editable cells

I have a table: ![Table I want to be editable](http://i.stack.imgur.com/nbukd.jpg) I want it to be editable only where the zeros appear. I read this post Generating an editable table that can be used as input because it's almost exactly what I want, but I couln't figure out how to keep uneditable the first column AND the first row. I don't show the modifications I did because they wouldn't shed any light.


point-wise transform of `Plot`

Suppose I have the following plot:               Plot[(1 - p2)^2/(p2^2 + (1 - p2)^2), {p2, 0, 1}, AxesLabel -> {"p2", "p1"}]      ![enter image description here](http://i.stack.imgur.com/a8nky.png) Now I want to do a point-wise transform to every point $(p2,p1)$ on the line (making a new plot) using: $ p1 \rightarrow \dfrac{p1-\gamma}{1-\gamma}\quad p2\rightarrow\dfrac{p2-\gamma}{1-\gamma} $ In other words, I want to move every point on the line $(p2,p1)$ to a new location $\left(\dfrac{p2-\gamma}{1-\gamma},\dfrac{p1-\gamma}{1-\gamma}\right)$. How should I achieve that?


Starting NDSolve from intermediate time step?

I always wondered if I could start NDSolve from an intermediate time step. What I mean is, in the code sample below, if I were to run my solution from `tmin=0` to `tmax=2` and then I realize that my solution hasn't converged yet, could I just change my `tmin` to `2` and then proceed with a larger `tmax` (in this case the solution coverges [attains steady state in this example] at `tmax=5`). This is because very often I solve 4th order Nonlinear PDEs with NDSolve, some of which take over 70-80 minutes to complete (as I run them for long times of a million time steps or so) and then I realize that the solution hasn't converged yet. So can I just, as in my presumed working example, change my `tmin` to my `tmax` from the previous run and change my `tmax` to a larger run?               tmin = 0;     tmax = 5;     sol = NDSolve[{D[u[t, x], t] == D[u[t, x], x, x], u[0, x] == 0,          u[t, 0] == Sin[t], u[t, 5] == 0}, u, {t, tmin, tmax}, {x, 0, 5}];     Plot3D[Evaluate[u[t, x] /. sol], {t, tmin, tmax}, {x, 0, 5},       PlotRange -> All]


Random variables with transformed discrete distributions cannot be applied to Probability[] function?

I have two discrete uniform distributions over same support:               Dx = DiscreteUniformDistribution[{-8, 8}];       Dy = DiscreteUniformDistribution[{-8, 8}];      I use random variables X $\sim$ Dx, Y $\sim$ Dy to model condition in some if- else clause in C code. For example,               if (3 * x + 1 > y) {        ...      }      So, I model this condition by random event 3*X + 1 > Y. Then probability I look for is:               Probability[       x > y,        {Distributed[x, TransformedDistribution[3 * x + 1, Distributed[x, Dx]]],        Distributed[y, Dy]}     ]      Unfortunately, Mathematica produces nothing. As for me, this is very strange behavior because Mathematica also cannot compute mean for the product distribution of {X, Y}. Maybe, this problem is caused by different support of X and Y. How can I compute this probability?


Mathematica Compiled Functions - additional functions

Mathematica supports an exact list of compilable functions: They are listed here: List of compilable functions. However, I would need to add the following functions: ToExpression, StringFreeQ, StringReplace, BinaryRead and BinaryWrite... Is it possible? I know that BinaryRead and BinaryWrite have simple C++ equivalents but how can I add this functionality to the Compile function? Furthermore, Compile only accepts Integer, Floats and Lists and Nested Lists as input. Can it be modified to accept Strings? Could reimplementing the Compile Function work?


ContourPlot and Colorfunction

I have the following code:               ContourPlot[     (2.7` (-3.8099999999999996` + 7.24` x - 3.24` x^2 + 3.62` y - 6.48` x y + 6.48` x^2 y))/     ( 11.43` - 6.48` x + 3.24` x^2 - 3.24` y + 6.48` x y) -      ( 3 (-(-1 + x)^2 + (1 + 2 (-1 + x) x) y))/( 3 + (-2 + x) x + (-1 + 2 x) y) ,      {x, 0.5, 1}, {y, 0, 0.5},      ContourStyle -> {Black, Thick}, Contours -> {0},       ColorFunction ->      (If[#1 > 0, Directive[Lighter[Lighter[Lighter[Yellow]]]], White] &)]      which gives me ![enter image description here](http://i.stack.imgur.com/bba1Z.png) But my color function should color the area above the black line white while color area below the black line yellow. However, if I use the colorfunction `Rainbow`, then it will give me the correct coloring result: ![enter image description here](http://i.stack.imgur.com/qapTk.png) What should I do to make my 1st color function behave as expected?


Conditioning on group of functions

I have two sets of functions which I want to implement them in a single function with an option indicating which set of functions should be used. Suppose that I have two lists like:(updated example)               b = {-1, 1, 0, 2}}     u = {{1, 1, 1, 1}, {1, 0, 0, 1}, {1, 0, 1, 1}, {0, 1, 1, 0}, {1, 0, 1,     1}, {0, 1, 0, 1}, {1, 0, 1, 0}, {1, 0, 1, 1}, {0, 1, 1, 1}, {1, 1,     0, 0}}      and I have this function:                AbEst[b0_, u0_, method_] :=       Module[{t, b = b0, u = u0, l, a, pos, theta, dif, se},       t = Table[i, {i, -4, 4, .01}];       L[b_, t_, u_] :=         Product[p[b[[i]], t]^u[[i]]*(1 - p[b[[i]], t])^(1 - u[[i]]), {i,           1, Length[u]}];       p[b_, t_] := 1/(1 + Exp[-1.7*(t - b)]);       l = L[b, t, #] & /@ u;       a = PDF[NormalDistribution[0, 1], t];       pos = Table[a, {Dimensions[u][[1]]}]*l;       Which[method == "ML",        theta =          t[[Position[l[[#]], Max[l[[#]]]][[1, 1]] & /@            Range[Dimensions[u][[1]]]]],        method == "MAP",        theta =          t[[Position[pos[[#]], Max[pos[[#]]]][[1, 1]] & /@            Range[Dimensions[u][[1]]]]],        method == "EAP",        theta = pos.t/Total[Transpose[pos]]];       dif = (Table[t, {Dimensions[u][[1]]}] -            Partition[Flatten[Table[theta, {Length[t]}]], Length[t]])^2;       Which[method == "ML",        se = Sqrt[Total[Transpose[l*dif]]/Total[Transpose[l]]],        method == "MAP",        se = Sqrt[Total[Transpose[pos*dif]]/Total[Transpose[pos]]],        method == "EAP",        se = Sqrt[Total[Transpose[pos*dif]]/Total[Transpose[pos]]]];       Return[Transpose[{theta, se}]]]      Now it returns `{theta,se}` for given `method`. I want to change it such that it returns theta by default (i.e. without computing `se`) and computes and returns `{theta,se}` if it was requested. 1) How can I do that? 2) How can I re-write more efficient function in which fits my purpose?


Labelling Curves Using ListLogLinearPlot within DynamicModule (So Close)

I currently have a large number of time-series datasets in the form where the name and time-series transposed data, so I have a list of lists of names for datasets and their time-dependant data. The _end goal_ is to graph a plot which **I already have as I want it by itself,** only with a **legend** that is, with other graphics, **finished as well.** Within this expression for `myPlot` I am able to generate the labels I need via inserting an `Epilog` expression, producing `SetAttributes[tt, Listable] tt[name_ -> data_] := Tooltip[data, name]` _(Just for manipulation)_ (1) `myPlot = ListLogLinearPlot[#, Epilog -> Table[Inset[Framed[DisplayForm[names[[i]]], RoundingRadius -> 5, Background -> White], {5.5, 25}], {i, len}]]` (2) `myPlot /@ tt[thirds@ruleData] // Column` which together yield a plot with unmovable labels for each dataset ((2) actually yields the plots with or without Epilog / labels, as specified by (1), whereas (1) alone unsquelched yields itself back in text-only output). But I am unable to combine these expressions with `DynamicModule` as another post on the Stack Forums suggests. http://stackoverflow.com/questions/7221315/how-do-i-label-different-curves-in- mathematica However, on top of a dummy graphic (table "pos" rather than plot) **I can get`DynamicModule` to have movable labels:** `DynamicModule[{pos = Table[{names[[i]]}, {i, len}]}, LocatorPane[Dynamic[pos], Appearance -> Table[Framed[Text@TraditionalForm[names[[i]]], RoundingRadius -> 5,Background -> White], {i, len}]]]` So, I would think the only problem then is figuring out how to "insert" the `myPlot` function(s) into `DynamicModule`. I am almost certain the presence of the `#` in my `ListLogLinearPlot` function is the culprit. I need to combine these expressions labels are movable ON the graph just as they are on the dummy table. Thank you again, I deeply appreciate any resposnes.


Importing or reading data in binary format 212

I have a binary data file in format 212, and I want to import the file into _Mathematica_. How do I read or import binary format 212? I almost have no direct experience of working with any binary format. I would appreciate your help. Here is the link to the data file: physionet.org/physiobank/database/mitdb/100.dat The specification of the format is "Each sample is represented by a 12-bit two’s complement amplitude. The first sample is obtained from the 12 least significant bits of the first byte pair (stored least significant byte first). The second sample is formed from the 4 remaining bits of the first byte pair (which are the 4 high bits of the 12-bit sample) and the next byte (which contains the remaining 8 bits of the second sample). The process is repeated for each successive pair of samples." From the following link: http://www.physionet.org/physiotools/wag/signal-5.htm#sect9


Multiple screens support for slideshows

I really like using Mathematica for building slideshows/presentations. But is mirroring the only way to see the content both on the laptop's screen and on the projector? When using screen mirroring, the projector display is blurry because the resolution doesn't match. When not using screen mirroring, having to constantly switch back and forth between the screen, the audience and the keyboard is really not convenient. Is there a better way to use Mathematica on multiple screens?


Why can't I change the style of a cell repeatedly?

I ran into this when I was working with an example from the Help Pages of V9. `Cells` is a new function added in V9. The following appears to work the first time it is evaluated in a notebook with `nb` assigned to some appropriate value, say, `EvaluationNotebook[]`.               Scan[(CurrentValue[#, StyleNames] = "Title") &, Cells[nb, CellStyle -> "Section"]]      However, if I try again to change the cells affected by the first evaluation to another style or back to the original style, nothing changes. Neither this               Scan[(CurrentValue[#, StyleNames] = "Text") &, Cells[nb, CellStyle -> "Title"]]       nor this               Scan[(CurrentValue[#, StyleNames] = "Section") &, Cells[nb, CellStyle -> "Title"]]        has any effect. For other `CurrenValue` targets such as `FontSize`, it's easy to change the value repeatedly.                Scan[(CurrentValue[#, FontSize] = 100) &,  Cells[nb, CellStyle -> "Section"]]      Scan[(CurrentValue[#, FontSize] = 30) &,  Cells[nb, CellStyle -> "Section"]]


Mark selected sub-lists in the list they were selected from

I've got this simple problem with two lists. I select some items from a list, but I want to visualize the difference between the previous list and the list that I create with `Select`. For instance:               a = {{7, 0, 0, 2}, {0, 0, 2, 5}, {10, 4, 8, 7}, {7, 1, 9, 2}, {1, 3, 6, 7},           {6, 9, 2, 9}, {2, 0, 7, 1}, {2, 5, 1, 1}, {9, 6, 4, 0}, {9, 9, 2, 8}};     b = Select[a, #[[4]] > 5 &];      I want a list that compare the two lists in this manner               results =        {{7, 0, 0, "-"}, {0, 0, 2, "-"}, {10, 4, 8, 7}, {7, 1, 9, "-"}, {1, 3, 6, 7},         {6, 9, 2, 9}, {2, 0, 7, "-"}, {2, 5, 1, "-"}, {9, 6, 4, "-"}, {9, 9, 2, 8}};


How to make Mathematica returns the exact expression I typed

I'm using _Mathematica_ to compare some constants. Before playing around with those constants, I would like to check that I didn't make any mistake in typing them. So my question is the following: "What is the command that return the expression I typed?" Just to be clear. The expression               4*Sum[Log[Gamma[k]], {k, 3, IntegerPart[n] + 2*(n - IntegerPart[n])}]      returns: ![enter image description here](http://i.stack.imgur.com/RvG3h.png) And that is what I want. On the other hand, the expression               Sum[(2*n - 2*m - 1)*Log[n*(m + 1)], {m, 0, IntegerPart[n] - 1}]      returns: ![enter image description here](http://i.stack.imgur.com/962bs.png) and that is what I want to avoid!


Evaluate code to some point

How can I evaluate my code, up to some point? I don't want to evaluate all of my code always. I have to use `Shift` \- `Enter` for every line from the first cell up to the point I want to be, and it's not easy when you have a lot of code.


Mismatch between numerical and analytic evaluation of an integral

I evaluated the following integral               NIntegrate[Sqrt[r] Abs[Cos[(k + 1/2) Pi r]], {r, 0, 1}]      getting as a result 0.413232 for `k=1` Then I evaluated the same integral as               Assuming[k ∈ Integers && k ⩾ 0,       Integrate[ 1/Sqrt[2] Sqrt[r (1 + Cos[2 (k + 1/2) Pi r])], {r, 0, 1}]]      and then I evaluated the result               -((4 (-1 + FresnelS[1]))/((1 + 2 k)^(3/2) π))      for `k=1` and I get the following result 0.137646. I am checking this result because I am mainly interested in               Integrate[ 1/Sqrt[2] Sqrt[r (1 + Cos[2 (k + 1/2) Pi r])], {r, R, 1}]      as a function of `R`. Where is my error?


Simplify expressions that contain full derivatives

The best way to show what I want is by giving an example: How to go from               Exp[-a[x, y]] (g[x, y]*Derivative[1, 0][f][x, y])/h[x, y] +      Exp[-a[x, y]] (f[x, y]*Derivative[1, 0][g][x, y])/h[x, y] -      Exp[-a[x, y]] (f[x, y]*g[x, y]*Derivative[1, 0][h][x, y])/h[x, y]^2      to               Exp[-a[x, y]] D[f[x, y]*g[x, y]/h[x, y], x]      If the Exp were not there, i.e. the expression is a full derivative, then integrating would work 1               expr = With[{anti =      Integrate[(g[x, y]*Derivative[1, 0][f][x, y])/     h[x, y] + (f[x, y]*Derivative[1, 0][g][x, y])/     h[x, y] - (f[x, y]*g[x, y]*Derivative[1, 0][h][x, y])/h[x, y]^2,     x]}, HoldForm[D[anti, x]]]


Antialiasing option behaves weird (polygon edges visible in ContourPlot)

When I set the `Antialiasing` option in `Style`, I get the followings:               plot = ListContourPlot[        Table[Sin[i + j^2], {i, 0, 2, 0.05}, {j, 1.2, 2, 0.05}],         ColorFunction -> ColorData["AvocadoColors"], Contours -> 10,         Mesh -> False, ImageSize -> 400];     Grid@{{        Style[plot, Antialiasing -> Automatic],        Style[plot, Antialiasing -> True],        Style[plot, Antialiasing -> False]        }}      ![Mathematica graphics](http://i.stack.imgur.com/D0gb9.png) For `Antialiasing -> Automatic`, everything is fine. Though `Antialiasing -> True` reveals polygon edges while still maintaining antialias on contourlines, frames, etc. `Antialiasing -> False` gives a plot where nothing is antialiased and polygon edges are not visible. There is this thing written in the documentation for `[Antialiasing][1]`: > With the default setting Antialiasing -> Automatic, choices are made to > optimize appearance on each type of computer system. I would not say this is an optimal appearance. Can anyone tell me the logic/algorithm behind `Automatic` in this case?


Cannot calculate an integral

I am new to _Mathematica_. So I just run a basic procedure but _Mathematica_ didn't calculate this integral. Maybe it is too complicated to be done.               Integrate[(a E^(I g x - 1/2 (d + a ArcSinh[(-c + x)/b])^2))/(b Sqrt[ 2 π]                Sqrt[1 + (-c + x)^2/b^2]), {x, -∞, ∞}]      $a,b,c,d$ and $g$ are constants. Could you suggest what I should do?


Inconsistent GraphicsRow behaviour

During the debugging of my previous question (somewhat related), I encountered this strange behaviour: when the global option `Antialiasing` is set to `True` in **Option Inspector** , the following code gives **non-antialiased** plots (observe e.g. frames):               GraphicsRow@{       ListContourPlot[        Table[Sin[i + j^2], {i, 0, 2, 0.05}, {j, 1.2, 2, 0.05}],         ColorFunction -> ColorData["AvocadoColors"], Contours -> 10,         Mesh -> False, ImageSize -> 400],       ListDensityPlot[        Table[Sin[i + j^2], {i, 0, 2, 0.05}, {j, 1.2, 2, 0.05}],         ColorFunction -> ColorData["AvocadoColors"], Mesh -> False,         ImageSize -> 400]       }      ![Mathematica graphics](http://i.stack.imgur.com/oLQ1F.png) The next input is from the same notebook, same session, the only difference is that `GraphicsRow` only contains one plot object. Result is **antialiased** (visible polygon edges are of no concern here, see other post).               GraphicsRow@{ListContourPlot[        Table[Sin[i + j^2], {i, 0, 2, 0.05}, {j, 1.2, 2, 0.05}],         ColorFunction -> ColorData["AvocadoColors"], Contours -> 10,         Mesh -> False, ImageSize -> 400], ""}      ![Mathematica graphics](http://i.stack.imgur.com/s8BjO.png) **Question** Is it a bug of `GraphicsRow`?


Using GraphHighlight interactively

I want to build a small GUI, where the user can select either a single edge or a single node of a graph. I got to this point:               selection = {};          Dynamic[Graph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3,         3 \[UndirectedEdge] 1},       PlotLabel -> selection,       VertexShapeFunction -> (EventHandler[           Disk[#1, .1], {"MouseClicked" :> (selection = {#2})}] &),       EdgeShapeFunction -> (EventHandler[           Arrow[#1, .1], {"MouseClicked" :> (selection = {#2})}] &),       GraphHighlight -> selection,       GraphHighlightStyle -> "Thick",       ImageSize -> 200       ]]      Which gives the following (note that I already highlighted an edge by clicking on it for clarity): ![Mathematica graphics](http://i.stack.imgur.com/wPDjG.png) Now if I try to click on one of the **nodes** , the dynamic visualization breaks, giving back the unevaluated result: ![Mathematica graphics](http://i.stack.imgur.com/oN3i1.png) Note, that the `GraphHighlight` and `PlotLabel` options correctly registered the click, as the selected node is on their right hand sides. Any idea what the difference is in this context between edges and nodes? The two clicking functionality are meant to be identical.


Are later versions of the Front-End compatible with older Kernels?

At my graduate school, all of the clusters still use version-6, and I only have version-7 and version-8 installed on my computer. I would like to use those machines remotely. Are either of the versions I have compatible with the version-6 kernel?


Speeding up NDSolve for system of differential equations

I am wondering if there is a way to speed up this function that solves a system of ordinary differential equations with NDSolve? Thus far I've tried specifying a few different methods such as LSODA, BDF, StiffnessSwitching; however, none of these has significantly affected the execution time. Is it possible to use Compile here?               Atotal = 100.;      Btotal = 100.;      Ctotal = 100.;      Rtotal = 100.;      input = Table[i, {i, 0.5, 6.5, 1.0}];     runs = Table[i, {i, 1, 6}];     simtime = 60*{15., 30.};           chiscore[input_Real, runs_Integer, simtime_Real, k1_Real,       k1m_Real, k2_Real, k2m_Real, a_Real, k3_Real, k3m_Real,        k4_Real, k4m_Real, k5_Real, k5m_Real, k6_Real, k6m_Real,       kn_Real, kc_Real, k8_Real, k8m_Real, k9_Real, k9m_Real,       k10_Real, k11_Real, negoff_, Atotal_Real, Btotal_Real,       Ctotal_, Rtotal_Real] :=       Block[{soln, t, A, B, Cin, Cout, R},          soln = NDSolve[             {               Derivative[1][A][t] == (((k1*input)/(1 + negoff*(R[t]/k10)))*               (Atotal - A[t]))/(k1m + (Atotal - A[t])) - (k2*A[t])/(k2m + A[t]),               Derivative[1][B][t] == (k3*A[t]*(Btotal - B[t]))/               (k3m + (Btotal - B[t])) - ((k4 + k11*R[t])*B[t])/(k4m + B[t]),               Derivative[1][Cin][t] == ((k5*B[t] + a*Cin[t])*(Ctotal - Cin[t] - Cout[t]))/               (k5m + (Ctotal - Cin[t] - Cout[t])) - (k6*Cin[t])/(k6m + Cin[t])               - kn*Cin[t] + kc*Cout[t],                Derivative[1][Cout][t] == kn*Cin[t] - kc*Cout[t],               Derivative[1][R][t] == (k8*Cout[t]*(Rtotal - R[t]))/               (k8m + (Rtotal - R[t])) - (k9*R[t])/(k9m + R[t]),             A[0] == 0.,             B[0] == 0.,              Cin[0] == 0.,             Cout[0] == 0.,             R[0] == 0.            },           {A, B, Cin, Cout, R},           {t, 0., simtime}][[1]]        ]          Table[chiscore[input[[i]], runs[[i]], simtime[[2]], 4.0, 0.0043,       0.0713, 0.039, .02, 1.561, 0.502, 0.0752, 0.000284, 1.48658,       0.0575, 0.746837, 0.442668, 0.182, 0.00176, 0.0375, 2.73359,       0.000685, 0.0567, 0.1735, 0.0367, 1.0, Atotal, Btotal, Ctotal,      Rtotal][[1]],     {i, 1, 5}]; // Timing


Can mathematica rearrange an equation and solve/plot it?

Suppose we have this equation: $$ sin(x+y+z) = x^2y - wz$$ I want mathematica to plot contours of $x$ with axes of $y$ against $z$ in the limit $w \rightarrow 1$, tried this code but didn't work.               a = Reduce[ Sin(x+y+z) == x^2y - wz, x]     a /. w -> 1     ContourPlot[a, {y, 0, 1}, {z, 0, 1}]      I tried a different method here, using Solve, but didn't work either:               ContourPlot [x /. Solve[Sin(x+y+z) = x^2y - z, x], {z,0,1}, {y,0,1} ]


How can I convert x^2 to x*x?

When I try the following code:               a b^2 c /. b c -> e      _Mathematica_ gives me: > >     a b^2 c >   but what I want is: > >     a b e >   The `FullForm` of `a b^2 c` is `Times[a, Power[b, 2], c]`, so it can not match the pattern `b c`. the problem above is a simplified version of my practical one as below: * * * The practical problem which comes to me is:               dat = {Subscript[n, c] Subscript[n, d] Subscript[v, c] Subscript[v, d],Subscript[n, d] Subscript[p, c] Subscript[v, c] Subscript[v, d],I Subscript[h, d] Subscript[n, d] Subscript[p, d] Subscript[v, d],I Subscript[h, d] Subsuperscript[n, d, 2] Subscript[v, d],Subscript[n, c] Subscript[p, d] Subscript[v, c] Subscript[v, d],Subscript[p, c] Subscript[p, d] Subscript[v, c] Subscript[v, d],I Subscript[h, d] Subsuperscript[p, d, 2] Subscript[v, d],I Subscript[h, d] Subscript[n, d] Subscript[p, d] Subscript[v, d],I Subscript[h, c] Subscript[n, c] Subscript[p, c] Subscript[v, c],I Subscript[h, c] Subsuperscript[p, c, 2] Subscript[v, c],-Subscript[h, c] Subscript[h, d] Subscript[p, c] Subscript[p, d],-Subscript[h, c] Subscript[h, d] Subscript[n, d] Subscript[p, c],I Subscript[h, c] Subsuperscript[n, c, 2] Subscript[v, c],I Subscript[h, c] Subscript[n, c] Subscript[p, c] Subscript[v, c],-Subscript[h, c] Subscript[h, d] Subscript[n, c] Subscript[p, d],-Subscript[h, c] Subscript[h, d] Subscript[n, c] Subscript[n, d]}          rules = {Subscript[h, c] Subscript[p, c]->I Subscript[h, e] Subscript[n, e]+Subscript[h, f] Subscript[p, f],Subscript[h, c] Subscript[n, c]->Subscript[h, f] Subscript[n, f]+I Subscript[h, e] Subscript[p, e],Subscript[p, c] Subscript[v, c]->I Subscript[n, e] Subscript[v, e]+Subscript[p, f] Subscript[v, f],Subscript[n, c] Subscript[v, c]->I Subscript[p, e] Subscript[v, e]+Subscript[n, f] Subscript[v, f],Subscript[h, d] Subscript[p, d]->I Subscript[h, f] Subscript[n, f]+Subscript[h, e] Subscript[p, e],Subscript[h, d] Subscript[n, d]->Subscript[h, e] Subscript[n, e]+I Subscript[h, f] Subscript[p, f],Subscript[p, d] Subscript[v, d]->Subscript[p, e] Subscript[v, e]+I Subscript[n, f] Subscript[v, f],Subscript[n, d] Subscript[v, d]->Subscript[n, e] Subscript[v, e]+I Subscript[p, f] Subscript[v, f]}          dat//.rules      some elements of the `dat` can't be matched by `rules` and `ReplaceRepeated`.


Width-dependent MatrixForm

When writing fractions, Mathematica has a quite intelligent behaviour: If the fraction gets too long to fit on the width of the notebook, it is automatically replaced by `/`. However, by default nothing like this happens for matrices given in `MatrixForm`. Therefore my question is: Is it possible to write a `DecayingMatrixForm` which shows as `MatrixForm` if the matrix fits into the notebook's width, but switches to showing the list when the notebook is resized to be more narrow? If that is not possible, is it at least possible to have that decision dependent on the current notebook width when first displaying the matrix? Note that the solution should work correctly also if `MatrixForm` is used _inside_ an expression, as in `Table[MatrixForm[Table[f[i,j],{i,1,n},{j,1,n}]],{n,1,20}]`.


Take a list with the amounts of the random samples from another list while holding the index

I have a list called `cant` with some amounts of samples to take from the list `community` as follows:               cant = {5, 1, 2, 3, 4};     community = {{1, 2, 3, 4, 5, 6}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 3}, {1, 2, 3, 4, 5, 6}};       I'm trying to find a better way to do this task:               where = {};     Table[AppendTo[where,       Table[Flatten[{RandomSample[community[[i]], 1], i}], {cant[[         i]]}]];, {i, Length[community]}];      The result is:               where      {{{3, 1}, {2, 1}, {3, 1}, {4, 1}, {4, 1}}, {{1, 2}}, {{3, 3}, {3, 3}}, {{1, 4}, {3, 4}, {1, 4}}, {{4, 5}, {1, 5}, {3, 5}, {1, 5}}}      Because with               where[[1]]     {{3, 1}, {2, 1}, {3, 1}, {4, 1}, {4, 1}}      The 5 samples in the first item (3, 2, 3, 4, and 4) have the index of community 1. I read about Reap and Sow, but really I couldn't understand how to implement this. Any idea of how to make this faster because I'm working with large communities and sampling thousands? I appreciate your help,


Using a ListDensityPlot to map color onto a ListPlot3D graph

I have a 3 column list of data points. The first two columns correspond to x and y coordinates, with data points creating a surface in the z direction from column 3. This gives me a nice wavy surface. I have a separate file of corresponding error values (chi) which amounts to a similar 3 columns: same x and y coordinates with chi values for each point in my data file. With this file, I've created a very nice (read: adequate) density plot, to show in 2 dimensions, via shading, the variation of chi across the parameter space. What I'd LIKE to do, is then use this 2D representation to shade the 3D plot, sort of like a "hot" and "cold" graph so I can visualize where the errors tend to be highest and lowest, while easily associating them with my data. Any ideas? Much appreciated! Edit: Adding code and plots for clarity.               `ListDensityPlot[gchi[[All, {1, 2, 3}]],ColorFunction -> "DarkRainbow"]`      ![Density Plot - Chi Values](http://i.stack.imgur.com/2oj71.png) These are the colors I'd like plotted on the following 3D plot (of different values). The colors vary by value from blue(low) to red(high).               `ListPlot3D[{gband[[All, {1, 2, 3}]]}, PlotRange -> Full, Mesh -> 6,ColorFunction -> Function[{gchix, gchiy, gchiz}, Hue[gchiz]]]`       ![3D Parameter graph](http://i.stack.imgur.com/0P0jP.png) This is the graph of "found" values for the functions I'm fitting. They're over the same space (x,y) coords as the density plot above, and here, the z components represent data points. I'd like to color this 3D graph by a projection of the 2D density plot (of different values z, same values x,y) onto the rendered surface. Arbitrary color scheme, I just want it to vary by a separate function determined by a separate list of values.


TrackedSymbols affected by CurrentValue. Another problem with SetDelayed(:=)+OwnVales in Initialization

It is MWE, only a `Disk[]` that should print `"Click"` when clicked. Also `"date... updating"` should be printed on the first evaluation and on each update of variable `enabled`. (which is **constant** in this MWE) In the `Column` there is another `Dynamic` object which shows current `MousePosition`. And this element is responsible for printing (flooding) `"date... updating"` even though `enabled` is not changing.               DynamicModule[{enabled = True, pos},      Column[{             Dynamic[Print[DateString[] <> " updating"];                     EventHandler[Graphics@Disk[], {"MouseClicked" :> Print["Click"]}],                     TrackedSymbols :> {enabled}]             ,             Dynamic[pos]             }]      , Initialization :> (pos := MousePosition["Graphics"])]      ![enter image description here](http://i.stack.imgur.com/sUOS5.png) I think I don't understand this and IMO it is not expected or desired behaviour. When one put another `Print` next to `Graphics` you will see that it is in face whole `Graphics` updating. **So the question is** : If it's not a bug (I missed something) then how to recreate this MWE so it behaves correctly. * * * I think it may be (but not necessarily) related to Why does a heavy background slow LocatorPane from updating, even if only the locators are Dynamic? p.s. `Dynamic[Refresh[..., TrackedSymbols:>{enabled}]]` behaves the same way. * * * **Edit** so at the end it seems to be more related to Button evaluation inside DynamicModule


Dealing with nested options

OptionValue allows for recent versions of Mathematica (I think as from 7) to easily access optional parameters if they are explicitely given to a function or their default values otherwise. For big functions using options of options can be useful but we don't have in such cases something like OptionValue in order to access them. We must resort to using Replace in order to use them. See for example the option "LegendGridOptions" in the answer of Jens to the question Creating legends for plots with multiple lines?               "LegendGridOptions" -> {Alignment -> Left, Spacings -> {.4, .1}}}      Has someone already tried to do something like OptionValue for sub-options ?


I'm trying to filter a date range by day of month and day of week - what am I doing wrong?

I am trying to generate a list of dates that match two criteria: they have to all be the first of the month, and they have to be a particular day of the week, Sunday in my case. The code I have written is this: `Select[DayRange[{1901, 1, 1}, {2000, 12, 31}], DayName[#] == Sunday && # == {_, _, 1} &]` I.e. I want to `Select` only those days in between the `DayRange` 1 january 1901 and 31 December 2000 that match the criteria of being a `Sunday` as well as (`&&`) being the first of the month (`{_, _, 1}`). However, this function just outputs an empty list. I'm still new to Mathematica, but in as far as I can see everything here should work fine. What am I doing wrong?


Bordermatrix from LaTeX

How would I create an output similar to the result produced by this LaTeX code:               M = \bordermatrix{~ & x & y \cr                       A & 1 & 0 \cr                       B & 0 & 1 \cr}      which when compiled, looks like ![enter image description here](http://i.stack.imgur.com/MJLX9.png)


Mathematica Application in Real Life

As an 'user'-level in _Mathematica_ , I mainly use built-in _Mathematica_ function and benefit _Mathematica_ as a mathematical tool-box for my specific scientific problem. My level is not yet programmer-level. The magic of _Mathematica_ is that there are endless level of skill to improve. It is hardly to evaluate a C-programmer by viewing his code. But for _Mathematica_ , be viewing the code, the level could be evaluated. Normally, when skilled level increases, the length of code decreases. Based on the idea of Leonid Shifrin and the level in online game, I myself auto evaluate my skill.   * Level 0 - Level 20: Beginner-Users who uses mainly built-in functions.    * Level 20 - Level 40: Intermediate, mix some long procedural programming and functional style   * Level 40 - Level 60: Expert, low-level system understanding Although I have " _Mathematica_ **_Advanced_** Foundation Level" certification, I think my level is Beginner - Pre-Intermediate about level 18- to level 22. I can not understand the Expert level, for example One-Line Code Competition. As we can see here, Expert level codes program in just 'one line'. :) ![enter image description here](http://i.stack.imgur.com/2mPTV.png) My question is, could you please introduce the use of Mathematica as a real- life application? It is not a question of technique, but a question of idea, imagination. Your applications could open my eye of the use of Mathematica in your real-life. I also see "User Stories" on _Wolfram_ site, but almost of them are scientific, industrial applications. In my case, as an researcher-lecturer at University, I intend to use Mathematica in my teaching. Correct the copies take me a lot of time. So my project is:   * Use _Mathematica_ to auto generate MCQ (Multiple Choice Question) question based on my question data base.   * Scan students answers as an image file.   * Use _Mathematica_ to generate the note by image manipulating on these scanned copies. (The optical reader in my university is really expensive, and not available for everyone). So coding my own _Mathematica_ code is optimal way. Ideas, projects of the use of _Mathematica_ in real life are welcome !


Keyboard Shortcut several Keys

I would like to set up a system (or define a keyboard shortcut) so when you type the following > sum I have the following print at the current selection.               NotebookWrite[      InputNotebook[],      ToBoxes[Unevaluated@Sum[Placeholder[ ], {t, 1, n}]],      Placeholder]      This only works partially works b/c it removes focus.               x = Input[""]


Produce {f[x],g[y],h[z]} in as many ways as possible

I have two lists of equal lengths but for my task I will use 3-element lists , namely `{x,y,z}` and `{f,g,h}`. The first contains variables and the second functions. I want to produce `{f[x],g[y],h[z]}` with input the above lists in as many ways as possible. Until now I have devised the following ones:               Inner[#1[#2]&,{f,g,h},{x,y,z},List]      and               MapThread[#1[#2]&,{{f,g,h},{x,y,z}}]      As pointed out , there is a very similar thread at wolfram's community. If I come up with more solutions I will add them here. **Update** I am updating with the one-liners. In _Wolfram's Community_ forum there are also solutions changing Attributes or using Append but I will omit them here.               MapThread[#1[#2]&,{{f,g,h},{x,y,z}}]          Inner[#1[#2]&,{f,g,h},{x,y,z},List]          Diagonal[Through/@Distribute[{f,g,h}[{x,y,z}],List]          MapThread[Compose,{{f,g,h},{x,y,z}}]      `Apply[List,{f,g,h}.{x,y,z}/.Times->(Operate[##1,0]&)]` and `Apply[List,{f,g,h}.{x,y,z}/.Times->(#1[#2]&)]` work only because f,g,h are before x,y,z in alphabetical order as very well pointed out by @andre                Apply[Compose,Thread[{{f,g,h},{x,y,z}}],{1}]           (#1[[1]][#1[[2]]]&)/@Transpose[{{f,g,h},{x,y,z}}]


From iterative to functional

How to write this small piece in a functional way (ie. without state variables)?:               test[oldJ_List, newJ_List] := Total[Abs[oldJ - newJ]] > 1;     relax[j_List, x_?NumericQ] := Mean[Nearest[j, x, 4]];          j = Range[100]; (* any numeric list *)     j1 = j/2; (*some initial value for the While[] test to return True*)          While[test[j1, j],      j1 = j;       (j[[#]] = relax[j, j[[#]]]) & /@ Range@Length@j]


Binning sequential sets of elements together in a list

Given a list of the form:               {{1,2,3,4,5},{6,7,8,9,10},{11,12},{13,14,15,16},{17,18,19,20,21,22,23},{24},{25,26},{27},{4}}      How can I bin each sequential set of N elements of the list together? For example, if N = 3, we would transform the above list into:               {{1,2,3,4,5,6,7,8,9,10,11,12},{13,14,15,16,17,18,19,20,21,22,23,24},{25,26,27,4}}      Of length 3.


CommunityGraphPlot doesn't size

When I need to plot a 'large' graph with CommunityGraphPlot the output is always sized at the Mathematica default value. The Graph object itself can be resized with ImageSize option. However that doesn't work with Mathematica 9.0.0. The only option is to enlarge the plot by clicking the image and pull it to the wanted size. Then you can export this graph to PDF and print it. Is there a alternative way?               g = RandomGraph[{200, 300}, VertexLabels -> "Name",ImagePadding -> 20, ImageSize -> Scaled[0.5]]      ![enter image description here](http://i.stack.imgur.com/fPbDj.png)               CommunityGraphPlot[g]      ![enter image description here](http://i.stack.imgur.com/wol4q.png) **UPDATE:** I just found out that the CommunityGraphPlot generated can be double clicked and then you can freely drag the vertexes etc while keeping the connections! Can't do that with Graph object by default.


Pattern issues weird warning

Take for example               head[b_[PatternSequence[_, _]]] := 9      I know this example serves no purpose as is. It also happens in useful examples such as               head[b_[_, arg : PatternSequence[_, _]]] := {arg, b}      The definition is made propely, but it issues the message > `Pattern::patvar:` First element in pattern `Pattern[1,_]` is not a valid > pattern name. >> A simpler example of the problem, suggested by @celtschk in comments               b_[PatternSequence[_, _]] :> 0      and               b_[PatternSequence[]] :> 0      Particularly interesting is an example @OleksandrR found, in which the mysterious numbering of patterns becomes more evident               (p : {a_, b_, c_})[PatternSequence[]] -> Null      > `Pattern::patvar:` "First element in pattern > `Pattern[4,{Pattern[1,_],Pattern[2,_],Pattern[3,_]}]` is not a valid pattern > name."


Higher order SVD

Does anyone know how to do a higher order SVD in Mathematica ? A good reference seems to be here http://www.sandia.gov/~tgkolda/pubs/pubfiles/SAND2007-6702.pdf but I don't understand their formalism yet, maybe someone has already some experience with this in Mathematica and this could speed up the understanding. Thanks Another interesting reference is here ftp://ftp.cs.sjtu.edu.cn:990/zhang- lq/Papers/TensorFactorization/2004icpr_tensorRepresentaion_Wang.pdf


Multiply value if it includes a period

I download data from an online source, now I have a problem: the source code doesn't allow to differ between values of 10 (which actually stands for 10) and 10.000 (which is 10'000, but _Mathematica_ reads it as 10 as well). Now I'm thinkg about letting all values that include a period like `10.000` multiply with the factor 1000 and let all the values without a period remain the same. Lets say I have the following vector `a={10.350,20,20.000,10.700,30,40.522}`. What I want to do is to multiply all elements of `a` except the second (`20`) and fifth one (`30`). Is there a chance to distinguish between 20 and 20.000 ? Thanks for your help in advance!!


How can I get Mathematica to allow me to apply FindRoot to an expression that contains NIntegrate?

I am trying to run the following command in Mathematica:               FindRoot[NIntegrate[D[f[x], x] / Sqrt[1 - x^2], {x, 0, 1}] - d, {a, 245}]      As you might expect, a is buried within f[x] and 245 is a reasonable initial guess at its value. As you may also have guessed, the above integral is an expression for d in terms of a but I can't do the integral in closed form so I can't invert the expression to find a in terms of d. So, I wish to numerically integrate my integral expression for d but that just give me the d that corresponds to a given value of a. I want to go the other direction, find the a value that corresponds to a given d. That's what I'm using FindRoot for (kudos if you're staying with me so far, it's taken me days to get to this point). So here's the problem: NIntegrate gets upset if anything in the integrand is an undefined variable so every variable in the above integrand is defined except a (because I don't know it yet). However, FindRoot does know it. What I mean is, FindRoot is presumably running in an iterative loop and in every iteration it is working with a guess at a so somewhere in the bowels of the code, a always has a definite value. If I could somehow get NIntegrate to know this, I think I can get the above command to work (which would be a nice example of a powerful one line Mathematica operation). Any tips or do you think I'm trying to do something impossible? Thanks, Dessie.


Autorotating 3D plots

These days, I have to produce quite a few 3D surface plots (mostly functions of the type $\rho(\theta,\phi)$ plotted with `SphericalPlot3D`). To exchange these results colleagues who don’t use Mathematica, or to include them in presentations, I need to export these plots as movies showing the surface rotating. What I’d love to do is to be able to choose one graph, and just export it as autorotating around the current vertical axis (i.e. the axis contain in the plane of the screen, and directed upwards). This not being possible, I'm trying to do the next best thing: a procedure that takes as an argument the produced 3D graphics (say, the output of `SphericalPlot3D`) and makes it automatically rotate. Here’s what I’ve been able to do with `Animate`, but I could follow the same logic and export it directly instead.               rotateMeHarder[g_] := Module[{range},        range = Max /@ (Abs@PlotRange /. AbsoluteOptions[g, PlotRange]);        Animate[         Show[          Graphics3D[{Red, Thick, Line[{{-1.2*range[[1]], 0, 0}, {1.2*range[[1]], 0, 0}}]}],          Graphics3D[{Green, Thick, Line[{{0, -1.2*range[[2]], 0}, {0, 1.2*range[[2]], 0}}]}],          Graphics3D[{Blue, Thick, Line[{{0, 0, -1.2*range[[3]]}, {0, 0, 1.2*range[[3]]}}]}],          g,          ViewPoint -> RotationTransform[\[Theta], {0, 0, 1}][{0, 2*Max@range, 0.2*Max@range}],          SphericalRegion -> True, Boxed -> False],         {\[Theta], \[Pi]/20, 2 \[Pi] + \[Pi]/20, \[Pi]/20}]        ];          p = SphericalPlot3D[       10 + 5*Re@SphericalHarmonicY[3, -3, \[Theta], \[Phi]], \[Theta], \[Phi],       Boxed -> False, Axes -> None, PlotStyle -> Opacity[0.7]];     rotateMeHarder[p]      * * * What I like about this:   * It does generate a nicely rotating object in simple cases.   * It draws axis lines on top of my graph, but that's just because it looks great on my pictures, it's not a requirement for the question… What I don’t like, or am unsure about:   * It doesn’t start with the current orientation of the graph, but works with a fixed rotation vector (along the 3D $z$ axis) and a fixed starting position (slightly above the $xy$ plane). If I understood this answer correctly, they is not way of retrieving the current viewpoint for a given interactive 3D graph. So bad!.   * It doesn’t seem very robust. In particular, it only works for 3D plots centered around the origin, which extend about the same length in each axis direction (i.e. does not deal with very anisotropic surfaces).   * It leaves a lot of white padding around the graphics. * * * So, the question is: what do you think of this code? **How could I make it more general, more robust, or in any way closer to my initial goal of a one- size-fits-all exporting procedure for 3D graphics?**


How to get a more traditional-looking for protected constants

Is there any solution to make rule to export as a traditional form protected constants. Here is example which doesn't work.               aa = I0*I0;     rules11 = {I0 :>      \!\(\*SubsuperscriptBox[     OverscriptBox[\(I\), \(^\)], \(0\), \(0, 2\)]\)};            aa //. rules11 // TraditionalForm


Creating a simple interactive app with CDF

I would like to implement an algorithm I have created using a ( _free_ ) CDF document as interface. The idea is:   * The user has to give some input values (maybe through a sort of text box, if possible —a slider would also apply).   * When the user has finished to inform those input values, he/she _starts_ the algorithm (by pressing a sort of button, if that is possible).   * That action makes the algorithm to start computing.   * When the algorithm has finished (that would be a few seconds later), the user can see in the CDF document some numerical results and some plots (that could be interactive, but no matter if they are not). The process is supposed to be transparent and black-boxed to the user. Specifically, _I do not want the user to see the code of the algorithm_ (this is an important point), but only the input boxes and the results. I have been looking into the Internet but I have not been able to find any "getting started" CDF tutorial or something similar. My questions are: (1) Is it possible to build such an app in ( _free_ ) CDF format (provided that the algorithm is already programmed in Mathematica as a series of steps)? (2) Which are some basic places to start learning to create CDF documents, step by step??? **[EDITED 5 aug 2014]** As far as I understand, the most reliable way to create a working free CDF document is embedding all the code within a `Manipulate` interactive command. I wonder if I can sort of _embed_ a quite simple algorithm (several steps starting from some input info and finishing with a numerical and graphical output) within a `Manipulate` sentence. **[EDITED 6 aug 2014]** I've been playing around, and I found that things like this are allowed:               Manipulate[f[x_] := Sin[x]; {Plot[f[x], {x, 0, a}], f[a]}, {a, 1, 50}]      I mean, it works —I can connect several expressions with `;`, and also I can show both graphical and numerical results. I am going to continue trying things, and if I manage to get the results I want, I'll post it as an answer to this question. Of course, any suggestions, help, comments... are still welcomed.


Memory problem in Mathematica 10

I'm having a problem with memory. I'm doing nonliner fits of several data lists to a system of differential equations. When I evaluate the "Do" cycle the memory grows with the iteration step up to my RAM memory (8GB). I tried to Clear the functions "sol" and "modelSIR" in each iteration, but even so the kernel keeps everything in memory. What is event more strange is that I ran this in Mathematica 9 and everything was ok. Now I'm running it in Mathematica 10. I post here one example of the data list.               DataANotTruncadaShifted[[1]] = {{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6,0}, {7, 1}, {8, 4}, {9, 6}, {10, 4}, {11, 5}, {12, 4}, {13, 6}, {14, 11}, {15, 6},{16, 9}, {17, 15}, {18, 18}, {19, 24}, {20, 5},{21, 9}, {22, 8}, {23, 15}, {24, 12}, {25, 12}, {26, 8}, {27, 6}, {28, 0}, {29, 0}, {30, 1}, {31, 0}, {32, 0}, {33, 8}, {34,3}, {35, 6}, {36, 1}, {37, 1}, {38, 1}, {39, 0}, {40, 0},{41, 0}, {42, 0}, {43, 0},{44, 0}, {45, 0}, {46, 0}, {47, 0}, {48, 0}, {49, 0}, {50, 0}, {51, 0}};               AList = Table[{}, {i, 1, 18}];     gamaList = Table[{}, {i, 1, 18}];     t0List = Table[{}, {i, 1, 18}];               Do[     Clear[sol, modelSIR];          sol = ParametricNDSolveValue[     {     beta[t] == (1000*gama)/(1000 - 1) + A*1/(1 + Exp[-(t - t0)/1]),     s'[t] == -((beta[t]*s[t]*i[t])/1000),     i'[t] == (beta[t]*s[t]*i[t])/1000 - gama*i[t],     r'[t] == gama*i[t],     s[0] == 1000 - 1, i[0] == 1, r[0] == 0}, {s, i, r}, {t, 0, 53}, {A, gama, t0}];     modelSIR[A_, gama_, t0_][t_] := Through[sol[A, gama, t0][[2]][t],List]/;And@@NumericQ/@{A,gama,t0,t};               fit = NonlinearModelFit[DataANotTruncadaShifted[[n]], {modelSIR[A, gama, t0][t],0.1 < A < 5, 1 < gama < 5, 0 < t0 < 40}, {A, gama, t0}, t, MaxIterations -> 200, Method -> {"NMinimize"}];               Afit = fit[[1]][[2]][[1]][[2]];     gamafit = fit[[1]][[2]][[2]][[2]];     t0fit = fit[[1]][[2]][[3]][[2]];          AList[[n]] = Afit;     gamaList[[n]] = gamafit;     t0List[[n]] = t0fit;          , {n, {1, 3, 4}}]


Doing arithmetic with binary numbers

How do I execute binary operations in Mathematica? I want to to multiply say 1010101011 (binary) to 1111101110 (binary) and getting the result 10100111101111111010? Then I want to add the result to say 10101010000111 (binary)? Assume the all binary numbers are given as lists such as {1,0,1...}. Thanks!


Seeking strategies to deploy a function securely without a front end

**Background** I have a fuction, which calculates an analytic solution to a multi-dimentional geometry problem. The function takes a list of real numbers (typically less than a dozen) and outputs a list of reals of equal length (12 reals in -> 12 reals out). The function runs fast and doesn't require a lot of computational resources. More typical solutions to the problem involve statistical sampling of something like 10^5 points and use a substantial parallel computing infrastructure or lots of time. The idea has a number of commercial applications including epidemiology and insurance. The function uses a number of "high-level" Mathematica functions including:               CholeskyDecomposition[]     IdentityMatrix[]     LinearSolve[]     Simplify[]      **What I need** I need to deploy this function into a Windows based technology environment so that the users can call the function from some of their process workflows (e.g., they may call it from a database stored procedure or another program). I need a deployment solution and have some concerns I need the solution to address, especially:   * keep the code proprietary;    * deploy reliable code; and    * make the function easy to use in the target environment. The target environment does not include Mathematica; they have no other need to run Mathematica, CDF, or Wolfram Player Pro. They have no need or interest in running a Mathematica front end. **An ideal but likely unworkable solution** Generation of a C code executable would provide an ideal solution, but the function's use of the "high-level" Mathematica functions listed above excludes this as a simple option. I'd consider developing my own versions of the high-level functions from lower-level Mathematica code that one could then compile to C code, but this just seems silly (and probably hard) If anyone has suggestions along these lines, thinks it possible, or can direct me to examples please let me know. One can readily get C implementations of the Cholesky Decomposition, but that would introduce a whole other layer of complexity. Also, I never wrote much C code and what I did I did a very long time ago. **A workable solution?** Running the kernel and the code from a script file (without the frontend) seems like a place to start: See: Mathematica Scripts It looks like I can send parameters to a script. From the documentation on `Script Parameters` > ...When running a Mathematica script, you may often want to modify the > behavior of the script by specifying parameters on the command line. It is > possible for the Mathematica code to access parameters passed to the > Mathematica script via $ScriptCommandLine. Promising, but the documentation does not provide a clear example of how I could call a `Mathematica Script` with a list as a parameter. If anyone has suggestions on how to go about this or can refer me to information that gets me part of the way to a solution, please let me know. * * * _Sidebar -- the tutorial makes no mention of running Mathematica Scripts under Windows. This has me a little worried. An answer to anearlier question I asked implies that one can do this on a Windows platform see: Chris' answer at the bottom. Does anyone know for certain? Examples appreciated._ * * * Using `Encode[]` seems like it could also help by securing the code and making it less likely that anyone could view it. This raises some questions: The documentation for `Encode[]` states: > On certain computer systems Encode["source","dest",MachineID->"ID"] can be > used to generate an encoded file that can be read only on a computer with a > particular $MachineID. This would help a great deal in securing the code, but the documentation does not list the "...computer systems..." on which this will work. Any ideas? More `Encode[]` questions. Does one use `Encode[]` to encode:   * single functions?    * notebooks including the function?   * packages (.m files)?   * something else? The example in the documentation doesn't seem clear on this. **The beginning of a solution...** It seems like the following begins to give me a workable approach if I can clear up some of the issues:   * Use `Encode["source", "dest", MachineID->"ID"]` to secure the code.   * Run the kernel(s) and the function from a `Mathematica Script`. The target environment will need a Mathematica license and processes and policies to launch and shut down the kernels, but I can work with that. Can I create a workflow wherein I:   * launch the kernel by a script at the begining of a day;    * use a script to call the function on the kernel throughout the day; and    * close the kernel at the end of the day? This would help address the reliability issue. Or should the kernel launch, run the function, then close everytime I want to use the function? So...I've got a general idea of one way to go about this. I could use some guidance take it down another level of detail. Oh, course if anyone has other ways to go about this, let me know.


Simulation Beta Distribution

Suppose a function such as: $\phi^{\alpha} (x,y) = \left\\{ \begin{array}{l l} \alpha x & \quad \text{if $x < y$}\\\ x & \quad \text{if $x = y$}\\\ \alpha x + (1 -\alpha) & \quad \text{if $x > y$}\\\ \end{array} \right.$ I wish to run a simulation for 5 random walks (each with length 100) on $\phi$ where $x$ is drawn from a beta distribution with parameters (3,1) and $\alpha = 0.5$. I don't know how to deal with $\phi$ in the random walk process, especially given its 3 conditions. EDIT: $y$ is the mean of all the previous $x$. For instance, suppose we are at time $t=3$ and observations start at $t=0$. Then, $y_3 = \frac{x_0 + x_1 + x_2}{3}$. * * *               ϕ[x_, y_] := Piecewise[{       {α*x, x < y},        {x, x == y},        {α*x + (1 - α), x > y}}]     ϕ[x, y]      ![](http://i.stack.imgur.com/8ODgj.png)


Eliminate 3 Variable from 4 Equations

I am trying to use _Mathematica_ to `Eliminate` 3 following variable from 4 equations. Any clue or link to similar solved problem is highly appreciated:               eq = {       Cos[θ] + Cos[ϕ] + Cos[ψ] == a,       Sin[θ] + Sin[ϕ] + Sin[ψ] == b,       Cos[2 θ] + Cos[2 ϕ] + Cos[2 ψ] == c,       Sin[2 θ] + Sin[2 ϕ] + Sin[2 ψ] == d};     Eliminate[eq, {θ, ϕ, ψ}]


Changes in Handling of Real Zeros

I recently upgraded from Mathematica 5 to Mathematica 8 and I have a number of notebooks that no longer work correctly. The problems relate to the use of units. I don't need complicated unit conversions so I typically just tag values with symbols for the units. Under Mathematica 5, I could write the following (I understand that this example isn't physically meaningful):               3. in + 4. in - 7. in + 5. lb      And Mathematica would return               5. lb      Now, under Mathematica 8, I get               0. + 5. lb      This breaks a large number of notebooks. Can someone explain what is happening, and what if anything I can do to get the old behavior back? Thanks!


Aligning two lists

I have two lists, L1 and L2, each with a key and some data. Let us say the key is a person's name, a string, and the data follows. (To respond to _rasher_ 's query:) Let us also assume the lists are sorted by key:               L1 = {            {"Joseph O'Rourke", data1, data2, ... },            ...          }      I would like to "align" the two lists in the following sense. If L1 has a name A that is not in L2, then L2 is padded to include a "blank" record for A. And vice versa: If L2 has a name B that is not in L1, then L1 is modified to include a "blank" record for B. Then I will have two lists that "align":               L1' = { {A,...}, {0,...}, {C,...},  {D,...}, ...}     L2' = { {A,...}, {B,...}, {0,...},  {D,...}, ...}      where maybe `0 == {}`. With the lists aligned in this fashion, I could make a two-column table (one column per list) that would directly compare one list against the other. My question is: > What is a clean method for accepting L1 and L2 as input, and returning L1' > and L2' as output, with the latter two lists aligned as above? I can accomplish this via tedious list For-loops, but I suspect the cognoscenti :-) will offer more concise and efficient methods. Thanks for your help!


Function Interpolation with Automatic / Algorithmic Values Mesh

I have an underlying function f(x,y,z) that is computationally intensive, but is smooth and continuous. I'm needing to find the function values along a line in xyz. Currently, I'm calculating f at discrete steps and I'm wondering if there is a way to get mathematica to automatically chose the step size and work out an interpolating function based on some inputs like how accurate I need it to be and what the initial step size should be. I'm thinking it would kind of work like the mesh function does in plotting by evaluating functions more often in areas of higher complexity. Does anyone have any ideas where to start?


Stopping Agglomerative clustering under a condition in Mathematica

How do I instruct Agglomerative clustering to stop/NOT merging two particular clusters if the distance between the two clusters is larger than a threshold value? I know that we can implement a custom distance measure and a custom linkage function. Distance measure says how to measure the distance between any two data points. So even if I implement a custom distance measure, it just says what is the distance between any two data points. Where in the code should/can I mention a threshold value, that if not met, should prevent thw clusters from being merged. Thus, at the end, if only two clusters are remaining, and if the threshold value is not met between these two clusters, then these two clusters should not be merged into one global cluster. Is this possible in Mathematica?


Computing Many Slow I/O Operations

In working on a custom stock screener, I often need to run mathematica code like this:               {#, FinancialData[#, "DividendYield"]} & /@ Take[FinancialData["NYSE:*"], 30]      In this example, I've limited the result set to 30, but ideally I'd like to get the dividend yield for a much larger set. This is a specific example of a more general problem I have with mathematica, which is that sometimes I need to run a large number of distinct network IO calls and this blocks further computations. Is there some workaround for writing calls like this that won't block further computations? I am a fairly competent programmer and therefore can implement a system in my Mathematica code to compute results one at a time, but I am trying to avoid reinventing the wheel. I feel this must be a very common problem for Mathematica users who use the built in data sources/Wolfram|Alpha integration.


Data acquisition from NI USB-6008, NI-DAQmx

I want to connect an interface from National Instruments to Mathematica in mac, i already download the driver Ni-DAQmx_Base_3.6 from NI page. How to tell Mathematica to dump data from the interface?


How to create strong types?

In a program I'm writing, I create a list of lists, that looks something like this:               {{100, {1,2,3,4,5}},      {105, {2,4,6,8}},      {42, {42,39,56}}}      I then pass this list of lists around to other functions. All well and good -- the problem is that this program has been developed iteratively, and this representation has changed, and so now I'd like to take more care in checking that the function is receiving the right kind of input. In another language I could make this list of lists into its own type, and the compiler would enforce things. I know Mathematica has some facility for doing type checking, at least with primitive types, such as:               myFunc[a_String, b_Integer] := ...      But are there facilities available for creating (and enforcing, or at least checking) one's own ADTs?


Function for Autocorrelation

Is there a built in function to compute the autocorrelation of a signal ?


TeX and TraditionalForm

I have a little problem, and hope, with your help, I'll be able to solve it. As you got from the title, I have some trouble with TeX in Mathematica. Imagine, I want to output a nice DisplayFormula, such that it would represent a function, which evaluates piecewise. In TeX it would look like this (Let's take a uniform distribution for example) $$\left\\{ \begin{aligned} &0,& t\leq x_{\min} \\\ &\frac{t-x_{\min}}{x_{\max}-x_{\min}},&x_{\min}<t\leq x_{\max} \\\ &1,& t>x_{\max} \end{aligned} \right.$$ So what's the best way to create that exact output in Mathematica? I've tried `TraditionalForm[CDF[UniformDistribution[{x_ {min}, x_ {max}}], t]]`, but that gives me almost the same output, but without the zero part. ![enter image description here](http://i.stack.imgur.com/D4N8f.png) I do know, it's not significant whether to write or not the 0 part in the piecewise function. So it works well for CDF, but with PDF there's an extraneous part is shown at the end               TraditionalForm[CDF[UniformDistribution[{x_ {min}, x_ {max}}], t]]      ![enter image description here](http://i.stack.imgur.com/OZUup.png) So in the CDF Mathematica's decided not to output the 0 part, but in the PDF it's shown. I've also tried to use               TraditionalForm[       Piecewise[        {{0, t <= Subscript[x, min]},         {(t - Subscript[x, min])/(Subscript[x, max] - Subscript[x, min]),           Subscript[x, min] < t <= Subscript[x, max]},         {1, t > Subscript[x, max]}},        t       ]     ]      But that variant also reveals the part that I haven't specified. ![enter image description here](http://i.stack.imgur.com/xCkPI.png) The last thing I've tried to use is `ToExpression["TeX source",TeXForm]`, but this one can't parse the simple TeX source with aligned environment (or I haven't found a way to make it work).


Why does Hash return different values in Version 7?

This function does not work correctly for me. The generated Gravatars do not match the ones actually produced by using the corresponding address. The problem was traced to differing output from the `Hash` function. VLC points out that the `Hash` documentation pages for version 7 and version 8 have common examples but show different outputs. From version 7 I get:               IntegerString[Hash["gmailuser+10511@gmail.com", "MD5"], 16, 32]      > >     "cc270b8fbfb33469629c14e358183dd7" >   Version 8 users apparently get: > >     "d9c48b644b8cc89bbcd07ec7a54dafc9" >   Why do I get a different result and how do I get the right one?


Operator-Input Form for Lists?

The documentation on Operator-Input Forms shows the following example ![enter image description here](http://i.stack.imgur.com/trzvh.png) which suggests that there is an alternative, convenient, operator-style, tidy technique for inputting lists. However, there is not enough clarity in the example to determine what that technique or operator might be. I tried `e11``Space``e12` and `e11``Tab``e12`, but they both result in `Times[e1,e2]`, somewhat predictably, since space normally denotes multiplication in Mathematica notebooks. Any ideas whether there is an operator form for inputting lists? What does the documentation mean in this case?


How to fit a one-dimensional dataset with respect to several bounded parameters?

I have this set of data               mydata={{1244,0.90237},{1289,0.83072},{1306,0.76147},{1360,0.6094},{1388,0.40952},{1428,0.29419},{1488,0.15592},{1494,0.11718},{1527,0.09192},{1537,0.07757},{1590,0.04546},{1594,0.04563},{1654,0.03229},{1737,0.01976},{1740,0.01949};      and I need it fitted into a function of the form               Exp[-(A*TT*^n*Exp[-Ea/(R*TT)])*t]      where $R$ is the gas constant $R=8.31\dots$ and $t=0.002$. This is a decay and the function in the exponent is the Arrhenius factor. I checked the help for the fitting tools, but what I found was either in one variable, or in more variables, but for a higher dimensional plot. I also have variable bounds which I need to implement. I have this simple curve with parameters               A, n, Ea      $A$ is bounded by $10^{12}$ and $10^{14}$, $Ea$ lies between $270000$ and $320000$, $n$ close to zero (single digit). The plot of the function should be with respect to temperature $TT$ is the varying variable on the x-axis.


Trial version 10 vs Version 10 Prerelease 13

When I open the new trial version (creation id 5099521; 10.0.30732.17750) I get these error messages ![enter image description here](http://i.stack.imgur.com/Ez2Ry.jpg) and only a partial view of the "About" box ![enter image description here](http://i.stack.imgur.com/dUUP1.jpg) I haven't run into any particular problem, except that color of 3D plots are different from version 10 prerelease 13 (but now using PlotTheme -> {"Classic", "ClassicLights"} thanks to this web site!) Using Windows 7 64 bit professional


Simpler way to fill date gaps with zero values

One basic problem when working with data like sales and dates is the case where you dont't have sales in all days, so you have to fill it to take information as average or to make a plot. See this toy code as example:               dateList={{{2012,1,1},1},{{2012,1,2},2},{{2012,1,5},3},{{2012,1,8},4}};      And I need to get this answer:               {{{2012,1,1},1},{{2012,1,2},3},{{2012,1,3},0},{{2012,1,4},0},{{2012,1,5},3},{{2012,1,6},0},{{2012,1,7},0},{{2012,1,8},4}}      where the missing dates are filled with value zero. They are date and sales values that I get from an SQL database. I created this functions, but I fell that it could be simplified:               getDateRange[dtIni_,dtFim_]:=NestWhileList[DatePlus[#,1]&,dtIni,(#!=dtFim)&]          fillDateGaps[list_]:=Module[{sortedOrgList,dateRange,listGaps},         sortedOrgList=SortBy[list[[All,1]],#[[1]]&];         dateRange=getDateRange[First@sortedOrgList,Last@sortedOrgList];         listGaps={#,0}&/@Complement[dateRange,sortedOrgList];         Union[list,listGaps]     ]      With this function I can do calculations and things like this:               DateListPlot[fillDateGaps[dateList], Joined -> True]      ![DateListPlot with filled zeros](http://i.stack.imgur.com/zmXQg.png) How to make it simpler and faster?


Scaling edge thicknesses

* * * **UPDATE** There may be some confusion as to the specification of the problem. kguler's answer doesn't really answer the question. I'll try to elaborate a bit at **the bottom of the post**. * * * One problem with the solutions of the custom arrow shaft question is the specification of the edge thickness. In the design of the arrows, the thickness of the edge _in relation to the overall size of the arrow_ is part of the effect one wants to achieve. ![Mathematica graphics](http://i.stack.imgur.com/ajCIw.png) Unfortunately, the two methods that can be used to specify the edge thickness, namely `Thickness` and `AbsoluteThickness` are not sufficient for this goal. As an easy illustration of the problem, I'll draw some circles here. **Thickness**               Graphics[{FaceForm[], EdgeForm[{Thickness[0.1], Blue}], Disk[{0, 0}]}, ImageSize -> 200]      ![](http://i.stack.imgur.com/tummV.png) Add some **identical (!)** copies of the same circle:               Graphics[{FaceForm[], EdgeForm[{Thickness[0.1], Blue}],               Disk[{0, 0}], Disk[{3, 0}], Disk[{6, 0}]}, ImageSize -> 600]      ![Mathematica graphics](http://i.stack.imgur.com/Z9nqd.png) The number in the `Thickness` specification is a fraction of the horizontal image extent. **AbsoluteThickness**               Graphics[{FaceForm[], EdgeForm[{AbsoluteThickness[20], Blue}], Disk[{0, 0}]}, ImageSize -> 200]      ![Mathematica graphics](http://i.stack.imgur.com/qZKuy.png) Now, let's reduce the image size:               Graphics[{FaceForm[], EdgeForm[{AbsoluteThickness[20], Blue}], Disk[{0, 0}]}, ImageSize -> 70]      ![Mathematica graphics](http://i.stack.imgur.com/niktc.png) In both cases, the ratio between the edge thickness and the object size changes. Sometimes that may be desirable, but here it isn't. What is needed is either a thickness specification that is related to object size or a status variable from which the current image extent can be read, so that with known object size the edge thickness can be scaled. The latter would be something akin to `CurrentValue` or so. Something self-referential like               pl = Graphics[{Text[Norm@PlotRange[pl][[2]] // Dynamic, {10, 10}]}]      could work, but is rather ugly and, frankly, scary. When I changed `PlotRange` to `ImageSize` I got my frontend hanging. Any ideas? * * * **UPDATE** Trying to further clarify the question. * * * First, some definitions: ![Mathematica graphics](http://i.stack.imgur.com/n0SyH.png) We have one or more objects with a given **object size**. In this case, circles with a radius of one. This size is given in Mathematica's internal, dimensionless canvas coordinate system. We want to specify the **object edge thickness** in terms of this object size. However, MMA doesn't have that capability. You have to either specify the `EdgeForm` as `Thickness` (which measures edge thickness as a fraction of the horizontal `PlotRange`) or as `AbsoluteThickness` (which measures edge thickness in terms of printer's points, 1/72 of an inch). The `PlotRange` is the dimensionless size of MMA's canvas as displayed in the figure. It is fully independent of the `ImageSize`, which determines the graphics's physical size in printer's points. This leads to the following problem :               Graphics[{FaceForm[], EdgeForm[{Thickness[0.1], Blue}], Disk[{0, 0}]}]      ![Mathematica graphics](http://i.stack.imgur.com/1xf7h.png)               Graphics[{FaceForm[], EdgeForm[{Thickness[0.1], Blue}], Disk[{0, 0}], Disk[{3, 0}], Disk[{6, 0}]}]      ![Mathematica graphics](http://i.stack.imgur.com/CoJy8.png) Both figures have the same `ImageSize`, but the `PlotRange` has increased (more of MMA's internal canvas is revealed), which means that edge thickness related to object size increases too, since the thickness in canvas terms increases whereas the object remains at the same canvas size. The circle's edge now takes up most of the circle's area, which wasn't the case before. If we specify thickness with `AbsoluteThickness` we get:               Graphics[{FaceForm[], EdgeForm[{AbsoluteThickness[10], Blue}], Disk[{0, 0}]}]      ![Mathematica graphics](http://i.stack.imgur.com/YYuA4.png)               Graphics[{FaceForm[], EdgeForm[{AbsoluteThickness[10], Blue}],                Disk[{0, 0}], Disk[{3, 0}], Disk[{6, 0}]}]      ![Mathematica graphics](http://i.stack.imgur.com/V3swe.png) In this case, the edge thickness _in points_ remains the same, but the object size in points decreases because the `ImageSize` in points is the same, but more objects have to be fitted in that same space, so they get less points allotted per object. Again, the edge thickness related to the object size changes. Introducing `ThicknessC` as the desired edge thickness and `ObjectSizeC` the object size, both in canvas terms, we have               ThicknessC = C*ObjectSizeC       with C the desired constant ratio of these two variables. C is responsible for the appearance of the object. For instance, we might want to have a circle where the edge thickness is 1/10 of its diameter, so C = 1/10. Since `Thickness` is a fraction of the horizontal `PlotRange` we have:               ThicknessC = Thickness*PlotRange (hor.)      and hence, to get the desired edge thickness `ThicknessC`, we have to specify a `Thickness` given by:               Thickness =  C * ObjectSizeC / PlotRange (hor.)      Similarly, we have:               Thickness = AbsoluteThickness / ImageSize      and hence,               AbsoluteThickness = C * ObjectSizeC * ImageSize / PlotRange (hor.)      It seems that any object related edge thickness specification minimally needs to know the final `PlotRange` of the figure, which, on its turn, is determined by all objects in the figure. If we're going to use `AbsoluteThickness` (but why would we bother?) we'd also need awareness of the `ImageSize` in addition to knowledge about `PlotRange`. > So, there you have it. The problem can be solved if we can obtain the final > `PlotRange`. The question to be asked is: How can we determine the > `PlotRange` of a figure while we are drawing it? Of course, `PlotRange` can be set manually, or be obtained after the fact, but that would mean something ugly like:               pr1 = -Subtract @@PlotRange[             Graphics[{FaceForm[], EdgeForm[{Thickness[0.3], Blue}],                      Disk[{0, 0}], Disk[{3, 0}], Disk[{6, 0}]}]][[1]];     pr2 = -Subtract @@ PlotRange[             Graphics[{FaceForm[], EdgeForm[{Thickness[0.3], Blue}], Disk[{0, 0}]}]][[1]];     Graphics[{FaceForm[], EdgeForm[{Thickness[0.3 pr2/pr1], Blue}],                Disk[{0, 0}], Disk[{3, 0}], Disk[{6, 0}]}]     Graphics[{FaceForm[], EdgeForm[{Thickness[0.3], Blue}], Disk[{0, 0}]}]      ![Mathematica graphics](http://i.stack.imgur.com/ESZGG.png) This works, but isn't elegant.


1D Euler Equations

Is it possible to _accurately_ solve the 1D Euler equations in Mathematica using NDSolve? For example, let us consider the problem given here: http://www.csun.edu/~jb715473/examples/euler1d.htm Using the notation $(r,v,e)$ for $(\rho,v,E)$ we can formulate the problem in Mathematica as:               eqs = {         D[r[x, t], t] + D[r[x, t] v[x, t], x] == 0,         D[r[x, t] v[x, t], t] + D[r[x, t] v[x, t]^2 + p[x, t], x] == 0,         D[e[x, t], t] + D[v[x, t] (e[x, t] + p[x, t]), x] == 0     };      with $g:=\gamma$,               p[x_, t_] := (g - 1) (e[x, t] - r[x, t] v[x, t]^2/2);      and initial conditions               r0[x_] := 1.0 Boole[0 < x <= 0.5] + 0.25 Boole[0.5 < x <= 1.0];     v0[x_] := 0.0;     p0[x_] := 1.0 Boole[0 < x <= 0.5] + 0.1 Boole[0.5 < x <= 1.0];      Setting Dirichlet boundary conditions and throwing it into NDSolve:               ppR = 401;     ndsol = NDSolve[Join[eqs, {         r[x, 0] == r0[x], r[0, t] == r0[0], r[1, t] == r0[1],         v[x, 0] == v0[x], v[0, t] == v0[0], v[1, t] == v0[1],         p[x, 0] == p0[x], p[0, t] == p0[0], p[1, t] == p0[1]}],      {r, v, e}, {x, 0, 1}, {t, 0, 0.1},      MaxSteps -> 10^3, PrecisionGoal -> 4, AccuracyGoal -> 4,       Method -> {"MethodOfLines", "Method" -> "StiffnessSwitching",       "SpatialDiscretization" -> {"TensorProductGrid",        "DifferenceOrder" -> Pseudospectral, "MaxPoints" -> {ppR},        "MinPoints" -> {ppR}}}]      Taking the solution and plotting               DensityPlot[Evaluate[First[v[x, t] /. ndsol]], {x, 0, 1}, {t, 0, 0.1}, ColorFunction -> Hue]      ![Solution plot](http://i.stack.imgur.com/ZVXXy.png) We see some nasty numerical errors. Is there anyway to get an accurate solution using NDSolve? **Edit:** This paper suggests that the Method of Lines should apply: http://math.lanl.gov/~mac/papers/numerics/H79.pdf


silent soundnote and superimposing sound objects

In Mathematica 9, Soundnote[None] has zero duration if it is the last note in a Sound expression. For instance, the sound object               Sound[{SoundNote[None],SoundNote[None],SoundNote[1]}]      has a correct duration of 3 seconds, while               Sound[{SoundNote[1],SoundNote[1],SoundNote[None]}]      has a duration of 2 seconds. This means that a SoundNote[None] has a duration of 1 second if and only if it is not the last note, otherwise has zero duration. This does not make sense at all. Silent notes must have the same duration at any point of a musical composition. As an example of consequence of this non-sense behaviour, let us superimpose two sounds objets composed of the same number of notes, one of which has a silent note at its end:               s1 = Sound[{"Piano", SoundNote[1], SoundNote[5], SoundNote[8]}, {0, 3}];          s2 = Sound[{"Viola", SoundNote[3], SoundNote[1], SoundNote[None]}, {0, 3}];          Sound[{s1, s2}]        ![enter image description here](http://i.stack.imgur.com/vsMzb.png) You can see that they do not superimpose as you might expect. Each instrument should play a note every second. What happens instead, is that the Viola (green) plays every 1.5 seconds because has a silent note at the end.


Strange behavior of `BoundaryMeshRegion`

`BoundaryMeshRegion` is new function of version 10. I am not familiar with the function. I want to decide whether a point is inside or outside in the Boundary using `RegionMember`. This code is not able to work. why is it?               BoundaryMeshRegion[{{4, 4, 4}, {4, 4, 6}, {4, 6, 4}, {4, 6, 6}, {6, 4,         4}, {6, 4, 6}, {6, 6, 4}, {6, 6, 6}},       Polygon[{{2, 3, 1}, {6, 8, 7}, {2, 5, 6}, {1, 7, 5}, {4, 7, 8}, {2,          6, 4}, {2, 3, 4}, {6, 5, 7}, {1, 2, 5}, {1, 3, 7}, {3, 4, 7}, {8,          4, 6}}]]      > BoundaryMeshRegion[{{4, 4, 4}, {4, 4, 6}, {4, 6, 4}, {4, 6, 6}, {6, 4, 4}, > {6, 4, 6}, {6, 6, 4}, {6, 6, 6}}, Polygon[{{2, 3, 1}, {6, 8, 7}, {2, 5, 6}, > {1, 7, 5}, {4, 7, 8}, {2, 6, 4}, {2, 3, 4}, {6, 5, 7}, {1, 2, 5}, {1, 3, 7}, > {3, 4, 7}, {8, 4, 6}}]] But this is able to work. What is different.               BoundaryMeshRegion[{{4, 4, 4}, {4, 4, 6}, {4, 6, 4}, {4, 6, 6}, {6, 4,         4}, {6, 4, 6}, {6, 6, 4}, {6, 6, 6}},       Polygon[{(*{2,3,1},{6,8,        7},*){2, 5, 6}, {1, 7, 5}, {4, 7, 8}, {2, 6, 4}, {2, 3, 4}, {6, 5,          7}, {1, 2, 5}, {1, 3, 7}, {3, 4, 7}, {8, 4, 6}}]]      > ![Blockquote](http://i.stack.imgur.com/09jD3.png) ## Are these bugs too? **Case 1**               Graphics3D[{Opacity[0.5], tmp, Opacity[1], Red, PointSize[0.05],        Point[{2, 0, 0}]}, Boxed -> False]      > ![Blockquote](http://i.stack.imgur.com/ECyhn.png)               tmp = RevolutionPlot3D[{2 + Cos[t], Sin[t]}, {t, 0, 2 Pi},       PlotPoints -> 2]; tmp =       GraphicsComplex[tmp[[1, 1]], tmp[[1, 2, 1, 1, 5, 1]]];     r1 = BoundaryDiscretizeGraphics@tmp      > ![Blockquote](http://i.stack.imgur.com/UyCqH.png)               RegionQ[r1]      > True               RegionMember[r1, {2, 0, 0}]      > False **Case 2**               BoundaryDiscretizeGraphics[      GraphicsComplex[{{4, 4, 4}, {4, 4, 6}, {4, 6, 4}, {4, 6, 6}, {6, 4,          4}, {6, 4, 6}, {6, 6, 4}, {6, 6, 6}},        Polygon[{(*{2,3,1},{6,8,         7},*){2, 5, 6}, {1, 7, 5}, {4, 7, 8}, {2, 6, 4}, {2, 3, 4}, {6, 5,           7}, {1, 2, 5}, {1, 3, 7}, {3, 4, 7}, {8, 4, 6}}]]]      > ![Blockquote](http://i.stack.imgur.com/snusC.png)


Analysis of Facebook group

I am the admin of a Facebook group for our year at university and wanted to graph the members of the group like you can with your own friends so we can find the isolated people and get rid of them (as they are spamming). I have tried treating the page as an ID but don't really know how to proceed. Is this possible?


problem with Importing multiple files

I need to import about 100000 "dat" files to my progrom. I want to do this using the last answer to this question: Importing multiple files using a for-loop I know that I should define a list of all the names of my files, and at the end, I `Import` all of them. But I have a problem with this. The names of my files obey a special pattern, like this:               "mutomu,dms41,x1,dms51,x2,q24,x3,q25,x4.dat"      Which x1-x4 are integers in this way:               {x1, 1, 21}, {x2, x1, 21}, {x3, 1, 15}, {x4, 1, 15}      . When I am defining the names of my files, I do it as:               allprobabilityfiles = {Flatten[Table[{{x1, x2, x3, x4},"mutomu,dms41,x1,dms51,x2,q24,x3,q25,x4.dat"}, {x1, 1, 21,1}, {x2, x1, 21, 1}, {x3, 1, 15, 1}, {x4, 1, 15, 1}], 3]};      but in this way, the result is:               ....{{21, 21, 6, 5}, "mutomu,dms41,x1,dms51,x2,q24,x3,q25,x4.dat"},      {{21, 21, 6, 6}, "mutomu,dms41,x1,dms51,x2,q24,x3,q25,x4.dat"},      {{21, 21, 6, 7}, "mutomu,dms41,x1,dms51,x2,q24,x3,q25,x4.dat"}, ....      (x1-x4 don't change inside the file names in this table), but what I need is the following:               ....{{21, 21, 6, 5}, "mutomu,dms41,21,dms51,21,q24,6,q25,5.dat"},      {{21, 21, 6, 6}, "mutomu,dms41,21,dms51,21,q24,5,q25,6.dat"},      {{21, 21, 6, 7}, "mutomu,dms41,21,dms51,21,q24,5,q25,7.dat"}, ....      How can I solve this problem?