Inconsistent SpannableString setSpan() coloring?

Question: I'm trying to color only vowels in my String 1 color (ex red), and non-vowels another (ex: blue). But the SpannableString setSpan() method is being inconsistent when iterating thru each char. The function is detecting the vows and non-vows correctly, as I had checked the logged output,except that the coloring is not correct:
//ColorLogic.java:
public SpannableString colorString(String myStr)
    {
        SpannableString spnStr=new SpannableString(myStr);
        ForegroundColorSpan vowColor=new ForegroundColorSpan(Color.RED);
        ForegroundColorSpan conColor=new ForegroundColorSpan(Color.BLUE);
        int strLen=myStr.length();
        for(int i=0; i< strLen; i++)
        {
            if (vowSet.contains(Character.toLowerCase(myStr.charAt(i))))
            //if (i%2==0)
            {
                 Log.v(DTAG, "vow"+myStr.charAt(i));
                 spnStr.setSpan(vowColor, i, i, 0);

            }
            else
            {
                Log.v(DTAG, "cons"+myStr.charAt(i));
                spnStr.setSpan(conColor, i, i, 0);
            }
        }
        return spnStr;
    }

    //In my OnCreate of my activity class:
    //PASS
     //Log.v(DTAG, message);
     // Create the text view
     TextView textView = new TextView(this);
     textView.setTextSize(50);

     //Call Color Logic to color each letter individually
     ColorLogic myColorTxt=new ColorLogic();
     SpannableString spnMsg=myColorTxt.colorString(message);
     //Log.v(DTAG, "spnMsg: "+spnMsg.toString());

     textView.setText(spnMsg, BufferType.SPANNABLE);
    //textView.setTextColor(Color.GREEN);
     setContentView(textView);
     }

      ![Vows Only its correct (non-vowels only is correct as well)][1]
          ![With cons and vows, 2 letters then its incorrect!][2]

Comment: create a new span for each vovel/non vovel
Answer: You cannot reuse span objects. As pskink indicates, please use distinct ForegroundColorSpan objects for each setSpan() call.
Also, you may wish to use fewer spans overall. While your sample ("abibobu") requires the maximum possible number of spans, most words have consonants and vowels strung together. For example, the word "consonant" has two two-consonant spans ("ns" and "nt"). Those could be colored using a single ForegroundColorSpan, rather than two, improving rendering speed. Spans are easy but not the fastest, and so the fewer spans you use, the better your app will perform, particularly in animated situations (e.g., scrolling in a ListView).
Furthermore, you may only need to color either consonants or vowels, unless you are planning on a third color for hyphens and apostrophes. Remember: your text can start with a color (e.g., android:textColor).
Comment: I have already tried declaring a new span for vowel or consonant in .setSpan for each iteration of the for loop. It's the same unpredictable and incorrect output
Comment: @jerryh91: Then we have no way of helping you, since the code you have in the question is not the code that you are running. That being said, I would suggest that you think a bit more about the fourth parameter to `setSpan()`.


Convergence weak in a topological space

Question: Let a set $X$, a topological space $Y$ and a family $\Omega$  of functions $f$ defined from $X$ to $Y$.
I want prove that $x_n \rightarrow x$ in $\tau_{\Omega}$ if and only if $f(x_n) \rightarrow f(x)\quad \forall f \in \Omega$ .
$\tau_ {\Omega}$ is the weak topology.
Can I have a suggestion for starting the proof?
Comment: Can you add the definition for weak topology that you want to use? One could say that this holds by definition but I assume you want to start from a definition with open sets or neighborhoods and not a definition in terms of convergence.
Comment: Can you prove that a sequence $\langle x_n:n\in\Bbb N\rangle$ in a product space $X=\prod_{i\in I}X_i$ converges to $x$ if and only if $\langle p_i(x_n):n\in\Bbb N\rangle\to p_i(x)$ for each $i\in I$, where $p_i:X\to X_i$ is the projection map? The same ideas apply here.
Comment: Can you better explain the steps?
Comment: The definition  that I have is : let $X$ a set, $Y$ a topological space and $\Omega$ a family of functions $f: X \rightarrow Y$.We called $\Omega$-topology on $X$ the topology $\tau_{\Omega}$ more weak for which the functions in $\Omega$ become continuous
Answer: Because the weak topology makes all functions in $\Omega$ continuous, it is trivial that
$$(x_n)_n\to x \implies (f(x_n))_n\to f(x), \forall f \in \Omega$$
The other implication requires some work.

A topology makes all functions in $\Omega$ continuous if and only if it includes
$$S = \{f^{-1}(U) \mid f\in\Omega, U \in \tau_Y\}$$
where $\tau_Y$ is the topology on $Y$. In other words, $\tau_\Omega$ is the weakest topology such that $S \subseteq \tau_\Omega$. This means that $S$ is a subbasis for $\tau_\Omega$. By taking finite intersections we obtain a basis for $\tau_\Omega$:
$$B = \left\{\bigcap_{i=1}^n f_i^{-1}(U_i) \mid \forall i:f_i\in\Omega, \forall i:U_i \in \tau_Y\right\}$$
Now we have that $(x_n)_n\to x$ if and only if for every basis element $G \in B$ containing $x$, the sequence lies eventually in $G$.
What is left is pretty straightforward but can be tedious. You have to verify that everything I said is true, and that $(f(x_n))_n\to f(x), \forall f \in \Omega$ implies that for every basis element $G \in B$ containing $x$, the sequence $(x_n)_n$ lies eventually in $G$.
Comment: is my proof under right?
Comment: @GiuliaB. Yes that is right.
Answer: for the $\Leftarrow)$:
let $B=\{\bigcap_{i \in I} f^{-1}(U_i): \forall i \in I, f_i \in \Omega, U_i \in \tau_Y \}$.
Let U a neighborhood of x. Exists $J \subset I$ finished so ,that $\bigcap_{i \in I} f^{-1}(U_i) \subseteq U$ with $U_i$ neighborhood of $f_i(x)$.
Because $f_i(x_n) \rightarrow f_i(x)$ then $\forall i \in J$ exists $N_i \in \mathbb N: f_i(x_n) \in U_i \quad \forall n \ge N_i$.
Let $N=\max_{i \in J} N_i$ then $x_n \in U \quad \forall n \ge N$. Then $x_n \rightarrow x $ in $\tau_{\Omega}$
it's right?

Convergence weak in a topological space


How to connect to AWS Elasticsearch from EC2 using IAM?

Question: I am trying to connect my EC2 instance to my ES domain and keep getting the following error:
AuthorizationException(403, 'security_exception', 'no permissions for [indices:data/read/search] and User [name=arn:aws:iam::ACCOUNT_ID:role/my-role, backend_roles=[arn:aws:iam::ACCOUNT_ID:role/my-role], requestedTenant=null]')

Elasticsearch configuration:
public domain
fine-grained access control via IAM
access policy:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::ACCOUNT_ID:role/my-role"
      },
      "Action": "es:*",
      "Resource": "arn:aws:es:REGION:ACCOUNT_ID:domain/test/*"
    }
  ]
}

EC2 Configuration:
using IAM role my-role
with permissions:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "es:*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

All HTTP requests sent from EC2 to ES are being signed.  I have already verified signing works: if I use the security credentials of the IAM user that I also set as the IAM ARN master user when setting up my ES domain the requests between EC2 and ES work as expected.
Answer: The issue might be with fine-grained access control in ES. Same issue is mentioned here
Comment: thanks, i created a new domain with fine grained access disabled and everything is working as expected
Answer: If you want to connect to same ES cluster with FGAC from EC2 instance then you need to map EC2 IAM role with backend kibana roles. First you need to login to kibana with master user and then follow steps from doc to map EC2 IAM role to kibana 'all_access' role


Displaying block only when user visits his own profile page

Question: I want to display the block only when the current user visits own page.
So in block visibility I use the following PHP:
global $user;
if ($user->uid == arg(1)) {;
return TRUE;
} else {;
return FALSE;
};
endif;

But that block returns on every page.What am I doing wrong?
Comment: By own page you mean user profile page?
Comment: yes own profile page which is normally located on domain.com/en/user/#  , although I have set it to display as domain.com/en/username
Answer: If you are using the php code in the block visibility option than I guess the following should work:
<?php
global $user;
$user_id = $user->uid;
if (('user' === arg(0)) && ($user_id === arg(1))) {
  return TRUE;
} else {
  return FALSE;
}
?>

If your site is multi-lingual than may be you have to change the if condition as: if (('user' === arg(1)) && ($user_id === arg(2)))
Comment: If user on edit profile this section is also displaying.
Answer: The provided code is insufficient, as it does not check whether the user is editing their account (user/uid/edit), or simply viewing it (user/uid or user/uid/view).
<?php
$uid = $GLOBALS['user']->uid;
if ('user' == arg(0) && $uid == arg(1) && ('view' == arg(2) || NULL == arg(2))) {
  return TRUE;
}
return FALSE;
?>

The above code ensures that your block will ONLY ever be visible when the user account is being viewed (at /user/uid or /user/uid/view) by the user the account belongs to.
Personally, I would simply use Views to create a page, which uses a contextual filter that uses the currently logged-in user to display specific information about them.


Is square root sublinear?

Question: I want to prove that $\sqrt x $ is sublinear, but i don't know how to do it, precisely i'm having difficulties stating that $\sqrt x $ is sublinear in $[0, 1]$
$$\\ f(x)\ is\ sublinear\ \iff\ \exists\ a,b \in\ \mathbb R\ \mid\ |f(x)| \le a|x| + b  $$
Comment: Does this answer your question? [How to prove $\sqrt{x + y} \le \sqrt{x} + \sqrt{y}$?](https://math.stackexchange.com/questions/408177/how-to-prove-sqrtx-y-le-sqrtx-sqrty)
Comment: Forgive me if I'm mistaken, but according to your definition, can't you just let a=100000, and b=1 to create a line that is always above $|{\sqrt{x}}|$ in your given range?
Comment: This is not a proof, even with $a=10^{100}$. @yolo
Comment: Is this what you are looking for? https://math.stackexchange.com/q/408177/42969
Comment: No, i added the definition
Comment: @nicomezi I didn't bother with rigour to that excess as I assumed that it was a misnomer on the OP's wording, since it seemed too obvious,
Answer: Your $x$ is non-negative. We need $a$ and $b$ such that
$$ \forall x \ge 0 \quad 0\le\sqrt x \le ax +b.$$
Raise to the power $2$:
$$0 \le a^2 x^2 + (2 a b - 1) x + b^2$$
Take for simplicity $a=1$:
$$0 \le x^2 + (2 b - 1) x + b^2,$$
and that for $x\ge0$. It is sufficient to take $2b-1\ge0$.
Comment: But then if i use a b>0 the negative x straight line will not be under the graph of $\sqrt x$ like here:
https://www.google.com/search?q=square+root+of+x+is+not+lipschitz&rlz=1C1ONGR_itIT974IT974&sxsrf=APq-WBuvlxWBAtnvWD2JYeO7FGYuRBXHTQ:1649253422991&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjT16_jy__2AhWui_0HHSmWA8cQ_AUoAXoECAEQAw&biw=1242&bih=568&dpr=1.1#imgrc=gStxtpyljJLhqM
Comment: $\sqrt x$ is not defined for $x<0$. The first graph is $\sqrt{|x|}$ @GiuseppeFontanella
Comment: i'm sorry i intended that to be sublinear the function has to have its own graph contained between two straight line with opposite angular coefficients like in the link i posted in the previous comment
Comment: @Iruo Perhaps you should use this condition:

$\forall x_1,x_2, \exists K \mid \left | f(x_{1})-f(x_{2}) \right |\leq K\left | x_{1}-x_{2} \right |$
Comment: @Iruo then you need to ask for Lipschitz continuity, not sublinearity; square root is not Lipschitz continuous on $[0,\infty)$.

Is square root sublinear?


Ways to represent function with multi-dimensional array parameters

Question: I'm currently learning function that work with multi-dimensional array in C.
Let's say I have
short myArray[10][30].

I have declared following function prototype to work with myArray.
void first(int n, short ar[][30]);
void second(int n, short ar[30]);
void third(int n, short (*ar)[30]);

My understanding is that the ar parameter in both first and third function are equivalent. short ar[][30] in first function is equivalent to the short (*ar)[30] in third function because they are both pointer to array of 30 short.
The ar in second function is different because in short ar[30], ar is a pointer to short, not a pointer to array of 30 short.
Is my understanding correct?
Answer: Yes your understanding is correct. 1 and 3 are equivalent. And 2 is also right (But not for passing 2d array - it is correct for passing 1D array). But will clarify a bit the second case.
And the second one that 30 inside of third brackets are not considered by the compiler. You can omit it still the compiler won't complain. Actually here you have passed an 1D array of short that decayed into pointer to the first element (First element being short it is short*). So the second one you can also write as short *ar.
void second(int n, short ar[]);
void second(int n, short* ar );

These two works and they are equivalent in this context. The second one is for passing 1D array something like
   second(n, myArray[5]);

The thing is, most of the time array decays into pointer (exception is sizeof operator or Alignof etc). Passing an array to a function is a case where the array decays.
Also you are passing int arrays so it is wrong to write short.(int and short may have same size but it is guaranteed that size of int would be larger than or equal to the size of short). If you used short and then wrote int in the declaration that would have worked.
Edit: The second one is not for passing 2d array. Let's be clear on that. You can't pass 2d array to a function with the prototype declared as the second one. For pointers there are 2 things to consider - it's type and it's value. If you tried to pass a 2d array to the same function that would be illegal. 2d array decays into int (*)[30] which is not in anyway same as int * or int[].
Answer: 1 and 3 are indeed the same, as would be
void fourth(int n, short ar[10][30]);

because when you pass an array as function parameter, it decays to a pointer to its first parameter, so the compiler sees 1 and 4 as 3.
That explains why this would also be correct:
void fifth(int n, short arr[15][30]);

As it decays to a pointer, the declared size of the first dimension is not used. You are supposed to give the actual size in another way.
But this one is different:
void second(int n, short ar[30]);

and your compiler should raise a warning there because the expected paramater is a pointer to short, when you pass a pointer to an array of 30 short. Of course the pointers will have same value (same address), and common compilers will give expected results, but aliasing a pointer to array and a pointer to element is not allowed by the standard. So please avoid it.
With such a declaration, second should be called as
cr = second(n, arr[0]);

because arr[0] is a short array and will correctly decay to a short *.


Change block titles from h2 to h3

Question: I want that block titles have the h3 tag instead the h2 tag. As I understand I have to change this in the file block.tpl.php.
I found 4 block.tpl.php

root/modules/block/
sites/all/themes/omega/omega/templates
sites/all/themes/omega/starterkits/omega-xhtml/templates
sites/all/themes/omega/alpha/templates/

My question: Which one is the right file to change? I took now the one in the omega folder and it worked (the one in the modules folder did not). But I want to be sure whether this is the correct in order not to have side effects.
And what for is the modules/block directory with files?
thanks for any feedback
Answer: As a rule, we should never make changes in core files. If you will read the readme.md file in omega theme, you will see the following,

Omega 4.x is a base theme and as such should never be used or
  modified directly. Instead, you should use the sub-theming
  functionality provided by Drupal.
The easiest way to create a new Omega-based sub-theme is by using
  Drush. Omega comes with a very
  easy-to-use Drush command for generating sub-themes through a
  command-line wizard. You can start the sub-theme creation wizard by
  invoking drush omega-wizard in the command-line.

So you should first create omega sub-theme which is quite easy process and then make changes in sub-theme's block.tpl.php file.
Comment: thanks to both of you for the fast answers. I am not a programmer, but understood what has to be done.
Answer: Drupal gives you really easy ways to override core functionality, including themes and modules. In your case, the best thing you can do is to create a sub-theme for your Omega theme.
A sub-theme is basically a theme that inherits functionality from a parent theme. Follow the instructions from here: Creating a sub-theme
Once you've done that, you can manually copy those files from the parent theme into your sub-theme, to override them, and change them as much as you want.

Change block titles from h2 to h3


When calling JMeter using pure java, how to get a Generate Summary Results heartbeat in the logs?

Question: Let's say I'm running JMeter using pure Java. In particular, I am running JMeter using the cucumber technique roughly described here: https://automationcalling.com/2019/04/22/performance-test-framework-cucumberjmetertestng/
I pull in JMeter using the jmeter maven plugin. Then I run a TestNG cucumber test that runs JMeter.
Here is a very rough code snippet of how I am running JMeter:
    StandardJMeterEngine jmeter;
    jmeter = new StandardJMeterEngine();
    File jmeterConfigFile = Paths.get("target", "config.json").toFile();
    Map jmeterConfig = new ObjectMapper().readValue(jmeterConfigFile, Map.class);
    scenario.write("Jmeter config: " + jmeterConfig);
    Map configuration = (Map) ((List) jmeterConfig.get("configurations")).get(0);
    jmeterPath = (String) configuration.get("jmeterDirectoryPath");
    JMeterUtils.loadJMeterProperties(jmeterPath + "\\bin\\jmeter.properties");
    JMeterUtils.setJMeterHome(jmeterPath);
    JMeterUtils.initLocale();

    SaveService.loadProperties();
    jmeter.configure(testPlanTree);
    jmeter.run();

This works pretty great actually. But one big thing is that the logs are super silent while the test is running.
When you run JMeter from the command line, you get a little "Generate Summary Results" where it shows you the test has been running how many success, throughput, some general stats.

How can I get this same thing when running directly from pure java?
Answer: Figured it out by reading the JMeter.java class for the nonGUI path. There is something called Summariser. You can use it easily.
    jmeter.configure(testPlanTree);
    Summariser summariser = null;
    String summariserName = JMeterUtils.getPropDefault("summariser.name", "");
    if (summariserName.length() > 0) {
        summariser = new Summariser(summariserName);
    }
    ResultCollector resultCollector = new ResultCollector(summariser);
    resultCollector.setFilename(logFile.getAbsolutePath());
    testPlanTree.add(testPlanTree.getArray()[0], resultCollector);
    jmeter.run();


Creating Seaborn Barplots with Hues

Question: I have a dataset which contains the pageviews to all the pages (URLs) for a website for every single day for a few years.
For example, there might be 25 entries with the same date, each corresponding to a different URL and the associated pageviews to that URL.
I have added new columns in the pandas dataframe to include "Year" and "Month".
Now I would like to create a barplot to show the top 10 pages visited for each year using Seaborn.
I am able to make the plot for the entire dataset (i.e. every single page), but I can't figure out how to do so for just the top 10 most visited pages.
This is what I currently have, where 'Page path level 1' is the URL and content is the dataframe.
sns.countplot(x = 'Page path level 1', data = content, hue = 'Year')

Here's a snippet of the dataframe:
Answer: Considering Pageviews is the feature that you want to consider for defining top 10, you may use the below code.
sns.countplot(x = 'Page path level 1', data = content.groupby(by=['Page path level 1','year'])['Pageviews'].sum().reset_index().sort_values(by=['Pageviews'], ascending=False).head(10), hue = 'Year')

Answer: You can use nlargest to subset the values you plot.
import pandas as pd

# Instead of data = content use
data = content[content.Pageviews.isin(content.Pageviews.nlargest(10))]

Creating Seaborn Barplots with Hues


How do I get my custom module controller logic to trigger on only certain url paths?

Question: Hi all I am very new to Drupal and am trying to write a custom module.
So my site has a bunch of different urls for example example.com/users/3 or example.com/articles/47. I want my custom module code to run whenever the user is on a path that has exmaple.com/users/.. in it.
The custom code is in the module controller and has some api calls in it using Drupals global user entity. Right now I got it working where in the routing.yml file it takes the path I give it and just creates a new page where the custom code is working path: '/custom/page'
How do I get my custom code to trigger on certain url paths?
Answer: I would:

create a custom module
Add a hook_page_preprocess() function.
Check the URL with $current_path = \Drupal::service('path.current')->getPath(); (See this answer for more info)
Do your logic in the path match  example.com/users/

You could also checkout Event Subscribers below, but I'm unfamiliar with them.
For more info, see https://www.drupal.org/docs/creating-modules/subscribe-to-and-dispatch-events


Explanation of several remarks of Gauss on representations of a given number as sum of four squares.

Question: Remark 1: On p.384 of volume 3 of Gauss's Werke, which is a part of an unpublished treatise on the arithmetic geometric mean, Gauss makes the following remark:

On the theory of the division of numbers into four squares:
The theorem that the product of two sums of four squares is itself a sum of four squares, is most simply represented as follows: let $l,m,\lambda,\mu,\lambda',\mu'$ be six complex numbers such that $\lambda,\lambda'$ and $\mu,\mu'$ are conjugate. Let $N$ denote the norm, than $$(Nl+Nm)(N\lambda + N\mu)=N(l\lambda+m\mu)+N(l\mu'-m\lambda')$$ and also $$(N(n+in')+N(n''+in'''))(N(1-i)+N(1+i))=N((n+n'+n''-n''')+i(-n+n'+n''+n'''))+N((n+n'-n''+n''')-i(n-n'+n''+n'''))$$
From this it is easy to derive the following two propositions, in which different representation of a number by a sum of four squares refer to the different value systems of the four roots, taking into account both the signs and the sequence of the roots. 1. If the fourfold  of a number of the form $4k+1$ can be represented by four odd squares, then it can be represented half as often by one odd and three even squares, and vice versa, if a number can be represented in this way, that it can be represented twice as often in the first way. 2. If the fourfold of a number of the form $4k+3$ can be represented by four odd squares, then it can be represented half as often by one even and three odd squares, and vice versa, if a number can be represented in this way, than its quadruple can be represented twice as often in the first way.

Gauss than says that a certain identity of theta functions can be derived by these two theorems, namely the assertion (written here in modern notation):
$$\vartheta_{00}(0;\tau)^4 = \vartheta_{01}(0;\tau)^4 + \vartheta_{10}(0;\tau)^4$$
(Gauss denotes the three theta functions by $p(y),q(y),r(y)$).
Notes on remark 1:

The first identity in this passage was verifed algebrically by me, and I also suspect it might be intimately connected with quaternions.
The second identity follows directly from the first by substituting $\lambda = 1-i$ and $\mu = 1+i$. Since $N(1-i)+N(1+i)=4$, this identity enables one to generate new representations of an integer $4s$ as sum of four squares by simply changing the signs and order of the different numbers in the representation of $s$ as sum of four squares. For example, if $s = 13 = 2^2+2^2+2^2+1^2$ than this identity implies $52=4s = 5^2+3^2+3^2+3^2$.

Remark 2: On p. 1-2 of volume 8 of Gauss's Werke there is an additional note on the representation of numbers as sums of squares. According to Dickson's "history of the theory of numbers":

Gauss noted that every decomposition of a multiple of a prime $p$ into $a^2+b^2+c^2+d^2$ corresponds to a solution of $x^2+y^2+z^2\equiv 0 \pmod{p}$ proportional to $a^2+b^2,ac+bd,ad-bc$ or to the sets derived by interchanging $b$ and $c$ or $b$ and $d$. For $p\equiv 3 \pmod{4}$, the solutions of $1+x^2+y^2\equiv 0 \pmod{p}$ coincide with those of $1+(x+iy)^{p+1}\equiv 0$. From one value of $x+iy$ we get all by using: $$(x+iy)\frac{(u+i)}{(u - i)}$$ (where $u = 0,1,\cdots, p-1$). For $p\equiv 1 \pmod{4}, p = a^2+b^2$; then $b\frac{(u+i)}{a(u-i)}$ give all values of $x+iy$ if we exclude the values $a/b$ and $b/a$ of $u$.

Why is this interesting?
The reason why these passages interests me is that it might give a clue of answering a previous question I posted on math stack exchange Did Gauss know Jacobi's four squares theorem?.
Since these remarks show how to generate new resolutions into four squares in terms of known resolutions, Gauss seems to have developed an enumarting argument (of the amount of representations of a given number as a sum of four squares) in those remarks, an argument which might have guided him in the developement of the identity for the generation function of $\vartheta_{00}(0;\tau)^4$ (an identity which leads to Jacobi's four squares theorem); this generating function appears in p. 445 of volume 3 of his works, but with no specific reference to sums of four squares.
Questions

The two propositions which Gauss mentions in remark 1 are unclear to me, and I mean that the propositions themself are unclear, not their derivation. It is simply not formulated clearly. Therefore, I'd like to get an explanation of the two propositions which Gauss mentions.
I'd also like to understand how the theta function identity follows from the two propositions.
What is the meaning of the results in remark 2? they are very complicated and i don't have a clue of understanding its meaning.
Comment: _Why Gauss says that Euler's four squares identity is most transparently stated in this particular way?_ - Because quaternions weren't around yet?  And it's simpler than writing it just in terms of integers (which involves 8 variables and more complicated combinations of them).
Comment: @Kimball - i asked this question just to check if there was deepness here - since Gauss also seems to have anticipated the quaternions (in 1819), i just wanted to check if his formulation of Euler's four squares identity is connected with the theory of quaternions. Anyway, i agree with you that this is not an important question (the other two questions in my post are much more important); sometimes i just edit my questions in order to get more views and thereby increase the chances of getting an answer.
Answer: I use the following notation in what follows:
\begin{align}
\vartheta_2(q) &=\sum_{n\in\mathbb {Z}} q^{(n+(1/2))^2}\tag{1a}\\
\vartheta_3(q) &=\sum_{n\in\mathbb {Z}} q^{n^2}\tag{1b}\\
\vartheta_4(q) &=\vartheta_3(-q)\tag{1c}
\end{align}
Let $a(n) $ be the number of ways in which the positive integer $n$ can be expressed as sum of four squares. Then we have $$\vartheta_3 ^4(q)=1+\sum_{n=1}^{\infty} a(n) q^n\tag{2}$$
Let $b(n) $ represents the number of ways of expressing $n$ as a sum of four odd squares. Then $$\vartheta_2^4(q^4)=\sum_{n=1}^{\infty} b(n) q^n\tag{3}$$ Since $$\vartheta_2(q)=2q^{1/4}\sum_{n=1}^{\infty} q^{n(n+1)}$$ it follows that $$\vartheta_2^4(q)=16q\left(\sum_{n=1}^{\infty} q^{n(n+1)}\right)^4$$ and $\vartheta_2^4(q)$ is an odd function of $q$.
Hence we can rewrite $(3)$ as $$\vartheta_2^4(q^4)=\sum_{n=0}^{\infty} b(4(2n+1))q^{4(2n+1)}$$ or $$\vartheta_2^4(q)=\sum_{n=0}^{\infty} b(4(2n+1))q^{2n+1}\tag{4}$$ Next we can observe (using $(1c),(2)$) that $$\vartheta_4 ^4(q)=1+\sum_{n=1}^{\infty} (-1)^na(n)q^n\tag{5}$$ Therefore the coefficients of even powers of $q$ in $\vartheta_3^4(q),\vartheta_4 ^4(q)$ are equal and for odd powers of $q$ they differ in sign.
Now consider the target identity $$\vartheta_3 ^4(q)=\vartheta_2^4(q)+\vartheta_4^4(q)\tag{6}$$ which needs to be established. The first term on right side is an odd function and contains only odd powers of $q$. And we have noted that the coefficients of even powers of $q$ match on both sides. Thus our job is done if we can match the coefficients of odd powers of $q$ ie $$a(2n+1)=b(4(2n+1))-a(2n+1)$$ or $$b(4(2n+1))=2a(2n+1)\tag{7}$$ Next we observe that if an odd number $(2n+1)$ can be expressed as sum of four squares then either the expression consists of one odd square and three even squares or it consists of one even and three odd squares. Also the first case arises when $2n+1=4k+1$ and the second case arises when $2n+1=4k+3$.
For both these cases Gauss makes claims in his remark 1 and says that $$b(4(4k+1))=2a(4k+1),b(4(4k+3))=2a(4k+3)\tag{8}$$ which is same as identity $(7)$ and hence $(6)$ is established if we assume that both propositions in remark 1 are true.
Comment: i upvoted your answer because it seems useful, although i havn't made yet a careful reading of it. I believe i'll read it in the following days, and than I'll comment on it . I apologize for taking time to respond.
Comment: @user2554: there is no hurry here. I really like the efforts you have put to make sense of what Gauss did. My answer is still incomplete. And I have no idea of the remark 2 by Gauss.
Comment: @user2554: I have simplified my answer by removing unnecessary details and now the proof for theta function identity in remark 1 is complete.


Dúvida JavaMail - Anexos vindo null

Question: Possuo uma aplicação que faz download dos anexos que são enviados em um determinado e-mail e funciona perfeitamente.
Surgiu a necessidade de fazer a mesma coisa, em um outro e-mail. Os dois são gmail.
Porém, quando leio a caixa de entrada do segundo e-mail, todos anexos vem como nulo e isso não ta fazendo o menor sentido pra mim.
Código:
public static void main(String[] args) {

    try {

        Email email = new Email();

        Store store = email.conectar(ConfigEmail.host, ConfigEmail.email, ConfigEmail.senha);

        Folder inbox = email.selecionaPasta(store);

        Message[] mensagens = email.mensagens(inbox);

        for (int i = 0; i < mensagens.length; i++) {

            System.out.println("Lendo: " + mensagens[i].getFrom()[0]);

            if(email.hasAttachments(mensagens[i])) {

                Multipart mp = (Multipart) mensagens[i].getContent();

                for (int j = 1; j <= mp.getCount() -1; j++) {

                    Part part = mp.getBodyPart(j);

                    // Exibe -1 para todos anexos
                    System.out.println(part.getSize());

                    // Exibe multipart/MIXED
                    System.out.println(part.getContentType());

                    // Exibe um endereco de memória
                    System.out.println(part.getContent());

                    //Exibe null
                    System.out.println(part.getFileName());
                }

            }
        }

        inbox.close(false);
        store.close();

    } catch (MessagingException | IOException e) {

        e.printStackTrace();
    }
}

Estou tentando fazer o download de arquivos .XML
Não consigo entender o por que de no primeiro e-mail funcionar perfeitamente e no segundo, que é a mesma coisa, vir nulo.
Comment: dlosi, é legal você compartilhar a solução encontrada, mas pra ficar perfeito mesmo, seria legal você [edit] sua pergunta, recortando a solução, e colando no campo correto (o de respostas). Aí pode marcar sua própria resposta como aceita, assim o post fica marcado como solucionado.
Comment: Poderia separar a resposta (em um novo post) da pergunta?
Comment: Arrumei. Obrigado pelas dicas
Answer: SOLUÇÂO:
Por algum motivo, o e-mail que estou tentando ler, os anexos vem de uma forma diferente. Quando leio uma mensagem do inbox, pego o ContentType, se for multipart/MIXED, significa que possui anexos, então pego o conteúdo dessa mensagem e faço um for. Para cada iteração, eu estava esperando um anexo diferente, o q eu não estava acontecendo. Na verdade, estava vindo outro multipart/MIXED. Então fiz um método recursivo q resolvia este problema. Segue o código:
public void recursivo(Multipart mp) throws MessagingException, IOException {

    for (int i = 1; i < mp.getCount(); i++) {

        Part part = mp.getBodyPart(i);

        if (hasAttachments(part)) {

            Multipart multi = (Multipart) part.getContent();

            recursivo(multi);
        } else {

            if (part.getFileName().toUpperCase().contains(".XML")) {

                armazenaFile(part);
            }
        }
    }
}

Dúvida JavaMail - Anexos vindo null


R programming - Computational time taken for comparing strings vs comparing integers?

Question: I would like to know if string comparison is faster or slower than integer comparison for similar size (ex. 3 character string vs 3 digit number). Or is speed irrelevant to data type?
I'm asking this question because even a little difference would matter when I have to process millions of user's data.
Comment: Why don't you try it?  Use `library(microbenchmark)` and/or `system.time` and/or `Rprof`
Comment: Are these comparisons really the slow part of your code?  You may be suffering from premature optimization. http://c2.com/cgi/wiki?PrematureOptimization
Answer: It appears string comparison is slower.
<code>x <- 1:11+100; y <- 11:1+100; cx <- as.character(x); cy <- as.character(y)
library(microbenchmark) # In line with Richard Scriven's comment
microbenchmark(x == y, cx == cy, times = 1000000)
# Unit: nanoseconds
#      expr min  lq median  uq       max neval
#    x == y 318 408    477 664 108641192 1e+06
#  cx == cy 521 633    701 943 111547387 1e+06
</code>
Comment: I agree with the conclusion, but why are `x` and `y` such short vectors?
Comment: I can confirm the benchmark, even with much longer arrays, although the ~1.4 times difference in median times for 100 elements becomes a ~3.1 times difference for 100k elements.
Answer: use
<code>  start.time<-Sys.time()
  [your propgraming code]
  end.time<-Sys.time()
  s<-end.time-start.time
  s
</code>
you will get your answer. Apply this on both string and numerical digit. you can identify the computational time of both string and numeric digit.


Complicated grouping query, finding a ID not part of the GROUP BY

Question: I am having a bit of trouble with this SQL query, first some background
Table definition
create table [owner]
(
  [patientid] nvarchar(10) NOT NULL,
  [clientid] nvarchar(10) NOT NULL,
  [percentage] float NULL,
  [status] bit NOT NULL
)

alter table [owner] ADD CONSTRAINT PK_OWNER PRIMARY KEY CLUSTERED ([patientid],[clientid])

Example source data

| PATIENTID | CLIENTID | PERCENTAGE | STATUS |
----------------------------------------------
|      Pet1 |   Owner1 |        100 |      1 |
|      Pet2 |   Owner2 |         75 |      1 |
|      Pet2 |   Owner3 |         25 |      1 |
|      Pet3 |   Owner4 |         10 |      1 |
|      Pet3 |   Owner5 |         90 |      1 |
|      Pet3 |   Owner6 |        100 |      0 |
|      Pet4 |   Owner7 |         50 |      1 |
|      Pet4 |   Owner8 |         50 |      1 |

What I am looking for is I want the owner who has the highest percentage per pet who has a status of 1, in the event of a tie, it should go alphabetically by the Owner's name.
So here is the output I would want to see

| PATIENTID | CLIENTID |
------------------------
|      Pet1 |   Owner1 |
|      Pet2 |   Owner2 |
|      Pet3 |   Owner5 |
|      Pet4 |   Owner7 |

The closest I got was
SELECT f1.[patientid]
      ,f1.[clientid]
  FROM [OWNER] f1
inner join
(
  select [patientid], max([percentage]) as [percentage]
  from [owner]
  where status = 1
  group by [patientid]
) f2 on f1.[patientid] = f2.[patientid] and f1.[percentage] = f2.[percentage]
where status = 1

However that gives me two records for Pet4.

| PATIENTID | CLIENTID |
------------------------
|      Pet1 |   Owner1 |
|      Pet2 |   Owner2 |
|      Pet3 |   Owner5 |
|      Pet4 |   Owner7 |
|      Pet4 |   Owner8 |

What is the correct way to handle something like this so I only get one record and I apply that alphabetical ordering on the tie to find the one record?
Here is a SQL Fiddle workspace to try out any answers.

EDIT:
I figured a way how to do it, but to me it reeks of code smell, is there a more "proper" way of doing this?
select distinct f3.[patientid], (
  SELECT top 1 f1.[clientid]
    FROM [OWNER] f1
  inner join
  (
    select [patientid], max([percentage]) as [percentage]
    from [owner]
    where status = 1
    group by [patientid]
  ) f2 on f1.[patientid] = f2.[patientid] and f1.[percentage] = f2.[percentage]
  where status = 1 and f1.[patientid] = f3.[patientid]
  order by f1.[patientid], f1.[clientid]
)
from owner f3

Comment: bluefeet's solution is better: the server will read the rows just one time. For above solution, the server will read the rows two/three times: `f1`, `f2`, `f3`.
Answer: You should be able to use row_number() to get the result by applying a partition by the patientid and ordering it by the percentage and clientid:
select patientid, clientid
from
(
  select patientid, clientid, percentage, status,
    row_number() over(partition by patientid
                      order by percentage desc, clientid) rn
  from owner
  where status = 1
) d
where rn = 1;

See SQL Fiddle with Demo
Comment: Ah, much better than my solution.
Answer: A correlated subquery will also work, though partition may scale better
declare @tmpOwner table (
    PatientID varchar(50),
    ClientID varchar(50),
    Percentage int,
    Status smallint
)

insert @tmpOwner (PatientID,ClientID,Percentage,Status)
SELECT 'Pet1','Owner1',100,1 UNION
SELECT 'Pet2','Owner2',75,1 UNION
SELECT 'Pet2','Owner3',25,1 UNION
SELECT 'Pet3','Owner4',10,1 UNION
SELECT 'Pet3','Owner5',90,1 UNION
SELECT 'Pet3','Owner6',100,0 UNION
SELECT 'Pet4','Owner7',50,1 UNION
SELECT 'Pet4','Owner8',50,1

select x.PatientID,
(SELECT top 1 ClientID
 FROM @tmpOwner
 where Percentage=max(x.Percentage)
 and x.PatientID=PatientID
 order by ClientID) Win_Owner
from @tmpOwner x
where x.Status=1
group by PatientID

Answer: I think the windowing functions, as in the answer from @bluefeet, make this easier to read. But you were close to the alternative syntax. MIN() can resolve the alphabetical ordering on tied rows.  (Some people imagine that MIN() operates only on numbers.)
SELECT f1.[patientid]
     , MIN(f1.[clientid])
FROM [OWNER] f1
INNER JOIN
    (SELECT [patientid], max([percentage]) as [percentage]
     FROM [owner]
     WHERE status = 1
     GROUP BY [patientid]
    ) f2
ON  f1.[patientid] = f2.[patientid]
AND f1.[percentage] = f2.[percentage]
GROUP BY f1.patientid


How to prove the theorem about Riemann integrable function?

Question: I am trying to prove the following:
if $f$ is non negative riemann integrable on $[a,b]$ then there exist $a \leq c \leq d \leq b$ such that  $$\int_c^d f(x)dx = 1/2\int_a^b f(x)dx$$
Comment: hint: use IVT on $\int^x _af(t)dt$.
Comment: what does nonnegative have to do with it?
Answer: Consider $F(x):=\int_a^x f(x)dx$.
$F$ being continuous, the image of interval $[a,b]$ is interval $[0,M]$ with $M:=F(b)=\int_a^b f(x)dx$.
As $F$ takes all the values in $[0,F(b)]$ (by Intermediate Values Theorem), there is, in particular, a value $c$ such that $F(c)=F(b)/2$. (then take $d=b$).


Trocar imagem com JavaScript

Question: Tenho o seguinte código para trocar imagem automaticamente em JavaScript.
Queria utilizar ele para deixar como um gif, sem perder a qualidade.

var index = 1;

function changeImage(){

var rand = Math.floor (Math.random () * 4)
  jQuery('.img-rand').hide();

 jQuery(jQuery('.img-rand').get(index)).fadeIn();
 index++;

  if (index > 3){
   index = 0;
  }
}

setInterval(changeImage, 500);
.img-rand{
  display:none;
}

Porém está um efeito muito quebrado. Aalguém sabe uma forma de deixar com um aspecto de gif? No caso é a mesma imagem, apenas um clique aqui numa e na outra sem.
Comment: Ao analisar o seu problema, estou achando que você só precisa redimensionar as imagens para que tenham o mesmo tamanho, assim esse efeito de quebra irá sumir
Comment: Pior que não, se olhar no final da página vai ver o que estou falando https://www.boutiqueinfantil.com.br/testando
Answer: Em vez de utilizar setInterval() você poderia usar a função recursiva, utilizando os callbacks do .fadeIn() e do .fadeOut(), fazendo um delay de 500 milissegundos no .fadeOut(). Agora, o index deveria começar do 0, e não do 1, desta forma:

var index = 0;

function changeImage(){

   var rand = Math.floor (Math.random () * 4)
   jQuery('.img-rand').eq(index).fadeIn(function(){
      jQuery('.img-rand').delay(500).eq(index).fadeOut(function(){
         index++;
         // aqui o "1" é se vc possui 2 imagens
         if (index > 1) index = 0;
         changeImage();
      });
   });

}
changeImage();
.img-rand{
  display:none;
  width: 200px;
  height: 100px;
}

Trocar imagem com JavaScript


Why is addition not commutative under PM's notion of relation number?

Question: Quoting Bertrand Russell's "The Principles of Mathematics" p468 §299:

It is worth while to repeat the definitions of general notions involved in terms of what may be called relation-arithmetic*. If P, Q
be two relations such that there is a one-one relation S whose domain
is the field of P and which is such that Q = (˘S)PS, then P and Q are
said to be like. The class of relations like P, which I denote by λP,
is called P's relation-number. If the fields of P and Q have no common
terms, P + Q is defined to be P or Q or the relation which holds between
any term of the field of P and any term of the field of Q, and between
no other terms. Thus P+Q is not equal to Q+P. Again λP+λQ is defined
as λ(P + Q).
*Cf. Part IV, Chap. xxix, §231.

Where Principia Mathematica symbols and terminology use:

the symbol ˘ to denote the converse relation.
the word "field" to denote the union between the domain and co-domain of the relation.

First, a point of confusion is the tendency to assume binary relations in calling out  "domain" and "co-domain".  Is it not the case that n-place relations may have up to n distinct "domains", each of which supplies a value for a given place in a particular relationship of the relation's extension?
Second, as Russell specifies the two (n-ary) relations have "no terms in common" between their fields (as n-way unions of their respective n-domains), it seems the only compositional intension would be the disjunction (or) of their respective extensions. To bring this down to simple relation-tables:  One takes the rows of P and the rows of Q and puts them in the same relation table, regardless of row-order.  This is what one would expect of the + operator's logical analogue of or which, also, is commutative.
What am I missing?
Answer: It makes sense that addition between relations is not commutative.
Take this easy example:
let P be the series of natural number in order of magnitude and let Q the ordered couple (-1;-2).
Then the series P+Q is just the series that you get if, metaphorically, you "put" the couple Q at the "end" of P; while Q+P is just the series that you get by putting Q at the beginning of P.
The first series P+Q is a well ordered series but is not a progression (i.e: is not isomorphic to the series of natural number in order of magnitude; that term is used in Principia Mathematica *263); the second one, i.e, Q+P, is still a progression.
When P and Q are well ordered finite series, then it's true that P+Q=Q+P; but that result isn't true in general.
Answer: Re: (1), I question whether relations in this context are $n$-ary or specifically binary - your question suggests the former, but relation algebra is usually set up for the latter (and I don't know how to make sense of the converse of a more-than-$2$-ary relation).
Re: (2), I believe the key point is the clause

"or the relation which holds between any term of the field of P and any term of the field of Q

which distinguishes $P+Q$ from the mere union of $P$ and $Q$ (which is indeed commutative) - the idea is that if $p$ is in the field of $P$ and $q$ is in the field of $Q$, then $(p,q)\in P+Q$ but $(q,p)\not\in P+Q$ and conversely $(q,p)\in Q+P$ but $(p,q)\not\in Q+P$.
Comment: You must be correct that the context presumes binary P and binary Q but I don't understand the justification for assuming 2 place relations for relational algebra.  Moreover, this is relational arithmetic where the binary operation + is a binary function (binary N:1 relation -- the elements of whose field are relations).  As for making sense of "converse", that concept occurs only with regards to the "one-to-one" relation S  in the expression that defines 'like' relations P and Q:  Q = (˘S)PS


How to test the autocorrelation of the residuals?

Question: I have a matrix with two columns that have many prices (750).
In the image below I plotted the residuals of the follow linear regression:
lm(prices[,1] ~ prices[,2])

Looking at image, seems to be a very strong autocorrelation of the residuals.
However how can I test if the autocorrelation of those residuals is strong? What method should I use?

Thank you!
Comment: You don't need to test for autocorrelation. It is there. The plot shows that. You could look at the autocorrelation function of these residuals (function `acf()`), but this will simply confirm what can be seen by plain eye: the correlations between lagged residuals are very high.
Comment: @Wolfgang, yes, correct, but I have to check it programmatically.. I will take a look at acf function. Thanks!
Comment: @Wolfgang, I'm seeing acf() but I don't see a sort of p-value to understand if there is a strong correlation or not. How to interpret its result? Thanks
Comment: With H0: correlation (r) = 0, then r follows a normal/t dist with mean 0 and variance of sqrt(number of observations). So you could get the 95% confidence interval using +/- `qt(0.75, numberofobs)/sqrt(numberofobs)`
Comment: @Jim The variance of the correlation is not  $\sqrt{n}$. Nor is the standard deviation $\sqrt{n}$. But it does have an $n$ in it.
Answer: There are probably many ways to do this but the first one that comes to mind is based on linear regression. You can regress the consecutive residuals against each other and test for a significant slope. If there is auto-correlation, then there should be a linear relationship between consecutive residuals. To finish the code you've written, you could do:
mod = lm(prices[,1] ~ prices[,2])
res = mod$res
n = length(res)
mod2 = lm(res[-n] ~ res[-1])
summary(mod2)

mod2 is a linear regression of the time $t$ error, $\varepsilon_{t}$, against the time $t-1$ error, $\varepsilon_{t-1}$. If the coefficient for res[-1] is significant, you have evidence of autocorrelation in the residuals.
Note: This implicitly assumes that the residuals are autoregressive in the sense that only $\varepsilon_{t-1}$ is important when predicting $\varepsilon_{t}$. In reality there could be longer range dependencies. In that case, this method I've described should be interpreted as the one-lag autoregressive approximation to the true autocorrelation structure in $\varepsilon$.
Comment: This is called a Breusch-Godfrey test for autocorrelation.
Comment: thank you so much for the example. Only one doubt, How can I test if res[-1] is significant?
Comment: you'd test it the same way you would any other regression coefficient - look at the $t$-statistic and $p$-value
Comment: doing a fast test with: lm(rnorm(1000)~jitter(1:1000)) I get: Residual standard error: 1.006 on 997 degrees of freedom
Multiple R-squared: 0.0003463, Adjusted R-squared: -0.0006564
F-statistic: 0.3454 on 1 and 997 DF,  p-value: 0.5569  the p-value can't reject the null hypothesis
Comment: Macro, I have tested the residuals of the chart I plotted above, and the result is: Residual standard error: 0.04514 on 747 degrees of freedom
Multiple R-squared: 0.9241, Adjusted R-squared: 0.924
F-statistic:  9093 on 1 and 747 DF,  p-value: < 2.2e-16, It doesn't seem very good, It is very strange because there is a strong autocorrelation, what could I do?
Comment: @Dail - what you've told me indicates very strong autocorrelation in the residuals. Based on the $R^2$ value the correlation between consecutive residuals is approximately .96.
Comment: One moment, I didn't understand you. In the test I shown you the p-value: < 2.2e-16 is the result of: summary(mod2). What is .96 ?
Comment: $.96$ is aproximately the square root of the $R^2$ value you reported, which (when there is a single predictor that is continuous) is equal to the sample correlation between the predictor and the response. That is, the estimate of the correlation between $\varepsilon_{t-1}$ and $\varepsilon_{t}$ is .96
Comment: Macro - so I don't need to see the p.value? only r2?
Comment: No, you do need the $p$-value - it indicates a wildly significant relationship - I was only interpreting $R^2$ to put that statistical significance into more understandable terms.
Comment: so, if i get a very low p.value the relationship of the errors are very high, right?
Comment: yes, that's right.
Answer: Use the Durbin-Watson test, implemented in the lmtest package.
dwtest(prices[,1] ~ prices[,2])

Comment: The p-value is the probably of getting as much correlation as that observed if there is no real correlation. So if the p is very small, as it is, that suggests there is a lot of correlation present in the sample.
Comment: very strange I get: p-value < 2.2e-16, How it is possible? the data seems very correlated!
Comment: Do you mean a p-value like this indicates that the residuals are very autocorrelated?
Comment: hmm strange, take a look at: http://imageshack.us/f/59/17671620.png/ how is it possible that the right image is not autocorrelated?
Comment: :dail It would appear that the left image has a structural change in variance ( see Ruey Tsay's article "Outliers, Level Shifts, and Variance Changes in Time Series" , Journal of Forecasting, VOl 7, 1-20 (1988) for details ) which in this case does not "confuse" the DW perhaps due the fact the entire distribution is still normal while the right image has some visually obvious ( and empirically identifiable ) anomalies (Pulses) creating a non-normal ( leptokurtotic see wikopedia : A distribution with positive excess kurtosis is called leptokurtic ) distribution which causes havoc with the DW
Comment: @Dail. I can't see any sign of autocorrelation from the right plot.  In any case a time plot is not the best way of spotting autocorrelation. You would be better off using an ACF to see it.
Comment: @Rob, autocorrelation doesn't mean constant variance and constant mean?
Comment: @Dail. The ideas are largely separate. A series can have autocorrelation and  constant variance and constant mean. A series can have no autocorrelation but non-constant variance. Non-constant mean will usually induce autocorrelation.
Answer: The DW Test or the Linear Regression test are not robust to anomalies in the data. If you have Pulses, Seasonal Pulses , Level Shifts or Local Time Trends these tests are useless as these untreated components inflate the variance of the errors thus downward biasing the tests causing you ( as you have found out ) to incorrectly accept the null hypothesis of no auto-correlation. Before these two tests or any other parametric test that I am aware of can be used one has to "prove" that the mean of the residuals is not statistically significantly different from 0.0 EVERYWHERE otherwise the underlying assumptions are invalid. It is well known that one of the constraints of the DW test is its assumption that the regression errors are normally distributed. Note normally distributed means among other things : No anomalies ( see http://homepage.newschool.edu/~canjels/permdw12.pdf ). Additionally the DW test only test for auto-correlation of lag 1. Your data might have a weekly/seasonal effect and this would go undiagnosed and furthermore , untreated , would downward bias the DW test.
Comment: what are the tests for testing that residuals are significantly different from zero? If regression includes intercept, then residual mean is algebraicaly zero, so I am curious how is it possible to circumvent this problem.
Comment: This is just the standard "no omitted variables" assumption that is implicit in all regression analysis.
Comment: :mpkitas As you said when you include a constant the mean of the errors is guaranteed to be 0.0 but that doesn't guarantee that the mean of the errors is Zero everywhere. For example if a series has a change in mean , the overall mean will be a constant but will yield tw0 "clumps" of residuals , each with a different mean. You can pursue Ruey Tsay's article "Outliers, Level Shifts, and Variance Changes in Time Series" , Journal of Forecasting, VOl 7, 1-20 (1988) for details. OR http://faculty.chicagobooth.edu/ruey.tsay/teaching/uts/lec10-08.pdf OR Google "automatic intervention detection"
Answer: 2021: R Provides an Autocorrelation Function - acf
I'm assuming that the other answers posted were created before the acf function existed in R.
However, in 2021, there is a dedicated function for calculating the autocorrelation.
Here's how to use it:
# calculate the ACF for lags between 1 and 20 (inclusive)
autocorrelation <- acf(your.data.here, lag.max=20, plot=FALSE)

# Plot figure
plot(autocorrelation,
     main="Autocorrelation",
     xlab="Lag Parameter",
     ylab="ACF")

Reference:
https://www.datacamp.com/community/tutorials/autocorrelation-r
Comment: That link was put online in 2018, so acf() was available at least by that year instead of 2021. Not sure why you separate the two lines, as acf can directly plot using main, ylab and xlab without calling to plot() i.e. acf(your.data.here, lag.max=20, plot=FALSE), main="Autocorrelation", xlab="Lag Parameter", ylab="ACF")


Tabulator checkbox multiple selection

Question: In tabulator I used a checkbox for select all and deselect all ,
for checkbox checked and unchecked i used a following code,
For checked
$('input[name = custmisedtab]').prop('checked', true);

For Unchecked
$('input[name = custmisedtab]').prop('checked', false);

when I was checked it will checked a only that records that are shown in screen not all which is shown after scrollbar.
Answer: With Tabulator, you should not be modifying the DOM directly - instead, update the data object of the table.  You should have a column with a custom formatter to display a checkbox, checked based on the columns value.  To update their state, call table.updateData() or table.updateRow() for all the rows.
Your current code doesn't update the checkboxes beyond the scrollbar because of Tabulator's virtualization.  When you try to set the checkbox states, the rows beyond the scrollbar aren't actually part of the DOM yet, and thus aren't available to jQuery to update.

Tabulator checkbox multiple selection


How to use Fontawsome Pro icons in mkdocs material

Question: I have purchased a License for the Fontawesome Pro Icons package and was wondering how I can use the pro library kit in mkdocs material?
I currently use the free fonts like this, for example:
:fontawesome-solid-user-secret:

But I would like to use the "thin" version which is part of the pro package, like this:
:fontawesome-thin-user-secret:

How can I achieve that? TIA
Answer: First, declare a custom_dir in mkdocs.yml if you haven't already:
theme:
  custom_dir: docs/.overrides  # Relative to mkdocs.yml. Can be whatever you want.

Then download Font Awesome, extract it, and move the contents of the svgs directory (not including the folder itself) to {CUSTOM_DIR}/.icons/fontawesome. For example, if your custom_dir is docs/.overrides, you would move the contents of the svgs directory to docs/.overrides/.icons/fontawesome. Everything else that came with the download is safe to delete.
Your custom_dir should look like this:
.
└── .icons/
    └── fontawesome/
        ├── brands
        ├── duotone
        ├── light
        ├── regular
        ├── sharp-regular
        ├── sharp-solid
        ├── solid
        └── thin

You can then use Font Awesome Pro icons in the same way you already do the free ones (e.g. :fontawesome-thin-user-secret: will work as written).


c++ tolower a char array in a server and client program?

Question: I am sending the server a message.
For example: "Hello World."
I want the server to send back the message: "hello world."
<code>for(;;) //listen forever
{
    ClntLen = sizeof(ClntAddr);
    NewSockfd = Accept(Sockfd, (sockaddr*)&ClntAddr, &ClntLen);

    //Read message
    read(NewSockfd, Buff, MAX_SIZE);
    //convert to lower, send back to client
    write(NewSockfd, Buff, MAX_SIZE);
    close(NewSockfd);
}
</code>
I have tried using tolower(), but in a server I just can't get it right without giving me errors.
Summary: Read Buff (char array), convert it to lowercase, Write it back to the client.
Please explain how its done.
Thanks in advance.
Comment: What encoding is your character data?
Answer: Show us your code to call tolower, please
When you call read, you should get its return value as the actual data returned from socket and then call tolower to convert them to lowercase and then send this buffer back with the length it returned from read.
Comment: I havn't implemented it in the server.
I couldn't get it to work properly because of the constant loop the server does.
Comment: Ok, got it working :) Thanks.
I thought there would be a easier way, but this is fine.


Musical notation/tablature for isomorphic instruments

Question: I've started playing the harpejji, a 16-stringed instrument with an isomorphic fretboard.
Due to its very nature, there are several different frets for a given pitch. Has there been an attempt to remove the ambiguity in standard musical notation for similar instruments before?
Comment: "Remove the ambiguity for similar instruments"? You mean like a *GUITAR*? Yes, people have been playing guitars for quite a long time.
Comment: I wonder if there is some special notation used for indicating how to play certain passages on a chromatic button accordion, and in that case if that could be helpful for the harpejji.
Comment: no, not like a guitar. Because there are fewer strings and wider intervals between strings on a guitar, your choices are naturally very limited. On a harpejji there are many more choices because of the greater number of strings and the smaller intervals between them…
Comment: Nonsense. On a guitar a given pitch can be played at several different fret positions on several different strings. Playing polyphonic music on guitar is quite difficult precisely because the performer has to figure out which string to play a given note on based on what other notes he has to play nearby. I take it you have little experience with the guitar.
Answer: You are asking about tablature notation, which indicates not only the pitch to play, but which string to play it on. Tablature was developed for the lute and is used to this day for the guitar.
Standard notation for classical guitar addresses this also, by providing numbers next to notes. Certain numbers indicate which string to play the note on, or sometimes also which fret position to place the hand to reach the note. The notations "p", "i", "m", and "a" indicate which right-hand finger to use to pluck the note.
Comment: I have seen a little tablature notation for guitar (despite, as you correctly surmise above, not being a guitarist), but I can't help but think it would get quite unweildy for an instrument with 16 strings (to say nothing of the 24-string bass variant). Are there any other notation systems people have used over time?
Comment: You could modify the traditional guitar tab with the following changes: make a space between in each group of strings, use a different color for each group to make it stand out, use line width to express diameter of each string (a set of lower strings would have progressively heavier lines as you descend).
Comment: Not that I know of. You're a pioneering player of a new instrument, so maybe you can help develop a better method of notation. Study the standard classical guitar notation and the tablature as a starting point. Good luck!
Answer: I suppose a violin can be considered to have an "isomorphic fingerboard", as each string is tuned a fifth up from the one before (as opposed to the guitar with unequal intervals between the strings).  There are many notes that can be played on more than one string on the violin.  You will sometimes see an indication like "sul D", meaning "play this note on the D string."
Edit: Sometimes in violin music a single Roman numeral indicates which string should be played. Likewise in organ music I indicates Great manual, II the Swell, III the Choir or Positif. I think the violin strings are numbered from the top down. I is the E string.  Similarly you could assign Roman numerals to your instrument's strings and indicate which string would be used for the top note of the chord.
Comment: @awe: sorry, confusing choice of words. I mean neither, actually.

If you start a string at C, then go across the fretboard, the notes are:

C D E F# G# A# C
Comment: That's true, I hadn't considered the string section of instruments. The harpejji's strings are only a tone apart, though, so the number of options are much greater…
Comment: What's this about a guitar having "unequal intervals between the strings"? Guitars are tuned in all 4ths except for one exception, the major 3rd between the G and B strings.
Comment: Sounds like a good working definition of uneven to me…
Comment: @andrewdotnich: When you say "one tone apart", do you mean as notes in a C major scale, or as half steps as in 12 tone scale?
Comment: One exception is all it takes to be unequal: 4 4 4 3 4. Not isomorphic.


SQL table - name each row

Question: I am trying to write a query that adds names to each row of my table. It seems like it should be simple but I can't figure it out since I'm not an expert at SQL.
Here's what I want my table to look like:
         New    Cancels Net
Daily     0         1   -1
Weekly    0     1   -1
Monthly   25    34  -9
Quarterly 25    34  -9
Annually  535   552 -17
Total     3418  1398    2020

Here's my table now:
New     Cancels Net
0           1   -1
0           1   -1
25          34  -9
25          34  -9
535         552 -17
3418    1398    2020

Here's the query behind it (I'm using SQL Server Management Studio):
SELECT [New Orders]
      ,[Cancels]
      ,[Net]
FROM [DailyFigures]
WHERE [UID]  IN (
SELECT TOP 1 [UID]
FROM [DailyFigures]
ORDER BY [UID] DESC)
UNION ALL
SELECT [Orders]
      ,[Cancels]
      ,[Net]
FROM [WeeklyFigures]
WHERE [UID]  IN (
SELECT TOP 1 [UID]
FROM [WeeklyFigures]
ORDER BY [UID] DESC)
UNION ALL
SELECT [Orders]
      ,[Cancels]
      ,[Net]
FROM [MonthlyFigures]
WHERE [UID]  IN (
SELECT TOP 1 [UID]
FROM [MonthlyFigures]
ORDER BY [UID] DESC)
UNION ALL
SELECT [Orders]
      ,[Cancels]
      ,[Net]
FROM [QuarterlyFigures]
WHERE [UID]  IN (
SELECT TOP 1 [UID]
FROM [QuarterlyFigures]
ORDER BY [UID] DESC)
UNION ALL
SELECT [Orders]
      ,[Cancels]
      ,[Net]
FROM [AnnuallyFigures]
WHERE [UID]  IN (
SELECT TOP 1 [UID]
FROM [AnnuallyFigures]
ORDER BY [UID] DESC)
UNION ALL
SELECT SUM([Orders]) AS Orders, SUM([Cancels]) AS Cancels, SUM([Net]) AS Net FROM [AnnuallyFigures]

I was thinking of adding a column with the row count and somehow changing the row count from numbers to names, but I'm not sure how to do that. Any help would be appreciated. Thanks.
Comment: If you simply add a constant, such as 'Daily' to your select clause and change the union all to a union, Bob might be your uncle.
Answer: Just add a 'text string' for each individual select like this:
SELECT 'DAILY' as ' ', [New Orders],[Cancels],[Net]
FROM [DailyFigures]
WHERE [UID]  IN
  (SELECT TOP 1 [UID] FROM [DailyFigures] ORDER BY [UID] DESC)

UNION ALL

SELECT 'WEEKLY' as ' ', [Orders],[Cancels],[Net]
FROM [WeeklyFigures]
WHERE [UID]  IN
  (SELECT TOP 1 [UID] FROM [WeeklyFigures] ORDER BY [UID] DESC)

UNION ALL

SELECT 'MONTHLY' as ' ', [Orders],[Cancels],[Net]
FROM [MonthlyFigures]
WHERE [UID]  IN
  (SELECT TOP 1 [UID] FROM [MonthlyFigures] ORDER BY [UID] DESC)

UNION ALL

SELECT 'QUARTERLY' as ' ', [Orders],[Cancels],[Net]
FROM [QuarterlyFigures]
WHERE [UID]  IN
  (SELECT TOP 1 [UID] FROM [QuarterlyFigures] ORDER BY [UID] DESC)

UNION ALL

SELECT 'ANNUALLY' as ' ', [Orders],[Cancels],[Net]
FROM [AnnuallyFigures]
WHERE [UID]  IN
  (SELECT TOP 1 [UID] FROM [AnnuallyFigures] ORDER BY [UID] DESC)

UNION ALL

SELECT 'TOTAL' as ' ',
    SUM([Orders]) AS Orders,
    SUM([Cancels]) AS Cancels,
    SUM([Net]) AS Net
FROM [AnnuallyFigures]

Comment: I see no reason why this should be a union. A union will attempt to remove duplicates, and since you have a different constant on each row, this doesn't seem necessary - unless there is a terrible normalization problem inside any of the individual queries feeding the union.
Comment: originally, I just copied the query and used the union all, then after looking at it, I removed it.  I've used just UNION in my own stuff (not union all), but the previous comment made me think to remove it.  Maybe it should have stayed in?
Comment: I agree ... I just re-read some explanations on UNION vs. UNION ALL, and agree 100% with you.  I'll fix the answer.  Thanks.
Comment: Wow that was really easy, I'm not sure why I didn't know how to do that. Thank You!!!
Comment: I modified the answer so that it will show blanks for the column heading ... obv. you could make it say whatever you'd like...

SQL table - name each row


How do I draw the graph of $h(x) = f(-x+2)$ from the graph of $f(x)$?

Question: Let's say we have a function $f(x)$
How do I draw $h(x)$ from $f(x)$ if you knew that $h(x) = f(-x+2)$?
Comment: Why not try a couple of examples? $f(x) = x + 5$ becomes $h(x) = -x + 7$. Or $f(x) = x^2$ becomes $h(x) = x^2-4x+4$. Draw these graphs. Draw a few more. See if you can tell how one becomes the other. Or simplify. What if $h(x) = f(-x)$? What if $h(x) = f(x+2)$? What happens then? Your answer ought to be some combination of these two, doesn't it?
Comment: @Arthur The thing is that I'm so frustrated because I made a stupid mistake on the exam yesterday. I just wanted to hear some good news because I didn't believe it at first.
Comment: The punchline will involve the words "*reflect across*" and "*horizontal shift*" or equivalent phrases.
Comment: @JMoravitz I might have got 1 thing correct in all this mess. Can you state what's the horizontal shift?
Comment: $2$, either to the left or to the right depending on if you shift before reflecting or if you reflect before shifting.
Comment: @JMoravitz So the shift vector is (2, 0) right?
Comment: See several examples [here](https://people.richland.edu/james/lecture/m116/functions/translations.html).
Answer: First find $f(x+2)$ which is a shift of $2$ units to the left.
Then find $f(-x+2)$ by reflecting the graph of $f(x+2)$ about the x-axis.


If $Rx$ is nil then $Rxr$ is nil for any $r \in R$

Question: i am studying kothe's conjecture, ad got stuck here. if $R$  is any non commutative ring, then how is it true that if the ideal $Rx$ is nil then $Rxr$ is nil for any $r \in R$.
let $sx\in Rx$, then $(sx)^n=0$ for some $n$, but how is $sxr$  nilpotent for any $r\in R$.
Comment: What is $x$ here? Just some indeterminate?
Comment: x is any element of R.
Comment: Note, you don't want that $sx$ nilpotent implies $sxr$ is nipotent, but that every element of $Rx$ is nilpotent implies $sxr$ is nilpotent for any $s,r\in R$.
Answer: Notice that $$(sxr)^n = (sxr)(sxr)\cdots(sxr) = sx(rsx)\cdots(rsx)r = sx(rsx)^{n-1}r.$$ Because $rsx \in Rx$ and this left ideal is nil, for sufficiently large $n$ the expression above is zero.
Comment: also can you clear my this doubt that let x be any element of a nil left ideal say I. then (x)=RxR is nil. is it true?
Comment: A positive answer to your question is equivalent to Koethe's conjecture: http://en.m.wikipedia.org/wiki/Radical_of_a_ring#The_upper_nil_radical_or_K.C3.B6the_radical


linear programming problem given initial solution

Question: While dealing with a linear programming problem we usually try to start with the basic feasible solution corresponding to the identity Matrix in the coefficient matrix. I have no idea how to solve the following type of LPP:
Solve the LPP using simplex method starting with the basic feasible solution $x_1=4$ and $x_2=0$
Max $z=-x_1+2x_2$ subject to $$3x_1+4x_2=12$$ $$2x_1-x_2\leq 12$$ $$x_1\geq 0, x_2\geq 0$$
Please help!
Answer: This is a case where you have to introduce an artificial variable.  I don't know why an initial solution in terms of $x_1$ and $x_2$ is given since it is not with these variables that we begin.
I introduced an artificial variable $x_4$ to account for the first constraint being an equation.  The second constraint doesn't need an artificial variable because when we put it in the standard form, the slack variable $x_3$ gives us a basis to begin the iterations.  So our basic feasible solution here is $x_3 = 12$, $x_4 = 12$, but we now want to minimize a new objective function $w = x_4$.
After following the simplex algorithm, I get $w = 0$ which is surely its minimum, since $w$ is a non-negative function, and I end up with a basis in terms of variables $\{x_2, x_3\}$.  This means the original problem is feasible and attains its optimal solution at the same point $w$ attain its minimum --- which is at $x_2 = 3, x_3 = 15$, when $z = 6$.
So the final answer is $z = 6$ at $(0, 3)$ because the original problem is only involved with variables $x_1$, $x_2$, so we must not mention $x_3$ and $x_4$ here.
If you haven't seen artificial variables yet, you need to study that.  Once you know how to work with it, this answer should make sense.  If not, let me know the point of confusion and I'll clarify the answer.


Laplace approximation in high-dimensions

Question: Obviously computing the inverse Hessian is hard when a probability distribution is fitted on high-dimensional datapoints. One idea to reduce computational cost would be to approximate the distribution with a diagonal Gaussian. Are there any standard efficient techniques allowing to make efficient use of the Laplace approximation in high-dimensions?
Answer:
Are there any standard efficient techniques allowing to make efficient use of the Laplace approximation in high-dimensions?

Assuming that you are using a Laplace approximation for a random effect model, often groups of outcomes are conditional independent given the random effects. These model have a Hessian which sparse making it easy to work with high-dimensional problems. As an example, consider the following mixed logistic regression
$$
\begin{align}
y_{ij} &\sim \text{Bin}(\text{logit}(b_i + u_i), 1) & j &= 1,\dots 5 \\
u_i &\sim N(0, \sigma^2_u) & i &= 1, \dots, k \\
b_i &\sim N(0, \sigma^2_b) & i &= 1, \dots, k
\end{align}
$$
We can simulate from this model with $k = 3$ and plot the Hessian as follow
<code># simulate data
n <- 5
k <- 3
sig <- 1
set.seed(1)
dat <- do.call(rbind, lapply(1:k, function(i){
  u <- rnorm(2, sd = sig)
  x <- runif(n, -1, 1)
  y <- 1/(1 + exp(-u[1] - u[2] * x)) < runif(n)
  data.frame(y = y, x = x, grp = i)
}))

# approximate the hessian
library(numDeriv)
ll <- function(u){
  i_start <- (dat$grp - 1) * 2
  p_hat <- 1/(1 + exp(-u[i_start + 1] - dat$x * u[i_start + 2]))
  sum(log(ifelse(dat$y > 0, p_hat, 1 - p_hat))) +
    sum(dnorm(u, sd = sig, log = TRUE))
}
he <- hessian(ll, numeric(2 * k))
he[abs(he) < 1e-3] <- 0 # threshold just as an example here
print(he, digits = 2)
#R>       [,1]  [,2]  [,3]  [,4]  [,5]  [,6]
#R> [1,] -2.25 -0.42  0.00  0.00  0.00  0.00
#R> [2,] -0.42 -1.49  0.00  0.00  0.00  0.00
#R> [3,]  0.00  0.00 -2.25 -0.23  0.00  0.00
#R> [4,]  0.00  0.00 -0.23 -1.39  0.00  0.00
#R> [5,]  0.00  0.00  0.00  0.00 -2.25 -0.23
#R> [6,]  0.00  0.00  0.00  0.00 -0.23 -1.32
</code>
For this model, the Hessian is just a diagonal block matrix with 2x2 block matrices. Thus, it is easy to invert and to compute the determinant of. The number of non-zero entries of the Hessian is only $2^2k$ rather than $k^2$. This is the basis of much software like the lme4 package and the TMB package.

One idea to reduce computational cost would be to approximate the distribution with a diagonal Gaussian.

There are of course settings where the Hessian is not sparse. These include some Gaussian processes and autoencoders. Assuming a diagonal covariance matrix is a kind to the gaussian variational approximations used in many machine learning applications. However, I suspect that one might opt for some low rank approximation of the determinant instead.
Answer: You may want to look into the SR1 and BFGS (and its dual, DFP) optimization methods. Those iteratively update the approximated inverse Hessian using rank 1 (SR1) and rank 2 (BFGS) updates. They are also fairly efficient and can likely handle your problem.
Comment: The OP wants to apply a Laplace approximation so he needs to compute the determinant of the Hessian regardless of the optimizer he is using.
Comment: But that will not help the OP as the OP needs to evaluate the determinant? Using SR1 and BFGS approximations would still yield a dense Hessian approximation which the OP needs compute a determinant of in order to apply a Taylor approximation. This is computationally hard for larger problems which I guess is the reason that the OP asks for a diagonal approximation instead.
Comment: Yes, but if computing the inverse Hessian is hard, I've given OP a few methods to make that easier -- which is OP's ultimate goal ("idea to reduce computational cost").


Imprimir combinações de inteiros em ordem crescente

Question: "Dados dois número inteiros não-negativos m e n, gere todas as combinações de tamanho m dos inteiros de 0 a n-1, na ordem crescente.
Exemplo: m=3 e n=5
(0 1 2); (0 1 3); (0 1 4); (0 2 3); (0 2 4); (0 3 4); (1 2 3); (1 2 4); (1 3 4); (2 3 4)"
Eu não sei como resolver este exercício. O máximo que consegui foi criar o vetor 0 1 2. Percebi que preciso adicionar 1 ao último elemento até que ele atinja o valor n-1, depois pego o vetor 0 1 2 novamente e acrescento 1 aos dois últimos elementos, depois só ao último e assim por diante. Mas não sei como fazer isso. Pensei em usar um FOR para cada rodada de somas, mas no caso a quantidade de FORs dependeria do valor de m e o algoritmo deve servir para quaisquer valores de m e n, pelo que entendi.
public static void main(String[] args) {
        int n, m, i, j;
        Scanner ent = new Scanner (System.in);
        System.out.println("Digite o valor de m:");
        m = ent.nextInt();
        System.out.println("Digite o valor de n:");
        n = ent.nextInt();
        int [] v = new int [m];
        for (i=0; i<m; i++) {
            v[i] = i;
        }

Answer: Você pode resolver seu problema utilizando recursividade, segue uma classe em Java adaptada desse link.
public class Combinacao {

    private int numeros[];
    private int posicoes;
    private int resultado[];
    private int quantidadeCombinacoes;

    public Combinacao(int m, int n) {
        numeros = new int[n];
        for (int i = 0; i < n; i++) {
            numeros[i] = i;
        }
        posicoes = m;
        resultado = new int[posicoes];
        quantidadeCombinacoes = 0;
    }

    private void combinar(int inicio, int fim, int profundidade) {
        if ((profundidade + 1) >= posicoes) {
            for (int x = inicio; x <= fim; x++) {
                resultado[profundidade] = numeros[x];
                quantidadeCombinacoes++;
                System.out.print("(");
                for (int i = 0; i < posicoes; i++) {
                    System.out.printf("%d%s", resultado[i], (i == posicoes - 1) ? "" : " ");
                }
                System.out.print("); ");
            }
        } else {
            for (int x = inicio; x <= fim; x++) {
                resultado[profundidade] = numeros[x];
                combinar(x + 1, fim + 1, profundidade + 1);
            }
        }
    }

    public void imprimirCombinacoes() {
        combinar(0, numeros.length - posicoes, 0);
    }

    public int getQuantidadeCombinacoes() {
        return quantidadeCombinacoes;
    }
}

Para utilizar faça o seguinte:
public static void main(String[] args) {
    Combinacao combinacao = new Combinacao(3, 5);
    combinacao.imprimirCombinacoes();
    System.out.println("\nTotal de combinacoes: " + combinacao.getQuantidadeCombinacoes());
}

A classe Combinacao recebe depois parâmetros no construtor, esses parâmetros são respectivamente m e n, conforme está na sua pergunta.
Comment: Obrigada pela ajuda. O único problema é que não entendi... Eu sei apenas o básico do básico. Pelo que aprendi até o momento (que é o que a professora espera encontrar na resposta), devo utilizar laços FOR e variáveis auxiliares. Vou postar na pergunta o código que tenho até agora.
Comment: @CristianeDosSantosCosta, como eu era novo aqui, não tinha opção para comentar, então tive que responder, o código que te passei foi baseado no link que está na resposta, se eu encontrar ou conseguir fazer com FOR edito a resposta.
Comment: Muito obrigada!


Java version for Spring 3.1.1

Question: What version of Java do you need to be able to use Spring 3.1.1. The geeks of Spring never put down in their documentation clearly what version is needed. Someone please help.
Answer: "
Java SE and Java EE Support
The Spring Framework is now based on Java 5, and Java 6 is fully supported.
Furthermore, Spring is compatible with J2EE 1.4 and Java EE 5, while at the same time introducing some early support for Java EE 6.
"
http://static.springsource.org/spring/docs/3.1.1.RELEASE/spring-framework-reference/html/new-in-3.0.html#new-in-3.0-intro

Java version for Spring 3.1.1


Finding each centroid of multiple connected objects

Question: I am SUPER new to python coding and would like some help. I was able to segment each cell outline within a biological tissue (super cool!) and now I am trying to find the centroid of each cell within a tissue using this:

I am using this code:
img = cv2.imread('/Users/kate/Desktop/SegmenterTest/SegmentedCells/Seg1.png')
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(image, 60, 255, cv2.THRESH_BINARY)[1]

cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

# loop over the contours
for c in cnts:
    # compute the center of the contour
    M = cv2.moments(c)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])
    # draw the contour and center of the shape on the image
    cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
    cv2.circle(image, (cX, cY), 7, (255, 255, 255), -1)
    cv2.putText(image, "center", (cX - 20, cY - 20),
        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
    # show the image
    cv2.imshow("Image", image)
    cv2.waitKey(0)

However,  when I use this code, it is giving me the centroid of the ENTIRE object, and not each individual object to give this.

I have no idea where to go from here, so a nudge in the right direction would be greatly appreciated!
Answer: You can use the function regionprops from the module scikit-image in your case. Here is what I got.

This is the code I used.
import cv2
import matplotlib.pyplot as plt
from skimage import measure
import numpy as np

cells = cv2.imread('cells.png',0)

ret,thresh = cv2.threshold(cells,20,255,cv2.THRESH_BINARY_INV)

labels= measure.label(thresh, background=0)
bg_label = labels[0,0]
labels[labels==bg_label] = 0 # Assign background label to 0

props = measure.regionprops(labels)

fig,ax = plt.subplots(1,1)
plt.axis('off')
ax.imshow(cells,cmap='gray')
centroids = np.zeros(shape=(len(np.unique(labels)),2)) # Access the coordinates of centroids
for i,prop in enumerate(props):
    my_centroid = prop.centroid
    centroids[i,:]= my_centroid
    ax.plot(my_centroid[1],my_centroid[0],'r.')

# print(centroids)
# fig.savefig('out.png', bbox_inches='tight', pad_inches=0)
plt.show()

Good luck with your research!
Comment: Your welcome! I would appreciate it if you can mark my answer as the correct answer!
Comment: Hi again, So the code worked perfectly when I used it for the previous image, but when I switched images to something more complex it gave me both the centroids of the black AND white images regions, even though the white regions were only a few pixels wide. Any way I can only apply this to the black regions' outlines? Or to specify a minimum size that it will analyze?
Comment: You can specify a minimum size in the for loop by using 'prop.area' which returns the pixel number of each connected components. Please check the details at the function 'regionprops' I provided in the answer.
Answer: Problem
cv2.findContours uses an algorithm which has a few different 'retrieval modes'. These affect which contours are returned and how they are returned. This is documented here. These are given as the second argument to findContours. Your code uses cv2.RETR_EXTERNAL which means findContours will only return the outermost border of separate objects.
Solution
Changing this argument to cv2.RETR_LIST will give you all the contours in the image (including the one outermost border). This is the simplest solution.
E.g.
import cv2
import imutils

img = cv2.imread('/Users/kate/Desktop/SegmenterTest/SegmentedCells/Seg1.png')
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(image, 60, 255, cv2.THRESH_BINARY)[1]

cnts = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

# loop over the contours
for c in cnts:
    # compute the center of the contour
    M = cv2.moments(c)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])
    # draw the contour and center of the shape on the image
    cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
    cv2.circle(image, (cX, cY), 7, (255, 255, 255), -1)
    cv2.putText(image, "center", (cX - 20, cY - 20),
        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
    # show the image
    cv2.imshow("Image", image)
    cv2.waitKey(0)

Selecting only the innermost objects
To reliably omit the outer contours you can take advantage of the ability of findContours to return a hierarchy of the contours it detects. To do this, you can change the retrieval mode argument once again to RETR_TREE, which will generate a full hierarchy.
The hierarchy is an array containing arrays of 4 values for each contour in the image. Each value is an index of a contour in the contour array. From the docs:

For each i-th contour contours[i], the elements hierarchy[i][0] ,
hierarchy[i][1] , hierarchy[i][2], and hierarchy[i][3] are set to
0-based indices in contours of the next and previous contours at the
same hierarchical level, the first child contour and the parent
contour, respectively. If for the contour i there are no next,
previous, parent, or nested contours, the corresponding elements of
hierarchy[i] will be negative.

When we say 'innermost', what we mean is contours that have no children (contours inside of them). So we want those contours whose entry in the hierarchy has a negative 3rd value. That is,  contours[i], such that hierarchy[i][2] < 0
A small wrinkle is that although findContours returns a tuple which includes the hierarchy, imutils.grabContours discards the hierarchy and returns just the array of contours. All this means is that we have to do the work of grabContours ourselves, if we intend on working with different versions of OpenCV. This is just a simple if else statement.
res = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# switch for different versions of OpenCV
if len(cnts) == 3:
    _, cnts, hierarchy = res
else:
    cnts, hierarchy = res

Once you have hierarchy, checking if a contour, cnts[i] is 'innermost' can be done with hierarchy[0][i][2] < 0, which should be False for contours that contain other contours.
A full example based on your question's code:
import cv2
import imutils

img = cv2.imread('/Users/kate/Desktop/SegmenterTest/SegmentedCells/Seg1.png')
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(image, 60, 255, cv2.THRESH_BINARY)[1]

cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# switch for different versions of OpenCV
if len(cnts) == 3:
    _, cnts, hierarchy = cnts
else:
    cnts, hierarchy = cnts

# loop over the contours
for i, c in enumerate(cnts):
    # check that it is 'innermost'
    if hierarchy[0][i][2] < 0:
        # compute the center of the contour
        M = cv2.moments(c)
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])

        # draw the contour and center of the shape on the image
        cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
        cv2.circle(image, (cX, cY), 7, (255, 255, 255), -1)
        cv2.putText(image, "center", (cX - 20, cY - 20),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
        # show the image
        cv2.imshow("Image", image)
        cv2.waitKey(0)

Comment: is there any way I can get only the cells? I find when I change to RETR_LIST it gives all the contours AND the outermost, but how can I get the innermost? Thanks!!
Comment: @helpkate1991 I have updated my answer with a discussion on the 'hierarchy' of contours.


Meaning of some symbols in classical guitar tablature

Question: I am trying to learn classical guitar by myself. In the tablature of Romanza, I came across a few symbols whose meaning I couldn't find. I have learned basic music theory, and I can understand the staff notation. I don't understand the top or bottom of the symbol of the staff and tablature, e.g.:

What is the meaning of the 3 vertical lines connected with a horizontal line over the tablature (not over the staff). Does that refer to upward pluck?
What is the meaning of CV 3 and CVII 6.
Is there a good reference resource (or book) for where I can look up these symbols and their meaning?
Comment: I wonder why this music is expressed in 3/4 entirely covered in triplets, rather than being expressed in 9/8. Are there non-triplet 8th notes elsewhere in the score?
Answer: The C may stand for capotasto, cejilla or cejuela depending on the language. It basically means using a single finger to hold multiple strings, the same as a barre. The V or VII are Roman numerals and refer to the fret and the 3 or 6 tell you how many strings to hold down. Sometimes the letter B for barre and a number for the fret is used, i.e. B5.
CV 3 means barre the top 3 strings at the 5th fret
CVII 6 means barre all 6 strings at the 7th fret.
As you can see, the TAB supports this.
As for the 3 vertical lines connected by a horizontal line in the TAB, those are 8th note triplets, just like in the standard notation above. Note the 3 above the horizontal lines indicating triplets instead of regular eighth notes.
Thanks to @ElementsInSpace, @Lazy and @EuroMicelli for providing info on the various terms in the comments.
Comment: You might want to include that the C stands for _capotasto_.
Comment: Capotasto is italian and basically translates to "head fret" and means the nut. Barré notation allows both B and C, where the C *can* mean "capotasto", but also "cejilla", the spanish word for barré technique. In slighly older spanish scores we do also find the notation Cª, which does *not* fit "capotasto".
Comment: Ah, I see. I had learned "C" as meaning "cejilla" which is a word in Spanish for a barre (rarely used, it might depend on country; commonly I just call it "barra"). What I didn't know is that "cejilla" and "cejuela", both from "little eyebrows", are themselves synonym of "capotasto" (valid in Spanish too, of Italian origin). So, depending on where the notation originated, it probably stands for "capotasto", "cejilla" or "cejuela", but they all mean the same thing.
Comment: _Capotasto_ in English and various other languages refers to the device used to hold down the strings, the [_capo_](https://en.wikipedia.org/wiki/Capo), while _barre_ as far as I know is about the guitarist's finger holding down multiple strings. Does this notation mean "use a mechanical device on these strings" or does it mean "use your finger to hold them down"? Since you mention both _capotasto_ and _barre_ in the same context, assuming that the "C" does indeed refer to a finger, is it just the notation for a barre or is there a difference between the two? In short, I'm confused. Help?
Comment: @terdon I did some searching online and found only references to a device that holds down the strings for capotasto but in this case there is clearly not a mechanical device used to hold the strings down and scores of performances available online attest to that. Here is an example at about 1:08: https://youtu.be/2EHW8c85i00 I'm far from an expert on classical guitar notation but in this context it refers to a barre.
Comment: I'm no expert, but according to some basic research, it is the same thing: _capotasto_ is an Italian word, _barre_ is French word. Both refer to: either using a mechanical device, or a finger, to hold down multiple strings.
Comment: @phoog No, not really. Fret is not a particularly good translation here, but I do not know a better english word for the context. "Tasto" comes from "tastare", which means something like "to touch, to feel something with your fingers" (most likely from latin "tangere").

So in music "tasto" generally refers to *anything* that you touch to produce a sound, such as keys on pianos and stuff. The fretboard is not called "il tasto" but "la tastiera". So "sul tasto" rather means "at the touch". "At the fretboard" would be "sulla tastiera".
Comment: @phoog As I said, you find both "sul tasto" *and* "sulla tastiera". And also I said, "sul tasto" would literally mean "at the touch". I think the main reason you predominantly see "sul tasto" is because is less complicated to say than "sulla tastiera".
Comment: …maybe @ElementsinSpace would like to chime in on this…
Comment: Don't worry, *it is* just a barre notation. No capotasto implied. And I don't remember for sure but I'm not convinced "C" stands for "capotasto"; I'll see if I can find a reference.
Comment: I guess another edit is in order!
Comment: While the confusion seems to have been resolved, I would just point out that it isn't particularly odd for _capotasto_ to refer in some contexts to a particular device and in others to a technique; _mute_ comes to mind as another example of a device that is named for the thing it does.  But @Lazy doesn't _tasto_ mean "fingerboard" rather than "fret" (consider _sul tasto_ for a bowed instrument)?  In that light, I would read _capotasto_ the notational instruction as meaning "the head of the fingerboard [is temporarily at the specified fret]."
Comment: @EuroMicelli Not exactly, cejilla can mean the same as capotasto, but it (and the main form ceja) generally refers to something being "covered" (thus eyelid). So the term refers not only to the capotaster (device) and the nut, but also to the bridge. So sometimes "ceja" is used for a full barré and cejilla for a small barré where only the top strings are barred.
Comment: @Lazy why then is the bowing instruction _sul tasto_ rather than _sulla tastiera?_  It seems to imply that _tasto_ is at least a partial synonym for _tastiera._  (Furthermore, for sense 2(b) at https://www.treccani.it/vocabolario/tasto/, I suppose that "fret" is precisely the right translation, notwithstanding the fact that I've never seen a fret made of ebony or any other kind of wood, but the attribution of only "indicative" function suggests that the definition was written by a non-musician.)


With multiple imputed data, how do you probe a categorical-by-categorical interaction in logistic regression?

Question: I am working with 10 multiple imputed datasets in SAS. I used the command PROC SURVEYLOGISTIC to fit a multivariate model with 6 predictors (3 dichotomous and 3 categorical) and their interaction terms, controlling for a numbers of relevant covariates.
The predictor variables are as follow:

CVD (0 = No; 1 =Yes)
HCA (0 = Low; 1= High)
EDU (1=High School Dropout; 2=Graduated High
School; 3=Some College; 4=Graduated College)
POV (1=Low; 2=Medium; 3=High)
LAN (1=Spanish; 2=English)
STA (0=Old, 1=New, 2=None)

My outcome variable is diabetes medication use and is coded as 0 = no use and 1 = current use
I found the following:

One of the levels of the interaction of EDU*STA is marginally significant.
Only one of the levels of the interaction of POV*STA is marginally significant.

My questions are:

When working with multiple imputed data, how do you probe a categorical-by-categorical interaction in logistic regression?
What would be the appropriate approach to graphically represent the interaction?
Answer: If you have followed Rubin's rules for combining the results from the models on the multiply imputed (MI) data sets (which I presume SAS has done for you), there is no difference from standard multiple regression (whether logistic or otherwise) in how to evaluate interaction terms. The variance-covariance matrix of regression coefficients following MI and Rubin's rules takes into account both the within-imputation and across-imputation variances.
Whether MI is involved or not, you need to be very careful in evaluating individual coefficient estimates in interactions involving multiple-level categorical predictors. With the usual coding, individual pairwise interaction coefficients represent differences in outcome (log-odds here) for combinations of 2 predictor levels other than reference levels of those predictors. Thus changing the reference level of one categorical predictor can change both the values and apparent "significance" of interaction coefficients with other predictors (in addition to the coefficients of its own individual levels, which are usually expressed as differences in outcome from the reference). For example, if my recollection is correct that SAS uses the last category as the default reference level, then just doing the same analysis in SAS versus R (which by default uses the first category) could give different coefficients and p-values with multi-level categorical predictors because of the different choice of reference levels.
Unless you have specific pre-specified hypotheses about interaction terms, it's usually safest first to examine whether a group of interaction terms all together are significantly different from 0 before you evaluate any particular interaction terms. That's similar to the advice to make sure an ANOVA has overall significance before proceeding to individual comparisons. If you included all pairwise interactions in your model you have almost 40 pairwise interaction coefficients, so there's a good chance that you will find a couple of them apparently "significant" at p < 0.05 just by chance. You want to rule that problem out first.
For example, the EDU*STA interaction provides 6 separate coefficients. Examine whether the whole set of those coefficients is different from 0. That's sometimes called a "chunk test." Analyzing a set of interaction coefficients all together gets around the problems arising from which particular levels were specified as references. That can be done with a Wald test; I think you can do that with the CONTRAST statement in SAS, specifying all of a set of interaction coefficients = 0 as a combined null hypothesis (although I don't use SAS and might be mistaken). You also could do a likelihood-ratio test between the full model and the model without that particular set of interactions.
If you do find that an overall test on a set of interactions significantly rules out the null hypothesis, then you can proceed to evaluate particular circumstances. For illustration you should display model predictions for particular scenarios involving the interaction terms of interest, as the interaction terms alone can be hard to interpret without the rest of the model. For example, if you find a particular EDU*STA interaction to be interesting, fix all the other covariate/predictor values at reasonable levels and show how particular combinations of EDU and STA values lead to different outcomes than you would have expected based on each individually.


TFS - Set a branch to allow check ins of "Merge" changeset only

Question: In the company I work for we have a Release branch from which we publish versions to production.
I want to prevent a situation where someone checks in changes made in that branch directly without the changes were synced from the development branch.
Is there a way where I could set the Release branch to allow check-ins for change-sets which are of "Merge" type only?
By this I could ensure the change-set was originated from the development branch and achieve my goal in addition to preventing non synced code between production and development branches.
Answer: You cannot fully restrict a branch to allow merges only. But there is a checkin-policy made by a Microsoft MVP which you can configure. Combined with the checkin-policy from the TFS Power Tools you can configure it to a speficic folder. The configuration process is explained on teh download page.