Power analysis for a multinomial logistic regression

Question: How do I conduct a power analysis for a multinomial logistic regression analysis? I have 1 independent variable (with 3 levels) and 1 dependent variable (with 2 levels). All variables are continuous. I cannot do ordinal.
Thanks!
Comment: If you have 1 dependent variable w/ 2 levels, you have *binomial* logistic regression, not multinomial. Do you actually have $\ge 3$ unordered response categories? If not, there is a great deal of information about power analysis in my answer here: [Simulation of logistic regression power analysis - designed experiments](http://stats.stackexchange.com/a/35994/7290). Even if it isn't exactly what you're looking for, it may be worth your time to read that & get a clearer sense of the issues involved, as I don't think there is enough information in your question statement for it to be answerable.
Comment: "All variables are continuous" is inconsistent with each variable having either 2 or 3 levels.  Moreover, with just 2 non-ordinal variables, instead of using regression, you might be better off looking at chi-square and its related measures of association such as Cramer's V.
Comment: Thank you very much for all of your input. I appreciate both of you taking the time to respond to this. Based on your feedback I realized I needed to completely revise my statistical model based on the variables and study design. It turns out that a 3x3 mixed ANOVA is what winds up being best suited for the study.  I feel like you both helped get me on the right foot, not sure what to do with the bounty but @gung if you want to paste that in as an answer I can select it.
Comment: Thanks. I think @rolando2's comments are more on point here, given what your actual situation is. I wonder if it might be more appropriate for him to paste in his comment as an answer? If not, I can add mine in a day or so.
Comment: Ok that sounds great. Yes @rolando2 please feel free to do that. Thanks again!
Comment: bounty expires in 3 days! Someone claim it :)
Comment: @gung You are always a class act.
Comment: Should this question be deleted or just reworded? The title is now very misleading and this might cause confusion.
Answer: "All variables are continuous" is inconsistent with each variable having either 2 or 3 levels. Moreover, with just 2 non-ordinal variables, instead of using regression, you might be better off looking at chi-square and its related measures of association such as Cramer's V.


Meteor - How to Retry Failed HTTP Request without Losing Context?

Question: In my Meteor 1.0 app, I'm running a batch of server-side HTTP requests in order to retrieve fixture data in a synchronous fashion. Once a request completes and computations are run on that data, startNumber is incremented (by 5000) and the request is re-run with that new value. This loop system will continue until the API returns a blank response array, signifying all the data has been captured. This HTTP request is part of a larger, complex function that helps set the context of the request.
functionName = function(param1,param2,param3) {
  // ...
  // ...
  var startNumber = 1;
  do {
    var request = Meteor.http.call("GET", "https://url-to-api-endpoint",
      { params:
        {
          "since": startNumber
        },
        timeout: 60000
      }
    );
    if(request.statusCode === 200) {
      var response = request.data;
      // perform calculations on the response
      startNumber+=5000;
    }
  } (while response.length>0);
  // ...
  // ...
};

The do-while loop system is working fine, except that every few iterations the request is returning with Error: getaddrinfo ENOTFOUND. The URL is perfectly valid, and it appears these errors are resulting from a finicky/unreliable API as sometimes the same exact request will go through or error out. I want to replay failed requests in order to make sure my app is retrieving data chronologically before proceeding.
How can I replay a failed HTTP request as though it were being run for the first time? In other words, without losing the current context of all the variables, etc., in functionName?
Answer: FYI, incase someone else ends up in this predicament, I solved this problem by wrapping the HTTP request in a try-catch block. In the case of an error such as getaddrinfo ENOTFOUND or ETIMEDOUT, the error gets caught. Within the catch block, I call the functionName and pass in parameters for the current state (i.e. the current startNumber) - this allows me to essentially "replay" the request all over again.
// ...
// ...
try {
    var request = Meteor.http.call("GET", "https://url-to-api-endpoint",
      { params:
        {
          "since": startNumber
        },
        timeout: 60000
      }
    );
} catch(err) {
    console.log(err + '\nFailed...retrying');
    functionName(param1,param2,param3);
}
// ...
// ...


Como exibir o valor de uma query em C?

Question: Refazendo a pergunta:
Tenho uma tabela no Mysql onde preciso exibir o nome da pessoa assim que ela digita o seu RG.
Estou fazendo um código onde apenas tento fazer a pesquisa para ver se esta buscando normalmente, mas não consigo exibir este valor na tela.
Segue o código:
int main(){

    MYSQL conexao;
    int res;
    int esco = 2;
    char query[100];
    mysql_init(&conexao);
    if ( mysql_real_connect(&conexao, "localhost", "root", "", "teatro", 0, NULL, 0) ){
        sprintf(query,"select tb_aluno_nome from tb_aluno where tb_aluno_rg = '999999999';");
        res = mysql_query(&conexao,query);
        if (!res)
            printf("nome: %i",res);
        system("pause");
        return(0);

    }
}

Comment: coloque o código do que já foi feito ou explique melhor a situação, para ajudar a visualizar o seu problema
Comment: Talvez tirando o `!` de `if (!res)`... o `!` significa "negativo" (zero, null ou vazio), que me parece ser o contrário do que deseja.
Comment: Na verdade, o `!` significa _false_
Comment: Na verdade, o `!` significa *not*, não? :-)  -> [C Operators](https://www.w3schools.in/c-tutorial/operators/)
Answer: Testa ai meu bom!
int main() {
   MYSQL conexao;
   int res;
   int esco = 2;
   char query[100];
   mysql_init(&conexao);
   if ( mysql_real_connect(&conexao, "localhost", "root", "", "teatro", 0, NULL, 0) ){
       sprintf(query, "select tb_aluno_nome from tb_aluno where tb_aluno_rg = '999999999';");
       res = mysql_query(&conexao,query);
       if (res) {
           campos = mysql_fetch_fields(res);
           for (i=0; i < mysql_num_fields(res); i++) {
               printf("%s", (campos[i]).name);
           }
       }
   }
   mysql_close(&conexao);
   system("pause");
   return(0);
}

Como exibir o valor de uma query em C?


Login with a REST service (services module)

Question: I work with Drupal 7 (services 3.x) to implement a REST service. When I test a login request with this script:
$service_url = 'https://dev.mysite.org/api/blog/user/login.xml'; // .xml asks for xml data in response
$post_data = array(
  'username' => 'admin',
    'password' => 'admin',
    );
$post_data = http_build_query($post_data, '', '&'); // Format post data as application/x-www-form-urlencoded
// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string
curl_setopt($curl, CURLOPT_POST, true);             // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // POST this data
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
print "RESPONSE:\n";
var_dump($response);
// parse the response
$xml = new SimpleXMLElement($response);
$session_cookie = $xml->session_name .'='. $xml->sessid;
print "SESSION_COOKIE: $session_cookie";
file_put_contents('session_cookie.txt', $session_cookie);

I receive this error:
* upload completely sent off: 29 out of 29 bytes
< HTTP/1.1 401 Unauthorized: Missing required argument name
< Date: Sun, 09 Feb 2014 02:39:45 GMT
* Server Apache/2.2.22 (Ubuntu) is not blacklisted
< Server: Apache/2.2.22 (Ubuntu)
< X-Powered-By: PHP/5.3.10-1ubuntu3.9
< Expires: Sun, 19 Nov 1978 05:00:00 GMT
< Last-Modified: Sun, 09 Feb 2014 02:39:45 +0000
< Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
< ETag: "1391913585"
< Set-Cookie: DRUPAL_UID=-1; expires=Tue, 04-Mar-2014 06:13:05 GMT; path=/; domain=.dev.labdoo.org; secure
< Vary: Accept-Encoding
< Content-Length: 0
< Content-Type: text/html
<
* Connection #0 to host dev.mysite.org left intact
RESPONSE:
string(0) ""
PHP Fatal error:  Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/myuser/Desktop/test.php:23
Stack trace:
#0 /home/myuser/Desktop/test.php(23): SimpleXMLElement->__construct('')
#1 {main}

My REST service configuration is:

I followed this example to test the service.
It is activated the session authentication in the Services module.
It is activated application/x-www-form-urlencoded, json, xml....

UPDATE
It seems which the code has multiple mistakes....  I replaced my post_data variable for this:
$post_data = array(
  'name' => 'admin',
  'pass' => 'admin',
);

And now, I send the login request correctly ( I receive a 200 response),
but now, I try to parse the response message to get the cookie-session, I don't receive any response message. I am getting an error like this:
* upload completely sent off: 21 out of 21 bytes
< HTTP/1.1 200 OK
< Date: Wed, 12 Feb 2014 21:35:36 GMT
* Server Apache/2.2.22 (Ubuntu) is not blacklisted
< Server: Apache/2.2.22 (Ubuntu)
< X-Powered-By: PHP/5.3.10-1ubuntu3.9
< Expires: Sun, 19 Nov 1978 05:00:00 GMT
< Last-Modified: Wed, 12 Feb 2014 21:35:36 +0000
< Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
< ETag: "1392240936"
< Set-Cookie: DRUPAL_UID=-1; expires=Sat, 08-Mar-2014 01:08:56 GMT; path=/; domain=.dev.mysite.org; secure
< Content-Length: 1316
< Content-Type: application/xml
<
* Connection #0 to host dev.mysite.org left intact
RESPONSE:
string(1316) "
Fatal error: Unsupported operand types in /var/www/lbd/profiles/labdoo/modules/contrib/services/includes/services.runtime.inc on line 417

Call Stack:
    0.0000     334912   1. {main}() /var/www/lbd/index.php:0
    0.0347    4175712   2. menu_execute_active_handler() /var/www/lbd/index.php:21
    0.0348    4176376   3. call_user_func_array() /var/www/lbd/includes/menu.inc:517
    0.0348    4176756   4. services_endpoint_callback() /var/www/lbd/includes/menu.inc:517
    0.0366    4343036   5. call_user_func() /var/www/lbd/profiles/labdoo/modules/contrib/services/services.module:218
    0.0366    4343036   6. rest_server_server() /var/www/lbd/profiles/labdoo/modules/contrib/services/services.module:218
    0.0385    4449312   7. RESTServer->handle() /var/www/lbd/profiles/labdoo/modules/contrib/services/servers/rest_server/rest_server.module:39
    0.0432    4532668   8. services_controller_execute() /var/www/lbd/profiles/labdoo/modules/contrib/services/servers/rest_server/includes/RESTServer.inc:46
    0.0436    4534132   9. _services_controller_execute_internals() /var/www/lbd/profiles/labdoo/modules/contrib/services/includes/services.runtime.inc:106
    0.0436    4534176  10. _services_authenticate_user() /var/www/lbd/profiles/labdoo/modules/contrib/services/includes/services.runtime.inc:162

UPDATE 2
I am trying to create a new user to check if my error is related to working with an admin account. I tried (now with the script postman for Chrome) to create a new user via REST... It would be easy... but I wasn't ( I tested username,name,email,mail)...
Answer: This is the important bit:

HTTP/1.1 401 Unauthorized: Missing required argument name

Just change your payload to
$post_data = array(
  'name' => 'admin',
  'password' => 'admin',
);

Comment: Sorry @Clive, Is no it correct yet? I added the payload  as you comment.
Answer: Try watching this screencast, it helped me

Drupal 7 Tutorial - Web Services: Basics Part 1
and also take a look on X-CSRF-Token issue too
Drupal 7 Tutorial - Web Services: Basics Part 2
Comment: Thanks @sibiru. For the first tutorial, I followed all these steps, It helped me to fix my bug.... and with  the second tutorial, I would not implement tokens in my service yet.... I would like implement a simple authenticated service, tokens could be too complicated.
Answer: Finally, I have fixed the problem. It was a bug in the Services module. I updated from 7.x-3.5 to the 7.x-3.7 version, I followed the @sibiru tutorial and it started to work well.
Comment: Hi i am already using 7.x-3.15 but i am still getting this error


enable gzip compression on nginx give me long time server response

Question: I have a web application running on a very low web server (CPU: ARM926EJ-S, RAM: 128MB), when I enabled gzip on nginx, I found that the server takes longer to respond, and I don't know if there is something wrong with the configuration.
configuration:
<code>   gzip on;

   gzip_vary on;
   gzip_proxied any;
   gzip_comp_level 3;
   gzip_buffers 16 8k;
   gzip_http_version 1.1;
   gzip_min_length 256;
   gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
</code>
gizp enabled response time

gizp disabled response time
Answer: It seems like the CPU is just too weak to compress the data in a timely manner. Obviously for you to have any benefit the compression and transfer of the compressed data needs to be faster then just pure uncompressed data delivery.
Try reducing the compression level to 1. If it still takes longer than uncompressed data, you are SOL I guess, and need to live with the relative slow loads of uncompressed data :/
Comment: Depending on the content you serve [precompressed files](https://nginx.org/en/docs/http/ngx_http_gzip_static_module.html) might be an option.
Comment: thank you for answer, and  compression level 1 still takes longer than uncompressed data
Comment: @GeraldSchneider thank you very much this way work fine, but I should upload my static folder .gz


Creating smaller menus from chunks of a bigger menu

Question: I have this really big nav menu in Drupal 7. The top-level links go to child pages. Each of these child pages has several pages hierarchically under them.
On these child pages, I want a block that shows links to sibling pages and children of the current page (But not children of sibling pages).
It seems like it should be relatively easy, but I've been beating my head against a wall all afternoon. Any help? Thanks!
Comment: Have you come across [Menu Block](http://drupal.org/project/menu_block/) before? If I understand you right it does exactly what you're after
Comment: That's cool, I wasn't sure if it was what you wanted (hence the comment). Mikey had enough courage in his convictions to actually put it as an answer so I'd go ahead and accept that one :)
Comment: Okiedokie then. Upvoted both of yours comments so you at least get some rep out of it. :)
Answer: What you are describing is the primary feature provided by the Menu block module.


Relation of ellipse semi-axes with rotation angle and projection length

Question: In the following setup, assume $w$ (length of the projection of the ellipse) and $\theta$ (the rotation angle) are known. I want to know what equation(s) do I have here that helps me to derive the semi-axes ($a$ and $b$) of the ellipse based on $w$ and $\theta$.
I know the semi-axes are not unique in this problem but only the relation is needed.
Comment: In [this answer to related question](http://math.stackexchange.com/questions/33520/the-locus-of-two-perpendicular-tangents-to-a-given-ellipse/33555#33555), I show that $$x_{\star} = \sqrt{a^2\cos^2\phi + b^2\sin^2\phi}$$ where my "$x_{\star}$" is half of your "$w$", and my "$\phi$" is your "$\theta$". So, $$w = 2\;\sqrt{a^2\cos^2\theta + b^2\sin^2\theta}$$
Answer: $$\large 4(a^2\sin^2\theta+b^2\cos^2\theta)=w^2$$
Equation of an ellipse is:
$$\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$$
Diffrentiate:
$$\frac{dy}{dx}=-\frac{b^2}{a^2}.\frac{x}{y}$$
Polar form of ellipse:
$$P(\phi)\equiv(a\cos\phi,b\sin\phi)$$
Slope of tangent in polar form:
$$m=-\frac ba\cot\phi$$
Equation of tangent:
$$\frac xa\cos\theta+\frac yb \sin\theta=1$$
Distance between two parallel lines in form:
$$ax+by+c=0\\ax+by+c'=0$$
is:
$$d=\frac{|c-c'|}{\sqrt{a^2+b^2}}$$

Firstly those two lines are tangent at two points, and they are parallel too. So in the parametric form the slope of tangent at these two points – let them be called $P(\theta_1),Q(\theta_2)$ – must be equal.

slope $\propto\cot\phi$, where $\phi$ is parametric angle.
$$\implies \cot \theta_1=\cot\theta_2\implies \theta_1=\pi+\theta_2\quad\text{since}\quad\theta_1\ne\theta_2$$

Secondly the distance between the two tangents / two parallel lines must be $w$:

Tangent Lines are $$\frac xa\cos\theta_1+\frac yb\sin\theta-1=0\\\frac xa\cos\theta+\frac yb\sin\theta+1=0$$ (after putting $\theta_2=\pi+\theta_1$). So taking distance between them:
$$\frac{|1-(-1)|}{\sqrt{\frac{\cos^2\theta_1}{a^2}+\frac{\sin^2\theta_1}{b^2}}}=w$$

Thirdly slope of tangents at these points is $\theta$ so:
$$-\frac{b^2}{a^2}\cot\theta_1=\tan\theta$$
Try the rest yourself.
Comment: I edited your answer a bit, mostly to avoid MathJax error messages but also to improve the language a bit. But your second point looks somewhat confusing; I guess you'd want some more indices there, maybe use $\theta_1$ throughout? The first point is confusing as well: why switch from $\phi$ to $\theta$? I won't do too much guessing here when editing, since I've got a competing answer and don't want to edit yours until it looks like mine just because that's what I expect an answer to look like here.
Comment: @MvG thanks, such edits are always welcome, sorry for being lazy, will improve it, thanks for your suggestions
Answer: The unrotated ellipse can be parametrized as
$$\begin{pmatrix}a\cos\varphi\\b\sin\varphi\end{pmatrix}$$
so the rotated form (given the fact that you are apparently measuring rotation angle against vertical instead of horizontal and clockwise instead of counter-clockwise) would be
$$\begin{pmatrix}
\sin\theta & -\cos\theta \\
\cos\theta & \sin\theta
\end{pmatrix}
\begin{pmatrix}a\cos\varphi\\b\sin\varphi\end{pmatrix}
$$
The $x$ coordinate of that is
$$x=a\cos\varphi\sin\theta - b\sin\varphi\cos\theta$$
To look for extremal values in $x$ direction, compute the derivative:
$$\frac{\mathrm dx}{\mathrm d\varphi} =
-a\sin\varphi\sin\theta-b\cos\varphi\cos\theta\overset!=0\tag1$$
Take this equaton together with a second equation to express your width. All my ellipses so far are centered around the origin, so the maximal $x$ coordinate is at distance $\frac w2$ from the vertical axis, which leads to the second equation
$$x=a\cos\varphi\sin\theta - b\sin\varphi\cos\theta\overset!=\frac w2\tag2$$
Now you can combine these two equations to eliminate $\varphi$. I did so using resultants. The result is a single equation
$$w^2=(2a\sin\theta)^2+(2b\cos\theta)^2\tag3$$
Actually the resultants offer a second possible solution, namely $(a\sin\theta)^2+(b\cos\theta)^2=0$, but that's a degenerate situation where at least one of your semi-axes has length zero.
I coudln't yet make Wolfram Alpha do the variable elimination. In case you are interested in the Sage code behind my computation, here it is:
<code>sage: R1.<t, sintheta, costheta, a, b, w> = QQ[]
sage: cosphi = (1-t^2)/(1+t^2) # rational parametrization
sage: sinphi = (2*t)/(1+t^2)
sage: v1 = vector([a*cosphi, b*sinphi])
sage: rottheta = matrix([
....: [sintheta,-costheta],
....: [costheta,sintheta]])
sage: v2 = rottheta*v1
sage: c1 = v2[0].derivative(t)
sage: c2 = v2[0] - w/2
sage: c3 = c1.numerator().resultant(c2.numerator(), t)
sage: c3.factor()
(4) * (-4*sintheta^2*a^2 - 4*costheta^2*b^2 + w^2) * (sintheta^2*a^2 + costheta^2*b^2)
</code>


Nagios Graphing on Ubuntu server

Question: I have got most of my nagios install working, the only thing I am struggling with is any of the graphing pages, e.g. when I go onto the map page you get a page not found error.
When I try and compile, half way down the messages I get this message -
GD, PNG, and/or JPEG libraries could not be located
I have read you need these library's - gd-devel, png-devel, jpeg-devel but i'm not sure what they are called under Ubuntu, if i do and  apt-get install it cant find them.
Anyone got any pointers, i'm running Ubuntu Server 10.10
Cheers
Luke
Answer: For compiliation, you'll need the dev packages as the header files are included in those. You can use the interactive tool aptitude to search for package names, or use the command apt-cache pkgnames to list all available packages and grep your way through this list.
Generally, those packages will have names like libnpg-dev, libjpeg-dev, libgd2-xpm-dev etc.
Comment: i managed to find the missing one using apitude, for info it was zlib1g-dev i was missing

Nagios Graphing on Ubuntu server


How to access one private instance variable in ios

Question: I have a question want to consult you。The following:
class A is from the ios framework, one instance variable B of the Class A is not public, can i through the getter methods defined in the category C  to access instance variable B ?the category  C is  custom for the class A 。
example, the instance variable _viewDelegate  of the class UIView.can I create a category C of the UIView  to access instance variable _viewDelegate?   if define method -(UIViewController*)viewDelegate in the category C;
ThankYou,First !
Comment: Um, what? What are you asking?
Comment: sorry ,My English is not very good!But you should be able to read it!
Comment: possible duplicate of [Accessing private variables from an external class - iOS](http://stackoverflow.com/questions/11209843/accessing-private-variables-from-an-external-class-ios)
Answer: If the question is "can I access private variables via Category" then the answer is - depends.
First of all, the variable must be defined in the .h file.
If it is, then if marked as readonly, you can only read it. For example:
@property(nonatomic,readonly) somePropertyOfClassA
Otherwise, you can read/write to the property directly without a getter/setter, for example @property(nonatomic) NSInteger tag
The UIView _viewDelegate is marked as @package which means that the member is accessible only from the framework in which it is defined, which is the ios framework.


Parameters of a function for library Flet

Question: I'm trying to initiate myself to the library flet.
For example :
def btn_clicked(e):
 pass

def btn_clicked2():
 pass

How don't really understand what is the difference, sometimes I put a "e", and it works, but in another function, it could be not working.
I don't find the answer on Flet website, if someone could explain to me it would be great thanks a lot !
Answer: The e parameter you provide to your callback function is the event object, which contains some useful data about the event (ex: a button click) which triggered this callback. Flet passes this information to your callback function when calling it.
This event object e is of type ControlEvent, but could sometimes be of another type - which inherits from ControlEvent - containing more data on the event. (example here)
5 basic information are contained in the ControlEvent (see them here) - below, the description of the most useful ones:

e.control: the control through which the event got triggered
e.data: some possible extra data on the event
e.page: the page on which the event was triggered
e.name: the event's name (ex: "click", "dismiss")

If you find the need to see all the information contained in the event object, you could just use print statements as below:
import flet as ft

def main(page: ft.Page):
    def handle_click(e: ft.ControlEvent):
        print(e.__dict__)  # all
        print(f"e.data: {e.data}")  # single info
        print(f"e.name: {e.name}")  # single info

    page.add(ft.ElevatedButton("Press me to see data", on_click=handle_click))

ft.app(target=main)

Note that instead of e, you could name that parameter as you want or could even ignore it using the _ if you don't find it useful - we are in python. e is the short form for event, and has gotten quite popular in the Flet community.


Boolean Expression x'y + x(x + y')

Question: I'm still learning Boolean Algebra so I apologise if the question seems pretty straight forward. After working on this problem I thought the answer was 'x', my working out was:
x'y + x(x + y')
= x'y + xx + xy'
= x'y + x + xy'
= x + xy'
= x
but after runnng this through a logic circuit I realise if x = 0 and y = 1 then the ouput does not equal x.
Can someone help me simplify this expression
Comment: You lost the $x'y$ from the 3rd to the 4th line.
Comment: Yeah I thought I could simplfy that but turns out I cant
Comment: Maybe you wanted to apply something similar as in your last step. There it works because $x+xy' = x(1+y') \stackrel{1+y' = 1}{=} x$. But from the 3rd to the 4th line the situation is different.
Answer: Two really useful principles are:
Absorption
$x(x+y)=x$
$x+xy=x$
Reduction
$x(x'+y)=xy$
$x+x'y=x+y$
With those:
$x'y+x(x+y')\overset{Absorption}{=} x'y+x\overset{Reduction}{=} y+x$
Answer: You correct until the step

x'y + x + xy' = x + xy'

But you can go from there and see that x'y + xy' = x ⊕ y.
This follows since x'y = 1 ⇒ x=0, y=1 and xy' = 1 ⇒ x=1, y=0.
Following this x ⊕ y + x can be simplified.

x ⊕ y + x = x + y

With your final solution x'y + x(x + y') = x + y.

Boolean Expression x'y + x(x + y')


Node showing teaser, but not content

Question: My view is showing the list of teasers correctly, but when I want to read more and see the full body text I get the "Page not found" error. I've been searching through all my settings, permissions etc. and can't find the error. It might have something to do with the view, but I can't see any error there either. Any ideas?
Screenshot of the view settings:

I can easily find the node body in the MySQL table field_data_body.
Comment: Does the read more link contain the correct url? And what happens when you type the correct url in the browser bar?
Comment: Yes, the read more link contains the correct url.
Comment: Cross check with the read more URL and the node page URL, whether they are same or different. And also check your URL redirects settings.
Comment: They are the same but with different node id. `/node/%/`
Answer: I have an alternative solution in case it is not working. Include title, body (trimmed) and global text contain
Read More

Make sure include node path and drag it above so that it appears in replacement pattern down below
Answer: You can try this:
Add 'title field' two times as shown in below image.

For last 'title field', do the setting as shown in image below.

Make sure that "Link this field to the original piece of content" is checked. In Rewrite results your text could be anything like "Read more" or "Read full story"...
By this you will be directed to your original node page.
Comment: Getting a "Page not found" when I click "Read full story".
Comment: Have you checked by writing URL like localhost/example/node/nid for that particular content. Is that working fine ? Otherwise problem is in path. Check alias if you have used path auto.
Comment: No, it's not working when I enter direct url. How can I fix path?
Comment: Make sure that nid you entered was correct, because if its not working than question arises that 'where is the content ?' Every content has a system path like node/nid.
Comment: Well, parts of the content is shown in the teaser, so it's there somewhere. But not when I want to see the node with the full body etc.

Node showing teaser, but not content


Statistical analysis is very subjective

Question: After studying probability theory and inferential statistics by the famous Cassela and Berger's book, I'm starting to try my own analysis, of course, just small stuff only for training.
I'm trying to know if the column named Tip from the famous dataset called TIPS is normally distributed or not.
This looked like an easy task but it's not. That's what I did so far:

I can't use normality tests like Shapiro-Wiki, they aren't reliable because the impact of the sample size on these tests.

I can't use histograms either, in order to have a good choice of the number of bins I need to know if the data is normally distributed or not, for example Scott's and Sturges choices are more suitable for normal distributions instead of Friedmann-Diaconis choice.

I've analysed the skewness and the kurtosis of the data, which gives me 1.45 and 3.64 with minor differences between fisher and moment methods. I've heard different suitable ranges, I don't think there is a consensus here.

What left for me is using the Q-Q plot:

However this is highly subjective, there are some points fitted on the line but the tails are going further. I wouldn't bet my family savings on that. So how can I know how far from normality is good for me? Are there any method missing in my analysis? I fell hopeless, all this are very subjective for me as a former pure mathematician who are trying to become a statistician someday. I really need help!
Comment: We would expect 95% of points to be between +/-2 and 99% between +/-3 . We would expect virtually zero to be more than 4 or 5 in modulus. You have some residuals as big as 10 in modulus, the probability of this is basically zero.
Answer: The answer to the question "normally distributed or not" is very easy:  The answer is ALWAYS "not."  So dismiss that question and move on.  The more important questions are "In what ways does the distribution differ from normality?" and "how much does it matter?"
Regarding the first question, your q-q plot shows the skewness very clearly.  It also shows evidence of discrete components in that there are horizontal lines. If nothing else, this helps you to understand your data better - maybe there are some issues to investigate that you had not anticipated before.  (This is the essence of "exploratory data analysis.")
The answer to question "does it matter?"  depends on the purpose of the analysis.  If you are interested on predicting a new data value, it matters a great deal.  If you are constructing a confidence interval for a mean, it matters less.  If you are constructing a confidence interval for a standard deviation, it matters a great deal. More study is needed here.  Simulation is also very helpful.
Comment: It was just a training, I think I should have had an objective in mind. I feel so dumb now lol

Statistical analysis is very subjective


I use netbeans IDE and i'm getting ArrayIndexOutOfBoundsException when i use Integer.parseInt(args[0]). why? How to resolve this error?

Question: public static void main(String[] args) {

    int n;
    n = Integer.parseInt(args[0]);
    if(n>100)
    {
        System.out.println("The number is greater than 100.");
    }
}

Comment: Did you pass any arguments when you ran this?
Comment: How many elements are there in `args`?
Comment: @VeeraKannadiga I doubt whether that will help much.  I suspect that the issue here is simply that Shanti doesn't know how to get NetBeans to pass command line arguments to the program.
Comment: no @DavidWallace
Comment: yes sir you are right .I'm actually new to java @DavidWallace
Comment: This page  explains how to do it.  http://sanduntech.blogspot.co.nz/2015/03/java-command-line-arguments-in-netbeans.html
Comment: Ty sir @DavidWallace
Answer: The args array contains the arguments given to the program (command line parameters). You can give these either via:

the project run settings in an IDE
the command line

If you run your program without any arguments, the array will however be empty. Therefore, no item will be on index 0 and the ArrayIndexOutOfBoundsException is thrown.
If you want to fix this, you will either have to:

pass at least one argument via one of the mentioned methods aboven.
change your code so it does not depend on command line parameters.
Answer: change your code this way:
public static void main(String[] args) {
    if(args != null && args.length > 0) {
    int n;
    n = Integer.parseInt(args[0]);
    if(n>100) {
        System.out.println("The number is greater than 100.");
    }
    }
}

If you want also to handle the fact that args[0] could not be an integer, you can change it this way:
public static void main(String[] args) {
        if(args != null && args.length > 0) {
        int n;
try {
        n = Integer.parseInt(args[0]);
        if(n>100) {
            System.out.println("The number is greater than 100.");
        }
catch(NumberFormatException e) {
System.err.println("Not a number");
}
        }
    }


Exceção java.lang.NumberFormatException (arquivos)

Question: Galera, pelo o que eu chequei este código está tudo correto, inclusive depois do String[] linha = arquivo.split(","); se dermos um System.out.println(linha[0] + linha[1] + linha[2]) ele retorna certinho TV LED 1290.99 1(linha do arquivo original TV LED, 1290.99, 1), mostrando que na posição 0 = TV LED, posição 1 = 1290.99 e posição 2 = 1. Mas na hora de passar a String 1 da posição 2 para int ele dá essa exceção... Por quê ?
        Locale.setDefault(Locale.US);
    Scanner sc = new Scanner(System.in);
    List<Product> list = new ArrayList<>();

    System.out.println("Digite o caminho do arquivo .csv.txt:");
    String caminho = sc.nextLine();

    File file = new File(caminho);
    String acharDiretorio = file.getParent();
    boolean criaSubPasta = new File(acharDiretorio, "\\out").mkdir();
    String criaArquivo = acharDiretorio + "\\out\\summary.csv";

    try(BufferedReader br = new BufferedReader(new FileReader(caminho))){

        String arquivo = br.readLine();

        while(arquivo != null) {
        String[] linha = arquivo.split(",");

        String nome = linha[0];
        double preco = Double.parseDouble(linha[1]);
        int quantidade = Integer.parseInt(linha[2]); //erro aqui, java.lang.NumberFormatException

        list.add(new Product(nome, preco, quantidade));
        arquivo = br.readLine();
        }
        try(BufferedWriter bw = new BufferedWriter(new FileWriter(criaArquivo))){

            for(Product produto : list) {
                bw.write(produto.getNome()+", "+ produto.total());
                bw.newLine();
            }
            System.out.println(criaArquivo + ": SUCESSO");
        }

    }
    catch(IOException e) {
        e.getMessage();
    }

Comment: Poste o log da exceção, ele mostra o que foi encontrado na variável que não foi possível parsear.
Answer: É porque tá vindo um espaço em branco junto com o 1 depois da vírgula, tente um
linha[2].trim();

antes de fazer o parse pra Integer.


ARIA Accessibility in Angular 2 and 4

Question: I have been manually including ARIA attributes in my component templates when I came across the angular-aria module: https://docs.angularjs.org/api/ngAria
However, this is for AngularJS. Is there any equivalent module for Angular 2 and 4 which silently injects aria attributes on components at runtime?
I have looked at this question: How do I include ngAria in and Angular 2 application? but it doesn't seem to have an answer.
Answer: Your question has a short answer and a long one, let's see what are those?
Is there any equivalent module for Angular 2 and 4 which silently injects aria attributes on components at runtime?
Let's first refer to the KB for AngularJs:

Using ngAria is as simple as requiring the ngAria module in your
  application. ngAria hooks into standard AngularJS directives and
  quietly injects accessibility support into your application at
  runtime.

As Angular 2 has tried to have a built-in support for ARIA, there is no such equivalent module needed, and there is no supplementary one which I'm aware of.
So, Yes, it's implicitly supported, and No, there is no such a module (required).
Accessibility use cases for Angular include, at least: (Quoted from Marcy Sutton)

Handling aria-disabled, aria-required, and aria-checked for custom
controls
Handling aria-* value attributes on custom controls using ngModel
Discouraging click events on non-semantic div elements (could be done
through documentation)
Text alternatives: Labels for form controls, alt for images

You can simply investigate the above by inspecting the rendered output of your Angular template.
Final Note: It should be considered, anyway, that still complying manually with the rules of ARIA use are required, which is regardless of the version of the angular(JS or 2+) being use; e.g., avoiding to assign the click events to non-semantic elements, or embedding a giving label to elements which are not labelable.

ARIA Accessibility in Angular 2 and 4


$f$ is integrable on $[a,b]$ then $\int_{x}^{x+h}\frac{|f(t)-f(x)|}{h}dt\to 0$ if $h\to 0$ for almost all $x$

Question: I am trying to prove if $f$ is integrable on $[a,b]$ then $\int_{x}^{x+h}\frac{|f(t)-f(x)|}{h}dt\to 0$ if $h\to 0$ for almost all $x$ but I am not sure.
Attempt - Let $\phi(x)=\int_{a}^{x}\frac{|f(t)-f(y)|}{h}dt$. So $\int_{x}^{x+h}\frac{|f(t)-f(x)|}{h}dt=\phi(x+h)-\phi(x)\to h\phi'(x)=|f(t)-f(y)|\to0$ because $t\to y$ as $h\to 0$.
Answer: The problem with what you wrote is: if $f$ is not continuous, $\phi$ is not guaranteed o be derivable with derivative $f$ (sad).
What you can do:
$$
\int_x^{x+h} \frac{|f(t) - f(x)|}{h} dt
= \int_0^1 {|f(x + \theta h) - f(x)|} d\theta
$$
and now use the dominated convergence theorem.


What is the difference between base tables and data tables for content entities?

Question: Recently, Views was updated to use data tables (the data_table annotation on @ContentEntityType) by default. See the change record at https://www.drupal.org/node/2433153.
This caught me out since I had both defined on my entity. I hadn't thought much about it, and I don't even know which example got me to do that. I think I may have based mine off \Drupal\comment\Entity\Comment.
Anyway, what's the difference in terms of when they get used? It seems that, despite having defined data_table, all my data was being saved in the base_table anyway, and this caused Views not to work until I removed the data_table property from my @ContentEntityType definition altogether.
It seems my fields ought to be using data_table. What did I do wrong in my entity? I'm porting a module and thus using 8.0.0-beta9.
Answer: My guess is that you didn't actually set the translatable flag to TRUE. The data_table is only used then, but I guess views gets confused if you have it set but the entity type is not translatable, sounds like a bug in views but it also doesn't make sense to define the table and not have your entity type translatable.
The difference of those two tables is that it contains a row for each translation of your entity type. For example, {ńode} has just the nid, vid (which is the current revision), type and uuid. All the other fields are in the data table, like the node title, status, changed date, and so on.


Retorno array em SQL em uma variável php, para posterior montagem de HTML

Question: Preciso fazer uma pesquisa no banco em uma variável data e retornar apenas os Anos. Para isto fiz o seguinte :
No controle:
public static function getDataAnos() {
    $bd = new Banco(BANCO_HOST, BANCO_USUARIO, BANCO_SENHA, BANCO_BASE_DADOS);

    $sql = "SELECT YEAR (postagens.data) as ano FROM postagens GROUP BY ano";
    return $bd->executarSQL2($sql);
}

Na biblioteca para acessar o Banco:
public function executarSQL2($sql)
{

    $resultado = $this->query($sql);
    return $resultado->fetch_array();
}

No controle (disponibiliza ao carregar a página):
$anos = Postagens::getDataAnos();

Na visão:
<?php
  if ($anos !== false) {
      echo "
";
      var_dump($anos);
      foreach ($anos as $a) {
          echo "  <input type='radio' name='filtro' value=" . $a. ">" . $a. "
";
      }
      echo "
";
  }
?>

O PROBLEMA:
Tenho neste momento no banco 4 datas uma 2011, duas 2015 e uma 2017. O que deveria estar me retornando um array com [0] - 2011, [1] - 2015, [2] - 2017. Mas o var_dumps que coloquei esta mostrando isto:
array(2) { [0]=> string(4) "2011" ["ano"]=> string(4) "2011" }

Já tentei mudar no banco esta linha:
return $resultado->fetch_array(MYSQL_NUM);

Ai o retorno do var_dumps muda para:
array(1) { [0]=> string(4) "2011" }

Coloquei só as partes do código que achei relevante para o problema, é minha primeira pergunta aqui, espero ter conseguido demonstrar o problema e desde já agradeço por qualquer ajuda.
Comment: Você está usando o PDO para conectar-se com o banco de dados?
Answer: O problema é que a função fetch_array retorna apenas a proxima linha do resultset retornado na função query(). Para retornar todas as linhas do resultset pode-se usar a função fetch_all().
public function executarSQL2($sql)
{

    $resultado = $this->query($sql);
    return $resultado->fetch_all();
}

Recebendo dados na view
Como a função getDataAnos retorna um array de duas dimensões o conteudo laço for deve ser modificado para que a variavel $a não seja impressa (já que ela representa um vetor). Em fim, da para resolver assim:
 echo "  <input type='radio' name='filtro' value=" . $a['ano']. ">" . $a['ano']. "
";

Comment: Resolveu o problema, muito obrigado!

Mas apareceu um novo problema
No mesmo código da visão anterior o var dumps esta retornado certo:
    array(3) { [0]=> array(1) { [0]=> string(4) "2011" } [1]=> array(1) { [0]=>
    string(4) "2015" } [2]=> array(1) { [0]=> string(4) "2017" } }

Mas na hora de mostrar no html ao inves de mostrar os anos esta mostrando apenas ARRAY e o erro:  Array to string conversion in C:\xampp\htdocs\TrabBlog\visoes\listar.php on line 50
Comment: editei a resposta.


How can I use a boost function to transform the parameter types?

Question: I want to create a boost function object of the following signature:
void (int, boost::uuid);

However, I would like to bind it to a function of the following form:
void (SomeType, boost::uuid)

Where the SomeType argument comes from another function call, so that if I were to call it straight out it would look like:
SomeType myOtherFunction(int);//Prototype
...
myFunction(myOtherFunction(int), myUUID);

In other words, I want the top level function object to completely hide the concept of SomeType and the call to myOtherFunction from the user. Is there a way to do this with one or more boost::function objects created with boost::bind calls?
Answer: Functional composition: Live On Coliru
#include <boost/uuid/uuid.hpp>

struct SomeType {};
SomeType myOtherFunction(int) { return SomeType(); }
void foo(SomeType, boost::uuids::uuid) {}

#include <boost/bind.hpp>
#include <boost/function.hpp>

int main()
{
    boost::function<void(int, boost::uuids::uuid)> composed;

    composed = boost::bind(foo, boost::bind(myOtherFunction, _1), _2);
}

Anyways, in c++11 you'd write [](int i, uuid u) { return foo(myOtherFunction(i), u); } of course


Install new site from existing config plus data migration

Question: I need to install a new site on drupal 8 from existing config plus data like content, users.
I used config installer to install a new site from existing config.
How to make it import content after complete configuration import.
New ideas and other solutions are welcomed.
Answer: After doing some research I found multipurpose corporate profile a distribution which does the job and accelerates the development process.
It deserves discovering its key features.


How to add Login menu to the first sidebar (secondary menu)

Question: I need to remove from the 'secondary menu' the login/logout menu from the header, and display in the first sidebar,
It doesnt seem to be as easy as just draging and dropping in blocks,
Comment: Cleared the cache after moving block? Did you save the blocks' settings?
Comment: Use LoginToboggan to further expand your login functionality.
Answer: Try turning off the secondary menu (admin/structure/menu/settings).
Then, on the blocks admin screen (admin/structure/block), place the User menu in the first sidebar.


SQL to return matches from multiple queries

Question: I need to return values that appear across two or more queries from the same table. Feeling a bit like a noob here but just can't see the wood for the trees.
I have a table of users assigned to different groups. I need to return only the users that appear in all of the requested groups:
User   Group
frank  1
Jane   2
Tom    2
frank  2
Jane   1
Tom    3

This is want I need to output:
Result for Group 1 & 2:
frank
Jane

Result for Group 2 & 3:
Jane
Tom

Seems a very 101 question, but grateful for any pointers.
Answer: select user
from users
where group_id in (1,2)
group by user
having count(*) = 2;

You need to adjust the having count(*) = 2 condition to the number of groups that you want.
If a user can be assigned to the same group more than once, then Madhivanan's comment need to be taken into account:
select user
from users
where group_id in (1,2)
group by user
having count(distinct group_id) = 2;

(I used the column name group_id because group is a reserved word and should be used as a column name).
Comment: @a_horse_with_no_name Fantastic,, seems to work a treat :)
The column names were just for reference, but take your point. The records are unique per group as well, but good point for future reference.
Again, many thanks for the quick response :-)
Answer: select user from table
where group in (1,2)
group by user
having count(distinct group)=2


Reaproveitamento do HttpClient e ciclo de vida de um ApiController

Question: Com base nesse site e também em algumas respostas do StackOverflow [en] eu cheguei a conclusão de que não deveria usar a classe HttpClient em um bloco using apesar da mesma implementar IDisposable. Isso ajudaria no reaproveitamento do objeto já instanciado e traria melhorias de performance entre outras.
Mas considere o seguinte trecho de código:
public class MyServiceController : ApiController
{
    private static HttpClient _httpClient = new HttpClient();

    public void Post()
    {
        // ...
        var result = await _httpClient.GetAsync("https://pt.stackoverflow.com");
        // ...
    }
}

Minha API está consumindo um outro serviço, mas se quando falamos do ciclo de vida do MyServiceController, não haveria reaproveitamento já que cada requisição do Post criará uma nova instância da classe, correto? Nesse caso eu poderia implementar normalmente usando o bloco using?
Comment: @LeandroAngelo obrigado por seu comentário. Deixando o `HttpClient` público na classe `startup` não poderia me trazer problemas se `MyServiceController` receber muitas requisições simultâneas?
Comment: Se você torná-lo público e inicializar na startup
Answer: Eu criaria uma BaseApiController abstrata herdando a ApiController e adicionaria o HttpClient como público lá
public  abstract class BaseApiController : ApiController
{
    public static HttpClient meuHttpClient { get; set; }
}

E faria a inicialização no _Application_Start() da Global.asax.cs
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    BaseApiController.meuHttpClient = new System.Net.Http.HttpClient();
}

Assim você muda a herança das suas Controllers para a BaseApiController e poderá utilizar essa instância do HttpClient que foi incializado no início da aplicação.
public class MyServiceController : BaseApiController
{
    public void Post()
    {
        // ...
        var result = await meuHttpClient.GetAsync("https://pt.stackoverflow.com");
        // ...
    }
}

Comment: muito obrigado por usa resposta, mas ainda estou com dúvidas quando a [esse comentário](https://pt.stackoverflow.com/questions/351630/reaproveitamento-do-httpclient-e-ciclo-de-vida-de-um-apicontroller?noredirect=1#comment705633_351630).


Is there performance difference in image source file than base64?

Question: I am wondering if there is a performance difference between using pictures as base64, compared to using actual files, that user has to download on fly.
Comment: It depends. Base64 is actually faster, as the complete content is loaded once, but the page is displayed later, as everything is loaded synchronous.
Answer: An image with an HTTP URL of its own:

Requires a separate HTTP request (which is slow on HTTP 1 but fast on HTTP 2)
Can be loaded in parallel with the resource that references it
Can be cached so it doesn't need to be requested for subsequence pages or reloads of the initial page
Probably requires fewer bytes to transfer than a Base64 equivalent
Answer: using pictures as base 64 would be reduced the loading of images in webpage rather than downloading the source images.
dont really sure because external source images would be got cached by browser anyway after first load.
and looks like the base64 did not got cahced from browser
you can do some research from this:
https://varvy.com/pagespeed/base64-images.html


Windows 7 network performance tuning for LAN

Question: I want to tune Windows 7 TCP stack for speed in a LAN environment.
Bit of background info: I've got a Citrix XenServer set up with Windows 2008R2, Windows 7 and Debian Lenny with Citrix kernel, Windows machines have Tools installed the iperf server process is running on different host, also Debian Lenny. The servers are otherwise idle, tests were repeated few times to confirm results.
While testing with iperf 2008R2 can achieve around 600-700Mbps with no tuning what so ever but I can't find any guide or set of parameters that will make Windows 7 achieve anything over 150Mbps with no change in TCP window size using -w parameter to iperf.
I tried using netsh autotuining to disabled, experimental, normal and highlyrestricted - no change.
Changing congestionprovider doesn't do anything, just as rss and chimney.
Setting all the available settings to same values as on Windows 2008R2 host doesn't help.
To summarize:

Windows 2008R2 default settings: 600-700Mbps
Debian, default settings: 600Mbps
Windows 7 default settings: 120Mbps
Windows 7 default, iperf -w 65536: 400-500Mbps

While the missing 400Mbps in performance I blame on crappy Realtek NIC in the XenServer host (I can do ~980Mbps from my laptop to the iperf server) it doesn't explain why Windows 7 can't achieve good performance without manually tuning window size at the application level.
So, how to tune Windows 7?
Answer: Try enable RSS and TCP Offload Engine:
netsg int tcp set global rss=enabled
netsh int tcp set global chimney=enabled

Comment: That's the default on Windows 2008R2, it doesn't help.
Comment: Try disabling them.
Comment: disabled, enabled no difference
Answer: It could be a different network driver in Windows 2008R2 vs Windows 7.
Also, does xenserver always provide the same virtual nic to Windows 2008R2 and Windows 7?
Because if it's different then a different driver will be loaded.
There may be some performance differences.
EDIT:
I just remembered that windows 7 by default has very small send/receive buffers.
In some app's I was developing I found that under windows 7 it was something pathetic like 8kB.  Under ubuntu linux it's around 120kB.  You may read somewhere that the limit is 64kB.  This is actually incorrect for later versions of windows.  I've found it can be set to even as high as 1MB and beyond.  Although little performance increase will be noticed when it's this large.
This link provides some tcp tuning parameters in the registry that apply system wide.
Be aware that many of those options can be overridden by applications themselves.
http://www.psc.edu/networking/projects/tcptune/
http://www.psc.edu/networking/projects/tcptune/OStune/winxp/winxp_stepbystep.html
Try increasing the window size and send/receive buffers.  Hopefully those registry settings in the link still apply in windows 7.
Comment: Then why if I set larger TCP window the speed increases? And no, XenServer doesn't change the presented NIC.
Comment: I was only addressing that this might be a reason.  I'm a developer and I happen to be developing an application that's pushing loads of data at near gigabit speed.  However, developing on virtualbox I discovered performance differences with different nic drivers.  Yes, increasing TCP window will increase throughput because there will be less ack return packets.  Have you shut down all the other VM's in Xen to ensure that windows is the only one using it?
Comment: My usual usage of network on the Xen host is below 60-90KiB/s. And checked the driver, it loads the same one. As a side note, Xen and Virtualbox are completely different hypervisors, one is type 1 the second is type 2. Besides, I've seen the same performance problems with bare-metal installs. I mainly mentioned virtualization to rule out hardware problems.
Comment: I just remembered something.  Details in main answer.
Answer: MTU?
http://networking.nitecruzr.net/2007/11/setting-mtu-in-windows-vista.html
Comment: default, at 1500
Answer: TCP Autotuning (which you're already ruled out), MTU which has already been addressed and MMCS (Multimedia class scheduling) are usually the big differences. Since MMCS hasn't already been addressed, take a stab at disabling it.
Do ensure that your tcp window autoscaling is disabled if you're at or near LAN speed.
Instructions are available here: http://smallvoid.com/article/winnt-services-mmcss.html
Comment: I'm not sure if I did change it (as it has been over 6 months since) but it looks promising, I'll try it tomorrow.
Comment: Didn't help by much, made the performance about 10-20% better.
Answer: You should not see Realtek driver inside of Windows as a virtual machine on Citrix XenServer. If you do, that means you do not have XenTools installed. The Realtek NIC you see, is an emulated one provided by QEMU service inside of Dom 0 (domain 0). After install of Windows OS, before you do anything else, especially application install, you need to install XenTools. Also, the speed is hardcoded after XenTools is installed (As noted in the VM User Guide), as there is no limit to speed on a virtual device.
Comment: from opening question: "Realtek NIC in the XenServer **host**"


Rename parts of file names that match a pattern

Question: Say I have a list of file names like this:
some-file.ts
my-project-service.ts
other.ts
something-my-project.ts

I need to change the file names that have my-project in them to have just that part renamed to $appname$.
So my-project-service.ts would become $appname$-service.ts
And I need to do this recursively from a root directory.
I seem to be to be hopeless at PowerShell so I thought I would ask here to see if anyone can help me out.
Comment: [This](https://blogs.technet.microsoft.com/heyscriptingguy/2013/11/22/use-powershell-to-rename-files-in-bulk/) might help you.
Comment: @MartinBrandl Thank you for the great answer!
Answer: Use the Get-ChildItem cmdlet with the -recurse switch to get all items recursivly from a root directory. Filter all items containing my-project using the Where-Object cmdlet and finally rename them using the Rename-Item cmdlet:
Get-ChildItem "D:\tmp" -Recurse |
    Where {$_.Name -Match 'my-project'} |
    Rename-Item -NewName {$_.name -replace 'my-project','$appname$' }


How to extends types for section element in Typescript?

Question: In typescript, when our component extends a div we define our props types like this:

import { HTMLAttributes } from "react";

export interface IContainerProps extends HTMLAttributes<HTMLDivElement> {
    // You can add additional props specific to your container component here
    customProp?: string;
  }

However, when the component props extends section element props, I did not find something like this HTMLSectionElement:
In typescript, when our component extends a div we define our props types like this:

import { HTMLAttributes } from "react";

// HTMLSectionElement does not exist ?

export interface IContainerProps extends HTMLAttributes<HTMLSectionElement> {
    // other props
  }

Comment: Also [MDN on section](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section) mentions *This element only includes the global attributes.*
Comment: There is no HTMLSectionElement for a good reason: it is exactly the same as a HTMLElement. Said differently, it does not come with properties of methods that HTMLElement doesn't come with. You can safely use HTMLElement...or create a type alias if you prefer using the HTMLSectionElement type.
Answer: You can view the IntrinsicElements in node_modules/@types/react/index.d.ts, to inspect how React types this:
interface IntrinsicElements {
  // ...
  div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
  // ...
  section: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
  // ...
}

So the type you are looking for is React.HTMLAttributes<HTMLElement>. This type is consistent with the fact that section is primarily used as a semantic tag and contains no unique attributes.

This element only includes the global attributes.


Problemas para mostrar cor da fonte em campo ativo

Question: boa noite!
Eu estou passando por um problema que está quebrando minha cabeça por dias. Eu tento deixar a cor da letra no campo ativo do tab, porém quando eu passo (color: #fff) para a classe especifica, ela não muda, porém ela reconhece o background passado na mesma classe. Tentei mudar varias classes, porém sem sucesso, como mostra a imagem.
Vocês poderiam me ajudar com alguma dica
Está é a página: https://www.colegiofreinet.com.br/duvidas-frequentes2/

Obrigado desde já :)
Answer: Tem que trocar a cor do a quando a li estiver com a classe .ui-state-active
.ui-state-active a {
    color: red;
}

Comment: @MoisesFausto agora eu estou no celular e não da pra.inspecionar, mas acredito seja Pq o bg esta na li já o color na A. E essa com do A pode estar sendo herdada do body  ou algum outra parte do CSS por isso fiz a regra pegando o estilo da Li e do A que esta dentro dela para ser mais especifico
Comment: Isso faz sentido, realmente tinha reparado que o color na A, vinha herdado e quando eu alterava, alterava todas as outras. Você foi muito perspicaz @hugo, agradeço novamentye pela ajuda.
Comment: Obrigado meu amigo, isso resolveu o meu problema. Não querendo me aproveitar da suia boa vontade, mas eu fiquei sem entender o porque ela não respeitou o parametro da font, mas respeitou o do background ?
Comment: @MoisesFausto estamos aqui para ajudar, força nos estudos que logo vc fica fera! Abs
Answer: Moises Fausto eu irei responder a sua pergunta, porém antes eu gostaria de deixar bem claro algumas coisas para você.
O seu site não está seguindo nenhuma convenção de boas práticas, code clean, design patterns, metodologias entre outros, alguns problemas que eu analisei apenas inspecionando o código pelo browser foram o seguinte:

1) Na tag  você está inserindo


Weird looking binned residual plot

Question:
My binned residual plot is quite strange looking, the 95% confidence lines are so very jagged, with points between.  I have colored this "inside" of the 95% confidence interval because it is really hard otherwise to tell which points are inside and which are outside.  This plot was made in R.  This is from a generalized estimating equation-logistic regression, with many correlated clusters and a AR-1 correlation structure.  I am not sure if this is a reasonable way for this plot to look or if I have done something wrong.  Has anyone else had a plot that looks like this?  Thanks in advance,
Jesse
Answer: It's fairly obvious that the distribution of outcomes are integer valued and you have some sort of positive relationship between the outcome and the predictor of interest. That creates the stratified "downward sloping" lines in the residuals. Luckily, residual plots are practically irrelevant. It comes as no surprise given that these residuals are produced from a logistic regression which models the risk of a binary outcome. Residuals from a logistic regression make 0 sense except for calculation of a Brier score for risk prediction. More specifically, your x-axis is "expected values" that are on the log-odds scale $\mbox{logit}(\pi)$. whereas the outcome is on the risk scale, $\pi$. So in particular, these residuals should have a slight S curve shape to them, but the variability in the distribution of your exposures is not great enough to drive that association. Hence, they appear approximately linear.

Weird looking binned residual plot


Are underarm serves fair in tennis? If so, why are they looked upon as a means of disrespect?

Question: As my title says all about the question, are underarm serves a fair thing in tennis? Because the reaction of Chris Garin says me otherwise when Alexander Bublik served him an underarm serve.
I was watching some YouTube videos where it mentioned 2019: Year of the Underarm Serve because of (Nick) Kyrgios hitting many of them. Even this year it was fairly common during matches. Just yesterday we saw Daniil Medvedev hitting one against Alexander(Sascha) Zverev. In his post-match interview/press-conference, he told that: "I didn't want to disrespect him (Zverev) but my wide serve was not working as well as I would like today and he was returning it good. [...]"
Prior to this, in February 2019, Rafa was rather enraged by Kyrgios's underarm serve. He commented, "[...] He lacks respect for the public, the rival and towards himself."
Why did Medvedev mention the fact that Sascha could have been disrespected because of that serve technique? Also, why did Rafa look at it like a wrong act?
Comment: You ask if they're legal, and then point to several instances of pros using them during their match.  Are you actually asking if they're legal?  Or do you really mean the "why/disrespect" part of your question?
Comment: Pros can do illegal stuff as well. But yes, since they aren't banned already, I would say it is pretty legal. I will edit my question to convey a better meaning. Thank you @Joe.
Answer: Underarm serves are completely fair in tennis.
The act of starting a point is very deeply rooted to the "ritual" of performing an overhead serve. Hence a player always expects to return an overhead serve. Consequently, underhanded serves have the benefit of surprise.
The overhead serve has a reason for being so common: it is far superior to the underhand serve in terms of difficulty of returning. The technique is designed to produce a much longer kinetic chain than underhand serves. Also, the point of impact for overhead serves is much higher than the net, allowing for better trajectories. Thus, the element of surprise is the only benefit to underhanded serves.
A professional serving underhanded would be somewhat analogous to a good free-throw shooter throwing underhanded: he can do it "properly" and yet chooses not to. The fundamental difference is that the element of surprise in an underhanded free-throw is meaningless, while in tennis it greatly affects the returner.
The reactions you cite are essentially a consequence of being caught-off-guard by a technique which, in terms of quality-of-shot alone (disregarding the mental aspect), is objectively far inferior.


Incorporating averaging models from AIC and still using k-fold cross validation?

Question: I've a county/district that I've divided into ~300 grids that are 15km^2 in size attributed with various habitat and economic variables that have been summarized and standardized.  I then have 2 types of data 1) presence/absence of leopard caused human deaths and 2) counts of those human deaths. Of the 300 grids 80 had >=1 human death.  I came up with 14 a-priori hypotheses to test.
Initially, I simply ran AIC model selection and averaged the best models.  The reviewers said this was incomplete as I still need to validate the models. It was suggested I do k-fold cross validation (KCV) to validate the model and get at model performance or predictive accuracy.  However, I am having difficulties figuring out how to do that when multiple models (say 3 models for example) are the "best" according to AIC and how you would do KCV over an averaged model in R.  I've also been seeing that some people have used CV methods for model selection itself.  That is, they select the "top model" based on the one that predicts the best instead of using AIC, BIC, etc.  But, model selection using AIC and CV are asymptotically equivalent.  That is, as sample size increase the AIC top model will converge to the "best predicting" top model selected using CV methods.  How would I know if my sample size is "enough" to use CV instead of AIC?
Can I still use AIC - and then only run the KCV on the absolutely best top model?  Or run the KCV over all three best models and then somehow compare between them?
I found the R package cvTools which has a cv.Select command, but I have yet to see any discussion of interpretation for the results or to know what it is exactly I am doing outside of the PDF that has the short short example.
Basically k-fold type techniques were developed for assessing predictive accuracy for a single model... I've got multiple models according to AIC that work -- so what to do?
Is the reviewer correct in saying I need to validate the model?  If CV and AIC model selection are asymptotically equivalent.  That is, as sample size increase the AIC top model will converge to the "best predicting" top model selected using CV methods -- would I even have to do this as CV would essentially give the same result?
Answer: If possible, you could randomly subset your data into a training and testing set. You could run your AIC on the training data, do your model averaging, and then compare the predictions to your testing set. Not exactly K-fold CV, but it would give you an idea of how well your model performs.
Answer: I'm clueless regarding your dataset or model building. But...
I think there might be some confusion of terminology here. I assume that the reviewer would like some form of internal validation - some measure of the optimism or over-fitting of the model. Just google "internal validation" or "steyerberg internal validation" and you should be set.
Random subset is a great recommendation since it is easy given your complex model building strategy. Unfortunately, unless you've got a huge dataset, it is not going to get you published. Bootstrapping is the gold standard. I assume the reviewer recommended k-fold assuming that the complex model building strategy employed would be difficult to recreate using bootstrap validation and that k-folds would be feasible alternative. But I don't really understand your model building - it may not be possible to replicate it in k-fold either. Then a subset would be very helpful and your only reasonable option I think.
Regarding AIC model selection: it is unclear why you don't think it is prone to over-fitting the data.
Hope there is something useful here.


activities/fragments' lifecycle methods called in the main thread?

Question: Are all activities/framgents' lifecycle methods called in the main thread by default?
I'm implementing a class which checkes if the app is currently in foreground/background. I'm using activities' onPasue/onResume to do that. I would like to make sure that I don't have to synchronize methods of my class.
Comment: I hope you did have a look at [registerActivityLifecycleCallbacks](http://developer.android.com/reference/android/app/Application.html#registerActivityLifecycleCallbacks(android.app.Application.ActivityLifecycleCallbacks)) since this probably makes things easier than using activity and fragment lifecycle methods.
Comment: @DavidMedenjak +1 for mentioning about Application.ActivityLifecycleCallbacks but I'm developing API 10+
Answer: Yes, they are.  In general, if something is called off the main thread the documentation will state so.


MATLAB - set title

Question: is any way to get string from this type?:
I would like to set title from this code:
f = inline('(x-3).^2 - 1');
and for title:
figure(1)
...
title(func2str(f))
...
it's any way to set title direct from inline?
Comment: cniak, what exactly do you mean by "direct from `inline`"? `inline` just defines the function, it can't do anything else. You can of course write a function that does these two things. Also note: According to the help in R2013a, "inline will be removed in a future release. Use anonymous functions instead."
Comment: i'm searching any way to set title by any func whose collect string from `inline` and create string which can be add to title :)
Comment: But that's exactly what your code does, using `func2str` and `title`. So what's missing?
Comment: problem: it is not work.
Answer: This is done by capturing the figure handle and editing the title from it.
fg_title = 'my figure title';
fg = figure;
set(fg, 'name', fg_title); //set the figure title

but the figure 1 text will still be preset at the title bar, if you want to remove it just disable numbered title:
set fg, 'NumberTitle', 'off'); //disable numbered title

MATLAB - set title


Job failed for Integration in GitLab (jq: error (at :9): Cannot iterate over null (null))

Question: I am working in GitLab and I connect my GitLab with salesforce. I created a Gitlab-ci.yml in my project directory. Now when I execute the pipeline in GitLab testing phase pass but failed in integration part at following code PACKAGE_VERSION_JSON="$(eval sfdx force:package:version:list --concise --released --packages $PACKAGE_NAME --json | jq '.result | sort_by(-.MajorVersion, -.MinorVersion, -.PatchVersion, -.BuildNumber) | .[0]? // ""')"
Can anyone tell me how can I resolve this issue. ?
Answer: Please make sure that you have generated package in the same org,which you are using for git lab authentication.


Smallest cube ending in $2017$

Question:
What is the smallest cube ending in $2017$?

My try: I know that the only possible units digit is $3$,
$$(a+3)^3 = 2017 \mod 10^4\;$$
and
$$a^3 + 9a^2 + 27a = 1990\mod 10^4$$
I don't know how to proceed, I tried factoring and adding $10^5$ and $1990$ but when I saw the answer, this approach would take forever.
Comment: You should use $10a+3$ instead of $a+3$ since $3$ is the units digit, and that will help you to make more progress.
Comment: It's rather modulo $10^4$
Answer: Recall Carmichael's theorem: $a^{\lambda(m)} \equiv 1 \bmod m$ for all $a$ coprime with $m$.
For $\lambda(10^4)=500$, we get $1 + 500 = 167 \cdot 3$ and so $a \equiv a \cdot 1 \equiv a \cdot a^{500} \equiv (a^{167})^3 \bmod 10^4$.
Thus, the answer is $2017^{167} \bmod 10^4$, which is $9073$, by repeated squaring.
There is only one solution mod $10^4$ because $x \mapsto x^3$ is injective in $U(10^4)$, as we have seen above.
Answer: $x^3\equiv 7 \pmod {10}$. So $x\equiv 3 \pmod {10}$.
Put $x=10y+3$, and compute $\pmod {100}$.
This yields $1000y^3+900y^2+270y+27 \equiv 17 \pmod {100}$. Thus $70y \equiv -10 \pmod {100}$, or equivalently, $7y \equiv -1 \pmod {10}$. Divide by $7$: $y \equiv 7 \pmod {10}$.
Put $y=10z+7$, hence $x=100z+73$. I think you see the pattern now: calculate modulo $1000$, it gives you the $\pmod{10}$ remainder of $z$, and one more iteration gives you the $\pmod {10000}$ remainder of $x$, which is also the smallest solution.
(Solution: $9073$)
Answer: $a^3 + 9a^2 + 27a = 1990\mod 10^4\Longleftrightarrow\cases{a^3 + 9a^2 + 27a = 1990\mod 2^4\\a^3 + 9a^2 + 27a = 1990\mod 5^4\\}$
Now $2^4=16$, so the first equation is easy and happens to have only one solution, $14\bmod 16$.
As for the second, the only solution is $320\bmod 625$.
By the CRT, the only solution modulo $10000$ is $9070$, resulting in the least solution $$9073^3=746883272017$$

Smallest cube ending in $2017$


The difference to apply display:flex to the outer container and to the child item

Question: I am confused by what the difference is between apply display:flex to a whole container and to an item of that container.
From my experiment, I know that it causes different layout. But why does this cause different layout? And how the different layouts are decided?
if applied to the whole container,

if applied to subitem in the menu,

code,

.advanced-nav ul {
  /* display: flex;*/
  /*change me!*/
}

.advanced-nav li a {
  display: flex;
  /*or change me!*/
  width: 100%;
  /* justify-content: flex-start;*/
}

Advanced Menu

            Home
            is where the heart is

            Food
            is nourishment for the soul

            Recipes
            guide you on your journey

            News
            brings new things

with code above, although most of css styles are stripped, difference still exists. Any feedback is appreciated; thanks.
Comment: This ***[link](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes)*** can help you.
Answer: Add this css
.advanced-nav ul li {
     display: inline-block;
     width: 100%;
}
.advanced-nav ul li a {
     display: inline-block;
     width: auto;
}

.advanced-nav ul li a .icon {
     display: inline-block;
     width: auto;
}

.advanced-nav ul li a .button-text {
     display: inline-block;
     width: auto;
}

Comment: The OP is asking for an explanation, not code.


pthread returns 251

Question: pthread_create returns the value 251 without creating the thread.  Does anyone know what the problem is? Please help.  The machine is a HP-UX.
I'm new to multi-threading.
   #include <stdio.h>
   #include <stdlib.h>
   #include <pthread.h>

   void *print_message_function( void *ptr );

   main()
   {
        pthread_t thread1, thread2;
        char *message1 = "Thread 1";
        char *message2 = "Thread 2";
        int  iret1, iret2;
        /* Create independent threads each of which will
         * execute function */

        iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
        iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);

        /* Wait till threads are complete before
         * main continues. Unless we  */
        /* wait we run the risk of executing an
         * exit which will terminate   */
        /* the process and all threads before the
         * threads have completed.   */

        pthread_join( thread1, NULL);
        pthread_join( thread2, NULL);
        printf("Thread 1 returns: %d\n",iret1);
        printf("Thread 2 returns: %d\n",iret2);
        exit(0);
   }

   void *print_message_function( void *ptr )
   {
        char *message;
        message = (char *) ptr;
        printf("%s \n", message);
   }

Answer: Edit : On HP-UX11. pthread_create is failing with error 251: Function is not available.
Check whether -lc comes before -lpthread in your link order.
If this is the case, then the call would resolve to stub in C-library
and could cause this error.

Did you link with -lpthread?
You should use errno.h to see what error 251 is on your system or this should give you a more detailled message :
printf("%s\n", strerror(errno));

Moreover, when using pthread, you should check for the return value of almost every call to pthread* (see the man of every function to check for possible error returned)
For pthread_create, you have at least 2 possible errors (depending on your system and pthread implementation) :
pthread_create() will fail if:
[EAGAIN]           The system lacked the necessary resources to create
                        another thread, or the system-imposed limit on the
                        total number of threads in a process
                        [PTHREAD_THREADS_MAX] would be exceeded.
[EINVAL]           The value specified by attr is invalid.
Answer: This compiles and runs on my Linux box with the following result:
Thread 1
Thread 2
Thread 1 returns: 0
Thread 2 returns: 0

So it looks like the problem is not in your code, but something in the environment. I haven't used HP-UX for over 10 years, so I can't help you there.
Comment: Yes, looks like it's got something to do with the environment.

pthread returns 251


Confirmation of normality using residuals from an linear regression

Question: 95% of my residuals from an linear regression lie within 2 standard deviations of the predicted values. Is this enough to confirm normality or could any other distributions have 95% of residuals that lie within 2 standard deviations? Obviously I could plot the residuals to check normality, but I'm interested in knowing if the 95% within 2 standard deviations is enough to confirm normality.
Answer: A large variety of distributions will tend to have something reasonably close to 95% of the residuals within 2 standard deviations.
For example here's the result of simulating 1000 regressions (each at n=100), with exponentially distributed errors (shifted exponential with mean 0), and computing the proportion of residuals within $0\pm 2s$:

In about 3/4 of the simulations, the proportion of the residuals within 2sd's was between 94 and 96%, ande in more than 9/10 simulations, between 93 and 97% of the residuals were within 2sd's.
So having very close to 95% of the residuals within 2sd's is pretty consistent with very non-normal residuals as well.
An interesting fact -- for symmetric, continuous*, unimodal distributions (whose first two moments are finite) the proportion of the distribution within two standard deviations of the mean is limited to be between 88.9% and 100%... so for those cases, it's actually hard to get very far away from 95%. Lots of common distributions come out within a few percent of 95% of the distribution within 2sds, so something like my example would occur with many other choices of distribution.
* continuous everywhere, except perhaps at the mode
[The deleted mention of symmetry relates to an older inequality; there's no need for it now]
Comment: The 100% is easy since it's a matter of simply finding an example (and the obvious one works). On the 88.9% (more precisely, it's 8/9) -- that was one I found myself as a student many years ago; I presumed then that it wasn't new, and started researching to try to find it (this was long before browsers or widespread internet, so it took a lot of time and effort) ... to eventually discover a slightly more general result had been proved in the 19th century. The inequality I mentioned is [here](http://en.wikipedia.org/wiki/Chebyshev%27s_inequality#Unimodal_symmetrical_distributions), ...(ctd)
Comment: Any chance of a link for that 88.9%-100% figure? If it isn't a question here already it deserves to be, I think.
Comment: (ctd) ... though more recently than the 19th century, the [Vysochanskij–Petunin inequality](http://en.wikipedia.org/wiki/Vysochanskij%E2%80%93Petunin_inequality) removes the need for symmetry for it to apply to intervals about the mean (the original inequality was in relation to the mode, but in symmetric unimodal distributions with a mean, they're the same). That was published before my rediscovery of the older result, but I only became aware of the generalization recently (and am apparently still in the habit of needlessly restricting it).
Answer: No, there are several reasons why 95% of residuals lying within 2 standard deviations need not imply normality.
I'll consider cases in which the assumptions (other than normality) of the Classical Linear Regression Model hold, in particular that there is no heteroscedasticity or autocorrelation. If these assumptions do not hold there would be further complications.
Normality, in a regression context, generally refers to normality of the distribution of disturbances or error terms in a population regression model (throughout this answer I use the term 'disturbances' in this population-related sense).  In estimating a regression model, we usually take a sample of observations from the population of interest, and calculate the regression on the sample data.  The fact that we rely on a sample introduces considerations that can impact on any inference from the distribution of the residuals to the distribution of the disturbances.
Firstly, the sample might be selected by a biased process.  If so, then (even if the sample is large) the distribution of residuals may not give any useful information about the distribution of the disturbances.
Secondly, the sample (even if selected in an unbiased manner) will be subject to sampling error, which can be an important consideration if the sample is small.  Sampling error in this context can have two consequences.  One is that the distribution of residuals may not be representative of the distribution of the disturbances.  The sample might for example happen to include a disproportionately large or small number of outliers.  A second consequence is that the standard error of the regression $s$ may not equal the standard deviation of the disturbances $σ_0$.  This is explained further below.
The standard error of the regression is calculated as:
$$s = \sqrt{\frac{SSR}{N-K}}$$
where $SSR$ is the sum of squared residuals, $N$ is the number of observations (sample size), and $K$ is the number of parameters estimated.  It can be shown that $s$ is an unbiased estimator of $\sigma_0$ (1).  However, for an estimator to be unbiased is a repeated sample property.  It doesn't mean that $s$ as estimated from one sample will equal  $\sigma_0$.  Considered over repeated samples, $s$ is a random variable with an approximately chi-square distribution given by (2):
$$s^2 \sim \frac{ \sigma_0^2\chi_{N-K}^2}{N-K}$$
This formula is exact when the disturbances are normally distributed.  How good an approximation it is when their distribution is not normal appears rather intractable, but I justify its use here on the grounds that I am only identifying what can happen as a result of sampling error, not what must happen.  Let's see what the formula implies with, say, $N = 100$ and $K = 2$.  Then:
$$s^2 \sim \frac{ \sigma_0^2\chi_{98}^2}{98}$$
The upper 5% (1-tail) limit of a $\chi_{98}^2$ distribution is about 122, from which we can infer (dividing 122 by 98 and taking the square root) that the upper 5% (1-tail) limit of the distribution of $s$ may be about $1.1\sigma_0$.  So the probability that the standard error of the regression is more than 10% higher than the standard deviation of the disturbances may be about 5%.  And if the sample size is less than 100, that probability is likely to be higher.
Thus if we compare the distribution of the residuals with an interval of two standard deviations either side of zero, taking the standard deviation to be the standard error of the regression as calculated from the sample data, neither side of the comparison is necessarily a true reflection of the distribution of the disturbances.   The residuals may not be representative, and the standard deviation may not be correct.  It is fair to add that these two effects will to a considerable degree be related.  Nevertheless, an inference built upon such insecure foundations (unless the sample size is large) cannot be reliable, even if it leads to a correct conclusion on some occasions.
Finally, there is the case in which the sample is large, the distribution of residuals is representative of that of the disturbances, and the estimated standard deviation does equal that of the disturbances.  Even if all those conditions are satisfied, there is still the major problem, well explained in the answer by Glen_b, that there are many non-normal distributions meeting the condition that 95% of values lie within 2 standard deviations of the mean.
Sources:

Ruud P A (2000) An Introduction to Classical Econometric Theory p
158.
Ruud (as above) p 199.


Why does my output for triple quotes have two newlines?

Question: I was trying to print sans undertale with a glowing eye (which meant I had to use a seperate print line for the variable instead of the triple quotes), but the output has two empty lines, above and below the part that has color (line with XD), I'd like to remove. I assume its a problem with triple quotes print functions meeting one-line (as in not triple quote) print functions Here is the code:
from termcolor import colored, cprint
text = colored('8XD8', 'cyan')

print ('''

                888888888888888888
            8888                  8888
          88                          88
          88                          88
        88                              88
        88                    888888    88
''')
print ("\t\t88                    ", text,"    88")
print ('''
        88    888888    88    888888    88
          88          888888          88
        8888  88                  88  8888
        88    8888888888888888888888    88
        88      88  88  88  88  88      88
          8888    88888888888888    8888
         88888888888             8888888888
       88  888888888888888888888888888888  88
    8888  88    88      88      88    88  8888
    88      88    888888  888888    88      88
  88    8888  888888    88    888888  8888    88
  88        88    88          88    88        88
  88          88  88          88  88          88
    88      88    8888      8888    88      88
      8888  88    88          88    88  8888
        888888    88888888888888    888888
          8888    88888888888888    8888
        8888888888888888888888888888888888
        8888888888888888  8888888888888888
          888888888888      88888888888
      888888        88      88        888888
      88          8888      8888          88
        8888888888              8888888888
''')

The output looks like this:
                888888888888888888
            8888                  8888
          88                          88
          88                          88
        88                              88
        88                    888888    88

        88                     8XD8     88

        88    888888    88    888888    88
          88          888888          88
        8888  88                  88  8888
        88    8888888888888888888888    88
        88      88  88  88  88  88      88
          8888    88888888888888    8888
         88888888888             8888888888
       88  888888888888888888888888888888  88
    8888  88    88      88      88    88  8888
    88      88    888888  888888    88      88
  88    8888  888888    88    888888  8888    88
  88        88    88          88    88        88
  88          88  88          88  88          88
    88      88    8888      8888    88      88
      8888  88    88          88    88  8888
        888888    88888888888888    888888
          8888    88888888888888    8888
        8888888888888888888888888888888888
        8888888888888888  8888888888888888
          888888888888      88888888888
      888888        88      88        888888
      88          8888      8888          88
        8888888888              8888888888

Is there any way to fix this?
Comment: Okay, cool. So what's wrong with it? Please read [ask].
Comment: Every print add a newline to the end by default.
Answer: Assuming you are using python3 print can be given an end parameter, by default print will end in a newline so you need to overwrite it with something else such as the following
print ('''
                888888888888888888
            8888                  8888
          88                          88
          88                          88
        88                              88
        88                    888888    88
''', end = "")
print ("\t\t88                    ", "text","    88", end = "")
print ('''
        88    888888    88    888888    88
          88          888888          88
        8888  88                  88  8888
        88    8888888888888888888888    88
        88      88  88  88  88  88      88
          8888    88888888888888    8888
         88888888888             8888888888
       88  888888888888888888888888888888  88
    8888  88    88      88      88    88  8888
    88      88    888888  888888    88      88
  88    8888  888888    88    888888  8888    88
  88        88    88          88    88        88
  88          88  88          88  88          88
    88      88    8888      8888    88      88
      8888  88    88          88    88  8888
        888888    88888888888888    888888
          8888    88888888888888    8888
        8888888888888888888888888888888888
        8888888888888888  8888888888888888
          888888888888      88888888888
      888888        88      88        888888
      88          8888      8888          88
    8888888888              8888888888
''')

Answer: I believe this is what you want:
print ('''

                888888888888888888
            8888                  8888
          88                          88
          88                          88
        88                              88
        88                    888888    88''')
print ("        88                    ", text,"    88")
print ('''        88    888888    88    888888    88
          88          888888          88
        8888  88                  88  8888
        88    8888888888888888888888    88
        88      88  88  88  88  88      88
          8888    88888888888888    8888
         88888888888             8888888888
       88  888888888888888888888888888888  88
    8888  88    88      88      88    88  8888
    88      88    888888  888888    88      88
  88    8888  888888    88    888888  8888    88
  88        88    88          88    88        88
  88          88  88          88  88          88
    88      88    8888      8888    88      88
      8888  88    88          88    88  8888
        888888    88888888888888    888888
          8888    88888888888888    8888
        8888888888888888888888888888888888
        8888888888888888  8888888888888888
          888888888888      88888888888
      888888        88      88        888888
      88          8888      8888          88
        8888888888              8888888888
''')

On my computer I got:

                888888888888888888
            8888                  8888
          88                          88
          88                          88
        88                              88
        88                    888888    88
        88                     8XD8     88
        88    888888    88    888888    88
          88          888888          88
        8888  88                  88  8888
        88    8888888888888888888888    88
        88      88  88  88  88  88      88
          8888    88888888888888    8888
         88888888888             8888888888
       88  888888888888888888888888888888  88
    8888  88    88      88      88    88  8888
    88      88    888888  888888    88      88
  88    8888  888888    88    888888  8888    88
  88        88    88          88    88        88
  88          88  88          88  88          88
    88      88    8888      8888    88      88
      8888  88    88          88    88  8888
        888888    88888888888888    888888
          8888    88888888888888    8888
        8888888888888888888888888888888888
        8888888888888888  8888888888888888
          888888888888      88888888888
      888888        88      88        888888
      88          8888      8888          88
        8888888888              8888888888

Python takes the newlines you put in to type the figure as the newline escape character \n.
Let me know if this helps!
Comment: My pleasure! Nice figure, by the way :)


Converter String para OffSetDateTime (dd 'de' MMMM 'de' yyyy 'às' HH:mm:ss)

Question: Tenho essa String :

17 de Outubro de 2008 às 11:35:04

E esse Pattern:

dd 'de' MMMM 'de' yyyy 'às' HH:mm:ss

E esse código:
private OffsetDateTime getData(){
     return Optional.ofNullable(page.<HtmlTableCell>getFirstByXPath(String.format(DOMAIN_XPATH, "Data de Distribuição")))
            .map(HtmlTableCell::asText)
            .map(DATE_TIME_PATTERN::matcher)
            .filter(Matcher::find)
            .map(Matcher::group)
            .map(str -> LocalDateTime.parse(str, DateTimeFormatter.ofPattern(DATE_TIME_PATTERN.toString())).atOffset(ZoneOffset.ofHours(-3)))
            .orElse(null);
}

Quero transformar essa data em um OffsetDateTime porém usando esse Pattern não está funcionando, ele não passa pelo find().
Comment: Atualizei a minha resposta para pegar o mês de Março (faltou a `ç` na expressão regular)
Answer: Pelo código, estou assumindo que DATE_TIME_PATTERN é um java.util.regex.Pattern.

Pois bem, o padrão usado em um java.util.regex.Pattern deve ser uma expressão regular (regex), que é bem diferente do padrão usado em um DateTimeFormatter.
A expressão regular serviria para verificar se a string está em determinado formato (como "dois dígitos, seguido de espaço, seguido de várias letras (o mês), etc"). Então ela poderia ser assim: ¹
Pattern DATE_TIME_PATTERN = Pattern.compile("\\d{2} de [a-zA-Zç]+ de \\d{4}.+\\d{2}:\\d{2}:\\d{2}");

Com isso, você verifica se a String está no referido formato:

\\d{2} quer dizer "dois dígitos" e \\d{4} quer dizer "quatro dígitos"
[a-zA-Zç]+ quer dizer "uma ou mais letras" (incluindo ç, para o mês de Março), o que é o suficiente para o nome do mês, já que o DateTimeFormatter irá verificar o nome posteriormente
.+ é "um ou mais caracteres"

Já para fazer o parsing da data, eu também sugiro setar o java.util.Locale para o idioma português, por causa do nome do mês. Se você não especificar um locale, será usado o default da JVM, e nem sempre é garantido que seja português:
// expressão regular para verificar se a String se parece com uma data no formato que você precisa
Pattern DATE_TIME_PATTERN = Pattern.compile("\\d{2} de [a-zA-Zç]+ de \\d{4}.+\\d{2}:\\d{2}:\\d{2}");

// usar o pattern para fazer o parsing da data, com locale em português por causa do nome do mês
DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd 'de' MMMM 'de' uuuu 'às' HH:mm:ss", new Locale("pt", "BR"));

OffsetDateTime odt = Optional.ofNullable("17 de Outubro de 2008 às 11:35:04")
    .map(DATE_TIME_PATTERN::matcher)
    .filter(Matcher::find)
    .map(Matcher::group)
    .map(str ->LocalDateTime.parse(str, parser).atOffset(ZoneOffset.ofHours(-3)))
    .orElse(null);
System.out.println(odt); // 2008-10-17T11:35:04-03:00

A data obtida será 2008-10-17T11:35:04-03:00.

1: Geralmente expressões regulares para verificar datas válidas são bem mais complicadas, já que precisam verificar se o mês possui 28, 29, 30 ou 31 dias, se o ano é bissexto, etc (além de poder ter outras melhorias, como só aceitar nomes dos meses válidos e por aí vai).
Mas neste caso, estamos usando a regex apenas para extrair um trecho que parece uma data (que está no formato indicado, e portanto tem potencial para ser uma data válida), e em seguida validando com DateTimeFormatter, então a regex pode ser mantida simples do jeito que está (pois o parse já irá verificar todos os detalhes, como o nome do mês, valores válidos para cada campo, etc). Se a data for inválida, o parse lançará um DateTimeParseException.

Você também pode trocar a regex para:
Pattern.compile("\\d{2} de [a-zA-Zç]+ de \\d{4} às \\d{2}:\\d{2}:\\d{2}");

Usando às diretamente, em vez de .+, pois aí só vai aceitar strings que contenham exatamente esses caracteres (já que .+ é mais abrangente, pois aceita várias ocorrências de qualquer caractere). Enfim, use o que melhor se encaixar nos seus casos de uso.
Se optar pelo .+, sugiro também trocar por .+?, para o caso de ter mais de uma data na mesma String. Exemplo:
Pattern DATE_TIME_PATTERN = Pattern.compile("\\d{2} de [a-zA-Zç]+ de \\d{4}.+\\d{2}:\\d{2}:\\d{2}");

String s = "17 de Outubro de 2008 às 11:35:04" +
    "  blablabla " +
    "10 de Outubro de 2018 às 10:35:04";

Neste caso, toda a string será passada para parse, resultando em erro. Isso acontece porque .+ é ganancioso e tenta pegar o máximo possível de caracteres. Para evitar este comportamento, basta trocar .+ por .+?. O ? depois do + cancela a ganância, fazendo com que somente a primeira data seja pega pela regex e passada para parse.

PS: por padrão, DateTimeFormatter faz alguns ajustes para datas como 31 de abril (que é ajustado para 30 de abril). Se quiser que ele só aceite datas válidas, pode mudar o java.time.format.ResolverStyle para STRICT:
DateTimeFormatter parser = DateTimeFormatter
    .ofPattern("dd 'de' MMMM 'de' uuuu 'às' HH:mm:ss", new Locale("pt", "BR"))
    .withResolverStyle(ResolverStyle.STRICT);

Desta forma, o ajuste de 31 de abril não é mais feito, e em vez disso é lançado um DateTimeParseException. Para mais detalhes, veja esta resposta.
Se quiser, também é possível fazer um DateTimeFormatter case insensitive, caso o nome do mês esteja todo em minúsculas (ou maiúsculas). Para isso usamos um java.time.format.DateTimeFormatterBuilder:
DateTimeFormatter parser = new DateTimeFormatterBuilder()
    .parseCaseInsensitive()
    .appendPattern("dd 'de' MMMM 'de' uuuu 'às' HH:mm:ss")
    .toFormatter(new Locale("pt", "BR"))
    .withResolverStyle(ResolverStyle.STRICT);

Assim, o nome do mês pode ser tanto "outubro", quanto "Outubro" ou "OUTUBRO".


TestCafe headless localization parameters

Question: I am writing a fixture, and multiple tests assert the page's title to be some value. However, I did not account for the fact that the website is localized. My normal browser settings are English, but when I run the testcafe chrome:headless myTests.js my tests fails because the Localization changes, perhaps due to my PC's language?
I have tried running my local chrome installation and adding :userProfile, but without luck sadly.
The only other information I can find regarding this issue is, but I can't make it work:

TestCafe & chrome:headless : how to force the browser language (locale)
Answer: I found my answer here - go give them a like if it solves your issue as well.
Solution:
I use the following command to launch chrome headless with a locale specified:
testcafe chrome:headless --lang=en-US