How to preform multiple linear regression on a dataset in python with scikit-learn?

Question: My python code originally outputted these results, a list of dictionaries of the population of a census tract (basically an area of land) and the various land cover types. Here that is:
[{'Total Population:': 4585, 'Total Water Ice Cover': 2.848142234497044, 'Total Developed': 17.205368316575324, 'Total Barren Land': 0.22439908514219134, 'Total Forest': 34.40642126612868},

 {'Total Population:': 4751, 'Total Water Ice Cover': 1.047783534830167, 'Total Developed': 37.27115716753022, 'Total Barren Land': 0.11514104778353484, 'Total Forest': 19.11341393206678},

 {'Total Population:': 3214, 'Total Water Ice Cover': 0.09166603009701321, 'Total Developed': 23.50469788404247, 'Total Barren Land': 0.2597204186082041, 'Total Forest': 20.418608204109695},

 {'Total Population:': 5005, 'Total Water Ice Cover': 0.0, 'Total Developed': 66.37545713124746, 'Total Barren Land': 0.0, 'Total Forest': 10.68671271840715},

...
]

Then taking that code placing it into a pandas object:
import pandas as pd
df = pd.DataFrame(output)
print(df)
#   Total Barren Land  Total Developed  Total Forest  Total Population:  Total Water Ice Cover
#0           0.224399        17.205368     34.406421               4585               2.848142
#1           0.115141        37.271157     19.113414               4751               1.047784
#2           0.259720        23.504698     20.418608               3214               0.091666
#3           0.000000        66.375457     10.686713               5005               1.047784

Then to get the pearson 'r' correlation:
pd.set_option("precision",4)  # only show 4 digits

# remove 'Total ' from column names to make printing smaller
df.rename(columns=lambda x: x.replace("Total ", ""), inplace=True)

corr = df.corr(method="pearson")
print(corr)
#                 Barren Land  Developed  Forest  Population:  Water Ice Cover
#Barren Land           1.0000    -0.9579  0.7361      -0.7772           0.4001
#Developed            -0.9579     1.0000 -0.8693       0.5736          -0.6194
#Forest                0.7361    -0.8693  1.0000      -0.1575           0.9114
#Population:          -0.7772     0.5736 -0.1575       1.0000           0.2612
#Water Ice Cover       0.4001    -0.6194  0.9114       0.2612           1.0000

Now I have all the pearson 'r' correlation values between population and various land cover types.
What I want to do now is calculate the multiple linear regression. I am trying to perform multiple linear regression between the population density and area percentage of the following surface covers and calculate the R2 of the regression: developed, class planted/cultivated class and maybe some other. Could this also be done through pandas?
Thank you
Answer: You can do a multiple regression with either Scikit-learn or Statsmodels.
You can see an exemple of multiple regression using scikit_learn here: Multiple linear regression in Python
As for Statsmodels, you can do something like that:
import statsmodels.api as sm

X = df[["variable_1", "variable_2"]]
y = df["target"]

model = sm.OLS(y, X).fit()
predictions = model.predict(X)
model.summary()

Comment: Thank you What would target be? And what would variable_1 and variable_2 be in context of my dataset.
Comment: target is the variable that you want to predict with your regression, while variable_1 and variable_2 are the variables that you want to use to predict the variable target.
Comment: Thank you. If I want to perform multiple linear regression between the population density and area percentage of the following surface covers and calculate the R2 of the regression: developed, class planted/cultivated. Would population be my target, and variable_1 be developed and variable_2 be class planted/cultivated?
Comment: Yes, it would be that in your case


How to create async http requests in a loop?

Question: Yesterday I've found out how to create several async http requests without async/await. But today I need to do it in a loop: if some of responses don't satisfy some condition - I need to change a request for them and send these requests again. It may be repeated several times.
I've tried this code:
do
{
    var loadingCoordinatesTasks = new List<Task<Terminal>>();
    var totalCountOfTerminals = terminalPresetNode.ChildNodes.Count;
    var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();

    foreach (var terminal in terminals.Except(_terminalsWithCoordinates))
    {
        var address = terminal.GetNextAddress();
        var webRequest = (HttpWebRequest)WebRequest.Create(GeoCoder.GeoCodeUrl + address);
        var webRequestTask = Task.Factory.FromAsync<WebResponse>(webRequest.BeginGetResponse,
                                                                 webRequest.EndGetResponse,
                                                                 terminal);
        var parsingTask = webRequestTask.ContinueWith(antecedent =>
        {
            // Parse the response
        });
        loadingCoordinatesTasks.Add(parsingTask);
    }

    Task.Factory.ContinueWhenAll(loadingCoordinatesTasks.ToArray(), antecedents =>
    {
        foreach (var antecedent in antecedents)
        {
            var terminalWithCoordinates = antecedent.Result;
            if (antecedent.Status == TaskStatus.RanToCompletion &&
                !terminalWithCoordinates.Coordinates.AreUnknown)
            {
                _terminalsWithCoordinates.Add(terminalWithCoordinates);
                _countOfProcessedTerminals++;
            }
        }
    });
} while (_countOfProcessedTerminals < totalCountOfTerminals);

but is it possible to check the condition in while just after every single set of requests executed?
Answer: You can perform the check after increasing the count:
_countOfProcessedTerminals++;
if (_countOfProcessedTerminals >= totalCountOfTerminals)
{
    break;
}

Is _countOfProcessedTerminals thread-safe though?
Comment: No, it's not thread-safe yet, but I can do that. The question is: how to organize the loop?
If to write `while(true)` it'll create plenty of extra requests.
Answer: I manage to do it using recursion:
public void RunAgainFailedTasks(IEnumerable<Task<Terminal>> tasks)
    {
        Task.Factory.ContinueWhenAll(tasks.ToArray(), antecedents =>
        {
            var failedTasks = new List<Task<Terminal>>();
            foreach (var antecedent in antecedents)
            {
                var terminal = antecedent.Result;
                // Previous request was failed
                if (terminal.Coordinates.AreUnknown)
                {
                    string address;
                    try
                    {
                        address = terminal.GetNextAddress();
                    }
                    catch (FormatException) // No versions more
                    {
                        continue;
                    }
                    var getCoordinatesTask = CreateGetCoordinatesTask(terminal, address);
                    failedTasks.Add(getCoordinatesTask);
                }
                else
                {
                    _terminalsWithCoordinates.Add(terminal);
                }
            }
            if (failedTasks.Any())
            {
                RunAgainFailedTasks(failedTasks);
            }
            else
            {
                // Display a map
            }
    },  CancellationToken.None,
        TaskContinuationOptions.None,
        TaskScheduler.FromCurrentSynchronizationContext());
}

private Task<Terminal> CreateGetCoordinatesTask(Terminal terminal, string address)
    {
        var webRequest = (HttpWebRequest)WebRequest.Create(GeoCoder.GeoCodeUrl + address);
        webRequest.KeepAlive = false;
        webRequest.ProtocolVersion = HttpVersion.Version10;
        var webRequestTask = Task.Factory.FromAsync<WebResponse>(webRequest.BeginGetResponse,
                                                                webRequest.EndGetResponse,
                                                                terminal);
        var parsingTask = webRequestTask.ContinueWith(webReqTask =>
        {
            // Parse the response
        });
        return parsingTask;
    }


Neo4j graph database design for combining data from different sources

Question: I am trying to analyze data from two different running systems by modeling them as a graph. Many of the users in the two systems are common but could have different properties: e.g. some users have omitted their middle names or prefixes in one system but not in other.
For my analysis, I'd like to consolidate users across the systems as logically one for their relationships. I'm not sure how I should be storing them. Should I store two different nodes and logically group them together as one during my queries? Or should I store them as one node at the first place? How would I store varying properties like slight variations in the names for the same person?
Answer: I think it would be better to create only one node for each user as, they are not different users and this way you can have advantage of property graphs.
You can create two properties, e.g. for name each user node will have,
name-system1 and name-system2.
Creating two different user nodes for same users and then connecting them with a relationship will affect your query performance so better to go for one node for each user.
I hope it helps!


Relationship on a complex of vector spaces

Question:
Fact: If $U,V,W$ are $k-$vector spaces and there is a short exact sequence
  $$0 \rightarrow U \rightarrow V \rightarrow W \rightarrow 0$$
  then the following relation holds:
  $$\textrm{dim}~V =\textrm{dim}~U + \textrm{dim}~W.$$

Show that if
$$C:0 \rightarrow V_{n} \rightarrow V_{n+1} \rightarrow \dots \rightarrow V_1 \rightarrow V_{0} \rightarrow 0$$
is a complex of $k-$vecotr spaces, then
$$\sum_{i=0}^{n} (-1)^i \textrm{dim}~V_i = \sum_{i=0}^{n} (-1)^{i} \textrm{dim}~H_i(C).$$
While studying for my preliminaries I came across this problem. Any help is much appreciated.
Comment: @MichaelAlbanese, I tried to use the definitions. Exactness means that the map from $U$ to $V$ is injective and $V$ to $W$ is surjective. I tried to reduce the given complex for the set up as in the "Fact" I stated but wasn't successful. That's why I asked.
Comment: "Exactness means that the map from $U$ to $V$ is injective and $V$ to $W$ is surjective" — not quite, it means something more.
Answer: For a compltex $C$ of the form $0 \to V_1 \to V_0 \to 0$, we have $\textrm{dim } V_0 - \textrm{dim } V_1 = \textrm{dim } H_0 (C) - \textrm{dim } H_1 (C)$.
By induction, we assume that this result holds for $0 \to V_{n} \to \cdots \to V_2 \to V_1 \to V_0 \to 0$. Then for $0 \to V_{n+1} \to V_{n} \to \cdots \to V_2 \overset{f}{\to} V_1 \to V_0 \to 0$, we decompose it two short complexes $$0 \to V_{n+1} \to V_{n} \to \cdots \to V_2 \to \text{im f} \to 0$$ and $$0  \to \text{im f} \to V_1 \to V_0 \to 0.$$ Then we can get the result.
Comment: The word "short" is kind of misleading, as you get a complex of the same length :-)
Comment: @Alejo, thank you very much for your explanatory answer. Apologies for my lack of knowledge and misunderstanding.
Comment: @  Alejo oh, I have added my answers.
Comment: @bing, thank you very much for your answer as well.
Answer: Note that by definition of homology of a complex
$$\cdots \to V_{i+1} \xrightarrow{d_{i+1}} V_i \xrightarrow{d_i} V_i \to \cdots$$
you have short exact sequences
$$0 \to \operatorname{im} d_{n+i} \to \ker d_i \to H_i (V_\bullet) \to 0$$
And so (by your Fact, which is also known as the rank-nullity theorem)
$$\tag{*} \dim H_i (V_\bullet) = \dim \ker d_i - \dim \operatorname{im} d_{i+1}.$$
On the other hand, you have short exact sequences
$$0 \to \ker d_i \to V_i \to \operatorname{im} d_i \to 0$$
and hence relations
$$\tag{**} \dim V_i = \dim \ker d_i + \dim \operatorname{im} d_i.$$
Now just put together (*) and (**).

By the way, the number $\chi (V_\bullet) = \sum_i (-1)^i \, \dim V_i = \sum_i (-1)^i \, \dim H_i (V_\bullet)$ is called the Euler characteristic of $V_\bullet$.


PDF generation in mvc4 with itextsharp

Question: I am working on pdf generation, it is successfully implemented  using itextsharp.dll. It's working fine on local environment after publish also. We have our own server at other site
But same code doesn't work on the server,pdf is not generated instead it gives an error: 'The document has no pages.'
    Initially I thought it is due to no data in document but it works locally with or without data in the document.
I had code implemented as follows to make a web request Is any problem in that ??
<code>try
            {
                var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strPdfData + "?objpatId=" + patID);

                var response = myHttpWebRequest.GetResponse();
                myHttpWebRequest.Timeout = 900000;
                var stream = response.GetResponseStream();
                StreamReader sr = new StreamReader(stream);
                content = sr.ReadToEnd();
            }
</code>
Comment: can you post the code for pdf generation as well?.
Also where is the code located. As in same server or different server?
Comment: yup thanks for reply code is located on different server.Here is my code for it.will you please provide your email id so i can able to send attachment to you because here it is not possible to send you complete code due to more characters in it.
Comment: this might be any issue due to cross-domain interaction try to access some other method from the same server. Don't post your entire code just post the required snippets.
Comment: Hi Nikitesh I got following error -                                              A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Comment: Either the server u r trying to access is not accessible or the service you are calling might be throwing some exception.
Check the settings of server where the method is hosted.
This link might help you if you are making an ajax call.
Comment: Thanks nikitesh, I am making the call to the method like this  function callmethod(){window.location.href = "@Url.Action("generatePdf", "Admin")?patID=" +@user.PatientId +"&strPass=" + txtPassValue;}
Comment: try this http://stackoverflow.com/questions/5943630/basic-example-of-using-ajax-with-jsonp
Comment: I have tried this one but when i go to download the pdf it doesn't show the dialogue box.
          here is code which i did for download pdf.
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=EMRDetails.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
Answer: create a method in the controller:
<code>     [HttpGet]
     public JsonResult GetFile()
     {
       var json = new WebClient().DownloadFile(string address, string fileName);
       //This code is just to convert the file to json you can keep it in file format and send to the view
       dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
       var oc = Newtonsoft.Json.JsonConvert.DeserializeObject<countdata[]>(Convert.ToString(result.countdata));
       return Json(oc, JsonRequestBehavior.AllowGet);
     }
</code>
In the view just call this function:
<code>@Url.Action('genPDF','GetFile');
</code>

PDF generation in mvc4 with itextsharp


Limit of the given sum: $f(x) = \lim_{n\to \infty} \sum_{r=1}^n 3^{r-1}\sin^3(x/(3^r))$

Question: $$f(x) = \lim_{n\to \infty}  \sum_{r=1}^n 3^{r-1}\sin^3(x/(3^r)) $$
I tried using the formula relating $\sin(3x)$ to $\sin^3(x)$ but got later stuck with a similar series who's sum I didn't know how to calculate
Comment: Note that $$\sin^3\theta=\dfrac{1}{4}(3\sin\theta-\sin 3\theta)$$
 and $$\sum_{r=0}^n\sin k\theta=\dfrac{\sin\left(\dfrac{n\theta}{2}\right)\sin \left(\dfrac{(n-1)\theta}{2}\right)}{\sin  \left(\dfrac{\theta}{2}\right)}$$
Comment: I don't understand what is being summed here. Is the equation as stated correct?
Comment: I've edited it to try and make sense of your formula but you might want to check if this is actually what you intended to ask.
Comment: I feel like there is a good chance that this always diverges because $3^{n-1}$ grows exponentially, while the sum is bounded and does not, to my knowledge, converge to zero.
Comment: I'm trying to but I can't get to place the infinity sign i n the limit
Comment: @bburGsamohT Its been edited properly now
Comment: @Nil yeah bur isn't that used when the angles are in arithmetic progression ?
Comment: What is the question? Are you asking for a closed form for $f(x)$? Or are you asking for the values of $x$ for which the limit exists?
Comment: The limit of the sum is a function of x . The question is to find the function . Its clearly evident
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{\mrm{f}\pars{x} =
\lim_{n\to \infty}\sum_{r = 1}^{n}3^{r - 1}\sin^{3}\pars{x \over 3^{r}}:\ ?}$.

\begin{align}
\mrm{f}\pars{x} & =
\lim_{n\to \infty}\sum_{r = 1}^{n}3^{r - 1}\sin^{3}\pars{x \over 3^{r}} =
{1 \over 4}\lim_{n\to \infty}\sum_{r = 1}^{n}\bracks{%
3^{r}\sin\pars{x \over 3^{r}} - 3^{r - 1}\sin\pars{x \over 3^{r - 1}}}
\\[1cm] & =\require{cancel}
{1 \over 4}\lim_{n\to \infty}\left\lbrace%
\bracks{\cancel{3\sin\pars{x \over 3}} - \color{#f00}{\sin\pars{x}}} +
\bracks{\cancel{3^{2}\sin\pars{x \over 3^{2}}} - \cancel{3\sin\pars{x \over 3}}}\right. +
\\[5mm] &\phantom{= {1 \over 4}\lim_{n \to \infty}\braces{\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!}}
\left.\bracks{\cancel{3^{3}\sin\pars{x \over 3^{3}}} - \cancel{3^{2}\sin\pars{x \over 3^{2}}}} + \cdots +
\bracks{\color{#f00}{3^{n}\sin\pars{x \over 3^{n}}} -
\cancel{3^{n - 1}\sin\pars{x \over 3^{n - 1}}}}\!\!\right\rbrace
\\[1cm] & =
{1 \over 4}\,\lim_{n \to \infty}\bracks{-\sin\pars{x} +
3^{n}\sin\pars{x \over 3^{n}}} =
\bbx{{1 \over 4}\bracks{\vphantom{\Large a}x - \sin\pars{x}}}
\end{align}


How to exclude a single-character expression from and to it from a slash-based partition?

Question: I would like to split some string in Java by forward slash symbol, but excude case when string contains only one symbol before and after it. Example - xx/xx/xxyy/ZZZ - splits ok, x/x - avoid splitting
I've tried to use a character set, but don't understand how to make an exclusion from standard [/]
I would be grateful for possible exclusion options
Comment: Thank you for reply. Unfortunately, I am limited only by the expression pattern, since it is transferred to the external API.
Comment: Do you want to split `x/xxx`? I have an impression it should not be split.
Comment: No, only x/x case
Comment: Try either 1) `(?<!^[^/])/(?![^/]$)` or 2) `/(?!(?<=^[^/]/)[^/]$)`. You can't use lookarounds (zero-width assertions) inside character classes, you won't be able to use these inside square brackets.
Answer: You can use this regex, which will not match a / if it is surrounded by only one character.
(?<=[^/\n].)/|/(?=.[^/\n])

Regex Demo
Java code showing split,
List<String> list = Arrays.asList("xx/xx/xxyy/ZZZ","x/x","/x/x/x/xxx");

list.forEach(x -> {
    String[] data = x.split("(?<=[^/\\n].)/|/(?=.[^/\\n])");
    System.out.println(x + " --> " + Arrays.toString(data));
});

Prints,
xx/xx/xxyy/ZZZ --> [xx, xx, xxyy, ZZZ]
x/x --> [x/x]
/x/x/x/xxx --> [/x/x/x, xxx]

Also, just in case you don't want to select a / for split, if it is surrounded by only one character on either side, you can use this regex,
(?<=[^/\n].)/(?=.[^/\n])

Demo 2
Comment: Thank you very much again, I'll continue search
Comment: Thank you, this is a great answer. And the final step - is it possible to transform it into character set and use in pair with others? For example, add to [ -]|[xXхХ]
Comment: @skydancer1990 No, you can't. Zero-width assertions cannot be used in character classes.
Comment: Does this mean that my problem cannot be solved through a character classes?
Comment: @skydancer1990 Exactly, as you need  lookarounds


Is the least squares solution to an overdetermined system a triangle center?

Question: My question relates to a simple case of the least squares problem. For example, take the system of equations
\begin{align*}
2x- y &= 2, \\
x + 2y &= 1, \\
x+y &= 4,
\end{align*}
which is clearly overdetermined. Using a least squares approach, we can solve the system $$A^TA\mathbf{x^*} = A^T\mathbf{b},$$ where $\mathbf{x^*}$ minimises $\|\ A\mathbf{x} -\mathbf{b} \ \|$, and  $$A = \begin{bmatrix} 2 & -1\\ 1 & 2 \\ 1 & 1 \end{bmatrix} \ , \quad  \mathbf{b}=  \begin{bmatrix} 2 \\ 1 \\ 4 \end{bmatrix} \quad \mbox{and} \quad \mathbf{x}=  \begin{bmatrix} x \\ y \end{bmatrix},$$
to obtain an approximation for the solution as $\left(\frac{10}{7}, \frac{3}{7} \right)$.
If you plot the three straight lines that constitute the system of equations, they intersect at three points that form the vertices of a triangle.
My question is - does the solution always fall within this triangle (as in this example), and if so, is this point a (non-traditional) triangle center?
Comment: The trouble is that scaling one of the equations does not change the triangle but it does change the least-squares solution. This is the difference between the geometry and the algebra of the problem. If you scale everything so that the rows of $A$ are unit vectors, you may get a meaningful triangle center.
Comment: The point minimizing the sum of the squares of the distances to the sidelines of a triangle is the symmedian point of the triangle. See http://en.wikipedia.org/wiki/Symmedian for the definition, and Exercise 7.3 in Ross Honsberger's "Episodes in Nineteenth and Twentieth Century Euclidean Geometry" (but ignore the word "inside", which isn't really needed) for the proof of the above property. Basically it follows from the Cauchy-Schwarz inequality, along with the fact that the distances from the symmedian point to the sidelines are proportional to the length of these sides.
Comment: I believe the result will always be the barycenter of the triangle, but do not have a proof.
Comment: It's not the barycentre.  What do you get when two of the lines are nearly parallel?
Comment: Good question. Suppose we "normalize" all the line equations -- we write them in the form $ax+by=c$, where $a^2+b^2=1$. Then I think you're asking ... what point in the interior of a triangle minimises the sum of the (squared?) distances to its three sides. I don't know the answer, but I'd like to know.
Comment: You might be interested in this work on triangle centers: http://faculty.evansville.edu/ck6/encyclopedia/
Comment: Thanks for the reference @darijgrinberg, I will try the exercise! I was initially thinking about minimising the sum of squares of the distances to the _vertices_, rather than the sides. The problem makes much more sense to me now, thanks to all commenters.
Answer: As Rahul Narain commented, the precise position of the least-squares solution depends on the scaling of the individual equations: as you scale up an equation, so does the importance of the distance of your solution to the corresponding line, and the least-squares solution will end up closer to that line. You can say that in any case the least-squares solution will lie in the interior of the triangle formed by the three lines, since for a point in any of the other $6$ sectors into which the lines cut up the plane, moving in some direction will decrease the distances to all three lines at the same time, so one can never have a minimum there.
In the spacial case where you scale the equations in such a way that for each of the the sum-of-squares-of-coefficients gives the same value (for instance$~1$), then you can describe the least-square solution as the unique point$~P$ such that the sum of the three vectors from $P$ to its orthogonal projections on the three lines is zero; in other words $P$ is the barycenter of its own pedal triangle (the triangle formed by those projections). That this is so can easily be seen by taking the formula implicit in the comment by @bubba and differentiating it.
Giving a geometric construction of such a point is an interesting problem that probably has been considered by people, but I don't see an easy solution right now, nor do I recall having seen anything directly related. In particular, I am unsure if this point coincides with any one of the many "centers" associated to a triangle; however given that there are so many of them, and the description of the point we are interested is is quite natural, I would bet that it does equal one of those centers.
Indeed, thank you darij grinberg for pointing out that this is the Symmedian Point, the properties listed under the link correspond exactly to what we are after here.
Comment: @BennettGardiner: I've reformulated a bit, and added a missing 's' to "orthogonal projection" whose absence made the sentence hard to decipher. I hope it is better now.
Comment: Excellent answer, thank you. Can you elaborate a little on "such that the sum of the three vectors from it to its orthogonal projection on the three lines is zero"?

I'm not quite sure what "it" refers to? What are we projecting onto the lines?

How does one calculate the Symmedian Point given the vertices?

Sorry for all the questions, this problem really struck me for some reason.


Is it okay to have two "primary" buttons?

Question: I have a dialog that allows the user to enter text to be processed.
Initially, there are two buttons: "Cancel" and "Assemble."
The latter button is the primary action (in Bootstrap, <code>.btn-primary</code>).
Once the user enters text and presses "Assemble," they have the option to either make changes and "Assemble" again, or to complete the action (closing the modal dialog and doing processing).
Does it make sense for the button to complete the action to also be primary?
Here's a picture to demonstrate what I mean.
The green success alert only appears after a user submits some valid code into the textbox and presses "Assemble."

My thoughts:

Before the user first assembles code, "Assemble" certainly is the primary action.
After the user assembles code, there really are two primary actions; either of the two buttons I've currently marked primary is a perfectly plausible next step.
It would probably be weird to make the "Assemble" button no longer a primary action after being pressed—to change its primary status at runtime—right?
Comment: By the way, should "Cancel" be a `.btn-danger`, or is this bad form?
Comment: Currently pressing on "Cancel" button, what will it do? Will it do the same function if I press "Assemble" button, where it takes you to the previous state?
Comment: Answers below are good.  The key consideration is that a UI framework should not "design" your UX.  UX needs to be done first, then you get what you need out of UI framework. Yes, there may be constraints on a UI platform, but the sequence of design is important.
Answer: Your dialog actually has three buttons - cancel, assemble, load into simulator. The primary button is "load into simulator", because that's the one that lets you close the dialog and proceed. By only displaying it after the user has generated valid code you're breaking the process down into steps, basically making this a kind of wizard, but not supporting it by a wizard-like layout.
If I understood correctly, there's no point where both Assemble and Load are enabled. If the user made changes, then he should assemble the text again, so Load is disabled. If he didn't make any changes, then he can only Load or Cancel, but there's nothing new to assemble.
I think that initially you should display all three buttons, all at the bottom right of the dialog, where the primary is "load into simulator", and it's disabled as long as no valid code has been assembled. "Assemble" even though it's the only "useful" button at first, is not of equal weight as "Load", because it doesn't let you close the modal and as far as I understand from your description, it doesn't really perform an action in the system, it's kind of a preview/test action.
Another option is to enhance the wizard approach by creating two screens. The first with Assemble (primary) and Cancel, and the second with Load into Simulator (primary), Make Changes and Cancel.
In any case, the fact that it's very plausible for a user to want to make changes, doesn't mean that Assemble should be the primary button after initial input. Many systems let users edit their input, but they always encourage them to submit it and move on. Otherwise you're basically encouraging them to enter an endless loop, where "keep making changes" is the primary action after each iteration. You want to encourage them to progress, not to run in circles :).
Answer: If I understand correctly, the picture below reflects what is going on? There's no problems having two primary buttons like this. Effectively, your Assemble button is an Apply role, and the Load button is an OK role.
Essentially there are two primary actions, but one (load) is disabled until you successfully click the other (assemble).
There's no need to confuse the issue by nesting the functionality into different boxes.
Personally, I'd also probably separate the Cancel button from the primaries.
Answer: It's OK to have two primary buttons, or even 5 sometimes.
The concept of primary/secondary/tertiary helps designers to think of what's more important by providing a 2 or 3 layer model. Nowhere does it say only one thing can be on each layer.
Yet, the more elements on each layer, the less noticeable each element will be as there's less visual contrast between it and others.
You also have to distinguish between something like 'Buy now' - where you really want the eye to land there, and something like your example, where how much the decision on what to make primary will aid the user is questionable.
In fact, I'd argue that all 3 buttons should be the same. Having them in different colours mean extra semantics for the brain to work out, and it promotes the interference effect; for instance, the eye may be drawn to the 'Cancel' button due to its colour. There's at least one research that shows optimal performance is achieved when the Cancel and OK buttons are same colour (it was posted a few times on this forum).


Conky own_window_type dock vs desktop

Question: I am having an issue getting Conky to both run and stay in the background.
If I set Conky own_window_type ='desktop', it runs behind other windows but opening nautilus will cause it to close. If I set own_window_type ='dock' it dose not close but it is in front of other windows.
Here is my conky.conf file:
conky.config = {

background = false,
update_interval = 3.0,
cpu_avg_samples = 2,
net_avg_samples = 2,
override_utf8_locale = true,
no_buffers = true,
out_to_console = false,
out_to_stderr = false,

own_window = true,
own_window_class = 'Conky',
own_window_type = 'dock',
alignment = 'top_right',
border_width = 1,
gap_x = 0,
gap_y = 25,
minimum_height = 5,
minimum_width = 5,

draw_borders = false,
draw_graph_borders = true,
draw_outline = false,
draw_shades = false,

use_xft = true,
font = 'DejaVu Sans Mono:size=12',
extra_newline = false,
uppercase = false,
use_spacer = 'none',

default_color = 333333,

color0 = ff3333,
color1 = 818181
}
conky.text = [[
${font Roboto:bold:size=10}${color0}SYSTEM INFO ${color1}  ${hr 2}
${font Roboto:bold:size=8}${goto 95}${color1}Uptime       ${alignr 0}${color1}  ${uptime_short}
${font Roboto:bold:size=8}${goto 95}${color1}Hostname     ${alignr}  ${nodename}
${font Roboto:bold:size=8}${goto 95}${color1}Kernel       ${alignr}  $kernel
${font Roboto:bold:size=8}${goto 95}${color1}Network      ${alignr}  ${addr eno1}
${font Roboto:bold:size=8}${goto 95}${color1}Distribution ${alignr}  ${execi 60 lsb_release -d | cut -f 2| tr "[:upper:]" "[:lower:]"}
${font Roboto:bold:size=8}${goto 95}${color1}CPU          ${alignr 0}${color1}${execi 1000 cat /proc/cpuinfo | grep 'model name' | sed -e 's/model name.*: //'| uniq | cut -c 9-26} ${freq_g cpu0}Ghz
${font Roboto:bold:size=10}${color0}Memmory${color1}  ${hr 2}
${font Roboto:bold:size=8}${goto 95}${color1}RAM ${goto 220}$mem / $memmax $alignr $memperc%
${goto 95}$membar
${font Roboto:bold:size=10}${color0}HDD${color1}  ${hr 2}
${font Roboto:bold:size=8}${goto 95}${color1}File systems ${goto 220} ${fs_used /} / ${fs_size /} $alignr ${fs_free_perc /}%
${goto 95}${fs_bar /}
${font Roboto:bold:size=8}${goto 95}${color1} File Storage ${goto 220} ${fs_used /var/store/files} / ${fs_size /var/store/files} $alignr ${fs_free_perc /var/store/files}%
${goto 95}${fs_bar /var/store/files/}
${font Roboto:bold:size=10}${color0} Processes ${color1}  ${hr 2}
${font Roboto:bold:size=8} ${goto 95} ${color1} NAME ${goto 200 } PID ${goto 250 } CPU% ${goto 300 } MEM%
${font Roboto:bold:size=8} ${goto 95} ${top name 1} ${goto 200} ${top pid 1} ${goto 250} ${top cpu 1} ${goto 300} ${top mem 1}
${font Roboto:bold:size=8} ${goto 95} ${top name 2} ${goto 200} ${top pid 2} ${goto 250} ${top cpu 2} ${goto 300} ${top mem 2}
${font Roboto:bold:size=8} ${goto 95} ${top name 3} ${goto 200} ${top pid 3} ${goto 250} ${top cpu 3} ${goto 300} ${top mem 3}
${font Roboto:bold:size=8} ${goto 95} ${top name 4} ${goto 200} ${top pid 4} ${goto 250} ${top cpu 4} ${goto 300} ${top mem 4}
${font Roboto:bold:size=8} ${goto 95} ${top name 5} ${goto 200} ${top pid 5} ${goto 250} ${top cpu 5} ${goto 300} ${top mem 5}
${font Roboto:bold:size=8} ${goto 95} ${top name 6} ${goto 200} ${top pid 6} ${goto 250} ${top cpu 6} ${goto 300} ${top mem 6}
]]

Comment: Try setting `own_window_type` to `normal` first and then `desktop` second.
Comment: @WinEunuuchs2Unix I So I tried that by just duplicating the own_window_type  line making one normal and the other desktop and it did not work.
Comment: I didn't mean add a new line. I meant change the existing line. First time try it with `normal` and if that doesn't work try it with `desktop. I see there is an answer now so lets hope that works.
Answer: I use the following settings for a transparent window, that is always displayed and can be covered by other windows.

own_window = true,
own_window_transparent = true,
own_window_type = 'normal',
own_window_hints = 'undecorated,sticky,below,skip_taskbar,skip_pager',
double_buffer = true,

Comment: While this works it it makes it a window that you can interact with. It has a header and a close button for example.
Comment: @Starblight try `own_window_type = 'dock',`. Either way, this answer works. Conky version `1.11.6_pre`
Answer: Just display your text editor with .conkyrc next to your conky window. If you change the settings and save them (do not close the text editor), conky will display the new setting 1-2 seconds later. So you can very fast try the effect of the changes. I would start by cutting:

own_window_class = 'Conky',

If it did not work, you can re-paste it.
Comment: Thanks for the suggestions sadly removing own_window_class = 'Conky', did not work.
Comment: I am not not completely sure from your description, what you want to achieve with the Conky window.  I would keep the text editor and the conky window side by side and try out different settings.
Comment: I want Conky to stop closing just because I open a folder. I also want it to always be in the background and lastly I do not want it to be a window that I can interact with. For example if I set own_window_type = 'normal', it then is a window with a header that can be moved and closed.  I was under the impression this is a normal expectation of Conky.

Conky own_window_type dock vs desktop


SQL index for regexp query

Question: How can I improve performance for the following query?
What kind of index should I use?
I am using MySQL
SELECT b.title
FROM book b, person p, order o
WHERE b.bid = o.bid
AND o.pid = p.pid
AND b.title LIKE 'LOVE%';

Answer: You should have a look at how MySQL uses indexes.
In the case of your query:

I would particularly recommend indexes on b.bid, o.bid, o.pid and p.pid, as these are being used to join tables. You may even want to consider using foreign keys.
I would also consider an index on b.title, since you are using this in you where clause.

But if you want to know how changes are affecting your queries you should profile between each change to check how it has affected performance.
However, I would ask you to elaborate on your query - you're joining with tables order and person, but neither selecting from these tables nor using these in your where clauses. Are you just doing this to select books that have been ordered? In which case, why do you then join on person?
Comment: Actually my precise question is what kind of index to use on b.title? Considering that the query is using regexp for its search, should I use hash or B+tree in order to improve performance?

SQL index for regexp query


Similarity of products $AB$ and $BA$ of square matrices

Question: Given:$ A_{n\times n} , B_{n\times n} .$
Is it necessary true that there is similarity between $AB$ and $BA$?
I'm not quite sure how to check it is true for every non-singular M matrix. $M^{-1}ABM = BA$
Anyone have any ideas what am I missing to understand in similarity? If it's not necessary true then give a counter example.
Comment: Note that it is true when $A$ or $B$ is non-singular. If WLOG $A$ is nonsingular, $AB=AB(AA^{-1})=A(BA)A^{-1}$
Comment: @G.T.R If A or B is non-singular it will be similar for $A^{-1}$
Comment: To say that $C$ and $D$ are similar does not mean that for EVERY matrix $M$ we have $C = M^{-1}DM$.  It means that for SOME matrix $M$, that holds.  "For some" means at least one.
Answer: While @Surb has given a counter-example, we do have the following result when $A$ or $B$ are singular (or even not square matrices):
Suppose that $AB$ and $BA$ are both square matrices and $\lambda$ is a non-zero eigenvalue of $AB$.  Then $\lambda$ is an eigenvalue of $BA$.
Proof: Suppose $ABv=\lambda v$.  Then $BA(Bv)=B(ABv)=B(\lambda v)=\lambda(Bv)$.  Since $ABv\neq 0$, we have $Bv\neq 0$, and so $Bv$ is an $Bv$ is an eigenvector of $BA$.
In fact, more can be said: up to a factor of $t^k$ (which is necessary to correct degree issues when $A$ and $B$ are not square), $AB$ and $BA$ will have the same characteristic polynomials.  And, since $B(AB-\lambda)^k=(BA-\lambda)^kB$, we have a matchup not just of eigenvalues, but of approximate eigenvalues as well, and so the only obstruction to $AB$ and $BA$ being similar lies in their generalized zero-eigenspaces.
So again, while @Surb has showed that the matrices need not be similar, the problems that can occur are of a very limited nature.
Answer: Let $A = \begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}, B = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}$, then $AB = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}$ and $BA = \begin{pmatrix} 0 & 0 \\ 0 & 0 \end{pmatrix}$.
It is clear that $MBAM^{-1} = \begin{pmatrix} 0 & 0 \\ 0 & 0 \end{pmatrix} \neq AB$ for every invertible matrix $M$.
Comment: With pleasure :)


Conditional Controller in Rails

Question: I am very new to Rails, so bear with me while I learn.
I have a model, show, with an attribute preview_url. How can I build a call that only returns shows that have a non-null preview_url and what would be the best way to word the controller method?
i.e. localhost:3000/shows/?preview_url ??
Thanks in advance.
Comment: You should read a book on rails. That'll give you structured knowledge and save you (and us) some time :)
Answer: In your ShowsController you would have an action named with_preview like this:
def with_preview
  @shows = Show.where('preview_url IS NOT NULL').all
end

The url for this action would be /shows/with_preview
Comment: I am getting `Couldn't find Show with id=with_preview` when I try this. I have the standard `index` and `show` methods in place.
Comment: Good practice would be creating a named scope on your model. So you would do Show.whith_preview.all. So if you do need that condition in another controller action you don't need to repeat the where clause.

Conditional Controller in Rails


Not chaging Text.Color in disabled Button

Question: I want change the Text.Color when the Button is disable. How can I do it?
Xaml Button:
<Button Text="-" TextColor="White" Padding="0" CornerRadius="4" FontAttributes="Bold" FontSize="Small" IsEnabled="False" BackgroundColor="#3F3C42" Clicked="QntLabelLess" x:Name="QntLess" Grid.Column="1" Grid.Row="1"/>

Code-Behind:
private void QntLabelLess(object sender, EventArgs e)
        {
            if (Qnt == 2)
            {
                QntLess.IsEnabled = false;
               // QntLess.TextColor = Color.FromHex("#FFFFFF");
                QntLess.BackgroundColor = Color.FromHex("#3F3C42");
            }
            if (Qnt == 10)
            {
                QntPlus.IsEnabled = true;
                QntPlus.TextColor = Color.FromHex("#000000");
                QntPlus.BackgroundColor = Color.FromHex("#FF8A00");
            }
            Qnt--;
            QntLabel.Text = Qnt.ToString();
 }

I know that have a lot of useless code for this question but I prefer put all my method code.
Comment: This only happens when disabled?
Comment: @G.hakim Yes, looks like Disabled button have a default Text.Color and I cant change it. I tested change only the Text and the BackgroundColor and it changed, this only happens with Text.Color.
Comment: try changing the `TextColor` first then disabling the button!?
Comment: @G.hakim Didnt work.
Answer: If I'm reading this correctly, the button starts in a disabled state. Because of this, your click event will never get called because the button is already disabled. I'm guessing you ONLY see the button in the disabled state and never in an enabled state.
Comment: My click event to enable the button isn't click on it, my button "+" is responsable to enable it. The only thing that doesnt work in this code is the Text.Color of the button "-" when it is disabled. Maybe you got that conclusion because I didn´t show my xaml code of my "+" button and the code behind of it. But dont mind this, isn´t so important, but thank you for your attention.
Answer: If you want to achieve that ,you should achieve a custom renderers  for button.
Here is running GIF.

For Android.
[assembly: ExportRenderer(typeof(Xamarin.Forms.Button), typeof(MyButtonRenderer))]
namespace ButtonStyle.Droid
{

public class MyButtonRenderer : ButtonRenderer
{
    public MyButtonRenderer(Context context) : base(context) { }

    protected override void
    OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> args)
    {
        base.OnElementChanged(args);
        if (Control != null) SetColors();
    }

    protected override void OnElementPropertyChanged(object sender,
    PropertyChangedEventArgs args)
    {
        base.OnElementPropertyChanged(sender, args);
        if (args.PropertyName == nameof(Xamarin.Forms.Button.IsEnabled)) SetColors();
    }

    private void SetColors()
    {
        Control.SetTextColor(Element.IsEnabled ? Element.TextColor.ToAndroid() :
        Android.Graphics.Color.Red);
        Control.SetBackgroundColor(Element.IsEnabled ?
        Element.BackgroundColor.ToAndroid() : Android.Graphics.Color.Purple);
    }
 }
}

For IOS(I did not take my Mac today, you had better to test it for yourself)
 [assembly: ExportRenderer(typeof(Button), typeof(MyButtonRenderer))]
 namespace ButtonStyle.iOS
 {
  public class MyButtonRenderer : ButtonRenderer
 {
    protected override void OnElementChanged(ElementChangedEventArgs<Button> args)
    {
        base.OnElementChanged(args);
        if (Control != null) SetColors();
    }

    protected override void OnElementPropertyChanged(object sender,
     PropertyChangedEventArgs args)
    {
        base.OnElementPropertyChanged(sender, args);
        if (args.PropertyName == nameof(Button.IsEnabled)) SetColors();
    }

    private void SetColors()
    {
        Control.SetTitleColor(Element.IsEnabled ? Element.TextColor.ToUIColor() :
       UIColor.Red, Element.IsEnabled ? UIControlState.Normal :
      UIControlState.Disabled);
        Control.BackgroundColor = Element.IsEnabled ?
      Element.BackgroundColor.ToUIColor() : UIColor.Purple;
    }
}

There is code MainPage.xaml
 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:ButtonStyle"
         x:Class="ButtonStyle.MainPage">

<StackLayout>

    <Button Text="------------------------" TextColor="White" Padding="0" CornerRadius="4" FontAttributes="Bold" FontSize="Small" IsEnabled="True" BackgroundColor="#3F3C42" Clicked="QntLabelLess" x:Name="QntLess"/>
    <Button Text="++++++++++++++++++++++++" TextColor="White" Padding="0" CornerRadius="4" FontAttributes="Bold" FontSize="Small" IsEnabled="True" BackgroundColor="#3F3C42" Clicked="QntLabelPlus" x:Name="QntPlus"/>

</StackLayout>

There is code for MainPage.xaml.cs
   public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }
    private void QntLabelLess(object sender, EventArgs e)
    {
        int Qnt=2;
        if (Qnt == 2)
        {
          //  QntLess.TextColor = Color.FromHex("#FF0000");
        //    QntLess.BackgroundColor = Color.FromHex("#3F3C42");
            QntLess.IsEnabled = false;

        }
        if (Qnt == 10)
        {
            QntPlus.IsEnabled = true;
            QntPlus.TextColor = Color.FromHex("#FF0000");
            QntPlus.BackgroundColor = Color.FromHex("#FF8A00");
        }
        Qnt--;
        QntLabel.Text = Qnt.ToString();
    }

    private void QntLabelPlus(object sender, EventArgs e)
    {

    }
}

Comment: Are there any updates for this issue? If the reply is helpful, please try to mark it as an answer,  it will help others who have similar issue.


Can't upgrade from Xcode 4.2 to 4.2.1

Question: I'm trying to upgrade from Xcode 4.2 (4D199) to Xcode 4.2.1 (4D502).
On AppStore, when I try to install the new version, it says I already have Xcode installed and  I have to use Software Update instead.
When I run Software Update, it says all applications are up to date.
Any clues?
Thanks,
Ecil
Comment: This isn't programming related. Better try asking on the Apple developer forum.
Comment: I deleted "Install Xcode.app" from Applications folder and then it solved the problem. Thanks.
Comment: @DarkDust Stackoverflow is not only for programming, it's also for "software tools commonly used by programmers" http://stackoverflow.com/faq#questions
Comment: @gcamp: While that's true and useful e.g. to cover topics like _How do I this with SubVersion_ I doubt that it's useful to a larger audience that there's an issue with updating to a dot release of an IDE. So the close reason _too localized_ would fit here as well.
Comment: I also am having this problem.  It is really frustrating that this question - which is very much on-top for stackoverflow - has been closed!
Answer: Use the App Store under the Apple menu. Enter "Xcode" in the search field. Click "INSTALL" under the Xcode icon.
Answer: Uninstall xcode completely (delete all folders having anything to do with it besides the projects you want to keep) then re install.

Can't upgrade from Xcode 4.2 to 4.2.1


Original source of igu=1 parameter to display google in iframe

Question: As many on stackoverflow have noticed, using trying to display google in an iframe like this doesn't work:

However, this does:

Who discovered this? I cannot find the original source.
Comment: I'm also trying to find out myself. what does the "igu" mean? And how would you know to look for this let alone it working?
Comment: My best guess: it means "ignore user", because Google seem to detach the search page from the current logged-in user when this parameter is set. For Google that is a pretty sufficient protection from the risk of embedding the page to design a click jacking attack on Google accounts.
Comment: Google's official statement is this: support.google.com/programmable-search/answer/2631042?hl=en They don't seem interested to suggest this parameter formally.
Answer: The discovery of using the "igu=1" parameter to display Google search results in an iframe is not attributed to a specific individual or source. It appears to be a workaround that was discovered and shared within the developer community to bypass certain restrictions imposed by Google on embedding search results in iframes (using the X-Frame-Options header). Since this workaround is not officially documented by Google, it also means its long-term reliability and compatibility cannot be guaranteed.
The "igu" parameter is likely an arbitrary choice made by the developers.
In my opinion, "igu" might stand for "iFrame Google URL" or "iFrame Google Utility", but we can't be sure. As @rineez also mentions on this reply, the user is logged out, which could

[...] mean[s] "ignore user" [...]


getting 'nativeElement.querySelector is not a function' exception in Angular2

Question: I'm trying to access a div in Angular2 like below:
import { Component, ViewChild, ElementRef, AfterContentInit } from '@angular/core';

@Component({
    selector: 'main',
    template: `

  `
})

export class MainComponent implements AfterContentInit {
    @ViewChild('target') elementRef: ElementRef;

    ngAfterContentInit(): void {
        var child = this.elementRef.nativeElement.querySelector('div');
        console.log(child);
    }
}

but I get the following exception:

Exception: Call to Node module failed with error: TypeError:
  this.elementRef.nativeElement.querySelector is not a function
Comment: That is strange the `ElementRef.nativeElement` is type `any`. What version of angular are you using or what dose your `package.json` look like?
Comment: i'm using angular 2.0.0. shouldn't work with this version?
Comment: It should work an it works here https://plnkr.co/edit/fRsQot7KtIAUGSIIZdKA
Comment: yes, it should work but it doesn't. i also upgrade my project to Angular 2.4.5 but still the same result. i can't understand why.
Comment: Can you post the full code, with it not working somewhere?
Comment: i'm using http://www.telerik.com/blogs/cooking-with-aspnet-core-and-angular-2 template for my project which has the issue. but when i use plnkr is working fine. also if i use a simple angular2 project without this template is working fine as well
Answer: That template uses angular2-universal for server-side rendering.
https://github.com/angular/universal#universal-gotchas
Try:
import { Component, AfterContentInit, ViewChild, ElementRef } from '@angular/core';

@Component({
    selector: 'main',
    template: `

`
})
export class MainComponent implements AfterContentInit {
    @ViewChild('target') elementRef: ElementRef;

    constructor(private renderer: Renderer) {}

    ngAfterContentInit(): void {
        var child = (this.elementRef.nativeElement as any).querySelector.apply(this.elementRef.nativeElement, ['div']);
        console.log(child);
    }
}

https://angular.io/guide/migration-renderer
Comment: This is now deprecated. Does any one have an updated answer?
Comment: `const rowHeight = (el as any).querySelector.apply(el, ['.datagrid-table > .datagrid-row']).getBoundingClientRect().height;`


Why JSON.stringify giving JSON undefined error?

Question: I am trying to use JSON.stringify in my javascript page (EXTJS) code but it's giving me JSON is undefined error. Error happends only in IE (ver.10). This code will work in FF and Chrome. Below is a sample code that I am trying to use. Why is it failing? This seems like a valid example and works in other browsers. Thanks in advance.
var contact = new Object();
contact.firstname = "Joe";
contact.surname = "Smith";
contact.gendere= "male";
var jsonText = JSON.stringify(contact);

Comment: What happens when you use {} instead of new Object()? Does it work if you use a hardcoded object like { firstname : 'Joe', surname : 'Smith', gendere : 'male' }?
Comment: Hi schlingel, I get same error "JSON undefined" when I hard code.
Answer: Put
<!DOCTYPE html>

at the top of your document (and of course remove any other doctype you might have).
Without it, IE10 is in a weird compatibility mode where many "new" features aren't available, for example JSON.
Comment: This is truth,and if you are doing new development, the only solution. HOWEVER, if you are maintaining and old page that relies on the broken layout, you can include json.js from the json.org website.
Comment: @JeremyJStarcher That's true. But do people still maintain applications compatible with IE8 and not compatible with other browsers ?
Comment: Not so much on public facing websites, but there are still a lot of intraweb and private websites that have not been brought up to date.  A lot are limited to older IE engines to do ActiveX dependencies.
Answer: Use <!DOCTYPE html> if you only need to support IE10.  If you need to use earlier versions of IE (some people still need to support IE6) you can use the JS implementation of JSON: https://github.com/douglascrockford/JSON-js
Comment: Ok I tried  but no effect, same problem, JSON undetified error. Any other ideas?
Comment: @JS11 did you try using the JSON-js implementation from my response?
Comment: Hi Nirk,  I am currently using json2.js and i notice this on the link you recomended: "json.js: This file does everything that json2.js does. It also adds a
toJSONString method and a parseJSON method to Object.prototype. Use of this
file is not recommended."
Comment: Use of this file is not recommended - portion is what confuses me
Comment: @JS11 use the file json2.js -- that replicates the JSON object (with parse and stringify).  json.js was an older interface
Comment: Thanks for all the answers. I fixed the path to json2.js file and now it is working.
Comment: Why don't you use the Ext.JSON.encode method? You already have it included in your page, why load another library?
Answer: You have the framework already, use it:
Ext.JSON.encode/decode  http://docs.sencha.com/extjs/4.1.3/#!/api/Ext.JSON


Can't add the data to list using Provider in flat button on flutter

Question: I'm using provider 4.3.2 in this flutter code, this is a simple flutter app that has a text filed, flat button, and a list view builder that contain the text widget. I created a class ListData that has the list and is shown in the list view builder using provider. Here is the problem, I created a addData method in the ListData class. I used this method to add data to list using provider in the onPressed method of flat button add it is throwing error, unable to find. the solution for this problem. Also this is a short form of my main app
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    String data;
    return ChangeNotifierProvider(
      create: (context) => ListData(),
      child: MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: Text("list"),
          ),
          body: Column(
            children: [
              TextField(
                onChanged: (value) => data = value,
              ),
              FlatButton(
                child: Text("Add"),
                color: Colors.blue,
                onPressed: () {
                  Provider.of<ListData>(context).addData(data);
                },
              ),
              Expanded(
                child: MyListView(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class MyListView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (context, index) {
        return Text(Provider.of<ListData>(context).listData[index]);
      },
      itemCount: Provider.of<ListData>(context).listCount,
    );
  }
}

class ListData extends ChangeNotifier {
  List _listData = [
    'Hello',
    "hi",
  ];

  UnmodifiableListView get listData {
    return UnmodifiableListView(_listData);
  }

  int get listCount {
    return _listData.length;
  }

  void addData(String data) {
    _listData.add(data);
    notifyListeners();
  }
}

Answer: You can copy paste run full code below
You need Builder and listen: false
code snippet
Builder(builder: (BuildContext context) {
        return FlatButton(
          child: Text("Add"),
          color: Colors.blue,
          onPressed: () {
            Provider.of<ListData>(context, listen: false).addData(data);
          },
        );
      }),

working demo

full code
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    String data;
    return ChangeNotifierProvider(
      create: (context) => ListData(),
      child: MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: Text("list"),
          ),
          body: Column(
            children: [
              TextField(
                onChanged: (value) => data = value,
              ),
              Builder(builder: (BuildContext context) {
                return FlatButton(
                  child: Text("Add"),
                  color: Colors.blue,
                  onPressed: () {
                    Provider.of<ListData>(context, listen: false).addData(data);
                  },
                );
              }),
              Expanded(
                child: MyListView(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class MyListView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (context, index) {
        return Text(Provider.of<ListData>(context).listData[index]);
      },
      itemCount: Provider.of<ListData>(context).listCount,
    );
  }
}

class ListData extends ChangeNotifier {
  List _listData = [
    'Hello',
    "hi",
  ];

  UnmodifiableListView get listData {
    return UnmodifiableListView(_listData);
  }

  int get listCount {
    return _listData.length;
  }

  void addData(String data) {
    _listData.add(data);
    notifyListeners();
  }
}

Answer: You need to wrap your FlatButton in a Consumer widget because Provider.of is called with a BuildContext that is an ancestor of the provider.
return ChangeNotifierProvider(
    create: (_) => ListData(),
    child: Consumer<ListData>(
      builder: (_, listData, __) => FlatButton(onPressed: () => listData.addData(data)),
    },
  );

Check out this to learn more with simple examples to help you understand why you get the error and how to use it.
https://pub.dev/documentation/provider/latest/provider/Consumer-class.html


Multi Tenancy - Register JNDI datasources dynamically

Question: I would like to know how to register JNDI datasources dynamically with the multi-tenant-core-plugin in the single-tenant mode. I searched for nearly two weeks and found some hints how to do it, like the JndiTemplate or the BeanBuilder. But I wasn't able to figure it out ..
I would appreciate if someone could help me..
Some information to this:
Grails 1.3.7,
Hibernate 1.3.7
Tomcat 1.3.7
Multi-tenant-core plugin 1.0.0
It would be really nice to register a customer with his own datasource on the fly without stopping the program and adding him in the grails.naming.entries and in the DatasourceTenantMap... I know that there is a domain class DataSourceTenantMap.groovy :
<code>class DataSourceTenantMap {
   String dataSource
   Integer mappedTenantId

   static constraints = {}
}
</code>
but I have to register more than just the mappedTenantId and the datasource. Therefore I tried to bind a BasicDataSource with JndiTemplate or the NamingManager. But it hadn't worked..
If more information are needed, please ask for them!
Comment: Hi there,

Has anybody got any ideas? Would be great if someone could give some insights...

Cheers, Mel
Answer: I'm posting this as an answer as I can't figure out how to do a comment. (meaning, I don't see an "Add comment" link, above).
I have had the same issue with Grails 2.0.3
See: Grails 2 multiple dynamic datasources in services
I am perhaps a little further ahead, because I am injecting the datasource bean - ie, I have exactly the same scenario - but it's not getting picked up by Grails.
The problem is universal and I was hoping somebody on the grails team with insight would answer:
Multitenant Application running as a service should allow for addition of another tenant at runtime. That means, if I want to tell the app that there's a brand new tenant database that it should use, I should be able to do that at runtime, instead of bouncing the app.


what does the GM mean in xcode release

Question: I am new to xcode and ios development. recently I've seen the xcode releases with, for example xcode 6.0 GM and then xcode 6.0. I wonder what should we do with the GM or we need to wait until the non GM release in order to build ios app.
could anyone explain me about this ?
Answer: Xcode 6.0 GM (Golden Master) is the version released before 6.0, and it can be used to build & submit to App Store, which is not possible with other betas.
This is necessary because apps should, ideally, be updated before a new iOS is officially released. Waiting for the official new Xcode would be too late, since it is always released with the new iOS.
Comment: can you update this answer for 2022, it there any GM version currently in 2022, or the latest at moment 14.2 will be considered the GM version

what does the GM mean in xcode release


How to remove white space after sequence of characters in a csv file?

Question: Can anybody point me to where i can write a script to remove white space in a csv file, however i only want to remove white space after a specific sequence of character(s) so i expect to need Regular Expressions
fName, lName, age, address 1 address 2, <example>   <tag>  </tag>  </example>
fName, lName, age, address 1 address 2, <example>   <tag>  </tag>  </example>
fName, lName, age, address 1 address 2, <example>   <tag>  </tag>  </example>

EDIT:
Desired outcome:

fName, lName, age, address 1 address 2, <example><tag></tag></example>
fName, lName, age, address 1 address 2, <example><tag></tag></example>
fName, lName, age, address 1 address 2, <example><tag></tag></example>

So in the example above, i would like to remove the white space before and after the brackets in the tags, but leave the space in the other values.
Any help would be greatly appreciated.
Comment: This kind of depends on what you're using to make these changes... Perl? PHP? Python? Sed?  AWK?  Also, you should show us what you'd like the desired output to be, so there's no confusion.
Answer: In perl:
s/\s+</</g;
s/>\s+/>/g;

Will remove leading spaces before < and trailing spaces after >.
Also, based on your update; if you just want to remove whitespace between > and < you can simply do s/>\s+</></g;
Comment: You could do pretty much the exact same command with `sed -i` to edit existing files.


Find $x, y$, and $z$ such that $x^3+y^3+z^3=k$, for each $k$ from $1$ to $100.$

Question: It's called a Diophantine Equation, and it's sometimes known as the "summing of three cubes".

A Diophantine equation is a polynomial equation, usually in two or
more unknowns, such that only the integer solutions are sought or
studied (an integer solution is such that all the unknowns take
integer values).

It seems easy for $x^3+y^3+z^3=8$.
$x=1$, $y=-1$ and $z=2.$
But what for higher values of $k$?
Comment: https://en.wikipedia.org/wiki/Sums_of_three_cubes
Comment: For $k=42$ , the problem turned out to be extremely difficult, but a solution was recently found. Now we know for all $k$ upto $100$ a solution or we know that none exists.
Comment: [The sum of three cubes](https://math.stackexchange.com/q/1523130/318073)
Answer: Using positive integers only for $x,y,z$ there are no solutions for $k<3$ but here are $3\le k \le 100$. The use of non-positive integers follows.
<code> (x,y,z,k)
 (1,1,1,3)
 (1,1,2,10)
 (1,2,2,17)
 (2,2,2,24)
 (1,1,3,29)
 (1,2,3,36)
 (2,2,3,43)
 (1,3,3,55)
 (2,3,3,62)
 (1,1,4,66)
 (1,2,4,73)
 (2,2,4,80)
 (3,3,3,81)
 (1,3,4,92)
 (2,3,4,99)
</code>
It appears that at least one of x,y,z must be positive if k is positive.
<code> (x,y,z,k)
 (-100,1,100,1)
 (-99,1,99,1)
 (-98,1,98,1)
 (-97,1,97,1)
 (-96,1,96,1)
 (-95,1,95,1)
 (-94,1,94,1)
 (-93,1,93,1)
 (-92,1,92,1)
 (-91,1,91,1)
 (-90,1,90,1)
 (-89,1,89,1)
 (-88,1,88,1)
 (-87,1,87,1)
 (-86,1,86,1)
 (-85,1,85,1)
 (-84,1,84,1)
 (-83,1,83,1)
 (-82,1,82,1)
 (-81,1,81,1)
 (-80,1,80,1)
 (-79,1,79,1)
 (-78,1,78,1)
 (-77,1,77,1)
 (-76,1,76,1)
 (-75,1,75,1)
 (-74,1,74,1)
 (-73,1,73,1)
 (-72,1,72,1)
 (-71,1,71,1)
 (-70,1,70,1)
 (-69,1,69,1)
 (-68,1,68,1)
 (-67,1,67,1)
 (-66,1,66,1)
 (-65,1,65,1)
 (-64,1,64,1)
 (-63,1,63,1)
 (-62,1,62,1)
 (-61,1,61,1)
 (-60,1,60,1)
 (-59,1,59,1)
 (-58,1,58,1)
 (-57,1,57,1)
 (-56,1,56,1)
 (-55,1,55,1)
 (-54,1,54,1)
 (-53,1,53,1)
 (-52,1,52,1)
 (-51,1,51,1)
 (-50,1,50,1)
 (-49,1,49,1)
 (-48,1,48,1)
 (-47,1,47,1)
 (-46,1,46,1)
 (-45,1,45,1)
 (-44,1,44,1)
 (-43,1,43,1)
 (-42,1,42,1)
 (-41,1,41,1)
 (-40,1,40,1)
 (-39,1,39,1)
 (-38,1,38,1)
 (-37,1,37,1)
 (-36,1,36,1)
 (-35,1,35,1)
 (-34,1,34,1)
 (-33,1,33,1)
 (-32,1,32,1)
 (-31,1,31,1)
 (-30,1,30,1)
 (-29,1,29,1)
 (-28,1,28,1)
 (-27,1,27,1)
 (-26,1,26,1)
 (-25,1,25,1)
 (-24,1,24,1)
 (-23,1,23,1)
 (-22,1,22,1)
 (-21,1,21,1)
 (-20,1,20,1)
 (-19,1,19,1)
 (-18,1,18,1)
 (-17,1,17,1)
 (-16,1,16,1)
 (-15,1,15,1)
 (-14,1,14,1)
 (-13,1,13,1)
 (-12,1,12,1)
 (-12,9,10,1)
 (-11,1,11,1)
 (-10,1,10,1)
 (-9,1,9,1)
 (-8,-6,9,1)
 (-8,1,8,1)
 (-7,1,7,1)
 (-6,1,6,1)
 (-5,1,5,1)
 (-4,1,4,1)
 (-3,1,3,1)
 (-2,1,2,1)
 (-1,1,1,1)
 (0,0,1,1)
 (-47,-24,49,2)
 (-6,-5,7,2)
 (0,1,1,2)
 (-5,4,4,3)
 (1,1,1,3)
 (-58,-43,65,6)
 (-1,-1,2,6)
 (-1,0,2,7)
 (-100,2,100,8)
 (-99,2,99,8)
 (-98,2,98,8)
 (-97,2,97,8)
 (-96,2,96,8)
 (-95,2,95,8)
 (-94,2,94,8)
 (-93,2,93,8)
 (-92,2,92,8)
 (-91,2,91,8)
 (-90,2,90,8)
 (-89,2,89,8)
 (-89,41,86,8)
 (-88,2,88,8)
 (-87,2,87,8)
 (-86,2,86,8)
 (-85,2,85,8)
 (-84,2,84,8)
 (-83,2,83,8)
 (-82,2,82,8)
 (-81,2,81,8)
 (-80,2,80,8)
 (-79,2,79,8)
 (-78,2,78,8)
 (-77,2,77,8)
 (-76,2,76,8)
 (-75,2,75,8)
 (-74,2,74,8)
 (-73,2,73,8)
 (-72,2,72,8)
 (-71,2,71,8)
 (-70,2,70,8)
 (-69,2,69,8)
 (-68,2,68,8)
 (-67,2,67,8)
 (-66,2,66,8)
 (-65,2,65,8)
 (-64,2,64,8)
 (-63,2,63,8)
 (-62,2,62,8)
 (-61,2,61,8)
 (-60,2,60,8)
 (-59,2,59,8)
 (-58,2,58,8)
 (-57,2,57,8)
 (-56,2,56,8)
 (-55,2,55,8)
 (-54,2,54,8)
 (-53,2,53,8)
 (-52,2,52,8)
 (-51,2,51,8)
 (-50,2,50,8)
 (-49,2,49,8)
 (-48,2,48,8)
 (-47,2,47,8)
 (-46,2,46,8)
 (-45,2,45,8)
 (-44,2,44,8)
 (-43,2,43,8)
 (-42,2,42,8)
 (-41,2,41,8)
 (-40,-17,41,8)
 (-40,2,40,8)
 (-39,2,39,8)
 (-38,2,38,8)
 (-37,2,37,8)
 (-36,2,36,8)
 (-35,2,35,8)
 (-34,2,34,8)
 (-34,15,33,8)
 (-33,2,33,8)
 (-32,2,32,8)
 (-31,2,31,8)
 (-30,2,30,8)
 (-29,2,29,8)
 (-28,2,28,8)
 (-27,2,27,8)
 (-26,2,26,8)
 (-25,2,25,8)
 (-24,2,24,8)
 (-24,18,20,8)
 (-23,2,23,8)
 (-22,2,22,8)
 (-21,2,21,8)
 (-20,2,20,8)
 (-19,2,19,8)
 (-18,2,18,8)
 (-17,2,17,8)
 (-16,-12,18,8)
 (-16,2,16,8)
 (-16,9,15,8)
 (-15,2,15,8)
 (-14,2,14,8)
 (-13,2,13,8)
 (-12,2,12,8)
 (-11,2,11,8)
 (-10,2,10,8)
 (-9,2,9,8)
 (-8,2,8,8)
 (-7,2,7,8)
 (-6,2,6,8)
 (-5,2,5,8)
 (-4,2,4,8)
 (-3,2,3,8)
 (-2,2,2,8)
 (-1,1,2,8)
 (0,0,2,8)
 (0,1,2,9)
 (-3,-3,4,10)
 (1,1,2,10)
 (-2,-2,3,11)
 (-11,7,10,12)
 (-46,23,44,15)
 (-1,2,2,15)
 (-94,-48,98,16)
 (-12,-10,14,16)
 (0,2,2,16)
 (-52,25,50,17)
 (1,2,2,17)
 (-2,-1,3,18)
 (-95,47,91,19)
 (-77,26,76,19)
 (-16,-14,19,19)
 (-2,0,3,19)
 (-56,21,55,20)
 (-2,1,3,20)
 (-86,28,85,21)
 (-14,-11,16,21)
 (-10,8,8,24)
 (2,2,2,24)
 (-1,-1,3,25)
 (-1,0,3,26)
 (-100,3,100,27)
 (-99,3,99,27)
 (-98,3,98,27)
 (-97,3,97,27)
 (-96,3,96,27)
 (-95,3,95,27)
 (-94,3,94,27)
 (-93,3,93,27)
 (-92,3,92,27)
 (-91,3,91,27)
 (-90,3,90,27)
 (-89,3,89,27)
 (-88,3,88,27)
 (-87,3,87,27)
 (-86,3,86,27)
 (-85,3,85,27)
 (-84,3,84,27)
 (-83,3,83,27)
 (-82,3,82,27)
 (-81,3,81,27)
 (-80,3,80,27)
 (-79,3,79,27)
 (-78,3,78,27)
 (-77,3,77,27)
 (-76,3,76,27)
 (-75,3,75,27)
 (-74,3,74,27)
 (-73,3,73,27)
 (-72,3,72,27)
 (-71,3,71,27)
 (-70,3,70,27)
 (-69,3,69,27)
 (-68,3,68,27)
 (-67,3,67,27)
 (-66,3,66,27)
 (-65,3,65,27)
 (-64,3,64,27)
 (-63,3,63,27)
 (-62,3,62,27)
 (-61,3,61,27)
 (-60,3,60,27)
 (-60,22,59,27)
 (-59,3,59,27)
 (-58,3,58,27)
 (-57,3,57,27)
 (-56,3,56,27)
 (-55,3,55,27)
 (-54,3,54,27)
 (-53,3,53,27)
 (-52,3,52,27)
 (-51,3,51,27)
 (-50,3,50,27)
 (-49,3,49,27)
 (-48,3,48,27)
 (-47,3,47,27)
 (-46,3,46,27)
 (-45,3,45,27)
 (-44,3,44,27)
 (-43,3,43,27)
 (-42,3,42,27)
 (-41,3,41,27)
 (-40,3,40,27)
 (-39,3,39,27)
 (-38,3,38,27)
 (-37,-36,46,27)
 (-37,3,37,27)
 (-36,3,36,27)
 (-36,27,30,27)
 (-35,3,35,27)
 (-34,3,34,27)
 (-33,3,33,27)
 (-32,3,32,27)
 (-31,3,31,27)
 (-30,3,30,27)
 (-29,3,29,27)
 (-28,3,28,27)
 (-27,3,27,27)
 (-26,3,26,27)
 (-25,3,25,27)
 (-24,-18,27,27)
 (-24,3,24,27)
 (-23,3,23,27)
 (-22,3,22,27)
 (-21,3,21,27)
 (-20,3,20,27)
 (-19,3,19,27)
 (-18,-10,19,27)
 (-18,3,18,27)
 (-17,3,17,27)
 (-16,3,16,27)
 (-15,3,15,27)
 (-14,3,14,27)
 (-13,3,13,27)
 (-12,3,12,27)
 (-11,3,11,27)
 (-10,3,10,27)
 (-9,3,9,27)
 (-8,3,8,27)
 (-7,3,7,27)
 (-6,3,6,27)
 (-5,-4,6,27)
 (-5,3,5,27)
 (-4,3,4,27)
 (-3,3,3,27)
 (-2,2,3,27)
 (-1,1,3,27)
 (0,0,3,27)
 (-59,31,56,28)
 (-17,13,14,28)
 (0,1,3,28)
 (-20,13,18,29)
 (-3,-2,4,29)
 (1,1,3,29)
 (-6,5,5,34)
 (-4,-3,5,34)
 (-1,2,3,34)
 (-13,-8,14,35)
 (0,2,3,35)
 (-75,40,71,36)
 (-3,-1,4,36)
 (1,2,3,36)
 (-56,37,50,37)
 (-3,0,4,37)
 (-27,16,25,38)
 (-3,1,4,38)
 (-52,20,51,43)
 (-13,8,12,43)
 (-7,-7,9,43)
 (2,2,3,43)
 (-7,-5,8,44)
 (-3,2,4,45)
 (-29,19,26,46)
 (-2,3,3,46)
 (-50,-50,63,47)
 (-30,-14,31,47)
 (-8,6,7,47)
 (-26,-23,31,48)
 (-2,-2,4,48)
 (-4,-2,5,53)
 (-1,3,3,53)
 (-18,-15,21,54)
 (-11,-7,12,54)
 (0,3,3,54)
 (-23,-23,29,55)
 (-9,-6,10,55)
 (-2,-1,4,55)
 (1,3,3,55)
 (-47,31,42,56)
 (-21,-11,22,56)
 (-2,0,4,56)
 (-38,25,34,57)
 (-2,1,4,57)
 (-4,-1,5,60)
 (-4,0,5,61)
 (-43,22,41,62)
 (-34,27,27,62)
 (-4,1,5,62)
 (-1,-1,4,62)
 (2,3,3,62)
 (-63,-37,67,63)
 (-58,-38,63,63)
 (-6,-4,7,63)
 (-1,0,4,63)
 (-100,4,100,64)
 (-99,4,99,64)
 (-98,4,98,64)
 (-97,4,97,64)
 (-96,4,96,64)
 (-95,4,95,64)
 (-94,4,94,64)
 (-93,4,93,64)
 (-92,4,92,64)
 (-91,4,91,64)
 (-90,4,90,64)
 (-89,4,89,64)
 (-88,4,88,64)
 (-87,4,87,64)
 (-86,4,86,64)
 (-85,4,85,64)
 (-84,4,84,64)
 (-83,4,83,64)
 (-82,4,82,64)
 (-81,4,81,64)
 (-80,-34,82,64)
 (-80,4,80,64)
 (-79,4,79,64)
 (-78,4,78,64)
 (-77,4,77,64)
 (-76,4,76,64)
 (-75,4,75,64)
 (-74,4,74,64)
 (-73,4,73,64)
 (-72,4,72,64)
 (-71,4,71,64)
 (-70,4,70,64)
 (-69,4,69,64)
 (-68,4,68,64)
 (-68,30,66,64)
 (-67,4,67,64)
 (-66,4,66,64)
 (-65,4,65,64)
 (-64,4,64,64)
 (-63,4,63,64)
 (-62,4,62,64)
 (-61,4,61,64)
 (-60,4,60,64)
 (-59,4,59,64)
 (-58,4,58,64)
 (-57,4,57,64)
 (-56,4,56,64)
 (-55,4,55,64)
 (-54,4,54,64)
 (-53,4,53,64)
 (-52,4,52,64)
 (-51,4,51,64)
 (-50,4,50,64)
 (-49,4,49,64)
 (-48,4,48,64)
 (-48,36,40,64)
 (-47,4,47,64)
 (-46,4,46,64)
 (-45,4,45,64)
 (-44,4,44,64)
 (-43,4,43,64)
 (-42,4,42,64)
 (-41,4,41,64)
 (-40,4,40,64)
 (-39,4,39,64)
 (-38,4,38,64)
 (-37,4,37,64)
 (-36,4,36,64)
 (-35,4,35,64)
 (-34,4,34,64)
 (-33,4,33,64)
 (-32,-24,36,64)
 (-32,4,32,64)
 (-32,18,30,64)
 (-31,4,31,64)
 (-30,4,30,64)
 (-29,4,29,64)
 (-28,4,28,64)
 (-27,4,27,64)
 (-26,4,26,64)
 (-25,4,25,64)
 (-24,4,24,64)
 (-23,4,23,64)
 (-22,-17,25,64)
 (-22,4,22,64)
 (-21,4,21,64)
 (-20,4,20,64)
 (-19,4,19,64)
 (-18,4,18,64)
 (-17,4,17,64)
 (-16,4,16,64)
 (-15,4,15,64)
 (-14,4,14,64)
 (-13,4,13,64)
 (-12,4,12,64)
 (-11,4,11,64)
 (-10,4,10,64)
 (-9,4,9,64)
 (-8,4,8,64)
 (-7,4,7,64)
 (-6,4,6,64)
 (-5,-3,6,64)
 (-5,4,5,64)
 (-4,4,4,64)
 (-3,3,4,64)
 (-2,2,4,64)
 (-1,1,4,64)
 (0,0,4,64)
 (0,1,4,65)
 (1,1,4,66)
 (-22,-19,26,69)
 (-4,2,5,69)
 (-64,23,63,70)
 (-21,11,20,70)
 (-33,-22,36,71)
 (-24,12,23,71)
 (-20,-16,23,71)
 (-3,-3,5,71)
 (-1,2,4,71)
 (-27,-13,28,72)
 (-10,7,9,72)
 (0,2,4,72)
 (-47,29,43,73)
 (-24,-12,25,73)
 (1,2,4,73)
 (-55,26,53,78)
 (-66,-49,74,79)
 (-33,-19,35,79)
 (-6,-6,8,80)
 (2,2,4,80)
 (-18,10,17,81)
 (-15,12,12,81)
 (3,3,3,81)
 (-11,-11,14,82)
 (-36,-32,43,83)
 (-29,22,24,83)
 (-23,-15,25,83)
 (-5,-2,6,83)
 (-2,3,4,83)
 (-16,-9,17,88)
 (-4,-4,6,88)
 (-4,3,5,88)
 (-7,6,6,89)
 (-100,31,99,90)
 (-73,-32,75,90)
 (-51,-35,56,90)
 (-48,19,47,90)
 (-27,13,26,90)
 (-9,-8,11,90)
 (-5,-1,6,90)
 (-3,-2,5,90)
 (-1,3,4,90)
 (-5,0,6,91)
 (0,3,4,91)
 (-8,-5,9,92)
 (-5,1,6,92)
 (1,3,4,92)
 (-5,-5,7,93)
 (-22,14,20,96)
 (-22,17,18,97)
 (-3,-1,5,97)
 (-15,9,14,98)
 (-3,0,5,98)
 (-37,16,36,99)
 (-5,2,6,99)
 (-3,1,5,99)
 (2,3,4,99)
 (-6,-3,7,100)
</code>
Comment: Did you render $x^2+t^3+[z^3=k^3$?  $k$ is not cubed in the q.
Comment: @ Oscar Lanzi  Thanks for pointing out the oversight.
Answer: This is the low-tech approach I took for this question. Note the optional output file in lines 140 and 220. The user may copy/paste or import the data into a spreadsheet for sorting as I did for the other answer.
<code> 100 print "Enter limit";
 110 input l1
 120 print time$
 130 print
 140 rem   open "outfile.txt" for output as #1
 150 for n1 = -l1 to l1
 160     for n2 = n1 to l1
 170        for n3 = n2 to l1
 180            t0 = n1^3+n2^3+n3^3
 190            for t9 = 1 to l1
 200                if t0 = t9
 210                   print "    " n1 n2 n3 t9 "."
 220                   rem  print #1, n1 n2 n3 t9 "."
 230               endif
 240             next t9
 250         next n3
 260     next n2
 270         rem The following IF/ELSE skips zero
 280         rem     for the next iteration of n1
 290         if n1 = -1
 300            n1 = 1
 310            goto 160
 320         endif
 330 next n1
 340 print time$
</code>


Ways of adding nodes in a normal binary tree

Question: Take the following binary tree as an example. Let's say we wanted to add some node (the value associated isn't important). Where can we add the node?

In the picture below, I know I can add nodes at the end of the tree (like the green one I drew). But can we also add nodes in the middle of a certain edge (like the red ones I drew)?

I know this isn't true for a Binary Search Tree, but what about a normal Binary Tree? Also, if the answer is affirmative, is there another way of adding nodes in a normal Binary Tree?
Thanks for any help in advance! (and I am sorry about my drawing skills)
Answer:
can we also add nodes in the middle of a certain edge (like the red ones I drew)?

Yes, the edge splits into two edges, where the inserted node will just have one child.

I know this isn't true for a Binary Search Tree, but what about a normal Binary Tree?

It could sometimes work out for a binary search tree too, but it wouldn't be good practice, as it leads more quickly to an unbalanced tree than the normal insertion procedure would lead to.

is there another way of adding nodes in a normal Binary Tree?

You can also make the new node the root of the binary tree, and its only child would be the old root.


File Upload control unable to browse

Question: i am using  fileupload control on my master page enable asp.net form . When i try to browse it should pop up a dialog box to show files but it does not work . i tried to debug it on console using chrome when i hit browse button it shows me this error .
Uncaught ReferenceError: $ is not defined
here is my html code

 <asp:FileUpload id="FileUploadControl" runat="server" />
    <asp:Button runat="server" id="UploadButton" text="Upload" />
    <asp:Label runat="server" id="StatusLabel" text="Upload status: " />

Comment: This error has no relation to the download file. This mean that your jquery is not load correctly.
Comment: yes indeed i tried to uplaod new CDN but still having same issue
Comment: i am using this CDN
Comment: May be you load script too late.
Comment: @igor Semin i Loading CDN
Comment: Try this valid url . And no more. But i don't understand your problem - you can't insert jquery  to your page or can't upload file?
Comment: well i cant upload the file because when i click on upload button it throws this Uncaught ReferenceError: $ is not defined error instead of browsing file
Comment: Try moving script reference from asp:Content element to 'head' section of your masterpage.
Comment: well problem is resolved i downloaded new JQUERY and added this reference to my master page and it worked .
Answer: I realized that my jQuery reference was too old in my solution. I did following steps and it worked:

downloaded latest jQuery library and removed previous one
Added new reference tag it worked perfectly:

File Upload control unable to browse


using a vbscript to run another vbscript in all subfolders?

Question: I am trying to run a vbscript in all the subfolders of my current dir.
So far I have:
CreateObject("Wscript.Shell").Run("""*\dirlistnew.vbs""")

But that doesn't work. If I remove the *\ it will work in the current dir, but not the subs. I know I'm missing something simple. Been searching and trying things for hours to no avail.
Comment: Search for "vbscript subfolders recursion site:stackoverflow.com"
Comment: Hmm... *"Been searching and trying things for hours to no avail."* really, I searched 4 minutes ago and found that duplicate, what did you search?
Answer: Got you this from my library of snippets, adjust to you needs.
Not tested, I'm more in to Ruby the last couple of years.
'call our sub with the desired path as option
' this needs to be a Folder object, not a String
' FSO.GetFolder will return that object given a path as string
ShowSubfolders FSO.GetFolder(path)

Sub CreateHtml(path)
  ' put here the code from your other script (best)
  ' or do your call to execute the other script
  ' you probably need the path so you pass it as a parameter
End Sub

Sub ShowSubFolders(Folder)
' a Folder has the method SubFolders,
' gives a collection of subfolders that can be enumerated
' with For Each construct
  For Each Subfolder in Folder.SubFolders
    ' print the subfolder so you can follow the progress
    Wscript.Echo Subfolder.Path
    ' and call the sub that creates the html file
    CreateHtml Subfolder.Path
    ' here the magic of recursion, the sub is calling itself with
    ' as parameter the subfolder to process the subsubfolders etc
    ShowSubFolders Subfolder
  Next
End Sub

NB in Ruby it's just one line Dir["#{folder}/*"].each{|f| puts f if File.directory?(f) }
Comment: and I suppose now he gets that.., so let's finish this discussion
Comment: When you decide to answer questions like this you just encourage more of them. The question is poor at best and shows little or no attempt to approach the problem themselves, not to mention it's also been answered before.
Comment: yes but you scare new users away like that, hadn't seen it was a double though
Comment: NB: they are asking for a VBScript solution not Ruby.
Comment: If they scare away that easily then this isn't the place for them. I made the same mistakes but instead of running away, I read the tour and checked [ask], I asked on [meta] and adjusted. We shouldn't have to change because some are too sensitive to readjust and realise we are trying to help them. All this does is validate that what they are doing is right, which is the wrong message.
Comment: I'm more concerned about you getting it tbh.
Comment: I didn't run away I'm in Australia. I went to bed. Now I'm going to work. Oh and we all started somewhere didn't we. I'm trying to understand all of this and just asked for some help, not attitude... Whatever!
Comment: @greg I didn't say you did, I was referring to being scared off *(refer to peter's [earlier comment](http://stackoverflow.com/questions/41790493/using-a-vbscript-to-run-another-vbscript-in-all-subfolders#comment70770408_41790584))*. But to be honest your attitude is all wrong anyway judging by that response, just expecting help with little or no effort on your part isn't the best away to ask here. I recommend you read [ask] thoroughly first, maybe even look through [meta] to understand the community better.
Comment: Ok I'm sorry if I came across all wrong I really didn't mean it. I don't know much at all about VB scripts and I have searched through here and google trying to make sense of it all, but I just can't figure out how it all works. I know I'm missing something probably obvious to you guys who know this stuff very well.
Comment: I don't do this for a living, I'm just trying to set something up for our family to watch home videos and probably trying to get too tricky with it. I'm just a hobbyist who's admittedly not to bright when it comes to this stuff. I didn't mean to come across with a bad attitude. I really have searched and tried quite a few different ways, but I just can't find a way to do what I want to do. Maybe I'm asking at the wrong website. Sorry.
Comment: @greg in which case I doubt peters answer without explanation is going to help you much. You should try providing more information, one line of code and saying it doesn't work tells us nothing about what you are trying to accomplish with next to no VBScript experience.
Comment: @peter relevant - [Is answering a dupe acceptable as to not "scare away" new users?](http://meta.stackoverflow.com/a/284361/692942)
Comment: I understand that this is a dupe now, just learned what that means... look at me go! I have a vbs file in each subdir of the current dir that will read the dir it is in and create an html file with links to each file in each dir. The problem is I need to run the vbs in each sub dir to create the html file. I am trying to automate this instead of manually going through each dir to execute the vbs. I hope this makes sense. As I have said I am sorry for my ignorance but something is just not clicking with me.
Comment: @Greg, since you are beginner, I added some comments to help you get what is going on in the code, feel free to ask if you don't understand
Comment: @Lankymart, funny you reference to a dupe yourself, they clearly have their positive sides
Comment: @Greg Ill adapot the answer to reflect that
Comment: @Peter thank you I will take your answer and see what I can do with it. Thank you all for your time.
Comment: @peter I selected that one purely because of the wording of the question and the answer, the others it's marked as a dup of don't quite fit.
Comment: @Greg, you'r welcome, if the answer helps please accept it as an answer otherwise the question remains open, if not you'd better delete the question in order to avoid more comments like these from Lankymart
Comment: @peter You're never going to get it! You completely undermine the work we are trying to do here and what annoys me more is you know what you're doing but carry on doing it. Undermining me in your comments just shows your lack of respect for the [so] ethos and your real drive behind answering questions. Last I'm going to say, but disappointed is an understatement!
Comment: @peter if you want an example of a [recursive function answer](http://stackoverflow.com/a/41192464/692942), I ended up giving this on a duplicate after [being bullied into it](http://stackoverflow.com/questions/41187136/apply-existing-vbs-folder-search-to-sub-folders/41192464#comment69584111_41187947) - bear in mind, it was me who flagged the question as a duplicate in the first place! We get bullied into answering because people have an expectation, which leaving answers like this to duplicate questions breeds.


macOS: Determine real size of icon returned from iconForFile method

Question: I'd like a way to tell whether a file's icon only provides a 32 x 32 image or if it has modern large icon sizes (512 x 512), so that I know which upscale method to use when enlarging.
I've found that many cross-platform apps still only provide 32 x 32 size Mac icons, which tend to look terrible when blown up to larger sizes, unless upscaled with a nearest neighbour method. On the other hand, modern large icons tend to look terrible when upscaled with nearest neighbour. In my QuickLook extension, I get icon images using [[NSWorkspace sharedWorkspace] iconForFile:path] which always returns an NSImage of size 32 x 32, but provides no clue to what the actual largest icon size available is.
If I iterate through its image representations, the largest one is always 2048 x 2048 pixels.
Is there a way to find out?
Answer: You need to check image representations. If it's NSPDFImageRep you can just call [image setSize:NSMakeSize(512,512)];
The easiest solution to get largest bitmap representation:
NSImageRep *imgRep = [image bestRepresentationForRect:NSMakeRect(0, 0, 2048, 2048) context:nil hints:nil];
NSLog(@"%@",NSStringFromSize([imgRep size]));

Alternatively check all given bitmap representations.
NSURL *URL;
CFErrorRef error;
URL = (__bridge_transfer NSURL *)LSCopyDefaultApplicationURLForContentType(kUTTypeVCard, kLSRolesViewer, &error);
NSImage *image = [[NSWorkspace sharedWorkspace] iconForFile:[URL path]];
NSArray<NSImageRep *>*representations = [image representations];
NSUInteger indexOfLargest = 0;
NSUInteger surfaceArea = 0;
for (NSUInteger i = 0 ; i < [representations count]; i++) {
    NSImageRep *rep = representations[i];
    if ([rep size].width * [rep size].height >= surfaceArea) {
        surfaceArea = [rep size].width * [rep size].height;
        indexOfLargest = i;
    }
}
NSLog(@"Representations %@", representations);
NSLog(@"Largest index is: %lu", (unsigned long)indexOfLargest);

Console output:
2021-07-16 19:02:07.816423+0200 testImages[13756:755791] Representations (
    "NSISIconImageRep 0x600002abe2b0 Size={32, 32} ColorSpace=Generic RGB colorspace BPS=0 Pixels=32x32 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe0d0 Size={32, 32} ColorSpace=Generic RGB colorspace BPS=0 Pixels=32x32 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abe1c0 Size={32, 32} ColorSpace=Generic RGB colorspace BPS=0 Pixels=64x64 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe3a0 Size={32, 32} ColorSpace=Generic RGB colorspace BPS=0 Pixels=64x64 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abe3f0 Size={16, 16} ColorSpace=Generic RGB colorspace BPS=0 Pixels=16x16 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe440 Size={16, 16} ColorSpace=Generic RGB colorspace BPS=0 Pixels=16x16 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abe490 Size={16, 16} ColorSpace=Generic RGB colorspace BPS=0 Pixels=32x32 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe530 Size={16, 16} ColorSpace=Generic RGB colorspace BPS=0 Pixels=32x32 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abe580 Size={18, 18} ColorSpace=Generic RGB colorspace BPS=0 Pixels=18x18 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe5d0 Size={18, 18} ColorSpace=Generic RGB colorspace BPS=0 Pixels=18x18 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abe620 Size={18, 18} ColorSpace=Generic RGB colorspace BPS=0 Pixels=36x36 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe4e0 Size={18, 18} ColorSpace=Generic RGB colorspace BPS=0 Pixels=36x36 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abe670 Size={24, 24} ColorSpace=Generic RGB colorspace BPS=0 Pixels=24x24 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe6c0 Size={24, 24} ColorSpace=Generic RGB colorspace BPS=0 Pixels=24x24 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abe710 Size={24, 24} ColorSpace=Generic RGB colorspace BPS=0 Pixels=48x48 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe760 Size={24, 24} ColorSpace=Generic RGB colorspace BPS=0 Pixels=48x48 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abe7b0 Size={128, 128} ColorSpace=Generic RGB colorspace BPS=0 Pixels=128x128 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe800 Size={128, 128} ColorSpace=Generic RGB colorspace BPS=0 Pixels=128x128 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abe850 Size={128, 128} ColorSpace=Generic RGB colorspace BPS=0 Pixels=256x256 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe8a0 Size={128, 128} ColorSpace=Generic RGB colorspace BPS=0 Pixels=256x256 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abe8f0 Size={256, 256} ColorSpace=Generic RGB colorspace BPS=0 Pixels=256x256 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe940 Size={256, 256} ColorSpace=Generic RGB colorspace BPS=0 Pixels=256x256 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abe990 Size={256, 256} ColorSpace=Generic RGB colorspace BPS=0 Pixels=512x512 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abe9e0 Size={256, 256} ColorSpace=Generic RGB colorspace BPS=0 Pixels=512x512 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abea30 Size={512, 512} ColorSpace=Generic RGB colorspace BPS=0 Pixels=512x512 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abea80 Size={512, 512} ColorSpace=Generic RGB colorspace BPS=0 Pixels=512x512 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abead0 Size={512, 512} ColorSpace=Generic RGB colorspace BPS=0 Pixels=1024x1024 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abeb20 Size={512, 512} ColorSpace=Generic RGB colorspace BPS=0 Pixels=1024x1024 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abeb70 Size={1024, 1024} ColorSpace=Generic RGB colorspace BPS=0 Pixels=1024x1024 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abebc0 Size={1024, 1024} ColorSpace=Generic RGB colorspace BPS=0 Pixels=1024x1024 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua",
    "NSISIconImageRep 0x600002abec10 Size={1024, 1024} ColorSpace=Generic RGB colorspace BPS=0 Pixels=2048x2048 Alpha=NO AppearanceName=NSAppearanceNameAqua",
    "NSISIconImageRep 0x600002abec60 Size={1024, 1024} ColorSpace=Generic RGB colorspace BPS=0 Pixels=2048x2048 Alpha=NO AppearanceName=NSAppearanceNameDarkAqua"
)
2021-07-16 19:02:07.854533+0200 testImages[13756:755791] Largest index is: 31

If you want to have access to original icon representations:
    NSImage *image = nil;
    OSErr err;

    err = GetIconRefFromTypeInfo(0, 0, CFSTR("pdf"), 0, 0, &iconRef);
    if (err == noErr && iconRef) {

        IconFamilyHandle iconFamily = NULL;
        err = IconRefToIconFamily(iconRef, kSelectorAllAvailableData, &iconFamily);
        ReleaseIconRef(iconRef);

        if(err == noErr && iconFamily)
        {
            NSData *data = [NSData dataWithBytes:*iconFamily length:GetHandleSize((Handle)iconFamily)];
            image = [[NSImage alloc] initWithData:data];
        }
    }

Console:
2021-07-19 13:35:33.716142+0200 testImages2[10434:559291] Representations (
    "NSBitmapImageRep 0x60000016e8b0 Size={512, 512} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=1024x1024 Alpha=YES Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600002a3eca0",
    "NSBitmapImageRep 0x60000014bc60 Size={256, 256} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=512x512 Alpha=YES Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600002a3eca0",
    "NSBitmapImageRep 0x60000014bdb0 Size={512, 512} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=512x512 Alpha=YES Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600002a3eca0",
    "NSBitmapImageRep 0x60000014bf00 Size={128, 128} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=256x256 Alpha=YES Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600002a3eca0",
    "NSBitmapImageRep 0x60000014ca10 Size={256, 256} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=256x256 Alpha=YES Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600002a3eca0",
    "NSBitmapImageRep 0x600000144000 Size={128, 128} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=128x128 Alpha=YES Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600002a3eca0",
    "NSBitmapImageRep 0x6000001441c0 Size={32, 32} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=64x64 Alpha=YES Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600002a3eca0",
    "NSBitmapImageRep 0x600000144310 Size={16, 16} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=32x32 Alpha=YES Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600002a3eca0",
    "NSBitmapImageRep 0x6000001443f0 Size={32, 32} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=32x32 Alpha=YES Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600002a3eca0",
    "NSBitmapImageRep 0x6000001444d0 Size={16, 16} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=16x16 Alpha=YES Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600002a3eca0"
)

Comment: @PetterSjölund I updated answer. Those methods still work but are deprecated. If original icns file has only 16x16 - the last method will give only that icon and you can manually upscale with disabled antialiasing. If the file has upscaled icons -> dead end and you cannot do anything.
Comment: @PetterSjölund If the original document icon file is blurry at 512x512 -> it was created during packaging with "iconutil" like that (Xcode uses it on background).  AppKit + NSISIconImageRep -> it's created using [NSImage initWithIconRef:] with "setScalesWhenResized:YES" in a loop with predetermined sizes. Yes they use these deprecated functions on Big Sur. You can look into it using hopperapp + drag&drop AppKit.framework onto it (on Big Sur it's more complicated)
Comment: I finally hacked around this by detecting the most common blurry icons and replacing them with sharper images I included in the bundle. I'll still mark the answer as the solution, as it is likely to be more useful to other people than my hack.
Comment: Well, that's what I was doing, and apparently the  largest image representation for the icons I've checked is 2048 x 2048 although the actual icon image used to build the application is only 32 x 32. I guess this means that the 2048 x 2048 ugly blown-up version has already been created somewhere else, whenever macOS creates its icon images, and the system has no way of telling that this is not the original  icon size.
Comment: Just use something like this NSImageRep *imgRep = [image bestRepresentationForRect:NSMakeRect(0, 0, 512, 512) context:nil hints:nil];
    NSLog(@"%@",NSStringFromSize([imgRep size])); It's either you know what size you want or you want the largest.
Comment: The thing is, I don't know beforehand what size I want. This is for a QuickLook plugin that will show icons from many different application. Some of them are full sized 2048 x 2048, others are 32 x 32, and I'd like a way to determine which is which.
Comment: Do you have example when it's the icon blown up (upscaled 32)?
Comment: Here is an example. This is a TADS 3 game file that gets its icon from Gargoyle: https://ibb.co/p1hKn4n
Comment: And here is a mockup of how I would like it to look instead: https://ibb.co/pd9gs3C
Comment: Thanks for trying to help! Unfortunately that last method gives me a blurry 512 x 512 icon, so I guess that is my answer. It would be interesting to know where or when the upscaling happens, but that is out of scope for this question. If you add some mention of the the fact that what I want to do can't be done in this case, I will mark it as an accepted answer.