Is the index of a Fredholm operator in a $C^*$-algebra independent of the choice of representation?

Question: Suppose that $x$ is an element of abstract $C^*$-algebra $A$. For example if $x$ is normal, i.e. $x^*x=xx^*$ then if we use any representation $\pi$ of $A$ on some Hilbert space $H$ then $\pi(x)$ will be normal and therefore its index will be zero. I would like to know whether the following is true:

Suppose that $x$ is an element of a $C^*$-algebra $A$ and $\pi$ is a faithful representation on $H$ such that $\pi(x)$ is Fredholm. Is it true that the index of $\pi(x)$ is independent from the choice of such $\pi$?
Answer: No.  For instance, you can take the representation $\pi\oplus\pi$ on $H\oplus H$, and then $(\pi\oplus\pi)(x)$ will have twice the index of $\pi(x)$.


Exception of type 'System.OutOfMemoryException' was thrown in C#

Question: HtmlHelper.GetTagsAndValues(htmlContent);

and i get this error:
 at System.String.Split(String[] separator, Int32 count, StringSplitOptions options)
   at System.String.Split(String[] separator, StringSplitOptions options)
   at WebCrawler.Logic.CrawlerManager.UseRulesOnHtmlPage(Agencies agency, String pageUrl, List`1 listTagValuePair, RulesGroups ruleGroup) in D:\PROJEKTI\crawler\WebCrawlerSuite\WebCrawler.Logic\CrawlerManager.cs:line 263
   at WebCrawler.Logic.CrawlerManager.GetAdvertismentFromHtmlContent(List`1 listTagValuePair, Agencies agency, String pageUrl) in D:\PROJEKTI\crawler\WebCrawlerSuite\WebCrawler.Logic\CrawlerManager.cs:line 191
   at WebCrawler.Logic.CrawlerManager.ImportAdvertisment2Database.Work(Crawler crawler, PropertyBag propertyBag) in D:\PROJEKTI\crawler\WebCrawlerSuite\WebCrawler.Logic\CrawlerManager.cs:line 668
   at WebCrawler.Logic.CrawlerManager.ImportAdvertisment2Database.Process(Crawler crawler, PropertyBag propertyBag) in D:\PROJEKTI\crawler\WebCrawlerSuite\WebCrawler.Logic\CrawlerManager.cs:line 584

i read this article:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/out-of-memory-does-not-refer-to-physical-memory
How can i prevent this error?
whole method:
public static List<TagValuePair> GetTagsAndValues(string htmlContent)
        {
            List<TagValuePair> tagsValues = new List<TagValuePair>();
            Dictionary<string, int> tagAppearance = new Dictionary<string, int>();

            HtmlDocument doc = new HtmlDocument();

            if (htmlContent != null)
            {
                doc.LoadHtml(htmlContent);

                if (doc.DocumentNode.SelectNodes("//*") == null)
                {
                    List<TagValuePair> tempList = new List<TagValuePair>();
                    tempList.Add(new TagValuePair("Error!", htmlContent, -1));
                    return tempList;
                }

                foreach (HtmlNode tag in doc.DocumentNode.SelectNodes("//*"))
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(tag.InnerHtml.Trim()))
                        {
                            if (!tagAppearance.Keys.Contains(tag.Name))
                            {
                                tagAppearance.Add(tag.Name, 1);
                            }
                            else
                                tagAppearance[tag.Name] = tagAppearance[tag.Name] + 1;

                            tagsValues.Add(new TagValuePair(tag.Name, tag.InnerHtml.Trim(), tagAppearance[tag.Name]));
                        }
                        else
                        {
                            // Help link: http://refactoringaspnet.blogspot.com/2010/04/using-htmlagilitypack-to-get-and-post_19.html
                            if (!string.IsNullOrEmpty(tag.GetAttributeValue("value", "").Trim()))
                            {
                                if (!tagAppearance.Keys.Contains("option value"))
                                {
                                    tagAppearance.Add("option value", 1);
                                }
                                else
                                    tagAppearance["option value"] = tagAppearance["option value"] + 1;

                                tagsValues.Add(new TagValuePair("option value", tag.GetAttributeValue("value", "").Trim(), tagAppearance["option value"]));
                            }

                            if (tag.NextSibling != null && !string.IsNullOrEmpty(tag.NextSibling.InnerHtml.Trim()))
                            {
                                if (!tagAppearance.Keys.Contains(tag.Name))
                                {
                                    tagAppearance.Add(tag.Name, 1);
                                }
                                else
                                    tagAppearance[tag.Name] = tagAppearance[tag.Name] + 1;

                                tagsValues.Add(new TagValuePair(tag.Name, tag.NextSibling.InnerHtml.Trim(), tagAppearance[tag.Name]));
                            }
                        }
                    }
                    catch (Exception)
                    {
                        return null;
                    }
                }
            }

EDIT:
exact error is here:
 doc.LoadHtml(htmlContent);

Comment: You should reorganize your code. a "global" System.Exception Catcher isn'T a good idea.
When removing the catch you could see an which exact position the exception is thrown. see also http://blogs.msdn.com/b/kcwalina/archive/2007/01/30/exceptionhierarchies.aspx
Comment: thx. so which type of errors do you suggest. problem is that i get this error after 12 hours of app working.
Comment: how often is this code running?
Comment: depends how fast read html. less then 20s
Comment: You could run this program until it gets the exception and then connect with visual studio debugger to see where the exception occured.
Also you can monitor if the memory is full.

Perhaps you got some memory leaks ?
Comment: yes problem is HtmlDocument.LoadHtml. I found exact error.
Comment: Improve `WebCrawler.Logic.CrawlerManager.UseRulesOnHtmlPage(...)`
Answer: I would suggest looking at a memory profiler to ensure you haven't got any leaks in your application. Given you say it occurs after 12 hours of app working, it seems to indicate that it may be a slow leak that eventually causes the OutOfMemory exception.
There are a number of ways that you can unitentionally hold onto references that will cause a slow leak. Running a profiler will help you identify these issues. It may not be the one line of code that is causing the problem. It may just be that the one line of code is often showing you the straw that breaks the camels back.
I have used Redgates Ants Profiler before (it comes with a 14 day free trial), and it helped me heaps to get memory usage down and increase performance. I seem to be plugging this a lot recently, but it is purely due to the fact I find it to be a very valuable tool.
Take a look through some of their walkthroughs and/or vidoes to see how to track down a leak.
Comment: +1 for the Ants profiler.  Also, specifically take notice of the large object heap stats.  That was the main culprit of OOMs in the process I've been working on.
Comment: I got stung by not unsubscribing to a particular forms events. When the form was closed, it was never cleaned up, so the forms (and everything they referenced) were left hanging around unable to be collected. One small change and it made a major difference.


Find all those graphs $G$ of order $n \geq 4$ such that the subgraph induced by every three vertices of $G$ is a tree.

Question: I thought a graph like this did not even exist? I suppose, at least, I cannot think of one that does.
Answer: Hint: For $n \geq 5$, there must be a vertex of degree $3$.  If there's no triangles, it's neighbours must not be adjacent, but this is a contradiction.
To prove the existence of such a vertex:

The subgraph induced by $\{1,2,3\}$ has a vertex of degree $2$, let's say it's vertex $1$.
Now consider the subgraph induced by $\{1,4,5\}$.
Answer: Consider the graph $G$ as a subgraph of a complete graph $K_n$. Then $G$ must contain exactly two edges from each triangle in $K_n$. It easily follows that $G$ must contain exactly two-thirds of the edges of $K_n$. This is impossible for $n=5$ since $K_5$ has $10$ edges, not divisible by $3$; so every graph of order $5$ (or greater) has an induced graph on $3$ vertices which is not a tree.
This leaves only the case $n=4$. The graph $G$ must have exactly $4$ vertices, exactly $4$ edges, and no triangles; the only such graph is $K_{2,2}=C_4$, which works.


how to differential exponential of a matrix variable $f(X)=e^{X(t)\mathrm{d}t}$?

Question: I have a function about a square matrix $X$ which depends also time: $f(X)=e^{X(t)}$, $t$ is time. So how to differential it about time to have $\frac{\mathrm{d}f(X)}{\mathrm{d}t}$?
I know that
$$e^{X(t)}=I+X(t)+\frac{X(t)^2}{2!}+\frac{X(t)^3}{3!}+\dots$$
But I dont know how to differential each term $\frac{X(t)^k}{k!}$ about time $t$. Or is there some other method to differential directly $e^{X(t)}$?
Any help will be appreciated. thanks.
Comment: what does dt mean?
Comment: dt is a very short time range(limit to $0$), just like the dt in a differential equation.
Comment: it could be seen as a constant, no problem
Answer: If $X(t)X'(t)=X'(t)X(t)$, for all $t$, then
$$
\frac{d}{dt}\mathrm{e}^{X(t)}=\mathrm{e}^{X(t)}\frac{dX(t)}{dt}.
$$
If not, then the above does not hold.
Comment: thank you very much. I dont think that my matrix satisfies that condition.
Comment: another question, if it satisfies your condition, can we have $\frac{d}{dt}\mathrm{e}^{X(t)}=\mathrm{e}^{X(t)}\frac{dX(t)}{dt}=\frac{dX(t)}{dt}\mathrm{e}^{X(t)}$? Thank you.
Comment: Yes. It also holds.
Answer: There is no simple formula for the derivative of the exponential of a matrix valued function.
However, there is a well known integral representation of the derivative.
$$\frac{d}{dt} e^{X(t)} = \int_0^1 e^{\lambda X(t)} \left(\frac{dX(t)}{dt}\right) e^{(1-\lambda)X(t)} d\lambda$$
Look at the wiki page for matrix exponential, there are some references for this integral representation.


proof about partial order

Question: Let R and S be two partial orders on a set X, and T is a relation on X such that aTb(i.e. a,b ∊ X) if and only if both aRb and aSb hold. Is T also a partial order on X?
how to prove it?
Comment: Why not check each of the defining properties of a partial order to see if they hold?
Answer: Check each of the required properties for a relation to be a partial order: reflexivity, antisymmetry, and transitivity.
Here, I go through the proof that $T$ is transitive.

Suppose $aTb$ and $bTc$.  We ask whether or not this implies that $aTc$ is also true.
Well... by $aTb$ we know in particular that $aRb$.  Further by $bTc$ we know in particular that $bRc$.  Since $R$ is a partial order, we know that from $aRb$ and $bRc$ and that $R$ is transitive that $aRc$ is also true.
Similarly, we can show that $aTb$ and $bTc$ imply that $aSb$ and $bSc$ from which it follows that $aSc$.
Since both $aRc$ and $aSc$ are true, it follows that $aTc$ is also true.
Thus, the relation $T$ is indeed transitive.

The remaining parts of the problem are just checking the other properties and they are all performed similarly.  Use what you know about how $T$ is defined in terms of $R$ and $S$ and use the fact that $R$ and $S$ are both partial orders themselves and have the desired properties.

proof about partial order


How to perform text mining, sentiment mining, and business category identification, and where to obtain a categorization library

Question: Currently I am working with Text Mining which includes sentiment identification and assigning corresponding business categories using open source tool R. I found these two documents which helped me to some extent:

http://www.jstatsoft.org/v25/i05/
http://epub.wu.ac.at/1923/1/document.pdf

My approach is to tokenize the text and then lookup for sentiment and business category. To do this I require positive and negative libraries for sentiment mining and category file which contains word and category. I was able to get positive and negative words but was unable to get a categorization library.

Where can I get a categorization library?
Is the above approach appropriate?  Is there a better way to do this?
Answer: One solution mentioned by Jeffrey Breen is to use Lu and Hiu's lexicon. He also gives a cool tutorial for sentiment mining on Twitter.
Answer: A few alternatives
1) Supervised learning: Ideally you'd want to have in your data the text and a label, where the label refers to the category you are interested. For this you'd need to manually label the data.
Then you can train a statistical/machine learning algorithm in order to classify the categories you've labeled. For this a simple approach in R is using the text2vec and glmnet packages.
2) Unsupervised learning: Another alternative if you are not willing to label the data, you can fit a statistical model to find topics, this is called latent dirichlet allocation. It's also supported by text2vec, there are other packages for this such as topicmodels.
3) Transfer learning: Finally, another option is transfer learning. The idea is you get labeled data from another problem, train a classifier and use the model to make predictions in your data. The problem is finding data of the same domain...
4) Using a dictionary (hack): Below is the original answer I wrote that is using a look-up table of a "dictionary" of positive and negative words. I'd now say this option is the last resource, it's sort of a hack as it too broad.
I think there are packages that implement this now.
EDIT
Below is my previous answer.
I've used Jeffrey's function to compute the score using the "look up" method.
I made a corruption index of polititians from Argentina. So the more people said they were corrupt, the higher the score.
For the data I had, as the tweets were in spanish, I just wrote a small dictionary more coherent with the needs of the problem. I guess it depends what you want to analyze.
Besides this approach, there are more sophisticated methods. I think there is a coursera course about NLP.
Here is another resource:
https://sites.google.com/site/miningtwitter/basics/text-mining
It says it's deprecated because of the changes of twitter API, but the author of twitteR package adapted the package to the new API. So you need first to install the updated package, perhaps the source version of it.
Here is the author's web page. _http://geoffjentry.hexdump.org/
The later is needed in order not to get duplicated tweets when making a call bigger than 100 tweets.
Jeffrey's Function:
score.sentiment = function(sentences, pos.words, neg.words, .progress='none')
{
    require(plyr)
    require(stringr)

    # we got a vector of sentences. plyr will handle a list
    # or a vector as an "l" for us
    # we want a simple array ("a") of scores back, so we use
    # "l" + "a" + "ply" = "laply":
    scores = laply(sentences, function(sentence, pos.words, neg.words) {

        # clean up sentences with R's regex-driven global substitute, gsub():
        sentence = gsub('[[:punct:]]', '', sentence)
        sentence = gsub('[[:cntrl:]]', '', sentence)
        sentence = gsub('\\d+', '', sentence)
        # and convert to lower case:
        sentence = tolower(sentence)

        # split into words. str_split is in the stringr package
        word.list = str_split(sentence, '\\s+')
        # sometimes a list() is one level of hierarchy too much
        words = unlist(word.list)

        # compare our words to the dictionaries of positive & negative terms
        pos.matches = match(words, pos.words)
        neg.matches = match(words, neg.words)

        # match() returns the position of the matched term or NA
        # we just want a TRUE/FALSE:
        pos.matches = !is.na(pos.matches)
        neg.matches = !is.na(neg.matches)

        # and conveniently enough, TRUE/FALSE will be treated as 1/0 by sum():
        score = sum(pos.matches) - sum(neg.matches)

        return(score)
    }, pos.words, neg.words, .progress=.progress )

    scores.df = data.frame(score=scores, text=sentences)
    return(scores.df)
}

Comment: Welcome to the site, @MartinBel. Is this meant as an answer to the OP's question? Would you mind fleshing out the connections between your post & the original question? I think this has a lot of potential, but it might help if it where a little more detailed.
Comment: @gung if you follow the link of Jeffrey Breen's blogspot posted in the first answer, it will make more sense. http://jeffreybreen.wordpress.com/2011/07/04/twitter-text-mining-r-slides/ He provides an R function to calculate the score of tweets using a Lu and Hiu's lexicon. The function is great, however the lexicon could be changed.
Comment: Thanks, that helps a little. 1 of our goals is to create a permanent repository of information about statistics & machine learning. Thus, 1 thing we worry about is linkrot. We don't want your answer to become less useful should those slides disappear. Would you mind including some supporting detail so that a future reader wouldn't need to have seen that to get full value from your post? Since you're new here, you may want to read our [about](http://stats.stackexchange.com/about) & [help pages](http://stats.stackexchange.com/help), which discuss things like this.


Hausman Test interpretation is based on the p-value? - R output

Question: I obtained the following output after running the Hausman test:
1) CASE 1 Hausman Test chisq = 13.943, df = 4, p-value = 0.007478 alternative hypothesis: one model is inconsistent
2) CASE 2 Hausman Test chisq = 0.49157, df = 4, p-value = 0.9743 alternative hypothesis: one model is inconsistent
According to the p-values and for significance <0.05, should I go for the fixed effects in CASE 1 and for the random effects in CASE 2?
Thanks
Answer: Yes. See the following taken from a Princeton slide:

To decide between fixed or random effects you can run a Hausman test
  where the null hypothesis is that the preferred model is random
  effects vs. the alternative the fixed effects (see Green, 2008,
  chapter 9). It basically tests whether the unique errors (ui) are
  correlated with the regressors, the null hypothesis is they are not.
  Run a fixed effects model and save the estimates, then run a random
  model and save the estimates, then perform the test. If the p-value is
  significant (for example <0.05) then use fixed effects, if not use
  random effects.

see: https://dss.princeton.edu/training/Panel101R.pdf
Comment: The link doesn't work anymore :)


What users are accessing and downloading in general in Azure DevOps

Question: Can I track what users are accessing and downloading in Azure DevOps? I know about the Audit log, however can the Usage tab to the job?
Answer: We cannot check who accessed or downloaded in general in Azure DevOps, we could only check the changes that occur throughout an Azure DevOps organization in the Auditing page. Since these operations have not changed Azure DevOps, we could not get the logs.
In addition, this API shows a list of all audit events your organization could emit. You could run it and check the support events.
<code>https://auditservice.dev.azure.com/{Org name}/_apis/audit/actions
</code>


error probability of decision function

Question: If I have a binary calssification task with prior probability $p(0) = 0.6$, and I make two decisions.
1) solely based on the prior probability  i.e. I make prediction 0 60% of the time and prediction 1 40% of the time.
2) always make the prediction 0.
As I can see, the error probability in both case is 0.4 right ?.  Why a constant decision rule and a rule based on prior gives same error ?
Comment: i think there is a typo, i think,  0.4*0.6*2 = 0.48
Comment: the error probability is not 0.4 in both cases.
Comment: @NikolasRieble can you elaborate it ?. How can i estimate the error probability then ?
Comment: your prediction is independent of the true target variable or any other information. Therefore, the error probability in the first case is 0.4 * 0.6 * 2 = 0.44, whereas the error probability in the second case is 0.4.
Comment: for your first case: What is the chance that you predict 0, whereas the correct value would be 1? (error A). What is the chance that you predict 1, whereas the correct value would be 0? (error B).
Comment: indeed, you are right.
Answer: To expand on a comment, under scenario 1) you lose under two possibilities: 1) you randomly choose 0 and the truth was 1 or 2) you randomly choose 1 and the truth was 0. In both cases the probability is 0.4*0.6 and thus the total error probability is 0.4*0.6*2=0.48. Under scenario 2), you lose whenever the truth is 1 which occurs with probability 0.4.

error probability of decision function


bash while loop through a file doesn't end when the file is deleted

Question: I have a while loop in a bash script:
Example:
while read LINE
do
echo $LINE >> $log_file
done < ./sample_file

My question is why when I delete the sample_file while the script is running the loop doesn't end and I see that the log_file is updating? How the loop is continuing while there is no input?
Answer: In unix, a file isn't truly deleted until the last directory entry for it is removed (e.g. with rm) and the last open file handle for it is closed. See this question (especially MarkR's answer) for more info. In the case of your script, the file is opened as stdin for the while read loop, and until that loop exits (or closes its stdin), rming the file will not actually delete it off disk.
You can see this effect pretty easily if you want. Open three terminal windows. In the first, run the command cat >/tmp/deleteme. In the second, run tail -f /tmp/deleteme. In the third, after running the other two commands, run rm /tmp/deleteme. At this point, the file has been unlinked, but both the cat and tail processes have open file handles for it, so it hasn't actually been deleted. You can prove this by typing into the first terminal window (running cat), and every time your hit return, tail will see the new line added to the file and display it in the second window.
The file will not actually be deleted until you end those two commands (Control-D will end cat, but you need Control-C to kill tail).
Answer: See "Why file is accessible after deleting in unix?" for an excellent explanation of what you are observing here.
In short...

Underlying rm and any other command that may appear to delete a file
  there is the system call unlink. And it's called unlink, not remove or
  deletefile or anything similar, because it doesn't remove a file. It
  removes a link (a.k.a. directory entry) which is an association
  between a file and a name in a directory.

You can use the function truncate to destroy the actual contents (or shred if you need to be more secure), which would immediately halt the execution of your example loop.
Answer: The moment shell executes the while loop, the sample_file contents have been read, and it does not matter whether the file exists or not after that point.
Test script:
$ cat test.sh
#!/bin/bash

while read line
do
    echo $line
    sleep 1
done < data_file

Test file:
$ seq 1 10 > data_file

Now, in one terminal you run the script, in another terminal, you go and delete the file data_file, you would still see the 1 to 10 numbers printed by the script.


Foreign Data Wrappers, ogr_fwd layer Postgresql

Question: I have make correctly(it connects me) a Server with foreign data this way:
CREATE SERVER myserver
  FOREIGN DATA WRAPPER ogr_fdw
  OPTIONS (
   datasource 'C:\Program Files\PostgreSQL\9.5\tmp\test\myfile.dbf',
    format 'ESRI Shapefile' );

Then i make a foreign table like this:
CREATE FOREIGN TABLE pt_test (
  "field1" integer,
  "field2" varchar,
  "field3" varchar,
  "field4" varchar,
  "field5" varchar)
  SERVER myserver
  OPTIONS (layer 'pt_two');

When i make a Select to pt_test, it gives me this error:
SQL Error: ERROR:  unable to connect to layer to "pt_two"
HINT:  Does the layer exist?

I dont now what is layer.
Any help?
Answer: Run command ogr_fdw_info -s "C:\Program Files\PostgreSQL\9.5\tmp\test\myfile.dbf" this can provide list of layers in your file. Select existed one and pass it into 'layer' option from CREATE FOREIGN TABLE command. More info can be found here.


Serenity test error element not available in headless mode

Question: The scenario is:
I have serenity tests that i launch with chromedriver that work
When i launch the tests without headless option the tests are "passed"
while with the headless mode the tests are failed with error:
net.serenitybdd.core.exceptions.SerenityManagedException: The following error occurred: Timed out after 5 seconds. Element not available
here the line command that launch the test : mvn clean verify -Dwebdriver.driver=chrome
And the serenity.properties:

webdriver.chrome.driver = chromedriver
webdriver.base.url= ********
webdriver.timeouts.implicitlywait=5000
chrome.switches=--headless;
serenity.browser.maximized = true
Answer: The solution is to add in chrome.switches --window-size=1920,1080;

chrome.switches=--window-size=1920,1080;--headless;
Comment: What does `serenity.browser.maximized = true` does?
Comment: serenity.browser.maximized = true should open the browser to the maximum size but it seems that it is only counted in the case of launch without headless mode
Comment: Tried this solution using chrome.switches=--window-size=900,600;--headless; which is the resolution used without the headless mode and on where the test cases are passing, but the issue still happens to me. Using chrome + chrome driver 108. Additional ideas ? Could be a bug into the selenium web driver for windows ?


Can $\sqrt[n]{\sqrt{a}+\sqrt{b}}+\sqrt[n]{\sqrt{a}-\sqrt{b}}$ be an integer?

Question: The number $\sqrt{a}+\sqrt{b}$ cannot be an integer if $a,b$ are integers such that $\sqrt{b}$ is not an integer. (In fact, this is true for any number of square roots, and I believe even for cube roots, etc.) Therefore $\sqrt[n]{\sqrt{a}+\sqrt{b}}$ cannot be an integer either, for any positive integer $n$.
What about if we sum it with the conjugate? That is, do there exist positive integers $n\geq 2,a,b$ such that $\sqrt{b}$ is not an integer but $\sqrt[n]{\sqrt{a}+\sqrt{b}}+\sqrt[n]{\sqrt{a}-\sqrt{b}}$ is an integer?
Update: As Jyrki Lahtonen points out in the comment, there do exist such integers. What about if we also require that $\sqrt{a}$ is not an integer either?
Comment: If you drop the assumption that $\sqrt{a}$ is not an integer, then you get plenty of examples. For example
$$(2+\sqrt3)^3=26+15\sqrt3=\sqrt{676}+\sqrt{675}$$ and similarly
$(2-\sqrt3)^3=\sqrt{676}-\sqrt{675}$, so
$$\root3\of{\sqrt{676}+\sqrt{675}}+\root3\of{\sqrt{676}-\sqrt{675}}=4.$$
You can similarly reverse engineer the sum of cube roots of the cubes of any conjugate pair $u\pm\sqrt v$.
Comment: But you are not multiplying the two expressions, you are adding them. How do you think $\sqrt{a}$ is supposed to 'disappear' in this case? I don't think it's possible. I might be mistaken, of course, I hope someone will correct me if it's the case
Comment: If you had $a+\sqrt{b}$ instead, I would say it's possible. But in your case, the second part is not really a conjugate - because $\sqrt{a}$ is not an integer
Comment: I was thinking of conjugate in the sense that $(\sqrt{a}+\sqrt{b})(\sqrt{a}-\sqrt{b})$ is an integer. But the question Is still interesting in your case, I believe.
Comment: Fine, I get your point. I'll edit to remove the assumption that $\sqrt{a}$ is not an integer.
Comment: This is not possible for $n = 2$; it boils down to requiring $\sqrt a + \sqrt{a - b} \in \Bbb N$, which is only possible if both of these are in $\Bbb N$.
Comment: If you look at cube roots (or any odd roots), clearly $\sqrt[3]{a} + \sqrt[3]{-a} = 0$ which is an integer. If you're willing to work with complex numbers a similar thing holds for square roots as well.
Comment: $a,b$ must be positive integers, so neither of them can be set to $0$
Answer: The answer is yes. Pell's equations solve the problem.
Let
$$A.N'^{2}+1=M'^{2}$$
the generic Pell equation, the solution of which is:
$N'=\frac{(M+N\sqrt{A})^{n}}{2\sqrt{A}}-\frac{(M-N\sqrt{A})^{n}}{2\sqrt{A}}$,
$M'==\frac{(M+N\sqrt{A})^{n}}{2}+\frac{(M-N\sqrt{A})^{n}}{2}$
where  $ M$ and $N$ are the basic solutions of $A$
(For example if we choose $A=8$, $N=1$ and $M=3$).
$\sqrt[n]{\sqrt{a}+\sqrt{b}}+\sqrt[n]{\sqrt{a}-\sqrt{b}}=M'$,
$\sqrt[n]{\sqrt{a}+\sqrt{b}}-\sqrt[n]{\sqrt{a}-\sqrt{b}}=N'\sqrt{A}$;
$a=2^{-2(n+1)}\Big((M+N\sqrt{A})^{n}+(M-N\sqrt{A})^{n}\Big)^{2}$,
$b=2^{-2(n+1)}\Big((M+N\sqrt{A})^{n}-(M-N\sqrt{A})^{n}\Big)^{2}$.
Let's take an example: $A=13$, $N=180$ and $M=649$,
we choose $n=4$, then
$\sqrt[4]{\sqrt{a}+\sqrt{b}}+\sqrt[4]{\sqrt{a}-\sqrt{b}}=1419278889601$,
$a=\frac{1053711982714216551873491874429255128997076465231993345538436469128908160121757992166220331730227201}{256}$,
$b=4116062432477408405755827634489277847644829942312474006009517457534797500475617156899298170821200$.
If we choose $A=8$,$M=3$ and $N=1$ and $n=5$, we get:
$\sqrt[4]{\sqrt{a}+\sqrt{b}}+\sqrt[4]{\sqrt{a}-\sqrt{b}}=3363$,
$a=\frac{47370562574818466708936539960450008969}{1024}$,
$b=\frac{5921320321852308338617067495056251121}{128}$,
and so on…
Comment: Now I'm wondering if it's possible if $a$ and $b$ are integers (but not squares).


Definition of cost function and likelihood: how one appears from the other

Question: I was reading this paper and the book "Introduction to Quantum State Estimation" by Yong Siah Teo and I am facing some issues trying to understand how the definition of the cost function given in these two references can match each other and how the likelihood function can rise from this definition.
The paper reads:

And the books says:

Although they seem the same, there are some differences that I cannot understand how to connect one with the other. I mean, the equation $(2)$ seems to be the same one as the $1.2.1$ from the book, except for the summation symbol when taking defining the average cost function. This summation symbol is defined later in the book as:

My issues are simply that:

I cannot see how to connect these two definitions. This summation symbol that is defining "a conditional average over all possible measurement data" does not seem to enter in any way in the definition of the paper, which seems more plausible since minimizing a cost function is just taking the average "over all possible true configurations" which is the integral the author on the paper stated.
why the likelihood function appears in the average?
How to connect these two definitions considering this summation (average) with the likelihood?
Answer: Thank you for the interest in my book! I am the author, so let me try to give you a simple answer to your questions.
In the paper, the cost function is defined with respect to a single measurement dataset ($\mathbb{D}$ with my notation, and D with theirs). This is often the cost function one is interested in since one is usually interested in the problem defined by this particular dataset. For the case of the book, the purpose was to connect ideas of various types of state estimators with the cost function, and so I considered the additional averaging over $\mathbb{D}$. This explains the additional data average sum, which involves the likelihood function for a correct statistical average over datasets.
In short, these are two different cost functions, and the one considered in the book is by no means the only legitimate one. It is only an option to introduce estimators. The choice of which cost function to use really depends on your objective.
Comment: Hello! Your book is excellent, I am using it as one of my main references for learning and understanding the subject. Thanks for your answer. It does make sense.


Localization of the coordinate ring $K[V]$, $K$ not necessarily algebraically closed.

Question: In his first chapter of "The Arithmetic of Elliptic Curves", Silverman develops some necessary background in algebraic geometry. He works over ground fields $K$, which are perfect but not necessarily algebraically closed. For example, we get the coordinate ring of $V/K$:
$$
K[V] = \frac{K[X_1, \dots, X_n]}{I(V/K)}.
$$
I am then wondering why Silverman defines the maximal ideal $M_P = \{f \in \bar{K}[V] : f(P) = 0\}$ and the corresponding local ring $\bar{K}[V]_{M_P}$ only for algebraically closed fields?
It seems to me that (for $P$ a $K$-rational point) we could define a maximal ideal $m_P = \{f \in K[V] : f(P) = 0\}$ and a corresponding local ring $K[V]_{m_P}$ — although I am not sure if this is still a DVR?
Answer: Yes, all of this still works for non-algebraically-closed fields. One doesn't even need $P$ to be $K$-rational: it's perfectly fine to think about the local ring of $\operatorname{Spec} \Bbb R[x]$ at the point $(x^2+1)$, for instance.
As for whether the local ring is a DVR or not, this is only the case when $V$ is of dimension one - in general, the local ring of a point has dimension equal to the codimension of the closure of the point in the variety. So for $K[V]_{I(P)}$ to have dimension one, $\overline{\{P\}}$ should be a codimension one subvariety of $V$, which if $P$ is a closed point can only happen when $V$ is of dimension one.
Comment: at the maximal ideal $(x^2+1) = \{f \in K[V] : f(i) = 0\}$  (in elliptic curves we want a group law on the points so it is weird to call a maximal ideal a point)


How to prove that $\sum_{n=1}^\infty{n^2a^{n-1}}=\frac{1+a}{(1-a)^3}$

Question: I want to prove that $$\sum_{n=1}^\infty{n^2a^{n-1}}=\frac{1+a}{(1-a)^3}$$
I start off at the sum and try to work my way into the equation.
I know that the sum is:
$$σ_{n}=1+2^2+a+3^2a^2+4^2a^3+\dots+n^2a^{n-1} (1)\Leftrightarrow$$
$$aσ_{n}=a+2^2a^2+3^2a^3+\dots+n^2a^n (2)$$
If I subtract (2) from (1), I get: $$(1-a)σ_{n}=1+2^2a+3^2a^2+\dots+n^2a^{n-1}-a-2^2a^2-\dots-n^2a^n \Leftrightarrow$$
$$(1-a)σ_{n}=(n^2+(n-1)^2)a^{n-1}-n^2a^n \Leftrightarrow$$
$$σ_{n}=\frac{n^2-(n-1)^2-n^2a^n}{1-a} \Leftrightarrow$$
$$σ_{n}=-\frac{1+n^2a^n}{1-a}$$
and that is what I've got so far. How can I continue solving this?
I don't know if this is the best solution of the proof, but my textbook had a similar proof for $$\sum_{n=1}^{\infty}na^{n-1}=\frac{1+a}{(1-a)^2}$$
So, I tried using the same way.
Answer: $\textbf{hint}$
$$
\sum n\dfrac{d}{da}a^n =\frac{d}{da}\sum na^n= \sum n^2a^{n-1}
$$
Do you need me to continue?
Comment: @Shevliaskovic For $|a|<1$, the classic geometric series is

$$\sum_{n=0}^\infty a^{n+1}=\frac{1}{1-a}$$

Chinny84's Hint is to take the derivative with respect to $a$ on both sides, twice. There are no integrals.
Comment: what is that $d$ ? Is it the derivative?
Comment: Aren't you treating $a$ as a variable when it is a constant?
Comment: I am treating it as a variable similar to differentiating under the integral sign.
Comment: Is there any way to solve this without using integrals? I know how to use them, but the Series chapter in my book is before the integrals chapter. (The question above is from the series chapter).
Comment: @Chinny84 yup, I know that. I also know that $$\sum_{n=1}^{\infty}na^{n-1}=\frac{1+a}{(1-a)^2}$$
Comment: It is not an integral .. You can solve using series. Differentiating under the integral sign was just showing you another area where you have a constant and treat it as variables
Comment: Then to finish off then make my hint similar to yours :).
Answer: We have to check that:
$$\left(1-3a+3a^2-a^3\right)\sum_{n=0}^{+\infty}(n+1)^2 a^n = 1+a. \tag{1}$$
Let $\delta$ be the backward difference operator:
$$ \delta g(n) \triangleq g(n)-g(n-1).\tag{2}$$
If we set $b_n=(n+1)^2\cdot I_{n\geq 0}$, line $(1)$ can be written as:
$$ \sum_{n=1}^{+\infty} \delta^3(b_n)\, a^n = 1+a. \tag{3} $$
For any $n\geq 3$, we have $\delta^3(b_n)=0$, since if $g$ is a polynomial, the degree of $\delta g$ is just the degree of $g$ minus one. So we just have to check that:
$$ \delta^3(b_0)=1,\quad \delta^3(b_1)=1,\quad  \delta^3(b_2)=0. \tag{4}$$
This is easy to do:
$$(1,4,9,16,\ldots)\stackrel{\delta}{\longrightarrow}(1,3,5,7,\ldots)\stackrel{\delta}{\longrightarrow}(1,2,2,2,\ldots)\stackrel{\delta}{\longrightarrow}(1,1,0,0,\ldots).\tag{5}$$


Project throwing IOException after readFile method call

Question: I'm currently writing a program that will read in a CSV file that contains data about age, height, and weight. My issue is, when I call in the method that reads the file from the main, it throws an IOException.  I'm not sure what's causing this, and as this is for a project, I am not allowed to throw an IOException from the main() method. I inserted a output print line to try and spot where the bug occurs, because debug mode in eclipse is not allowing me to do so, and it seems that the error occurs before the readFile() method even starts.
I am extremely rusty in java and code in general, and am taking this class after not touching coding for an extended period of time.  I'm not sure exactly where to start to try and debug this IOException.
public class Project1 {
    public static void main(String[] args) {

        //main method declaring project object
        Project1 project = new Project1();

        String fileName = project.checkArgs(args);
        File blah = null; //temporary name for the file don't pay attention to it

        try {
            blah = project.getFile(fileName); //gets the file and sets it to variable in main
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            project.readFile(blah, 500); //trying to read in file of 2d array in the readFileMethod
        }
        catch (IOException i) { //method gets caught here
            System.out.println("IOException");
        }
    }

    //readFile METHOD
    public String[][] readFile(File file, int numRecords) throws IOException {

//two parameters: file, being read in this method, and numRecords the amount
//of elements in the array (I haven't done anything with numRecords yet and I
//believe this may possibly be the source of the error

        Scanner reader = new Scanner(file); //scanner to read in file

        //2d array to be passed back to main
        String[][] data = new String[numRecords][3];

        System.out.println("hi"); //test for IOException, doesn't get to this point

        int iteration = 0; //to skip first line of text in csv file

        while (reader.hasNextLine()) { //loading in elements to 2d array
            iteration++;
            if (iteration < 1) {
                reader.nextLine();
                continue;
            }
            else {
                String list[] = reader.nextLine().trim().split(",");
                for (int i = 0; i < numRecords; i++) {
                    for (int j = 0; j < 3; j++) {
                        data[i][j] = list[j];
                        System.out.println(data[i][j]);
                    }
                }
            }
        }
        return data;
    }

The program catches the IOException in method main().
Comment: Edit your question and include the entire stack trace (as text, not as an image).
Answer: I can't find the reason, please provide a stack trace (i.printStackTrace()).
Since you do not use the delimiters of the scanner, you may try another way:
BufferedReader br = new BufferedReader(new FileReader(file), bufferSize);
String line;

if ((line = br.readLine()) != null) {
   // process the line
}


z-score for two variables

Question: Can we study the relationship between two variables using z score?
For example: Let us say that we have two classes A, B and we have 5 students in each class and we know the age and the grade for every student.  and we want to study the relationship between age and the grades.
<code>  age     class A  grades
  10       75
  13       85
  20       55
  16       45
  19       90

  age     class B  grades
  12       65
   9       54
  13       67
  21       90
  23       85
</code>
If we calculate the Z score for age and for the grades then we can estimate how far is the grades or the ages from the mean.
How can we visualize the relationship between the grades and the age using Z score in this case?
Comment: You might want to explore some of our higher-rated threads on [correlation](http://stats.stackexchange.com/search?tab=votes&q=correlation%20standardize%20z-score).  I believe the question at http://stats.stackexchange.com/questions/70969 may be practically the same.
Answer: You can calculate the z score for individual data points within either data set.  You could then compare these z scores for a gauge on the differences between the data points.  Since the z score is calculated for each individual data point, however, it is not generally a useful tool for comparing one data set with another data set.  It is better suited to comparing data points to each other.  I recommend the following videos to better understand z score.
http://www.snappyeducation.com/#!z-score/c1msv

z-score for two variables


How to disallow flags to get triggered if one of the user fields is empty?

Question: I have a user flag "Status" and I have some fields for that user like name, phone etc.
How do I not let moderators trigger that flag if any of that user field is empty?
Comment: merci for accept!
Answer: Use the Rules module to implement what you're asking for, as detailed in the blueprint below ...
Step 1: Create a custom rule
Create a rule like so:

Event: after updating an account.
Conditions:

user does not yet have role (say) "abc".
check that none of those user fields are empty.

Action: grant access to a role (say) "abc".

For an example of a rule (in Rules export format) that is pretty close to what you need, have a look at my answer to "How to implement admin verification for selected user profile fields?".
Step 2: Tune the configuration of the flag
Adapt the configuration of your "Status" flag, so that you only authorize it to be used by ... euh ... indeed, users who have access to role "abc".
Happy flagging with Rules!


Conflito jQuery-Prototype assíncrono

Question: Pois bem eu detenho do uso das duas bibliotecas e então para que não houvesse conflito optei por usar o jQuery.noConflict() entretanto ao mesmo tempo tentei manter o uso do dollar mas meu código quebra devido a "assincroniedade" do código.

veja que X não é imprimido, há como resolver?
Comment: O que tem de assíncrono aí? Acho que nada.
Answer: Não imprime porque o x está fora do escopo (deve estar dando um erro, não?).
Você precisa declarar x no escopo mais externo:
var x = 0; // DECLARE AQUI
(function($){
    $("body").css('background-color', 'red');
    // AQUI TIRE O var
    x = 1;
})(jQuery);

// Funciona!
console.log(x);

Comment: Como assim? Não entendi.
Comment: Existe alguma forma de se fazer isso só que com o prototype?
Comment: Dê um exemplo concreto do que você está tentando fazer, senão fica difícil dizer qualquer coisa.

Conflito jQuery-Prototype assíncrono


Como aumentar a largura das colunas da tabela e ajustar a largura da janela modal do JavaScript

Question: Preciso ajustar duas coisas em uma janela Modal Bootstap/javascript:
1 - A largura e altura da janela modal;
2 - Os nome das colunas da tabela estão quebrando para uma nova linha e deformando a aparência. Preciso fazer com que cada coluna ajuste-se de acordo com os nomes.
Alguém saberia como me ajudar?

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Histórico de Alterações

                <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>

@section scripts
    {

Answer: Para aumentar o tamanho do modal do Bootstrap, você pode usar normalmente css, por exemplo:
No código abaixo, olhe a classe que eu inseri na segunda DIV

 //ATENÇÃO À CLASSE bigModal

      seu header aqui

          seu body aqui

      seu footer aqui

E depois você adiciona a classe bigModal em um arquivo css:
.bigModal{
   width: 85%
   height: 500px;
}

Ou você pode usar o estilo 'in-line':
...

...
Mas de qualquer forma recomendo fortemente que você faça em uma folha de css separada para facilitar na manutenção do código
Sobre as colunas, o próprio Bootstrap já arruma a largura delas segundo seu conteúdo. Quando você aumentar a largura do modal como um todo, acredito que seu problema vai estar resolvido
Espero ter ajudado, um abraço
Comment: Obrigado @Mateus Alberghini!!! Funcionou 100% mano!!!
Comment: Magina cara, é um prazer. Keep Learning.


How can i remove the Azure WebApp AppSetting WEBSITE_TIME_ZONE

Question: when I delete the AppSetting "WEBSITE_TIME_ZONE" in my Azure Webapp (Linux), it is there again after refreshing.
I can delete other AppSettings without problems, but this particular entry keeps coming back.
This is how I proceed. I delete the setting "WEBSITE_TIME_ZONE" via the trash can button, click on Save (then the entry is gone), then I click on Refresh and then the entry shows up again.
Has anyone had this problem and can help me?
Comment: This shouldn't be the case. Can you try clearing your browser cache a doing a hard refresh?
Comment: Btw, the Timezone for Linux Apps on Azure is managed via the [TZ](https://sajeetharan.com/2019/11/12/how-to-set-timezone-in-azure-app-service/) application setting.
Comment: I usually work with the Chrome browser. For this case, I installed the Firefox browser very fresh and tried it through it. The problem remains the same.

When I delete the setting and save it, I get the message "The web app settings have been updated successfully", but when I click "Refresh", the app setting is back.
Comment: That's strange indeed. Could you please try deleting this one via the command line? [az webapp config appsettings delete](https://learn.microsoft.com/en-us/cli/azure/webapp/config/appsettings?view=azure-cli-latest#az_webapp_config_appsettings_delete) is the Azure CLI command.
Comment: P.S. You can use the [Azure Cloud Shell](https://shell.azure.com/bash) if you do not have Azure CLI installed on your machine.
Comment: Glad that helped! Summarized our discussion as an answer below. Please consider [upvoting and accepting the answer](https://stackoverflow.com/help/someone-answers) so it benefits others in the community who run into similar issues. :)
Comment: Having the same issue on windows server
Answer: Please try deleting that specific app setting via the command line.
az webapp config appsettings delete is the Azure CLI command:
<code>az webapp config appsettings delete --name <your-webapp-name> --resource-group <resource-group> --setting-names <setting-names>
</code>
P.S.: You can use the Azure Cloud Shell if you do not have Azure CLI installed on your machine.
Answer: You don't need to delete "WEBSITE_TIME_ZONE"
instead change it to a valid TZ table value.
For example "America/New_York"


Sql group by working not properly

Question: This is my query
select
 (sum(case when offer1_delivered is not null then 1 else null end) ) as PenetrationRate1
,(sum(case when offer2_delivered is not null then 1 else null end)) as PenetrationRate2
,count(TargetMkgListID) as TargetMkgListID from tablename

output
PenetrationRate1    PenetrationRate2    TargetMkgListID
1                   2                3

I need to include customername column in this query
select  customername,
 (sum(case when offer1_delivered is not null then 1 else null end) ) as PenetrationRate1
,(sum(case when offer2_delivered is not null then 1 else null end)) as PenetrationRate2
,count(TargetMkgListID) as TargetMkgListID from tablename
group by customername

If I include customername in my query, groupby is not working properly.
Answer: SELECT  customername
,(ISNULL(SUM(CASE WHEN offer1_delivered is not null THEN 1 ELSE 0 END),0)) AS PenetrationRate1
,(ISNULL(SUM(CASE WHEN offer2_delivered is not null THEN 1 ELSE 0 END),0)) AS PenetrationRate2
,COUNT(TargetMkgListID) as TargetMkgListID from tablename
GROUP BY customername

Comment: What is the purpose of the ISNULLs? `CASE .. THEN 1 ELSE 0` cannot result in `NULL`. When you see that they're redundant, then how is this answer different to another one posted 30 minutes earlier?
Comment: If we are using **ELSE 0**  Instead of **Else NULL** we don't need ISNULL in the select statement
Comment: Exactly, so why did you add it?
Comment: Don't need either one... I works with just `case WHEN offer2_delivered is not null THEN 1 End`
Answer: select  customername,
 (sum(case when offer1_delivered is not null then 1 else 0 end) ) as PenetrationRate1
,(sum(case when offer2_delivered is not null then 1 else 0 end)) as PenetrationRate2
,count(TargetMkgListID) as TargetMkgListID from tablename
group by customername

Comment: I am guessing by "not working" that you are seeing NULLs. If it's something else, please edit the question and add some sample data and expected results.
Answer: Assuming there is only one customerName value in the table, Try
select Min(customername),
       sum(case when offer1_delivered is not null then 1 end) PenetrationRate1,
       sum(case when offer2_delivered is not null then 1 end) PenetrationRate2,
       count(TargetMkgListID) TargetMkgListID
from tablename

If there is more than one customerName in the table, then you can't add customerName to Select clause and still get the sums of ALL the records in the table (only one row in output). You can only get the sum of the records by each customername, which is what your second query should be doing. So if that second query is not what you want then you have a problem because what you want is probably not logically possible with the data you have

Sql group by working not properly


How do you create a CCK field that presents a node creator with a list of the website's users?

Question: I'm trying to add a CCK field that will present a site manager with a list of instructors which are actually a sub-group of already-authenticated users with the role name of "instructor" for a "class" content type.
The list of instructors is pretty large, and I'd rather use the actual users that are already on the site to populate that field instead of just having a plain select list.
The "class" content type will have a couple other fields, like location, day of the week, and class type. The problem is figuring out how to add the instructors, who are already authenticated users to the content type via a select list of some kind. Does anyone have any ideas on how to best accomplish this? I can't find a suitable CCK field to do what I'm trying to do, and as mentioned previously, I don't want to use just a text/select list.
Answer: You can setup a view for those users and then install Views Field View module. With this module you can add a new field to your node which is a link to that view.
That view will be able to get arguments coming from the node where it's linked from.
Answer: You can use the modules Entity reference and Views.
Views will allow you to generate a list of authenticated users (see PS).
Entity reference will allow you to add a Reference field which can reference entities filtered by the view you choose during the field setup.
PS.
In order to make the view available on the field setup page, the view my have a "References" display.


Adding WHERE clause of third table in MySQL whose ID is present in first two Inner joined tables

Question: I have the following query, where count of two tables is divided and further other column values are displayed.
Both the tables are joined via Months/ year.
  select
        (a.count_one / b.count_two) as final_count, a.orders,
        a.Months, b.Sum
    from
        (
            select count(*) as count_one, DATE_FORMAT(`date`, "%M %Y") AS `Months`, orders
            from first_table
            GROUP BY Months)
        ) a
    INNER JOIN
        (
            select count(*) as count_two, DATE_FORMAT(`date`, "%M %Y") AS `Months`, sum(a) AS Sum
            from second_table
            GROUP BY Months)
        ) b
    ON a.Months = b.Months

Output:
**Month and Year**    **Final_Count**
January 2016              126
February 2016             123
March 2016                 45
....                      ....
...                       ....
...                       ....

What is required?

A third table is present, whose keys are in first_Table and second_table. I need to put a WHERE clause, based on third table, that is, WHERE thirdtable.name='Any name'
So, wherever the ID related to the thirdtable.name appears, those results should display, but I am unable to achieve this.
What I tried?
I tried a third INNER join AS:
INNER JOIN third_table ON a.shid= third_table.id WHERE thirdtable.name='Any name'

But, no results are displayed in this case.
Any suggestions?
Answer: The subqueries don't select the id column, so there's no a.shid to compare with. And since the subqueries are grouped by month, you can't select the id column in them.
You need to join with the third table in the subqueries.
select
    (a.count_one / b.count_two) as final_count, a.orders,
    a.Months, b.Sum
from
    (
        select count(*) as count_one, DATE_FORMAT(`date`, "%M %Y") AS `Months`, orders
        from first_table
        JOIN third_table ON first_table.shid = third_table.id
        WHERE third_table.name = 'Any name'
        GROUP BY Months)
    ) a
INNER JOIN
    (
        select count(*) as count_two, DATE_FORMAT(`date`, "%M %Y") AS `Months`, sum(a) AS Sum
        from second_table
        JOIN third_table ON second_table.shid = third_table.id
        WHERE third_table.name = 'Any name'
        GROUP BY Months)
    ) b
ON a.Months = b.Months


Como programar mobile com o Delphi?

Question: Olá, sei que o Delphi XE4 cria aplicativos mobile para IOS, mas será que ele faz a mesma coisa para Android mobile? E se faz qual é o nome da ferramenta?
Comment: De uma olhada neste link -> https://www.embarcadero.com/products/rad-studio/create-android-apps
Comment: Mas ai está falando do Delphi XE8, eu queria saber do XE4
Comment: Amigo acredito que somente a partir do Delphi XE5
Answer:
Não achei nada relacionado a Android e Delphi XE4, somente em versões superiores. Uma alternativa seria atualizar a ferramenta para uma versão mais recente.

RAD Studio XE8
Plataforma de aplicações conectadas para Windows e além
O Embarcadero® RAD Studio XE8 é a solução completa de desenvolvimento de softwares para o rápido design, codificação e extensão de aplicações "conectadas" do Windows, Mac, iOS, Android e IoT. Construa soluções de força industrial e prontas para os negócios, incorporando múltiplas plataformas clientes nativas, extensões mobile, dispositivos inteligentes como relógios inteligentes e outros gadgets IoT, serviços nas nuvens, dados corporativos e embutidos. Remova o fator dificultador de múltiplas equipes e múltiplas bases de código e crie aplicações nativas rápidas para Windows, OS X e mobile a partir de uma única base de código.
Fonte: Site Embarcadero
Visual Studio 2015 (Sugestão)
A Microsoft lançou o VS 2015 que está em RC(Release Candidate), ele possui a versão community para você usar gratuitamente.
Crie aplicativos para múltiplas plataformas para Windows, iOS, Android e muito mais usando um único IDE.

Xamarin para o Visual Studio: um código comum base em c# para todos
os dispositivos
Apache Cordova com o Visual Studio: um código comum base para HTML,
CSS e JavaScript ou Typescript
Visual Studio Tools para o Unity: desenvolvimento de jogos 2D/3D em
c#
C++ para desenvolvimento de plataforma cruzada: compartilhado
bibliotecas de código e aplicativos em C++

Com VS2015 é possível criar aplicativos para iOS, Android, Windows Phone. É possível também criar aplicativos Híbridos utilizando o apache cordova + html/css/JS.
Mais Informações no site do VS2015
Answer: Não é possível desenvolver para Android com Delphi XE4. Mas a partir do Delphi XE5 (out/2013) isso é possível.
A situação atual está na resposta de @MeuChapeu.
O nome do "framework" utilizado para desenvolvimento multiplataforma no Delphi é Firemonkey (FMX).
Veja também:
https://stackoverflow.com/questions/7598579/how-to-create-android-apps-using-delphi

Como programar mobile com o Delphi?


Como deixar um elemento com a altura da página o tempo todo?

Question: Tenho o seguinte problema: Preciso deixar que uma div tenha o a altura da tela o tempo.

...

 ...

 ...

Quero apenas fazer com o que a div com o identificador menulateral tenha o tempo todo a altura da tela.
Estava tentando fazer do seguinte jeito:
var altura = $("body").height();
$("#menulateral").height(altura);

Não sei se esse é o melhor jeito para eu fazer, porque gostaria que isso funcionasse sem problemas e em todos os dispositivos que pudessem acessar essa página. Existe uma solução melhor e mais confiável?
Comment: Você está usando _bootstrap_ no teu projeto?
Comment: sim estou bootstrap
Answer: Não tem necessidade de utilizar Javascript se você não pretende fazer uso desse valor durante a execução da sua aplicação. Como bem disse, esse menu terá o mesmo tamanho sempre, então basta a propriedade height das CSS:

html,
body {
  height: 100%;
  margin: 0
}

aside {
  background-color: #2ecc71;
  height: 100%; /* 100% da altura do elemento pai (no caso, o 'body') */
  width: 200px
}

Mas se quiser mesmo usar jQuery, além de definir o tamanho inicial (como fez no seu código), também precisará ouvir pelos eventos de redimensionamento da janela para atualizar o tamanho do elemento:

$(function() {

  var aside = $('aside');

  // Defininindo a altura inicial.
  aside.height($('body').height());

  // Redefinindo a altura sempre que a janela for redimensionada.
  $(window).resize(function() {
    aside.height($('body').height());
  });

});
html,
body {
  height: 100%;
  margin: 0
}

aside {
  background-color: #333;
  width: 200px
}

sopt
Answer:
Vou te sugerir utilizar um modelo de página com menu lateral que o
  próprio bootstrap sugere, Simple
  sidebar

Como você está fazendo, o menulateral está dentro de uma row, o que não é recomendável, pois a row é uma divisão na horizontal e seu menu precisa ser vertical.
O código é basicamente esse:

Da uma olhada no link do template

O sidebar-wrapper dentro de um wrapper irá criar um "espaço" para
  um menu responsivo com 250px de largura. Seria bacana você dar uma
  olhada no html do
  template
  e na documentação do
  bootstrap, você não
  precisa usar jQuery para isso. Claro, você pode fazer isso com jQuery,
  mas acho que fica mais fácil e viável utilizando CSS e como disse no
  começo, é uma sugestão.
Comment: entendi, então esse sidebar-wrapper já resolveria meu caso?
Comment: Alterei a resposta.


Problem of Inequality using wavy curve

Question: I came across a relatively simple problem in one of the reference books whose answer surprised me. It is based on finding the range of numbers that can be taken by x so that the inequality is satisfied.
The question goes on like this:

Find the number of integers satisfying the inequality; (x^2+2)/(x^2-1) < -2

What I did to find the answer was to being the '-2' to LHS and then simply to get a result:

[(3x^2)/{(x+1)(x-1)}] < 0

Since for any Real value of x the numerator will be positive, I took it to the RHS and simplified the inequality further:

[1/{(x+1)(x-1)}] < 0

Using the method of wavy curve:

I get the possible range of values of x as x ∈ (-1,1). Hence the answer to the question asked terns out to be "only one integer which here is zero.".
But here comes the real problem, when "zero, 0" is substituted inn the place of x in the above inequality the answer turns out to be:

{2/(-1)} < -2
Hence, (-2) < (-2)

which is clearly not correct. What is the mistake I am doing or is there some other flaws in the method of wavy curve?
Comment: Your error is the assertion that "for any Real value of x the numerator will be positive." In fact, you found exactly the counterexample.
Comment: It is indeed true that for any value of x^2 will be possible right? What is wrong in that?
Comment: $0$ is not positive........
Comment: When you "simplified the inequality further", you divided by 0 in the case where $x=0$.
Answer: The numerator in $$\frac {3x^2}{(x-1)(x+1)}$ is not positive for all real values of x.
It is zero at $x=0$ where you need to pay a special attention.

Problem of Inequality using wavy curve


"normalized accuracy" as an estimator for the classifier's performance -- what's the drawback?

Question: I am facing a problem with the classification of an imbalanced sample, and I was looking into solutions for both dealing with the imbalance (e.g. oversampling/undersampling) and a metric which would be suitable for the estimation of the classifier performance on the imbalanced sample.
I need to mention that my sample is not extremely imbalanced, at most 1:2 to 1:3 ratio.
Regarding the metrics, I found many alternatives to accuracy, except for the one which seemed very logical to me -- what I call in my head "normalized accuracy". Simply said, it is the average of the ratios of the correctly identified samples within each class. On a confusion matrix for two classes, it would be (TP/(TP+FN) + TN/(TN+FP))/2. This seems very logical to me, symmetrical and extendible to multilabel classification.

However, when I tried to find any mentions in the literature regarding this, I completely and repeatedly failed. Is it known under another name? Is it somehow so flawed that nobody ever discusses it anymore? Can someone enlighten me about this?
Answer: Your measure is a linear transform of Youden's J statistic. See wikipedia Youden's J statistic page for more information about how is computed. J statistic has one advantage, it's range which make it easier to compare.


Is it possible to show two Databricks dashboards side by side in another Databricks dashboard (or otherwise)

Question: I have two Databricks dashboard I would like to display side by side.  Is this possible?
Comment: are you talking about Databricks SQL dashboards or dashboards in notebooks?
Answer: As a work around, I was able to download each dashboard as an html file and then use something like the code shown below to display them side-by-side.


how to allow -non_number as arguments in python argparse

Question: python test.py --arg -foo -bar
test.py: error: argument --arg: expected at least one argument

python test.py --arg -8
['-8']

How do I allow -non_number to work with argparse?
Is there a way to disable short arguments?
Comment: This is the problem of handling an argument that looks like a flag: https://stackoverflow.com/questions/48322986/python-argparse-passing-argument-to-argument; https://stackoverflow.com/questions/16174992/cant-get-argparse-to-read-quoted-string-with-dashes-in-it
Answer: Call it like this:
python test.py --arg='-foo'

To allow specifying multiple:
parser.add_argument('--arg', action='append')
# call like python test.py --arg=-foo --arg=-bar

Comment: doesn't work for more than 1 arguments though. Edited question to reflect
Answer: I think you're looking for the nargs parameter to argparser.
parser.add_argument('--arg', nargs='?')

At the moment, --arg is interpreting the value '-8' as the input, whereas it thinks '-f' (with parameters 'oo') is a new argument.
Alternatively, you could use action='store_true', which will represent the presence or absence of the argument with a boolean.
parser.add_argument('--arg', action='store_true')

https://docs.python.org/3/library/argparse.html#nargs


When should I stop playing this dice game?

Question: The rules are as follows:
You start with \$1 and roll a six-sided die. If you roll anything but a 1, you double your money (so \$2 for the first roll, $4 for the second, and so on). If you roll a 1, you lose all your money. What is the optimal number of times you should roll the die to make the most money?
My initial theory:
The probability of rolling 2-6 consecutively $n$ times is $(\frac{5}{6})^n$; and the probability of rolling a 1 is just $\frac{1}{6}$. So, the expected value is going to be:
$$
E = (\frac{5}{6})^n2^n-\frac{1}{6}2^n \\
=2^n(\frac{5}{6}^n-\frac{1}{6})
$$
Now, if I solve for $n_{L}$ where $E=0$:
$$
0=2^{n_{L}}(\frac{5}{6}^{n_{L}}-\frac{1}{6}) \\
\frac{1}{6}=\frac{5}{6}^{n_{L}} \\
n_{L}=log_{5/6}\frac{1}{6}\\
\approx9.8
$$
Which means I should roll around 9 times to maximize my profit (or maybe 10 if I'm feeling lucky).
However, I tried running a quick simulation and got $n_{L}=5.01 \pm 0.05$ after 10,000 games.
Where did I go wrong? Thank you!
For reference:

import random
import numpy as np

def dice():
    return random.randint(1,6)

ns=np.array([])
for i in range(10000):
    n=0
    while dice() != 1:
        n+=1
    ns=np.append(ns,[n])
print(np.average(ns))
print(np.std(ns)/100)

Output

5.0093
0.05511008393207182

Edit:
Here's a more accurate simulation that reflects Ross Millikan's answer for my own reference.
import random
import numpy as np

def dice():
    return random.randint(1,6)

trials=np.array([[]])
for i in range(30):
    moneys=np.array([])
    for j in range(100):
        money=1
        numrolls=0
        while numrolls <= i:
            numrolls+=1
            if dice() != 1:
                money=2*money
            else:
                money=0
                break
        moneys = np.append(moneys,[money])
    print("i: "+str(i))
    trial = np.array([i,np.average(moneys)])
    print("money: "+str(np.average(moneys)))
    trials = np.append(trials,trial)

Output
i: 0
money: 1.74
i: 1
money: 2.48
i: 2
money: 4.88
i: 3
money: 6.56
i: 4
money: 14.08
i: 5
money: 28.8
i: 6
money: 32.0
i: 7
money: 40.96
i: 8
money: 81.92
i: 9
money: 112.64
i: 10
money: 245.76
i: 11
money: 737.28
i: 12
money: 1146.88
i: 13
money: 327.68
i: 14
money: 2293.76
i: 15
money: 3276.8
i: 16
money: 6553.6
i: 17
money: 13107.2
i: 18
money: 26214.4
i: 19
money: 52428.8
i: 20
money: 20971.52
i: 21
money: 0.0
i: 22
money: 83886.08
i: 23
money: 335544.32
i: 24
money: 335544.32
i: 25
money: 671088.64
i: 26
money: 1342177.28
i: 27
money: 8053063.68
i: 28
money: 0.0
i: 29
money: 0.0

Comment: I'm not fluent in python, but it seems to me that what your code actually does is compute the expected number of rolls until you hit a $1$, which is 6 (so 5 rolls before the $1$).
Comment: You're totally right. That accounts for the discrepancy. Thanks!
Answer: Your calculation is incorrect because $2^{n}\cdot \left(\frac 56 \right)^n$ is the expected profit of rolling $n$ times and quitting.  You should not subtract the $\frac 162^{n}$ because the loss of that is already reflected.
Planning to roll $n+1$ times is always better than planning to roll $n$ times.  If you plan to roll $n$ times your expected return is $2^{n}\cdot \left(\frac 56 \right)^n=\left(\frac 53 \right)^n$.  Each additional roll increases your expected return by a factor $\frac 53$ so you should never quit.  The mathematical problem with this is that the expected value does not converge, so it is not defined.  The psychological problem with this is that eventually you will roll a $1$ and get nothing.  This is a variant on the Saint Petersburg paradox.
Simulation is a poor approach for problems like this.  If you only try $10000$ or even $10^{100}$ times you will miss the rare event that you avoid rolling $1$ for an enormous time and win huge (assuming you stop).
Comment: Thanks for the answer! Intuitively, wouldn't the expected value as $n$ goes to infinity be zero though?
Comment: No, it grows without bound.  The chance of getting anything goes to $0$, but the something you get grows faster, so the expected value grows without bound.
Comment: Sorry, I'm a bit confused. The St. Petersburg problem goes to infinity because you never lose the money (there is no minus term) which makes sense intuitively as well. In this case, wouldn't I have a minus term? Also, the probability of rolling a 1 as $n$ goes to infinity is 100%. So you will always end up losing if you keep rolling. I based this idea on this https://math.stackexchange.com/questions/1974265/probability-how-to-play-a-game-when-the-expected-value-is-always-positive
Comment: The idea in St. Petersburg is also that the expected value is not bounded.  You are right that you never lose money there, but the increasing payoff with decreasing probability is the same.
Comment: It took me a while, but I finally got it...wow that was crazy. I tried running a simulation where I'd roll from 1 to 100 times 100 each, and I finally understood what you meant after seeing the average profit shoot up until it just hit zero. I never really thought about problems that aren't fit for simulations till now. Frustrating since my first mathematical guess was that it diverges, but my intuition said no so I tried to modify it haha. Thank you so much!
Comment: Ross Millikan and @siberowl Relevant [fundamental principle](https://math.stackexchange.com/questions/1516115/how-is-integrability-used-in-fundamental-principle-you-cant-beat-the-system)? or not really?
Answer: Your code is calculating the average number of rolls where you successfully cash out but it doesn't account for the fact that the prize doubles at each step. The expected value does and so taking more risks for the much larger reward is optimal at each step.
Comment: Oh I see, that makes sense. Thank you! I wonder if my theory is still correct, and if I should still be choosing 9 over 5 rolls.
Comment: Relevant [fundamental principle](https://math.stackexchange.com/questions/1516115/how-is-integrability-used-in-fundamental-principle-you-cant-beat-the-system)? or not really?


Having trouble get the right output from a MySQL Query

Question: I have a database that includes the following tables:

User
Category
Article

Inside our website we have a section called "editors pick" that has 5 of the best articles chosen by editors on that area.
Editors must set "is_recommended = yes" and also "recommended_location" which can be either 1,2,3,4, or 5; accordingly they will be placed on one of those 1-5 placements on the website.
Articles also have a "start_date" meaning the author can write an article assign it as is_recommended = yes and recommended_location = 3 and then set it for tomorrow 9pm. Therefore the article will only appear tomorrow and when it does it should sit on the 3 box of the editors pick.
Sometimes we may have an article such as below:

ID: 123
is_recommended: yes
recommended_location = 3
start_date = 06-05-2016 09:00:00 (let's say this is yesterday)

Which is currently holding the #3 spot.
I have another article:

ID: 456
is_recommended: yes
recommended_location = 3
start_date = 07-05-2016 09:00:00 (this is today and today it is already 11am)

However my query still continues to show ID: 123; while I want it to show the one in slot #3 that is the newest (meaning 456)
Can someone tell me what I am doing wrong in my query below, how can I assure that for each slot the newest item is selected?
This is the query:
select *
from (
    select article.*, user.username, category.title as ctitle, user.firstname, user.lastname, category.slug as cslug, category.category_id as pid
    from article
    left join user on article.created_by = user.id
    left join category on category.id = article.category_id
    where article.status='active'
    AND is_recommended='yes'
    AND article.start_date<='".date('Y-m-d H:i:s')."'
    AND recommended_location in (1,2,3,4,5)
    order by start_date desc
 ) as x
 group by recommended_location
 limit 5

Comment: you should have an end_date comparison as well even if it meant manually adding 1 day to start_date. that way you can use something like date BETWEEN start_date AND end_date...so there's no confusion between what rows should be returned.
Comment: @Turo has the solution you want. It's a non-trivial problem you are trying to solve. Read [this article](http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/) about trying to solve this type of problem
Comment: Thanks @AgRizzo this is exactly the problem. Now to put 2+2 together.
Comment: @TinTran but it does not make sense for our system, end dates are unclear and actually non-existant. Once an article is live it needs to stay live.
Answer: You havent't aggregation function so you don't need group by  (eventually use distinct if this is what you need)
select *
from (    select article.*, user.username, category.title as ctitle, user.firstname, user.lastname, category.slug as cslug, category.category_id as pid
    from article
    left join user on article.created_by = user.id
    left join category on category.id = article.category_id
    where article.status='active'
    AND is_recommended='yes'
    AND article.start_date<='".date('Y-m-d H:i:s')."'
    AND recommended_location in (1,2,3,4,5)
    order by start_date desc
 ) as x
 limit 5

If you want only a article for each recommended_location you should use
(select article.*, user.username, category.title as ctitle, user.firstname, user.lastname, category.slug as cslug, category.category_id as pid
from article
left join user on article.created_by = user.id
left join category on category.id = article.category_id
where article.status='active'
AND is_recommended='yes'
AND article.start_date<='".date('Y-m-d H:i:s')."'
AND recommended_location = '1'
order by start_date desc limit 1)
union
(select article.*, user.username, category.title as ctitle, user.firstname, user.lastname, category.slug as cslug, category.category_id as pid
from article
left join user on article.created_by = user.id
left join category on category.id = article.category_id
where article.status='active'
AND is_recommended='yes'
AND article.start_date<='".date('Y-m-d H:i:s')."'
AND recommended_location = '2'
order by start_date desc limit 1)
union
(select article.*, user.username, category.title as ctitle, user.firstname, user.lastname, category.slug as cslug, category.category_id as pid
from article
left join user on article.created_by = user.id
left join category on category.id = article.category_id
where article.status='active'
AND is_recommended='yes'
AND article.start_date<='".date('Y-m-d H:i:s')."'
AND recommended_location = '3'
order by start_date desc limit 1)
union
(select article.*, user.username, category.title as ctitle, user.firstname, user.lastname, category.slug as cslug, category.category_id as pid
from article
left join user on article.created_by = user.id
left join category on category.id = article.category_id
where article.status='active'
AND is_recommended='yes'
AND article.start_date<='".date('Y-m-d H:i:s')."'
AND recommended_location = '4'
order by start_date desc limit 1)
union
(select article.*, user.username, category.title as ctitle, user.firstname, user.lastname, category.slug as cslug, category.category_id as pid
from article
left join user on article.created_by = user.id
left join category on category.id = article.category_id
where article.status='active'
AND is_recommended='yes'
AND article.start_date<='".date('Y-m-d H:i:s')."'
AND recommended_location = '5'
order by start_date desc limit 1)

Comment: Thank you. Unfortunately this is not generating the right results.
I need to get the latest item per recommended_location; however this query is getting them and placing them randomly; I now have two items in the 1-5 that are set as recommended_location = 3
Comment: I have yet to check if this works but won't this be a massive load on server? We have over 100K users on the site and I am trying to find ways to optimize. I understand we can cache but generally a query this long is quite scary to say the least.
Comment: It is working ... I am contemplating if it is the right way to go ahead or not.
Comment: well if this answer working is a good result   .. then i think this is at  least useful ..  I think in that case (one element for each category ) .. the select union with limit is the simple (or the unique)  solution..
Comment: I appreciate your help on this. It saves us for a short period while we find the long period answer.
Comment: Well I'm my experience  .. i think the solution provided . is the more simple .. could be not the unique .. but concettualy  easy and poweful.. anyway . if answer id right .and coherent with the question . is fair flag as accepted too..
Answer: Make the aggregation first and then join the data you need
select x.recommended_location, x.start_date, ...
from
 ( select article.recommended_location, max(article.start_date) as  start_date
    from article
     where article.status='active'
     AND is_recommended='yes'
     AND article.start_date<='".date('Y-m-d H:i:s')."'
    AND recommended_location in (1,2,3,4,5)
    group by article.recommended_location
 ) as x
inner join article on x.recommended_location = artice.recommended_location
and x.start_date = article.start_date
inner join ...

But if 2 or more articles have the same start_date, you will get all of them this way...
Answer: Try this :
Use article.id with descending order in query
so your query is like this :
select *
from (
    select article.*, user.username, category.title as ctitle, user.firstname, user.lastname, category.slug as cslug, category.category_id as pid
    from article
    left join user on article.created_by = user.id
    left join category on category.id = article.category_id
    where article.status='active'
    AND is_recommended='yes'
    AND article.start_date<='".date('Y-m-d H:i:s')."'
    AND recommended_location in (1,2,3,4,5)
    order by article.ID desc, recommended_location desc, start_date desc
 ) as x
 group by recommended_location
 limit 5

I hope you will get solution.
Comment: Thanks for this, unfortunately it is not giving me the result I am looking for.


jackson exception in unirest: Serialization Impossible. Can't find an ObjectMapper implementation

Question: ObjectMapper mapper = new ObjectMapper();
ObjectNode object = mapper.readValue("{\"myjson\":\"string\"}", ObjectNode.class);
HttpResponse<JsonNode> postResponse = Unirest.post("")
    .header("accept", "application/json")
    .body(object)
    .asJson();

Causes the runtime exception in the title on the call to body. I'm not sure what to do here, I'm attempting to wrap a json string in a JsonNode object which I'd assume is normal procedure when sending via unirest interface (in the data body).
Answer: I don't think you can do it like that. You can't pass ObjectNode into body method. You might implement custom ObjectMapper for that type. But I don't think that it's what you want.
Perhaps you can do something like this:
.header("Content-Type", "application/json")
.body(mapper.writeValueAsString(object))

Answer: According to the docs you need to set up ObjectMapper, e.g.
Unirest.config().setObjectMapper(new JacksonObjectMapper());

If you already have object mapper configured for your needs, pass it to constructor:
new JacksonObjectMapper(yourObjectMapper);

There is a separate dependency for object mappers for Jackson or Gson implementation
Answer: Looking at the body implementation of HttpRequestWithBody:
public RequestBodyEntity body(Object body) {
    ObjectMapper objectMapper = (ObjectMapper) Options.getOption(Option.OBJECT_MAPPER);

    if (objectMapper == null) {
        throw new RuntimeException("Serialization Impossible. Can't find an ObjectMapper implementation.");
    }

    return body(objectMapper.writeValue(body));
}

It seems that passing an objet is ok if an ObjectMapper is available


svchost.exe -k netsvcs occupying >1GB memory

Question: I have noticed my production server "svchost.exe -k netsvcs" is occupying >1GB ram memory, steadily, which I think is a bit excessive.
This is what tasklist /svc will give me for this process:
<code>                               Appinfo, CertPropSvc, gpsvc, IKEEXT,
                               iphlpsvc, LanmanServer, ProfSvc, Schedule,
                               SENS, SessionEnv, ShellHWDetection,
                               Winmgmt, wuauserv
</code>
I was wondering what might be the process listed that is responsible for this memory leak and how to fix it. Has anyone had this same behavior in the past?
Server is running Windows Server 2008 R2 (Build 7601: Service Pack 1) and it's main function is to run in-house application processor workers.
Comment: OK. Well I would say the next step is to find out which exact service is consuming the memory, and the only way to do that is to break them out into their own svchost.exe processes one at a time by using `SC Config Servicename Type= own`. See http://serverfault.com/questions/12278/how-to-find-memory-usage-of-individual-windows-services
Comment: The service pack rolls up the hotfix with it, so you won't find it listed.
Comment: I do have SP1 installed, but now that you talked about it...
https://support.microsoft.com/kb/977357
get-hotfix -id KB977357
get-hotfix : Cannot find the requested hotfix on the 'localhost' computer. If I have SP1 installed shouldn't I have this hotfix installed?
Comment: You could also just stop / kill the services one at a time and see when the mem usage drops.
Comment: Focus your attention on Windows Update (that's the wuauserv process).  It's common for it to go haywire and start consuming huge amounts of memory.  MS has a number of fix-its and other tools to help with this.  If you're running a local WSUS that could also be contributing.
Comment: Are you sure the process is the legit svchost.exe?
Answer: The question is, is it a leak? You're saying that the memory usage is "steady".
Leak = memory usage increases over time, never decreasing, so you have to reload the server every once in a while.
If the taks is staying at ~1 GB for long time (say, two weeks), then the situation is perfectly normal. Modern software is made to use free memory whenever necessary, and I know a few programs that will just grab whatever there is just to save time on memory allocation.
If it doesn't impede system's operation, don't touch it.
Answer: Memory allocation is very expensive on the CPU's cycles compared to reusing existing, allocated memory. It is often that once a program starts, until it is finished its function, it will not "let go" of this memory.
For example, Firefox holds memory for some time. If you leave your computer on for a week with Firefox open, you'll notice it will constantly grow in memory size. After YouTubing, Google Play Music-ing, and browsing, mine hits 2-4GB in memory - which shrinks to 300MB after I restart the process. This is because of its caching features, and this behaviour is by design.
I would tend to believe that the SVCHost process is doing exactly as it should. How many services is your server running? 1GB Does not sound concerning - though that depends on which services you're running.
Answer: As the next step, if you want to investigate further, I would install process explorer (procexp.exe) which you can find it on the Microsoft site. That will give you what services use this process (see screenshot from procexp) you can then stop/start services and see if a particular service is associated with releasing/acquiring a large memory allocation. It will also tell you if it is Working set or Private (=mainly heap) allocated memory. If it is tied to a specific service then you will have a clearer path to research further.
It goes without saying you would need to do this testing in agreed outage/maintenance window or reproduce on a test server as you will be interrupting normal operations. Reboot and check list of services is back to your normal run set after testing is complete.
Screen shot:


Hystrix status is not exposed under /health

Question: According to the doc my application should serve hystrix data under /health. Despite open circuit-breaker the only thing i see under that url is
{"status":"UP"}

I expect to see something like that
{
    "hystrix": {
        "openCircuitBreakers": [
            "somedata::somedata"
        ],
        "status": "CIRCUIT_OPEN"
    },
    "status": "UP"
}

What did I miss?
My build.gradle
buildscript {
    ext {
        springBootVersion = '1.5.10.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }

}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.somecompany'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

ext {
    springCloudVersion = 'Edgware.SR1'
}

dependencies {
    compile('org.springframework.cloud:spring-cloud-starter-hystrix')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter-actuator')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

Application class
@EnableCircuitBreaker
@SpringBootApplication
public class HystrixDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(HystrixDemoApplication.class, args);
    }
}

Resource under Hystrix control
@RestController
public class SomeResourceController {

    @HystrixCommand(fallbackMethod = "defaultValue", commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="1500")})
    @RequestMapping(path = "/resource-with-hystrix", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public String someResource(){
        URI uri = URI.create("http://localhost:8080/some-resource");
        RestOperations restTemplate = new RestTemplate();
        return restTemplate.getForObject(uri, String.class);
    }

    private String defaultValue(){
        return "local value in case of something goes wrong";
    }
}

Answer: According to documentation:

The information exposed by the health endpoint depends on the management.endpoint.health.show-details property <...> The default value is never.

So, in order to show hystrix information you need to set management.endpoint.health.show-details to either one of:

when_authorized
always

like so:
management.endpoint.health.show-details = always

The answer provided by msfoster no longer works (as of Spring Boot 2.1.x and cloud release train Greenwich.RELEASE):

Endpoint sensitive flag is no longer customizable as Spring Boot no longer provides a customizable security auto-configuration . Create or adapt your security configuration accordingly
Answer: Set Health endpoint as not sensitive(default):
endpoints.health.sensitive=false

Depending on how an endpoint is exposed, the sensitive property may be used as a security hint. For example, sensitive endpoints will require a username/password when they are accessed over HTTP (or simply disabled if web security is not enabled).

From the documentation of the health endpoint:

Shows application health information (when the application is secure, a simple 'status' when accessed over an unauthenticated connection or full message details when authenticated).
Comment: The sensitive property is default to false, and tells that you dont need any authentication to see basic info. In order to see the details, you have to authenticate when the Application is secure.
Comment: Now I see 401 under /health :). There must be something else. Tried management.security.enabled=false as a temporary workaround and now it works but ignores endpoints.health.sensitive property.


Moving On Premises Infrastructure into Azure/AWS

Question: I am new to Server Fault (coming from StackOverflow) and please tell me if this is not the right place to ask this general question.
Basically our company is trying to move away from an on premises infrastructure to a cloud infrastructure. We are considering Azure/Aws for this.
Currently we have some virtual machines running on our local server. A Server with the Domain Controller, a File Server, a Database Server, and one for our websites with IIS installed. Our Exchange we already moved to Exchange online with Office365 and Azure Active Directory,
However, we also wanted to move the other servers into the cloud. I thought that we can create Virtual Machines on Azure for example and join all of them to the same Active Directory by connecting them to the same Virtual Network. Would this even be the right approach?
Now, saying that we would set up everything like this, if I informed my self correctly, we would need to set up a site-to-site connection so that we can access everything on these servers from our on premises network.
But is it even possible to join the Active Directory that is running on a Domain Controller on a Virtual Machine in Azure from our on premises network?
Another question, how is the performance? Of course it will be slower than having everything in house, but our files are not super large and the requests aren't too many.
Once again, I am net to this stack exchange and I am mainly a programmer. We are a small company though and I am trying to modernize our infrastructure a little bit. I am not an expert in networking, therefore I am asking you experts here hoping to gain some knowledge. So please be nice:)!
Comment: Short answer: yes. Since you're already in Azure you might as well stick with them. You will either need Azure training or to get someone in to help you do a good job of this, otherwise you could create problems with reliability, DR / backups, cost, performance, or even lose all the data if you do a really poor job. We can't teach you Azure / AWS. Linux Academy is a good training site, at least for AWS.
Comment: Cloud will let you provide more resilient, more reliable, more secure systems. It will also let you create less resilient, less reliable, less secure systems. You need someone with appropriate knowledge to help you on this journey. Cloud can be more expensive than on-premise hosted systems unless you re-architect everything for cloud native - e.g. using functions as a service, auto scaling and using smaller instance sizes. Cloud bandwidth tends to be very expensive as well.
Comment: Thanks for your reply! Would you think that this is a good approach or do you think that a company should always stick with on prem?
Answer: You are thinking correct and you should move to public cloud. You will get a far superior platform then you ever will have on-Prem.
You can look on Azure/aws as your remote datacenter and after you connect to it with a site-to-site VPN or Expressroute it will work with the domain, file server and so on.
As Tim stated you will either need to do a bit of research yourself or hire someone to avoid pitfalls. If you wish to learn yourselves I recommend Microsoft Learn as a starting point for Azure. And you can always ask questions here when needed.
Comment: ExpressRoute seems like the perfect solution in this case. Would you say ExpressRoute is better than a Site-to-Site connection?
Comment: @TomelSafadi Expressroute is better, but probably slightly more expensive and takes a couple of weeks to implement from your ISP(if they can offer it).


Serialization and file size

Question: When I serialize a file object (whose size on the hard drive is 3,404,851  bytes) using org.apache.commons.lang3.SerializationUtils such as :
File fileObject = new File(path);
byte[] fileBuffer = SerializationUtils.serialize(fileObject);

The fileBuffer.length returns 91! Shouldn't it be rather 3,404,851 ?
Comment: The utility only serializes the object which points to a file, not the entire file.
Comment: You're not serializing the contents of the file. The `File` class just represents the file on disk; so it probably contains the filename and maybe a few other things.
Answer: You're serializing the File object, not the file itself.
The File object contains just a few fields describing the file and its location, not the entire file contents.
Comment: how may I please achieve that in this case?
Comment: 1. That's a separate question
2. What are your trying to achieve?
Comment: I want to serialize the content of an audio file that I will frame then into UDP packets.
Comment: What do you mean by "serialize"? The file is already serialized by definition.
Comment: @sasuke Do you just mean you want to have the contents of the file as a `byte[]`? Because that can be done pretty easily with any of Java's classes designed for reading files.
Comment: @Kevin exactly that is what i meant. Thanks for pointing it out. I found the solution.
Answer: By looking at the serialization documentation (https://docs.oracle.com/javase/8/docs/api/serialized-form.html#java.io.File) you can notice that the serialization util only saves the path of the file (with the original separator which is converted while deserializing if needed), rather than its content.
In case of Oracle documentation refer to "See also" section of javadoc to get a link to description of the serialized form.

Serialization and file size


How to boost relevance of Search API solr with creation date?

Question: We have replaced Drupal's core search with SolR but we have noticed a recursiveness issue regarding the search results, for ex. when searching "executive committee", documents created in 2006 and 2007 are listed before newer documents created in 2010. (http://www.etuc.org/search-page)
What we would like to do is to sort the articles by date and by relevance.
We have tried to alter this at the View level (date + Search:relevance) but it short circuits SolR.
We have looked at the search api settings and it seems that one cannot boost date field. Only fulltext fields are 'boostable' (?)
We have also found a few articles related to the subject:

http://www.metaltoad.com/blog/date-boosting-solr-drupal-search-results
How to boost relevance of Search API solr with the value of a certain field?

but they weren't much help.
We are using Drupal 7, SolR 3 and the following modules

Search API 7.x-1.11
Search API autocomplete 7.x-1.0
Search facets 7.x-1.11
Search views 7.x-1.11
SolR search 7.x-1.4

Does anybody has an idea how to fix this issue?
Thank you very much in advance.
Comment: did u finally get a solution ? if so pls share
Answer: To do this (Drupal 7), one needs to implement the below hook:
hook_search_api_solr_query_alter(&$call_args, SearchApiQueryInterface $query)

This hook can go in the theme or module layer.
Example code could be:
/**
 * Implements hook_search_api_solr_query_alter().
 *
 * @see https://www.drupal.org/node/2009760#find-out-field-id
 * @see https://www.drupal.org/project/search_api_solr/issues/2194055
 * @see https://www.metaltoad.com/blog/date-boosting-solr-drupal-search-results
 * @see https://www.drupal.org/forum/support/module-development-and-code-questions/2014-12-18/extending-search-api-solr-search-with
 * @see https://www.drupal.org/project/search_api_solr/issues/2392499
 * @see https://www.drupal.org/project/search_api/issues/1694698
 * @see https://books.google.com.au/books?id=othpBgAAQBAJ&pg=PA157&lpg=PA157&dq=3.16e-11+solr
 */
function mytheme_search_api_solr_query_alter(&$call_args, SearchApiQueryInterface $query) {
  // Boost more recently created content. This is taken directly from an
  // apachesolr query with +1 boost (+1 for every 100).
  $fields_names = $query->getIndex()->server()->getFieldNames($query->getIndex());
  if (isset($fields_names['created'])) {
    // If using node property 'created', get solr name of it  e.g. 'dm_created'.
    $created_field_name = $fields_names['created'];
    // @codingStandardsIgnoreStart
    // Field name version.
    // $created_field_name = $fields_names['field_date'];
    // @codingStandardsIgnoreEnd
    // Ensure '$call_args['params']['bf']' exists.
    if (!isset($call_args['params']['bf'])) {
      $call_args['params']['bf'] = [];
    }
    $call_args['params']['bf'][] = "recip(ms(NOW,{$created_field_name}),3.16e-11,0.5,0.5)^100.0";
  }
}

Answer: I'm not 100% sure this will work, but definitely worth a try.
Go to /admin/config/search/search-api/index/your_index/edit
And then under this heading: CONFIGURE THE DEFAULT TRACKER
There are two options to set the "Default index tracker which uses a simple database table for tracking items."
Select "most recent items first". You will need to reindex the site after saving the settings for the change to take effect.
 Index items in the same order in which they were saved
 Index the most recent items first```

Comment: This doesn't work. This only modifies in what order Drupal will add items to the index. It will not modify the order in which items will show up in the search results.


Why do we have to wait for the goal line technology to be put into practice

Question:
Possible Duplicate:
Why is FIFA against adding instant replay to the game?

After watching England's world cup match i was eagerly waiting for FIFA to introduce the goal line technology. But it hasn't come out yet.
What are the disadvantages of using it? In all other games now days technology is very much used and has resulted in a reduction of refereeing or umpiring errors.
What has FIFA got against the use of technology in the game?
Comment: Your question is a bit subjective - since nobody really knows the true answer to how long it will be (if ever) for goal line technology to be put in place. I would recommend editing your question to ask something that we can actually provide a good answer to. Otherwise it's just speculation.
Comment: I just titled the question as such. But I was asking about the drawbacks that fifa claim against it.
Comment: which drawbacks specifically? Are you talking about FIFA saying it will reduce the human element to the game and interrupt the flow of the game?
Comment: Yeah all those which they say against it.
Comment: This question is a poor fit for the SE engine. Its kinda forumy.
Answer: One of the delays is the complexity of the technology and amount of testing that is currently being carried out. According to this article, 9 different methods are currently being trialied.
As to why the governing bodies have been so against the introduction of this:

You may find this question useful; Why is FIFA against adding instant replay to the game?.

The bosses from up-high (Sepp Blatter and Michel Platini) have been very much against the introduction of such technology, even though a survey found 90% of players want it introduced, and you often hear managers expressing their interest in it as well.
Sepp Blatter has been more sympathetic since the Frank Lampard goal during the 2010 World Cup against Germany, but Platini firmly believes "it would undermine the authority of referees and disrupt the natural flow of the game."

Other critics feel that the introduction of such technology "would impact on the human element of the game and remove the enjoyment of debating mistakes."

The cost of implementing such technology is high; especially for smaller clubs. It was thought that the introduction of more referees/ linesmen would be a cheaper and similarly effective alternative. This approach was publically trialled in the UEFA Group League Stages 2009 - 2010, and was extended to the 2010 - 2011 stages as well.
Comment: Very well documented answers. Hope others could bring in more points.