Models for testing non-linear dynamics (e.g., threshold effects), where threshold is not necessarily known

Question: Any recommendations for models (or applications in papers) to test theoretical predictions about non-continuous effects, e.g., based on a threshold, rather than marginal effects? Some examples of the sort of threshold theoretical predictions I'm interested in testing:
The simplest example would be where the threshold is known. e.g.,
\begin{equation}
Y_i=1 \ \text{if} \  X_i>0.5 \ \text{and}\  Y_i=0 \ \text{otherwise} \ \ \ \ \ \ \ \text{(1)}
\end{equation}
A more useful example would be where we theorize a threshold, but we don't know its value, or even assume that it's constant across individuals.
\begin{equation}
Y_i=1 \ \text{if} \  X_i>T_i \ \text{and}\  Y_i=0 \ \text{otherwise} \ \ \ \ \ \ \ \text{(2)}
\end{equation}
Where $T_i$ is a threshold that is allowed to differ across units indexed in $i$.
I don't just want to test whether $X$ has a positive effect on $Y$ (e.g., $Y$~$X$), but rather I want to test for evidence for the threshold prediction.
Comment: This kind of setup is not familiar to me, can you describe an application by any chance? It seems like we would need additional assumptions on the Ti in order for this to be feasible.
Comment: Theoretically, Stark (1991)'s theory of "target earner" migration is an example: i.e., migrants return to their home country after accumulating Ti savings in the destination country. Empirically, I haven't confronted a situation like this before. I could derive testable predictions myself but first I want to see if there are existing models with testable predictions like this. I've found work by Tsay on testing threshold model in time-series data (https://tinyurl.com/2p9bea5y) but I'm hoping to find something in cross-sectional data.
Answer: I think you're describing change point detection, and you can find an enormous amount of information on that topic once armed with the right term to search for. By the way, this kind of thresholding does not constitute "non-linear dynamics", since there is no non-linearity, and no dynamics over time.
There are lots of existing tools for doing change point detection, but here's a simple approach using a noisy version of your data:
<code>library(tidyverse)
x = 1:100
changepoint = 50
y_mean = ifelse(x < changepoint, 0, 1)
y = rnorm(length(x), y_mean, .5)
plot(x, y)
abline(v=changepoint)
</code>

<code>#' Log-likelihood of x under the best-fitting parameters
gaussian_loglik = function(x){
  m = mean(x)
  s = sd(x)
  dnorm(x, m, s, log = T) %>% sum()
}

evaluate_changepoint = function(proposed_changepoint){
  y_pre = y[x < proposed_changepoint]
  y_post = y[x >= proposed_changepoint]
  gaussian_loglik(y_pre) + gaussian_loglik(y_post)
}

changepoint_liks = map_dbl(x, evaluate_changepoint)
estimated_changepoint = x[which.max(changepoint_liks)]
plot(x, changepoint_liks, 'l',
     xlab = 'Value',
     ylab = 'Log lik. of changepoint')
abline(v=estimated_changepoint)
</code>
Comment: Thank you, I wasn't aware of change point detection and the code is very helpful. Am I understanding it correctly that this is testing for a single change point in a dataset, rather than testing if there are unit-specific change points?
Answer: You could model this with probit or logistic regression. Then you model the probability
$$\mathbb{P}(Y_i = y) = \begin{cases} p & \qquad \text{if $y=1$}\\
1-p & \qquad \text{if $y=0$}
\end{cases}$$
This $p = \mathbb{P}(Y_i = 1)$ is equivalent to the probability $\mathbb{P}(T_i < X_i) = F_{T_i}(X_i)$. That is, the probability of observing $Y_i = 1$ is equal to the cumulative distribution function of $T_i$ in the point $X_i$.
When $T_i$ is normal distributed then you have a probit model. When $T_i$ follows a logistic distribution then you have a logistic model. (Personally I feel that a probit model is more natural here, and logistic regression is more appropriate in classification problems)
Comment: Yeah, I really couldn't really tell from the question which kind of problem was being asked about here, but I think between our answers we must have it.
Comment: Thank you, this is helpful to imagine modeling the outcome in this way, but I'm not clear what the test statistic would be. What is the test of whether the effect of $X$ on $Y$ occurs through the threshold function I describe in Equation (2), as opposed to a continuous marginal effect of $X$ on $Y$?
Comment: @Dr.Beeblebrox if you do a logit or logistic regression then you are modeling a [sigmoid function](https://en.m.wikipedia.org/wiki/Sigmoid_function) which describes the relative frequency of $Y=1$ and $Y=0$ as function of $X$. Whether or not $X$ has a relationship with $Y$ can be tested with a likelihood ratio test. The difference between your situation 1 and 2 is less easy to test. If you have situation 1 then the classes Y = 1 and Y = 0 have perfect separation and the [fitting is difficult](https://stats.stackexchange.com/questions/469799).


Estimating Beta distribution parameter from Pert distribution ones

Question: The Pert distribution is a modification of a Beta distribution defined by 3 parameters (a, b, c).
Is it possible to specify the underlying Beta from those 3 parameters, transforming them into the usual $\alpha$ and $\beta$?
Answer: Given a four parameter beta distribution $beta(\alpha, \beta, a, c)$ with a and c being the minimum and maximum value of the desired distribution and $\alpha$ and $\beta$ shape parameters, Vose (2008) uses:
$$
\begin{aligned}
  \alpha &= \frac{(\mu - a)(2b-a-c)}{(b-\mu)(c-a)} \\
  \beta  &= \frac{\alpha (c - \mu)}{\mu - a} \\
  \text{with } \mu &= \frac{a + 4b + c}{6}
\end{aligned}
$$
Davis (2008) suggested to use
$$
\begin{aligned}
  \alpha &= \frac{2(c+4b-5a)}{3(c-a)} \cdot
            \left[ 1+4(\frac{(b-a)(c-b)}{(c-a)^2}) \right] \\
  \beta  &= \frac{2(5c-4b-a)}{3(c-a)} \cdot
            \left[ 1+4(\frac{(b-a)(c-b)}{(c-a)^2}) \right]
\end{aligned}
$$
This way Davis makes sure that the beta distributions we get with these parameters actually exhibit means and variances as specified by the PERT mean and variance formulas, which are:
$$
\text{mean} = \frac{c + 4b + a}{6} \\
\text{var}  = (\frac{c-a}{6})^2
$$
References
Davis, Ron. 2008. "Teaching Note - Teaching Project Simulation in Excel Using PERT-BetaDistributions." INFORMS Transactions on Education 8 (3): 139–48. https://doi.org/10.1287/ited.1080.0013.
Vose, D. 2008. Risk Analysis: A Quantitative Guide. 3rd ed. John Wiley & Sons. https://books.google.de/books?id=9CaoAqaRcVwC.


How to init a LinkedList?

Question: I want to init my LinkedList, but failed.
typedef int ElemType;

typedef struct LNode
{
    ElemType data;
    struct LNode* next;
}LNode, *LinkedList;

void Init(LinkedList L)
{
    L = (LNode *)malloc(sizeof(LNode));
    L->next = NULL;
}

int main()
{
    LinkedList head;
    Init(head);
    return 0;
}

If I Init my LinkedList like this it works.
LNode node = (LNode *)malloc(sizeof(int));
node->data = 5;
node->next = NULL;
LinkedList head = node;

but this will make my head with a value.
Comment: You need to decide which language you want an answer for `c` and `c++` are two different languages with different concepts in how to solve such task.
Comment: I've set the question's tag to `c` rather than `c++`, since the code is valid c and not in C++-flavor.
Comment: For other ideas, see [Singly Linked List (node only, no wrapper)](https://pastebin.com/5MPLU4wB) and then see [Singly Linked List of Integers (example)](https://pastebin.com/R2AewR3A) for the benefit of using a `tail` pointer providing O(1) insertions at the end of the list.
Answer: void Init(LNode **L, ElemType data)
{
    *L = malloc(sizeof(LNode));
    (*L)->data = data;
    (*L)->next = NULL;
}

int main()
{
    LinkedList head;
    Init(&head, 0);

    // ...

    free(head);

    return 0;
}

Initializing your head to not contain a value doesn't really make sense, unless you actually want head = NULL which I assume is not the case.
Comment: Finally got it I think, this is confusing haha.
Comment: I don't want init my list with value.Because I want use push_back() or push_front() function to add value. if I init head = NULL. All funtion that I write can't run.
Comment: `void PushBack(LinkedList L, ElemType data)
{
    LNode* node = CreateNode(data);
    if(L == NULL)
    {
        L = node;
        return;
    }
    LNode* tmp = L;
    while(tmp->next != NULL)
    {
        tmp = tmp->next;
    }
    tmp->next = node;
}` This is my push_back function.
Answer: You've chosen to define a linked list as a pointer to an element - the head element.
It's customary to initialize containers (like lists, queues, stacks etc.) to be empty. An empty list has no head element, so the pointer to the head element would be NULL. In other words, you would either write
LinkedList create_list()
{
   return NULL;
}

// ...

LinkedList mylist = create_list();

or
void initialize_list(LinkedList* list)
{
   *list = NULL;
}

// ...

LinkedList my_list;
initialize_list(&my_list);

The use of malloc() will be in functions which append or prepend a new node to the list.
Comment: I got it.I have another question.when I make my push_back() fuction like this:`push_back(LinkedList L, ElemType data)` this function run nothing in console. `push_back(LinkedList *L, ElemType data)` I can get what I want.It's confusing.
Comment: But this is an issue in C with every data type - because functions are "pass by value", not "pass by reference". Thus if you want to swap two int's, you have to write `void swap(int* a, int*b)` rather than `void swap(int a, int b)` which would do nothing.

How to init a LinkedList?


Is a batsman out if his broken bat is caught?

Question: If a batsman's bat breaks while he is hitting a shot and a fielder catches the broken bat - not the ball - is the batsman out?
Comment: What makes you believe the batsman might possibly be out?
Answer: No, the laws of cricket (http://en.wikipedia.org/wiki/Caught) clearly state that a batsman can only be out caught if the fielder catches the ball fully within the field of play without it bouncing after touching the batsman's bat or glove.
There are other modes of dismissal (http://en.wikipedia.org/wiki/Laws_of_cricket#Ways_to_get_out) none of which involve the fielder catching the batsman's bat (broken or otherwise).


Angular 4 -> Push Objects to an Array

Question: I'm having an issue with pushing a new object to an existing array.
What I am trying to do ->
I am trying to push a new card drawn into the existing array/object
app.component.ts
     @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
      })
      export class AppComponent {
      title = 'app';
      deck: any;
      cards = [];
      hand = 0;
      cardCount: number;

      constructor(private _data: DataService){
        console.log("Data Service ready to query api");

      };

      newDeck(){
            this._data.newDeck().subscribe(res => this.deck = res.json());

      }

      deal(cardCount){
          this._data.deal(cardCount, this.deck.deck_id).subscribe(response => this.cards = response.json());

          if(this.cards){

            this.cards.push(this.cards);

          }
      }

app.component.html

New Game

    <button (click)="newDeck()">Start</button>

{{ deck.remaining }} cards left!

Your Hand

        <button (click)="deal(2)">Deal</button> <button (click)="deal(1)">Hit</button>

Yes - My *ngFor is broken because it doesn't seem to believe the cards are stored in an array.

ERROR -> Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Nevertheless, I attached a screenshot of what is happening. I can select the Deal button, but when I click Hit, the counter does only pull 1 card but it is not stored in the array. Instead, it acts as a new object and displays as card.cards[0].image instead of card.cards[2].image, since there are already 2 objects in the array after clicking the deal button.
Any ideas on how to push the new cards to into the cards array? Image
It may help to see how the cards are received when called ->
                {
                  "remaining": 50,
                  "deck_id": "1omsivg9l9cu",
                  "success": true,
                  "cards": [
                      {
                          "image": "http://deckofcardsapi.com/static/img/KS.png",
                          "images": {
                              "svg": "http://deckofcardsapi.com/static/img/KS.svg",
                              "png": "http://deckofcardsapi.com/static/img/KS.png"
                          },
                          "suit": "SPADES",
                          "value": "KING",
                          "code": "KS"
                      },
                      {
                          "image": "http://deckofcardsapi.com/static/img/AH.png",
                          "images": {
                              "svg": "http://deckofcardsapi.com/static/img/AH.svg",
                              "png": "http://deckofcardsapi.com/static/img/AH.png"
                          },
                          "suit": "HEARTS",
                          "value": "ACE",
                          "code": "AH"
                      }
                  ]
              }

Comment: This row looks a little tricky: `this.cards.push(this.cards);`
Comment: Should this row be changed?
Comment: Can't really say, I have no idea, what are you trying to achieve.
Comment: watch your source `src="{{card.cards.image}}"` you are having `cards` which is a array and not a plain object. Update the post with the sample json object
Comment: @CommercialSuicide I'm trying to push new cards pulled with "hit" button. The hit button makes the cardCount =1, then draws 1 card. Right now, it draws a card as it's own individual object - I want to store it with the other cards in a single array.
Comment: @Aravind should be src="{{card.cards[0].image}}"?
Answer: You can directly use the card.cards object in your ngFor

Comment: Dude omg you are amazing thank you! Not I just need to learn to store the new card in the array with the other cards. Thank you so much
Comment: I'm hesitant to mark answer as I am having another huge issue
Comment: Hey @Aravind based on the above scripts, any ideas on how to push new cards to the cards array?
Comment: I didnt understand your question can you please elaborate?
Comment: I'm requesting assistance on pushing new cards to the cards array in app.component.ts.
Comment: are you available in teamviewer?

Angular 4 -> Push Objects to an Array


What is wrong with this proof? -3 = 3

Question: What is wrong with this proof?
$-3 = \sqrt[3]{-27} = {(-27)}^{\frac 13} = {(-27)}^{\frac 26} = \sqrt[6]{{(-27)}^2} = \sqrt[6]{{27}^2} = {(27)}^{\frac 26} = {(27)}^{\frac 13} = \sqrt[3]{27} = 3$
This is obviously false since $-3 \neq 3$.
But still I can't figure out which equation is the wrong one and why that is.
Thanks in advance for anyone who will help.
Comment: $(-27)^{1/3} = (-27)^{2/6} \neq ((-27)^2)^{1/6}$
Comment: The third equality is completely wrong...
Comment: It's obviously wrong because you reach a contradiction.. what made you think that would be true in the first place?
Comment: @yanko I know it's wrong. I asked this question to understand why.
Comment: You can also check some other related posts, such as: [Which step in this process allows me to erroneously conclude that $i = 1$](https://math.stackexchange.com/q/84436),  [Which step in this process allows me to erroneously conclude that $i = 1$](https://math.stackexchange.com/q/84436), [Why $\sqrt{-1 \times -1} \neq \sqrt{-1}^2$?](https://math.stackexchange.com/q/49169) and [When does $\sqrt{a b} = \sqrt{a} \sqrt{b}$?](https://math.stackexchange.com/q/2047349)
Answer: As suggested in comments, the $(-27)^{2/6} \neq ((-27)^2)^{1/6}$, because $a^{bc}=(a^b)^c$ does not generally hold for $a<0$.
You can find more related info in @mrf's answer here: Is $(-1)^{ab} = (-1)^{ba}$ true? => $(-1)^{ab} = ((-1)^a )^b$ is true?.
Answer: The mistake here:
$$(-27)^{\frac{2}{6}}=(-27)^{\frac{1}{3}}.$$
It's wrong because
$$(-27)^{\frac{2}{6}}=|-27|^{\frac{1}{3}}.$$
Also if we write $a^{\frac{1}{3}}$ then it's better to think that $a>0$.
Answer: you could aswell prove this:
$-1 = \sqrt {(-1)^2}=\sqrt{1}=1$
Clearly the first equality is wrong (and your's third equality is wrong for similar reason).

What is wrong with this proof? -3 = 3


Fork-server and grandchildren for exec

Question: I need help with fork-server. What I want to do is accept a client then fork to let other clients connect and at the same time redirect stdout & err to client. The client should then be able to send strings that should be exec by the execlp() which is located in a grandchild.
Im not able to locate my logic errors..
In main():
    while (1) {

        t = sizeof(remote);

        printf("Waiting for connection.\n");

        s2 = accept(s, (struct sockaddr*)&remote, &t);

        if (s2 == -1) {
            perror("accept");
            exit(1);
        } else {

            printf("Client connected.\n");

            if(!fork()) {

                close(1);
                dup(s2);
                handle(s2);
                exit(0);
            }
            close(s2);
        }
    }

In handle():
    char str[100];
    int n;

    while(1) {

        n = recv(client_socket, str, 100, 0);

        if(n <= 0) {

            perror("recv");
            exit(1);
        } else {

            if(!fork()) {

                execlp("/bin/sh", "sh","-c", str, NULL);
                exit(1);
            }
            wait(0);
        }
    }

The result of execlp is not redirected to the client and gives an error "sh: Can't open c".
Comment: what do you get when you execute this on console "/bin/sh sh c"
Comment: I guess because i tested execlp outside fork and it works.
Comment: When I type "/bin/sh sh c" in console I get the same error
Comment: What is the value of `str`? Is it properly terminated?
Answer: You should write: execlp("/bin/sh", "sh","-c", str, NULL); to pass option '-c' to the shell. You are passing option "c" which is interpreted as: run the script called c which doesn't exist.
See: http://unixhelp.ed.ac.uk/CGI/man-cgi?sh
Another thing: You should NUL terminate your string after reading from it:
if(n > 0)
    str[n] = '\0';

You should also read only 99 characters as you will write the '\0' character at the end of your string.
Comment: Im sorry but misstyped in the question got , "-c",
Answer: One possible reason is that the command you try to run isn't in the command search path.
Another reason might be that the string you fetch contains the command and its arguments, and passing it as a single argument to execlp will pass it as a single argument to the shell so it thinks the whole string is the command.
If it's the last, then you need to split the command and its arguments up in an argv like array, and use execvp instead.
It is also very important that the string is properly terminated. Does the connect client send with the terminating '\0' character? If not then you need to add it yourself (in which case you can only receive 99 characters).
Comment: Nothing wrong with the client, when i change the Var str to "ls" or whatever command it still gives errors.

Fork-server and grandchildren for exec


Is it efficient to visualize chords on sheet music as notes on a piano to know the qualities of it?

Question: For example, say you see sheet music (you are not in front of a piano) and you see the notes D F A . Is it efficient enough to visualize these notes as on a piano to determine that they are a minor chord or is there another more efficient way?
Comment: Seems to me "effective" might be more important than "efficient." And if it works for you…
Comment: I'm not sure if I understand the point of the question. Are you worried that you're learning some bad habits by visualizing the notes on your instrument?
Comment: @user1079505 yes, whenever I see a chord on sheet music I see the notes as notes on a piano to find out the qualities of the chord, and if there is a better way to find the qualities of the chord in sheet music, I want to break out of my habit and use the more efficient method instead
Comment: That's essentially how I started out, and I wouldn't say that's fundamentally changed, I'm just less reliant on it. Of course any experienced musician will "just know" that the notes D F A form a D minor chord, but there's no rule that you can't "just know" and visualize at the same time.
Comment: …Well, that and recognition of chord shapes helping to quickly identify the root, more than anything to do with each individual note.
Comment: No, it is certainly not efficient. You should be able to read a sequence of chord names and know what it would sound like without (a) constructing them into their constituent notes, (b) visualising them on a piano or any other instrument, and then (c) intuiting what *that* would sound like. It might be *effective* for you, for the time being, but it is not *efficient*, and you need to move beyond it. Quickly. When reading music and performing it in real time you don't have the time for all this.
Comment: @user207421 Efficiency is not that simple, and it certainly is not the result of absolute paths when dealing with mental capabilities, as each one of us have different ways of interpreting and relating to abstract structures. Music learning and understanding is extremely complex, and being efficient is about being able to put the less efforts in obtaining the result, which depends on a plethora of aspects when dealing with such complex forms, including experience, knowledge and, not less important, purpose. While some approaches *may* be more efficient than others, no one can be to everybody.
Answer: Yes, mostly. It's not the most efficient way but it's a good way to learn the most efficient way which is to just know DFA is minor as soon as you see it on the page. A good way to memorize and know chord qualities it to spend a lot of time evaluating chord qualities on the page using some slower method, and visualizing the piano is probably the best slower method.
One other thing you might do is learn to rattle off all the thirds quickly so you always know what's a third above or below any note. As in, ACEGBDFA. Or if you prefer, GBDFACEG. Whatever makes sense to you. This can also help with reading sheet music because lines are thirds apart and spaces are thirds apart.
Answer: Since the piano keyboard is 'graphic' - unlike most other instruments, it's the one that most students are expected to be familiar with, regardless of their primary instrument. Thus, using it as a template is a very good idea. The sharps/flats stand out, and the white keys form a pattern that's easily discernible and memorable - as you're finding.
I think most of us eventually leave that concept behind, as we've learned which notes constitute which flavours of chords, and will play the appropriate notes accordingly. Or see the notes, and just 'know' what sort of chord they constitute.
You ask specifically about qualities of a chord. Suffice to know that it's the interval between root and ^3 that dictate this - m3 =minor, M3 =major, as a basis.
As Todd says, the note sequences using notes on only lines, or only spaces, will be of assistance, but - need to bear in mind any accidentals, or key signatures that are applied. And using that method may not be as effective as visualising the ubiquitous piano keyboard. So, eventually (months, years) you'll just 'know' the different 'formulae' for all the chords!
Comment: I agree, adding that connections among aural/visual/tactile realms often are helpful even for advanced musicians. I never visualize a piano keyboard to know a chord quality (I don't ever remember doing that, but maybe I did when I was rather young). But even as someone with advanced theory knowledge and who has taught music theory, I will still find myself virtually "playing" a piece I don't know while moving my fingers as if I were playing an invisible piano to help "hear" it internally. (I don't generally do it in front of other people, but the aural/kinesthetic connection is helpful.)
Comment: "Most of us"? How I wish. As an amateur singer, I just wish that when the MD says "we'll sing the E-flat-major section" I could just see it on the page the way he does, but I'm a long way from achieving that. For me, it has to go via the mental image of the piano keyboard.
Comment: @MichaelKay - like I say, months , years, which I suspect the MD has.
Answer: Yes, if you want to 'count up' to see how many semitones are between each note, visualizing a keyboard is a good way.  A guitarist might 'count frets' in much the same way.   Eventually you'll just know that D, F, A is a D minor triad, in the same way as you don't have to spell out C,A,T, you just know it spells 'cat'.
(Any particular reason you NEED to analyze in this way?)


Layout botão em flutter

Question: Estou tentando construir um player de vídeo.
No entanto não estou conseguindo deixar o botão do jeito que eu gostaria.
É como se eu precisasse "estender" a dimensão do botão para que o ponto de interseção do borderRadius atingisse o local desejado.
1º Imagem primeiro quadro é como o botão está ficando usando Radius.elliptical
1º Imagem segundo quadro é como eu gostaria que ele ficasse
2º Imagem é uma ilustração da circunferência total do objeto pro ponto de interseção dentro do aspectRatio
3º Imagem é o que acontece se eu uso apenas um Radius.circular
Abaixo o código:
import 'package:flutter/material.dart';
import 'dart:math' as math;

void main() => runApp(
    MaterialApp(
      home: PlayerLayout(),
    )
);

class PlayerLayout extends StatefulWidget {
  @override
  _PlayerLayoutState createState() => _PlayerLayoutState();
}

class _PlayerLayoutState extends State<PlayerLayout> {

  BorderRadius borderStyle;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    borderStyle = BorderRadius.only(
      topLeft: Radius.elliptical(60, 120),
      bottomLeft:  Radius.elliptical(60, 120),
    );

  }

  Widget forwardBackward(angle){

    return Transform.rotate(
      angle: angle,
      child: Container(
        child: Material(
          shape: RoundedRectangleBorder(
              borderRadius: borderStyle
          ),
          child: new InkWell(
              borderRadius: borderStyle,
              onTap: (){print("tapped");},

              child: Stack(
                children: <Widget>[
                  Positioned.fill(
                    left: -32,
                    child: Icon(
                      Icons.play_arrow,
                      size: 38,
                    ),
                  ),
                  Positioned.fill(
                    left: 0,
                    child: Icon(
                      Icons.play_arrow,
                      size: 38,
                    ),
                  ),
                  Positioned.fill(
                    left: 32,
                    child:Icon(
                      Icons.play_arrow,
                      size: 38,
                    ),
                  )
                ],
              )
          ),
          color: Colors.transparent,
        ),
        decoration: BoxDecoration(
            color: Colors.green,
            borderRadius: borderStyle
        ),
        height: double.infinity,
      ),
    );

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: true,
        child: Column(
          children: <Widget>[
            AspectRatio(
              aspectRatio: 16/9,
              child: Container(
                color: Colors.black,
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: forwardBackward(180 * math.pi / 180),
                    ),
                    Expanded(
                      child: forwardBackward(360 * math.pi / 180),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

}

Alguém sabe como consigo deixar igual na segunda imagem?
Comment: @MatheusRibeiro fiz como aconselhou e acrescentei mais algumas informações! Espero que tenha ficado mais claro!
Comment: Você parece ser um usuário das antigas já, então faz o favor, edite sua pergunta e informa teu código aqui na sua pergunta para nós! É mais prático para te ajudarmos e segue o padrão do site...
Answer: Não acredito que esteja muito certo fazer um "círculo" para isso.
Fiz de outra forma (não revisei, então pode ser que tenha como melhorar) e não sei se é o que deseja, pois sua pergunta está meio bagunçada:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.greenAccent,
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Container(
          padding: EdgeInsets.all(5),
          height: 150,
          width: 150,
          decoration: new BoxDecoration(
            color: Colors.pinkAccent,
            borderRadius: BorderRadius.only(
              topRight: Radius.circular(90),
              bottomRight: Radius.circular(90),
            ),
          ),
          child: Container(
            alignment: Alignment.center,
            child: Stack(
              children: <Widget>[
                Icon(Icons.fast_forward, size: 70),
              ],
            ),
          ),
        ),
        Container(
          padding: EdgeInsets.all(5),
          height: 150,
          width: 150,
          decoration: new BoxDecoration(
            color: Colors.pinkAccent,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(90),
              bottomLeft: Radius.circular(90),
            ),
          ),
          child: Container(
            alignment: Alignment.center,
            child: Stack(
              children: <Widget>[
                Icon(Icons.fast_rewind, size: 70),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

Resultado

PS: testado no dartpad.dev/flutter

Layout botão em flutter


Etched border (Win32)

Question: I'm looking for a way to get an etched border style for a window under win32. I have tried DrawEdge with the EDGE_ETCHED flag, which does give me that, but I'm not sure how obtain the same style for a scrollable window. SetWindowLong with GWL_EXSTYLE and WS_EX_STATICEDGE gives me something close, but I haven't found any other style flags that yield a different border. So is this effect even possible?
Thanks in advance,
Christopher
Comment: Erm, what does WS_VSCROLL have to do with the border style?  Set the style flags in CreateWindowEx(), its a crap shoot after that.
Comment: Sorry, I should have pointed out that I'm actually calling win32/GDI stuff from LispWorks CAPI, the Common Lisp GUI tool-kit - so I don't create the windows myself. I've been using DrawEdge to draw an etched border, but anything drawn that way eventually gets scrolled off in a CAPI scrolling window.
Answer: You can do that sort of thing by handling WM_NCPAINT and other WM_NCxxx messages.
The NC stands for "Non Client area" of the window.  The normal drawable area returned in the Device Context (DC) from BeginPaint is clipped to the "client area" of the window.

Etched border (Win32)


Row/column swaps on $AA^T$ (Effect on Eigenvalues?)

Question: Let $A$ be a matrix.
I am trying to study how row/column swaps on $A$ affect $AA^T$, in particular its eigenvalues?
I was thinking that row/column swaps amount to pre- and post- multiplying  permutation matrices (https://en.wikipedia.org/wiki/Permutation_matrix) on $A$.
Hence, $A$ becomes the matrix $B=P_1AP_2$ after row/column swaps.
Then $BB^T=P_1AP_2P_2^TA^TP_1^T=P_1AA^TP_1^T$ since permutation matrices are orthogonal.
Is there any way I can proceed further?
Thanks.
Answer: Actually, given this form you can easily see that the eigenvectors of $AA^T$ have simply seen their components permuted too:
Let $u$ an eigenvector of $AA^T$ for eigenvalue $\lambda$, then if $v = P_1 u$:
$$BB^T v = P_1 AA^T P_1^T v = P_1 AA^T P_1^T P_1 u = P_1 AA^T u = P_1 \lambda u = \lambda v$$
Thus, $v$ is an eigenvector of $BB^T$ for the same eigenvalue $\lambda$.
This means that the permutation operation does not change the eigenvalues or their multiplicities, and only changes the order of the eigenvector components.
Comment: Very nice! Congrats on joining Math.stackexchange. Your answer has helped me a lot.


is Sigmoid activation function better than Leaky Relu?

Question: I recently implemented a neural network from scratch in python with one hidden layer on the iris dataset for classification. Initially i applied Leaky relu for hidden layer acrivations and got an accuracy around 40% then i switched to sigmoid and found that accuracy improved drastically to 93% accuracy.
How is that possible?
I learned from Andrew ng  lectures that Leaky relu is a best option.
Answer: My hypothesis is that you found a configuration (learning rate, batch size, number of hidden nodes, etc.) which happened to be better for the sigmoid network than the Leaky ReLU network. I assume that there's an alternative configuration for which the Leaky ReLU network is better than the sigmoid network.
As an aside, the main motivation of ReLU-type activations is that they work better in deep networks, where sigmoid and tanh networks tend to get saturated and the gradient vanishes. Using a network with 1 hidden layer is not necessarily going to highlight the contrast between sigmoid and ReLU activations.
I would caution against drawing any general conclusions from a single experiment using the Iris data. It's a small data set where one of the classes is linearly separable from the rest, so it's only useful as a toy problem; it's just not very complex.
Answer: There is no "best" activation function. If there were, all the neural network architectures would stick to the single "best" one, while what we see is something opposite: different neural networks, or even different layers of single network, use different activation functions. Some of them, like ReLU, are more popular then others, but there are cases where they don't work and you need to use different activation functions instead. People usually do what you did: start with what is currently known to be most promising solution, but if it fails, try also the alternatives.


Promotion options not visible to Editor role

Question: I have a "Editor" Role with limited access rights. It can basically only create blog type nodes.
I'd like to expose to them the possibility to make to publish the node to the frontpage via the drupal core "publish to startpage" Promotion Option.
By which permission is this controlled? I tried all the node ones, but could not find it.
Answer: It turned out this is controled by the administer content permission. It has security implications, as it also exposes the ability to change the author and creation time of the node.
If you don't what that, you'd need to use the form_alter hook to dissable the athor and creation time field for the Editor role.
For example:
<code>function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if (in_array('editor', Drupal::currentUser()->getRoles(), true)) {

    switch ($form_id) {
      case 'node_blog_edit_form':
      case 'node_blog_form':
         $form['author']['#access'] = false;
         break;
    }

  }
}
</code>


Certain users cannot get to my server

Question: I am finding more and more users that report they cannot reach my server (website or services). Their tracert from that user looks like this:
<code>Tracing route to domain.com [*.*.*.255]
over a maximum of 30 hops:
1 * * * Request timed out.
</code>
The server is up and functional and every else reports it is fine. But there are various users who cannot get to it. I have no firewall or anything that would block anyone.
Yes, the last part of the server IP is 255. Could this be causing it?
http://www.dslreports.com/forum/r18539206-Last-octet-255-bug-on-Windows
Or would a certain ISP be denying traffic to my server?
Or something on their router level?
Answer: That IP is definitely one I would avoid. Even if the end users devices can handle a .255, there's a chance some bad config anywhere between your server and your users might also be mishandling the traffic. Guessing it's a hold-over from the old class-based way of handling subnets.

Certain users cannot get to my server


Wpf Grid, how to set Row , Column programarically

Question: I have a grid with 5 rows, 5 columns, an need to add some paths programmatically, and need to set row an column to,each new path,
how can I do to set both , if SetRow, an SetColumn doesn't appear to be valid methods at my code behind?
My real,problem,is that those properties doesn't appear at my class.
the class is:
system.Windows.Controls.Grid
Comment: http://meta.stackexchange.com/questions/10647/how-do-i-write-a-good-title
Answer: Grid class has two static methods for that purpose Grid.SetRow and Grid.SetColumn:
Grid.SetRow(myControl, 1)
Grid.SetColumn(myControl, 1)

This will set Grid.Row and Grid.Column attached properties for myControl
Comment: It works whit system.Windows.Controls.Grid ? Somethig assembly missed?
Comment: What do you mean? These are static methods so you cannot call them from instance of Grid. You need to call them through Grid class type
Comment: Tks, sorry for my Ignorance.
Answer: They are attached properties, meaning you should call them view Grid.SetRow...


Proof - form of mean value theorem for vector valued function

Question: Can someone show me the proof of this form of the mean value theorem for vector valued functions?
Let $f:R^n \rightarrow R^n$ be a function of class $C^1$ and $a,b\in R^n$, than there exists some $d\in R^n : a<d<b$ such that
$(b-a)\cdot (f(b)-f(a))=(b-a)\cdot (f'(d)(b-a)) $
where $\cdot$ is a dot product
Thanks for any help in advance.
Comment: What does $a<d<c$ _mean_ for $a,b\in\mathbb R^n$?
Comment: Is $f'(d)$ a matrix? The notation is slightly unusual.
Answer: This is based on the theorem 3.10 of Analysis II of Amann and Escher:

Mean value theorem in integral form: let $E$ and $F$ be Banach spaces over $\Bbb R$, $X\subset E$ and suppose that $f\in C^1(X,F)$. Then
$$f(y)-f(x)=\int_0^1\partial f(x+t(y-x))(y-x)\,\mathrm dt\tag1$$
such that $[\![x,y]\!]\subset X$, with $[\![x,y]\!]:=\{x+t(y-x):t\in[0,1]\}$.

Setting $\varphi(t):=\langle v,f(x+t(y-x))\rangle$ for some $v\in F$ and applying the dot product $\langle v,\cdot\rangle$ to both sides of $(1)$ we get
$$\varphi(1)-\varphi(0)=\int_0^1\varphi'(t)\,\mathrm dt\tag2$$
because
$$\left\langle v,\int_0^1\partial f(x+t(y-x))(y-x)\,\mathrm dt\right\rangle=\int_0^1\langle v,\partial f(x+t(y-x))(y-x)\rangle\,\mathrm dt$$
cause $\langle v,\cdot\rangle$ is a linear function. Thus from $(2)$ we can use the MVT for real valued functions, that is
$$\varphi(1)-\varphi(0)=\varphi'(\eta)$$
for some $\eta\in [0,1]$, what is equivalent to the stated MVT of the question.


The cow in the field problem (intersecting circular areas)

Question: What length of rope should be used to tie a cow to an exterior fence post of a circular field so that the cow can only graze half of the grass within that field?
updated: To be clear: the cow should be tied to a post on the exterior of the field, not a post at the center of the field.
Comment: I'm guessing that most fence posts are at the edge of a field, which makes this a far more interesting problem.
Comment: @FordBuchanan: Correct. I've updated the question to (hopefully) make that clear. Sorry for the confusion!
Comment: Possibly related: https://math.stackexchange.com/questions/1942222/, https://math.stackexchange.com/questions/928008
Answer:
The field is the smaller/left circle, centered at A.  The cow is tied to the post at E.  The larger/right circle is the grazing radius.  Let the radius of the field be R and the length of the rope be L.
The grazable area is the union of a segment of the circular field and a segment of the circle defined by the rope length.  (A segment of a circle is a sector of a circle less the triangle defined by the center of the circle and the endpoints of the arc.)  The area of a segment of a circle of radius $R$ with central angle $t$ is $\frac{1}{2}R^2(t-\sin(t))$, where $t$ is measured in radians.
In order to express the grazable area in terms of $R$ and one angle, we consider the angles ∠CED and ∠CAD (which define the segments of the circles; call these α and β for convenience) and the triangle CEF. Let $\theta$ be ∠EFC. $2\theta$ is an inscribed angle for the central angle $\beta$ over the same arc, making $\beta = 4\theta$. The sum of angles in triangle CEF is $\theta + \pi/2 +\alpha/2=\pi$ or $\alpha =\pi-2\theta$.
The grazable area is $\frac{1}{2}L^2(\alpha-\sin\alpha)+\frac{1}{2}R^2(\beta-\sin\beta)=R^2(\frac{1}{2}(L/R)^2((\pi-2\theta)-\sin(\pi-2\theta))+\frac{1}{2}(4\theta-\sin(4\theta)))$, where $a = CE = L/R=2\sin(\theta)$.  We want that to be equal to half the area of the field, $\frac{1}{2}\pi R^2$.
That is, the equality of areas is $$R^2(2(\sin(\theta))^2((\pi-2\theta)-\sin(\pi-2\theta))+\frac{1}{2}(4\theta-\sin(4\theta)))=R^2\frac{\pi}{2}$$
Simplifying:
$$R^2(\pi+(2\theta-\pi)\cos(2\theta)-\sin(2\theta)=\frac{\pi}{2})$$
(The grazable area seems to be $\pi+\alpha\cos\alpha-\sin\alpha$; can this be seen easily?)

The desired equality of areas is obtained for $\theta = \text{ca. } 0.618$ or  $L=\text{ca. }1.159 R$ .
Answer: So, the area of the field is $\pi r^2$ and you want the cow to be able to graze an area equal to half of that.
All you need to do is set up the equation ($r_1$ is the radius of the field, $r_2$ is the length of the rope desired):
$$\frac{(\pi r_1^2)}{2} = \pi r_2^2$$
You can then simplify it down:
$$\frac{r_1^2 }{2} =r_2^2$$
and then taking roots:
$$r_2 =\frac{ r_1 }{\sqrt{2}}$$
So you need a rope that is equal to the radius divided by the square root of $2$, and the post can be no closer than this distance to the edge of the field.
Comment: The post must be on the boundary of the field.
Answer: Let the total area of the field = $A$.
We know $A = \pi R^2$ where $R$ = the radius of the field.
We want the cow to be able to graze half the area, so we solve for a length of rope $r$ such that $\pi r^2 = A / 2$.
This gives: $\pi r^2 = \pi R^2 / 2$, hence $r = R / \sqrt(2)$.
In words, the length of the cow's rope should be the radius of the field divided by sqrt(2).
Comment: Like myself, you assumed the post should be in the center of the field. I deleted my answer because of this mistake. The problem has been reformulated.


Generalized Linear Model in SPSS with common values among predictors treated as subpopulations. Why?

Question: I am teaching a class on logistic regression with SPSS. The textbook supplies a sample data set with a binary predictor and two numeric covariates. The sample contains 1000 rows and a number of these entries have common values for both predictors. One predictor takes only 5 values, for example, and the other takes around 20 distinct values.
According to the documentation of SPSS, when this happens, SPSS treats the data as coming from subpopulations, defined through the common values. This seems to produce a different likelihood and different degrees of freedom for the AIC than what you get if you ignore subpopulations.
I ran the data set in R, using glm. Degrees of freedom were 997, AIC=508.93
On SPSS, I get 99 degrees of freedom (for goodness of fit purposes) and AIC=181.341. The coefficient estimates are the same in both applications.
To make matters worse, when I fit the model in SPSS with only 1 of the 2 predictors, the likelihood is LARGER than with the 2 predictor model: -87 for the 2 parameter model, and -47 for the 1 parameter model. The AIC is also dramatically smaller in the 1 parameter model, but everything else suggests that both predictors are significant and necessary. So much for the AIC criterion.
I jittered the data in R, and sent it back to SPSS. I then got much the same results as in R with glm, since there were no phantom "subpopulations" for SPSS to cope with.
Questions:

can someone supply a reference to justify treating the data as coming from subpopulations (which they actually don't in this case) when the predictors contain common value sets?
How am I supposed to teach model testing by comparing the deviance between two models, using SPSS and this data set, given what's going on?
Can I make SPSS behave like R?
Comment: I don't have the answer, but it is good to know about this. I have a vague memory of SAS (Proc Logistic I think) giving different likelihoods and degrees of freedom if you specify the data as line-per-person (single-line syntax), or as aggregate data with counts of events/denominator for each unique set of covariates (events/trial syntax.) I may be suffering from a faulty memory, but potentially looking at what SAS does might give you (or someone else here) scope to work this out?
Comment: Just Google-booking Paul Allison's "Logistic Regression Using the SAS System: Theory and Application" (which I have a copy of in the office) -- pages 51-3 (all in the preview) talk about how SAS deals with the two different data layouts and the implications for calculating deviance statistics. I'm not mathematically minded enough to parse all the info there, but I hope it might have some hints that might be of use for the general issues, and that might lead to solving your practical problem!
Answer: Apparently you are using the NOMREG procedure.  From the SPSS NOMREG help.  Note that you can also use the newer GENLIN procedure to fit a logistic model.  All three will give the same coefficients and standard errors but may differ in other outputs.
Binary logistic regression models can be fitted using either the Logistic Regression procedure or the Multinomial Logistic Regression procedure. Each procedure has options not available in the other. An important theoretical distinction is that the Logistic Regression procedure produces all predictions, residuals, influence statistics, and goodness-of-fit tests using data at the individual case level, regardless of how the data are entered and whether or not the number of covariate patterns is smaller than the total number of cases, while the Multinomial Logistic Regression procedure internally aggregates cases to form subpopulations with identical covariate patterns for the predictors, producing predictions, residuals, and goodness-of-fit tests based on these subpopulations. If all predictors are categorical or any continuous predictors take on only a limited number of values—so that there are several cases at each distinct covariate pattern—the subpopulation approach can produce valid goodness-of-fit tests and informative residuals, while the individual case level approach cannot.
Comment: (+1) Nice summary. The last few sentences -- about sub-population approach and validity of goodness of fit tests when predictors only take on a few discrete patterns -- was the message I got from reading pp51-53 of Paul Allison's notes on aggregate data in Proc Logistic.
Answer: I did some research after posting my question and basically figured it out. @JKP is right, basically. There is a detailed discussion of this in McCullagh and Nelder, Generalized Linear Models. The subpopulation model assumes that the number of categories remains constant as the population increases. Think of a contingency table where the rows and columns are constant but the cell counts tend to infinity. The degrees of freedom involve an adjustment for the number of cells. That seems to be what SPSS implements under the Generalized Linear Model menu.
This explains why I got incompatible results when I added a variable. The categories changed. The two-parameter model is no longer nested in the one-parameter model, as it would be when the analysis is done by case.
SPSS's Regression -> Binary Logistic menu allows you to enter variables one by one (in what it calls Blocks), and then does the analysis of deviance chi-squared tests for you. Using that menu I was able to get the same results as in R.
In my sample data set, the number of categories is accidental (a result of rounding off a potentially continuous variable), and would probably increase with increased sample size. I am not sure that the subpopulation model would be appropriate here. It's not the one done by the textbook, I might add, which seems to ignore the issue.
Comment: Thanks for the info -- can you provide page or chapter numbers for the McCullagh and Nelder reference please?
Comment: I am using the 1983 edition. The sections of interest are 4.3.2 (asymptotic theory for grouped data) and the following section 4.3.3 on ungrouped. Chapter 4 is about binary data, which is where this is.


List the ProductName for all products in the "Classic Cars" product line from the 1960's

Question: The difficult thing with this question is the fact that there is no real date and I am supposed to extract the date from a description like this "1960 Ford".
I have tried using a sub-string but I was not successful.
this is the query that I used
Select productlines
from  products
where productsline= "Classic cars"
and substring('productname', 1, 4) =>1960 and substring('productname', 1, 4)>=1970

Comment: ``AND `productname` REGEXP '.*196[0-9].*$'``.
Comment: @Sik2 . . . You have single quotes around `'productname'`, so that is a string, not a column reference.  I am voting to close as typo.
Answer: You have done correct query but just you need to remove ' sign from sub string function because column name should not define in string.
Let me know if you still face difficulty.
Comment: removing the query worked but I cannot be able to specify a range, the code is only working with one year like 1969 could you help me specify a range like =>1960 and=<1960 this is the code   `code`Select productline
from  products
where productline= "Classic cars"
and substring(productname, 1, 4)= 1969
Answer: Please, try with below SQL Query:
Select productlines
from  products
where productsline= "Classic cars"
and CAST(substring('productname', 1, 4) as SIGNED) =>1960 and CAST(substring('productname', 1, 4) as SIGNED)>=1970

List the ProductName for all products in the “Classic Cars” product line from the 1960’s


Model Stacking algorithm

Question: I'm trying the stacking method to see if it improves my results, but before using some
R package, I decided to code it by myself. Here's a pseudocode of what I'm doing:
train.all = getTrain()

# separate 20% of data to test the stacked model
test.meta.idx = sample(nrow(train.all), floor(nrow(train.all)*0.2))
test.meta = train.all[test.meta.idx, ]

# remove these from train.all
train.all = train.all[-test.meta.idx, ]

# generate folds for cross-validation
k = 10
folds = generateFolds(k)

# dataset to store base learners predictions
train.meta = data.frame()

for (i in 1:k) {
   train.idx = folds[[1]]$train
   test.idx = folds[[i]]$test

   train = train.all[train.idx, ]
   test = train.all[test.idx, ]

   # train models
   model1 = fitmodel1(formula, train)
   model2 = fitmodel2(formula, train)
   model3 = fitmodel3(formula, train)

  # get model outputs
  y1 = predict(model1, test)
  y2 = predict(model2, test)
  y3 = predict(model3, test)

  y.obs = test$y

  # append to meta train.meta
  train.meta = rbind(train.meta, c(y.obs, y1, y2, y3))
}

Now I can use train.meta to fit a different model, which will give the final result
based on inputs from model1, model2 and model3 predictions. But, how do I test it? For each fold a fit a different model1, model2 and model3, so I will have 10 different model1, model2 , and model3.

Should i re-refit the base learners using the entire training data?
Is it ok to train the meta-model using the fitted base-learner values?

Thanks for any advice!
Comment: You may be interested in : [Introduction to blending in Python](https://www.thekerneltrip.com/python/stacking-an-introduction/) (method and implementation oriented) [Why does blending works ?](https://www.thekerneltrip.com/python/why-does-stacking-works/) (theoretical arguments about the success of this method)
Answer: If I understand your pseudo-code correctly, I don't see where the stacking model is being tested in the cross validation loop. I would expect to see something like
model4 = fitmodel4(model1, model2, model3, train)
y4 = predict(model4, test)

Similar to how the base models' hyper-parameters are being tuned using cross validation prediction error (e.g. neural network's number of nodes, regression's independent variables and potential transformations), there would also be tuning of the stacking model's hyper-parameters in the cross validation loop
As for your questions:

Yes, the final base learners are fit using the entire training data
Yes. The stacking model would use the outputs from the final base learners. Over fitting is related to model complexity and not training on more data.

Model Stacking algorithm


How to position figcaption vertical right from figure?

Question: I have a figure with a figcaption. I would like to position the figcaption beside the figure img, like the image below.
I already tried things like transform rotate and origin, but seems like the problem is that it not fit the new height/width of the parent object.
http://codepen.io/Caspert/pen/eWEvvL
Answer: You add position: relative with top: and left: attributes valued to your figcaption class.
Note: The image and caption will always have to be the same size, etc. if you want consistent results. Also, there is nothing in place for screen resizing causing blocks to move around. You will need to address this for responsiveness, but this is the basic idea.

figure {
  margin-top: 100px;
  position: relative;
}

figcaption {
  position: relative;
  background: rgba(255,0,0,0.6);
     -ms-transform: rotate(90deg);
  /* IE 9 */
  -webkit-transform: rotate(90deg);
  /* Chrome, Safari, Opera */
  transform: rotate(90deg);
   left: 280px;
   top: -102px;

/*   transform-origin: 100% 25px; */
}

figcaption p {
}

Gear

http://codepen.io/illdapt/pen/KmvWEx
Comment: Is there also a fix so I can align the text from the bottom as you can see in my design above?
Comment: I adjusted the codepen link at the bottom, basically added `margin-top` to the figcaption p element to move it into the desired position.
Answer: You could use Flexbox for positioning and transform-origin to control rotated element. You can also modify position of figcaption starting from bottom of figure using margin DEMO.

figure {
  margin-top: 100px;
  position: relative;
  align-items: flex-end;
  display: flex;
}
figcaption {
  background: rgba(255, 0, 0, 0.6);
  transform: rotate(90deg);
  transform-origin: top right;
}
figcaption p {
  margin: 0;
}

Gear


Infinite Perfect power of numbers in a certain form

Question: A question I found very interesting , which I found written on a blackboard while visiting a near by community science center is as follows.

Prove that there exist infinitely many $m,n,k$ for which $1^k+2^k+3^k \cdots +n^k$ is a perfect $m$ power.

I have been trying this from many days but I am unable to make out how to do it . I got one thing that $1^k+2^k+3^k \cdots +n^k | \; n+1$ but I don't thing this would help.
Comment: Note that $1^3+2^3+\cdots+n^3$ is always a square.
Comment: Apart from trivial cases, and $k=1$, $m=2$ (Pell equation) there seems nothing obvious.
Answer: There are many solutions with $m=2$ -- as André noted, the case with $k=1$ gives you infinitely many solutions via Pell's equation. I can't find any solutions where $m$ is not a power of 2 (excepting the trivial cases $n\in\{0,1\}$).


Efeito de contornar borda de uma div, como se desenhasse "à mão"

Question: Quero fazer um efeito de borda, que no hover de uma div quadrada, a borda é "desenhada", sai da parte superior esquerda da div, preenche até a superior direita, desce fazendo a lateral direita, retorna para a esquerda pela inferior, e sobe, completando o quadrado (como se estivesse desenhando a borda com uma caneta).
Pode ser com svg ou com puro css3.
Espero ter sido claro, qualquer dúvida me perguntem! Obrigado desde já.
Answer: Usando transições com delay, dá pra fazer. Veja um exemplo:

a { display:block; position:relative; background:#ffc; width:300px; height:180px }

a::before, a::after { content:""; display:block; box-sizing:border-box;
                      position:absolute;z-index:5; pointer-events: none;
                      width:0; height:0; opacity:0; border:2px solid red }

a::before { border-left:none; border-bottom:none; left:0; top:0;
            transition:width .5s linear 1.5s, height .5s linear 1s, opacity .1s 2s }
a::after  { border-top:none; border-right:none; right:0; bottom:0;
            transition:width .5s linear .5s, height .5s linear, opacity .1s 1s }

a:hover::before, a:hover::after  { width:100%; height:100%; opacity:1 }

a:hover::before { transition:width .5s linear, height .5s linear .5s, opacity .1s }
a:hover::after  { transition:width .5s linear 1s, height .5s linear 1.5s, opacity .1s 1s }
Ponha o ponteiro do mouse aqui

Basicamente criamos dois pseudoelementos, o ::before com a parte superior direita, e o ::after com a parte inferior esquerda.
Usamos posição absoluta nos pseudoelementos e display: block para garantirmos que o elemento ocupe a área toda do parent, que tem posição relativa, para limitar a área dos pseudoelementos.
O z-index:5 faz com que os elementos com borda apareçam sempre por cima do elemento principal, e o pointer-events:none evita que eles "roubem" o clique do mouse do elemento principal.
Como as bordas ficariam aparecendo nos cantos antes da animação, usamos o opacity para escondê-las até o momento certo.
Finalmente, para termos a animação desenhando e "desdesenhando" na hora que o mouse sai do elemento, aplicamos transitions diferentes dentro do elemento, e do elemento:hover.
Para alterar a velocidade, lembre-se de alterar todos os tempos na mesma proporção. A animação atual leva 2 segundos. Por exemplo, se quiser que dure um segundo só, tem que trocar nessa proporção:
Tudo que for  .5s por  .25s
               1s por  .5s
             1.5s por  .75s
               2s por  1s

              .1s você pode manter, pois é pra ser "quase instantâneo" mesmo.

Basta manter a proporção para outras velocidades.
Comment: Perfeito, amigo! Muito obrigado e parabéns pela resposta.
Comment: @TiagoP.C foi um "quebra cabeças" no começo, até eu imaginar como resolver, mas acho que no fim deu pra fazer um balanço legal entre complexidade e resultado. Espero que seja útil, ao menos como exemplo.
Comment: Procurei fazer de uma maneira que você possa usar independente do tamanho do elemento, e que aceite espessuras de borda conforme você achar melhor (desde que não seja muito espessa), mas se tiver alguma duvida em algum ajuste extra, comente aqui.
Comment: Isso é mágica. :)
Comment: Depois vou analisar esse código com calma, ótima solução


Não consigo rodar um player de audio utilizando o Flask com Python3.7

Question: Boa tarde!
Estou tentando realizar uma tarefa aparentemente simples, que é rodar um player de áudio em uma pagina Html utilizando um app feito em Flask, porém não consigo fazer com que o player carregue o áudio.
APP PYTHON:
# -*- coding: utf-8 -*-
#/usr/bin/python3

import os, sys

from flask import Flask, render_template

app = Flask(__name__, template_folder=os.path.abspath("templates"))
path_music = os.getenv("HOME") + "/project/musics/"

@app.route("/", methods=["GET"])
def index():
    return render_template("index.html", music=path_music+"music.mp3")

if __name__ == "__main__":
    app.run(debug=True, port=8080)

ARQUIVO HTML:
<!DOCTYPE html>

    <title>Sound Music</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <audio controls preload="metadata" id="tagAudio" style="width: 99%">
        <source src="{{music}}" type="audio/mpeg">
        Your browser does not support the audio tag.
    </audio>

RETORNO NO NAVEGADOR:

Fiz alguns testes rodando o arquivo index.html direto pelo Firefox retirando a sintaxe utilizada pelo Flask e o áudio é carregado.
RODANDO ARQUIVO PELO FIREFOX

Alguém já teve este problema pode me dar uma força ?
Desde já agradeço!
Answer: Observe que o que vai na sua variável {{music}} no template é criada apontando para o caminho em disco do arquivo mp3. Isso é criado como uma string (texto) e é esse texto que é colocado no HTML.
Quando você está servindo um projeto de um framework em Python, seja o Flask, ou outro, o caminho dos arquivos estáticos não é igual o caminho em disco - o que tem que ser feito é que em alguma configuração do projeto você tem que dizer qual é o diretório que tem seus arquivos estáticos - e alguma configuração para o framework pegar os arquivos de lá.
Com as configurações no lugar, você passa para o template só o nome do arquivo de áudio, e no template, chama a função embutida url_for desse jeito:
# Arquivo em Python
...

@app.route("/", methods=["GET"])
def index():
    return render_template("index.html", music="music.mp3")
...

# Template HTML para o flask:

    <audio controls preload="metadata" id="tagAudio" style="width: 99%">
        <source src="{{ url_for('static', filename=music) }}" type="audio/mpeg">
        Your browser does not support the audio tag.
    </audio>

(lembre-se, dentro das {{ }} nos templates, o que vale é a linguagem
do Jinja2, que lembra um pouco Python - então, ali dentro "music"  é a variável
que foi passada para o template, e o texto final que vai
ficar na tag "src=" do html que o browser vai enxergar é o retorno da função
url_for)
Com isso, o Flask vai montar a url correta para pegar os arquivos
da pasta que estiver configurada para servir arquivos estáticos.
Por padrão, se você não configurou, é a pasta static (no caso, dado
o nome que você colocou no exemplo, provavelmente project/static - (e você
pode colocar uma pasta "/musics" lá dentro).
Para mudar a pasta de onde o url_for puxa arquivos estáticos, na hora
de criar o objeto Flask, você pode passar a opção
static_folder= como em:
app = Flask(__name__,
            template_folder=os.path.abspath("templates"),
             static_folder='music',
)

Mas como para o projeto completo você vai precisar também de arquivos CSS, Javascript, etc...  o melhor pode ser deixar essa pasta como "static" mesmo, criar um "project/static/musics", e dentro código Python, saber que até  o project/static a função url_for gera pra você automaticamente, e você
constrói o caminho a partir dali:
path_music = "musics/"

@app.route("/", methods=["GET"])
def index():
    return render_template("index.html", music=path_music+"music.mp3")

Comment: Valeu cara! Você me salvou pela segunda vez!
Comment: Tenho um outro POST que com sua ajuda eu consegui resolver meu problema, só precisava finalizar ele, acredito que eu não tenha permissão para fazer tal operação, segue o link: https://pt.stackoverflow.com/questions/466193/herdar-m%c3%b3dulos-e-vari%c3%a1veis-de-inicializa%c3%a7%c3%a3o-em-um-script-python-para-outro-scrip
Comment: Se a resposta resolveu seu problema, é só marcar a resposta como aceita - não tem mais "finalizar". No caso do outro post, você pegou as dicas que deixei, e descreveu o que funcionou e marcou como aceito - não é o mais comum, mas é perfeitamente válido.


Como deixar minha WebView reiniciar automático a cada 30 m

Question: Queria saber como deixar minha página reiniciando automaticamente a cada 30 minutos em segundo plano. Quem puder ajudar, agradeço.
Public class tela2 extends AppCompatActivity implementa tela2 {

private Timer t;
private int TimeCounter = 0;
WebView xp1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tela2);

    xp1 = (WebView) findViewById(R.id.xp1);
    xp1.getSettings().setJavaScriptEnabled(true);
    xp1.setFocusable(true);
    xp1.setFocusableInTouchMode(true);
    xp1.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    xp1.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    xp1.getSettings().setDomStorageEnabled(true);
    xp1.getSettings().setDatabaseEnabled(true);
    xp1.getSettings().setAppCacheEnabled(true);
    xp1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    xp1.loadUrl("http://pt.clubcooee.com/client/start");
    xp1.setWebViewClient(new WebViewClient());

    getSupportActionBar().setTitle("pegando xp");
}
public  void  startTimer()
{
    t= new Timer();
    t.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // CODIGO A SER EXECULTADO EM SEGUNDO PLANO A CADA 30 MINUTOS

                }
            });
        }
    },18000000,18000000);

Answer: Para fazer executar alguma coisa em segundo plano, devemos usar os serviços(Service) do Android.
public class UpdatePageService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

Para iniciar um serviço, coloque essa linha de código na sua Activity. Pode ser no onCreate, por exemplo.
startService(new Intent(this, UpdatePageService.class));

Para agendar uma tarefa de tempos em tempos, é recomendado o uso do AlarmManager. O AlarmManager tem vários jeitos de ser implementado dependendo das APIs do Android que seu app irá abranger.
Um exemplo de um serviço com AlarmManager:
public class UpdatePageService extends Service {
    private AlarmManager alarmManagerUpdate;

    @Override
    public void onCreate() {
        super.onCreate();
        configureAlarmRefreshPage();
    }

    private void configureAlarmRefreshPage(){
        Calendar alarmHour = Calendar.getInstance();
        //configura alarmHour com hora atual
        alarmHour.setTimeInMillis(System.currentTimeMillis());
        //adiciona 30 minutos com base na hora atual
        alarmHour.set(Calendar.MINUTE, alarmHour.get(Calendar.MINUTE) + 30);

        alarmManagerUpdate = (AlarmManager) getContext().
                          getSystemService(Context.ALARM_SERVICE);

        //verifica a versão do Android para configurar com o método adequado
        if (Build.VERSION.SDK_INT >= 23) {
            alarmManagerUpdate.setExactAndAllowWhileIdle(AlarmManager.
            RTC_WAKEUP, alarmHour.getTimeInMillis(),
            PendingIntent operation);
        } else if (Build.VERSION.SDK_INT >= 19) {
            alarmManagerUpdate.setExact(AlarmManager.RTC_WAKEUP,
            alarmHour.getTimeInMillis(),
            PendingIntent operation);
        } else if (Build.VERSION.SDK_INT >= 15) {
            alarmManagerUpdate.set(AlarmManager.RTC_WAKEUP,
            alarmHour.getTimeInMillis(),
            PendingIntent operation);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // cancelar todos os alarmes
    }
}

No terceiro parâmetro da configuração de alarmManagerUpdate.set(), você precisa passar uma PendingIntent. A PendingIntent vai te informar quando o alarmManagerUpdate estiver no tempo de atualizar a página. A implementação da PendingIntent depende do jeito que você deseja obter o aviso do alarme.
Documentação PendingIntent
Observação importante: Seja cuidadoso com a implementação de um AlarmManager, pois se implementado de maneira incorreta, pode minimizar a duração da bateria.
Aqui tem alguns exemplos de implementações com PendingIntent


what would be initial capacity of a new dynamodb ondemand table

Question: If I create a new on-demand dynamodb table, what would be its initial allocated read and write units?
This link shows 40k read and write units - https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ServiceQuotas.html#default-limits-throughput-capacity-modes
Provisioned tables converted to on-demand will have provisioned units set as allocated ondemand capacity - https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html
Comment: With on-demand, there are no allocated read/write units.  40k that you mention is the max throughput that can be achieved by default. In tables that are set to on-demand, you pay per number of requests that are made, so the question of allocated read/write units doesn't make sense for on-demand tables
Comment: right, what I meant to ask was how much is the max peak set for new on-demand tables which haven't been used at all?
Answer: A newly created on-demand mode table has a previous peak of 2000 WCU and 6000 RCU.
As you can consume double your previous peak that allows you to make 4000 WCU and 12000 RCU per second.
Comment: Where does this information come from? The DynamoDB documentation (linked by OP) and Service Quota page in AWS accounts show read and write throughput limits for on-demand tables to be 40000
Comment: The OP is not asking about quotas, they are asking about initial allocated read and write units. The table level soft limit is 40k which is a different thing altogether.
Comment: what does table level soft limit mean? does it mean the max peak a table can go is 40k? I think that's not the case as I have seen tables with higher peaks.
Comment: That's why its called a soft limit, you can increase beyond that limit with a request using Service Quotas. But without a limit increase in place you will be throttled beyond 40k.


Example where unique stationary law, which is an occupation law, but no limit law exists

Question: I am currently learning about the balance equations, mass equation, limit law, occupation law and stationary law in Markov models. The following example is presented:

Example 2:
$$\mathcal{P} = \begin{bmatrix} 0 & 1 & 0 \\ 0.1 & 0 & 0.9 \\ 0 & 1 & 0 \end{bmatrix}.$$
The balance equations are
$$\pi_1 = 0.1 \pi_2, \ \pi_2 = \pi_1 + \pi_3, \ \pi_3 = 0.9\pi_2$$
The mass equation is
$$\pi_1 + \pi_2 + \pi_3 = 1$$
The unique solution to this balance plus mass system is
$$\pi_1 = 0.05, \ \ \ \pi_2 = 0.5, \ \ \ \pi_3 = 0.45.$$
So once again: if there is a limit law, then this is it.
However, a calculation shows that
$$\mathcal{P}^2 = \begin{bmatrix} 0.1 & 0 & 0.9 \\ 0 & 1 & 0 \\ 0.1 & 0 & 0.9 \end{bmatrix},$$
and that $\mathcal{P}^3 = \mathcal{P}$.
It follows that $\mathcal{P}^{2m - 1} = \mathcal{P}$ and $\mathcal{P}^{2m} = \mathcal{P}^2$ for $m = 1, 2, \dots$.
Thus the powers of $\mathcal{P}$ oscillate and do not converge; there is no limit law.

The following is then said:

In example 2, counting the oscillating terms shows that
$$m_{ij}(n) = \begin{cases} \delta_{ij} + \dfrac{1}{2} n(p_{ij} + p^{(2)}_{ij}) & \text{if} \ n \ \text{is even,} \\ \delta_{ij} + \dfrac{1}{2} (n + 1)p_{ij} + \dfrac{1}{2}(n - 1) p^{(2)}_{ij} & \text{if} \ n \ \text{is odd.} \end{cases}$$
Dividing by $n$, you will see that the limit exists and
$$\pi^*_{ij} = \dfrac{1}{2} (p_{ij} + p^{(2)}_{ij}) = \dfrac{1}{2}(0.1, 1, 0.9)$$
So we have a unique stationary law which is an occupation law, but no limit law exists.

There are two points of this that I am unclear on:

How did the author get

$$m_{ij}(n) = \begin{cases} \delta_{ij} + \dfrac{1}{2} n(p_{ij} + p^{(2)}_{ij}) & \text{if} \ n \ \text{is even,} \\ \delta_{ij} + \dfrac{1}{2} (n + 1)p_{ij} + \dfrac{1}{2}(n - 1) p^{(2)}_{ij} & \text{if} \ n \ \text{is odd.} \end{cases}$$
from example 2?

My understanding is that $\pi^*_{ij} = \dfrac{1}{2} (p_{ij} + p^{(2)}_{ij}) = \dfrac{1}{2}(0.1, 1, 0.9)$ is for the first (even) case (after division by $n$ and then taking the limit), but what happened to the second (odd) case?

I would greatly appreciate it if people would please take the time to clarify these two points.

EDIT:

Let $(X_n)$ be a Markov chain, and fix a state $j \in S$.
Define indicator variables: For $n = 0, 1, \dots$, let
$$I_n(j) = \begin{cases} 1 & \text{if} \ X_n = j, \\ 0 & \text{if} \ X_n \not= j. \end{cases}$$
$I_n(j) = 1$ says that the MC occupies state $j$ at time $n$.
The probability $I_n(j) = 1$ is $p^{(n)}_{ij}$ if $X_0 = i$.
$I_n (j)$ has a Bernoulli law with parameter $p^{(n)}_{ij}$.
Lemma 2. $E(I_n (j) \vert X_0 = i) = p^{(n)}_{ij}$.
Let $N_n (j) = \sum_{m = 0}^n I_m (j), \tag{6}$
$N_n (j)$ is called the occupation time of the state $j$ (up to time $n$).
Note that $\sum_{j \in S} N_n (j) = n + 1$.
The mean occupation time of state $j$, given the initial state $i$, is
$$m_{ij}(n) = E(N_n(j) \vert X_0 = i), \ \text{for all} \ i, j \in S.$$
Then $M(n) = (m_{ij}(n))_{ij}$ is called the mean occupation time matrix.
Theorem 3. The mean occupation time matrix is given by
$$M(n) = \sum_{m = 0}^n \mathcal{P}^m \tag{7}$$
Proof: It follows from Lemma 2 and (6) that
$$m_{ij}(n) = \sum_{m = 0}^n E[I_m (j) \vert X_0 = i] = \sum_{m = 0}^n p^{(m)}_{ij}.$$

$\mathcal{P}^n$ is the $n$-step transition matrix.
Comment: This is a really neat little example. Could you post a definition for $m_{ij}$ and $n$?
Comment: @eric_kernfeld See my edit. For more, see this related question: https://stats.stackexchange.com/q/454380/163242
Comment: @eric_kernfeld So, any chance you have an answer to confusion here?
Answer: Your second question is easier. In the limit, $\frac{n\pm 1}{n} \rightarrow 1$, so $$\frac{\delta_{ij}}{n} + \dfrac{1}{2} \frac{(n + 1)p_{ij}}{n} + \dfrac{1}{2}\frac{(n - 1) p^{(2)}_{ij}}{n}$$  goes to $\frac{1}{2}p_{ij} + \frac{1}{2}p^{(2)}_{ij}$.
For the first question: every time you go through an odd-numbered state, you increment by $p_{ij}$. This is because of theorem 3 combined with $P^n = P$ for odd $n$. Every time you go through an even-numbered state, you increment by $p^2_{ij}$. This is because of theorem 3 combined with $P^n = P^2$ for even $n$. If you write out the first few cases, you will see that's all these formulas do. For example, for $n = 5$, it's
$$\delta_{ij} + 3p_{ij} + 2p^{(2)}_{ij}.$$ The $3$ accounts for $n = 1, 3, 5$ and the $2$ for $n = 2, 4$. The delta accounts for $n = 0$.
The intuitive explanation here is that, in terms of little cars traversing the state space, there is a continuous morning and evening rush hour between the suburbs (states $1$ and $3$) and the city (state $2$). Thus, there is no equilibrium reached at any time. But when you average over many time points, the pothole distribution does converge.


Possible reasons for AUC=1 (from a fitted glm model)?

Question: I am running high-throughput microarray data (methylation array), and after running univariate, lasso and cross-validation lasso analyses, I was able to come down to a list of 15 probes (predictors).
Now, I want to run a ROC/AUC curve in order to check whether those predictors are in fact good candidates. Problem is that the result coming out of it is a ROC curve with an AUC=1. I have been trying to twitch the fitted model (i.e. family and maxit), but the results did not change.
Here is a sample of the data (with 8 predictors) and the downstream analysis, with some explanation:
          Tumor   probe_1     probe_2     probe_3    probe_4    probe_5    probe_6    probe_7     probe_8
Benign.A4    No -5.076257 -3.18658187 -2.91627872 -3.2393655 -2.4080861 -3.9414602 -4.5844204 -2.96877633
Benign.A1    No -3.232952 -2.21518181  0.71340947 -2.1103999 -1.4563154 -4.0614544 -2.9378821 -0.90468942
Benign.C2    No -4.487701 -3.34515435 -5.35341349 -2.0355878 -2.9573763 -4.2980546 -4.3421487 -2.35597830
Benign.C8    No -3.692610 -1.24332686 -0.59115736 -3.4852858 -2.3339160 -3.1302782 -3.0943430 -1.03581249
Benign.D7    No -2.978757 -0.05097524  0.02744634 -1.4946543 -1.5593915 -2.8860660 -2.7633458 -0.99299595
Benign.D3    No -2.441925 -1.98227873 -2.13478645 -3.0265593 -2.7789079 -3.9860489 -2.8512663 -2.61804934
Tumor.A6    Yes  1.044348 -5.85637090 -4.49697162  1.5033139  0.3226736  1.5937440 -0.4881769  0.95135529
Tumor.A5    Yes  1.749187 -2.93393903 -5.54439148  2.4403760  1.6238294 -1.1699169  3.0410728  1.07437064
Tumor.A2    Yes  2.323806 -6.57693143 -5.78690184  1.7684931  2.3522317  0.3517146 -1.9972320  1.46663990
Tumor.C1    Yes  2.229316 -6.69010615 -6.22036584  0.7482678  1.3277280  0.6128029  1.3349142  1.63602050
Tumor.C6    Yes  2.888489 -5.79079519 -5.02991621  1.4605461  1.3002248  1.1498193  0.4481215  0.81473797
Tumor.C5    Yes -1.861726 -5.14400193 -5.26197761  1.0023323  0.8582683  0.5492184  0.6720438  1.73785369
Tumor.D1    Yes  2.776804 -6.78537165 -6.20280759  2.0623420  1.8291220  1.7328508  1.3667038  1.77813837
Tumor.D6    Yes  2.985209 -6.13405436 -5.92181030  1.8801728  1.1815045  2.2210693  0.1363381  2.21102559
Tumor.D8    Yes  1.670136 -6.72855542 -6.61156537  1.9847271  1.6267041 -2.8621148  0.7134887 -0.56794735
Tumor.A3    Yes  2.106628 -5.61286600 -5.75976883  2.1291475  0.5839721  1.4210874  1.2746626  1.77239233
Tumor.A8    Yes  1.798005 -5.53405698 -5.34042037  3.0262657  1.2199790  1.2448107  1.2297283  0.25649834
Tumor.A7    Yes  1.798074 -6.03775348 -5.01964376  1.2428083  2.3899569  0.6292222  0.6439477  0.92047002
Tumor.C3    Yes  1.542737 -6.54219832 -5.94287577  1.6111676  2.1889028  0.1228641  0.7950770  1.38000135
Tumor.C7    Yes  3.369420 -6.84809093 -5.88474727  2.7525838  3.2090893  1.1435739  1.2199450  0.89089956
Tumor.C4    Yes  3.179484 -6.59432541 -5.68920298  2.4093288  2.3173752 -0.3378846  1.3653768  0.66432101
Tumor.D5    Yes  2.328382 -6.41234621 -6.18003184 -0.1768171  2.1202506  2.4287615  1.7804487  0.08098025
Tumor.D4    Yes  3.051829 -7.01875245 -6.32614849  1.4200916  2.3582254  2.4981644  1.7878118  1.14826500
Tumor.D2    Yes  2.686846 -3.57625801 -6.25573666  1.6330575  0.8448418  1.4229245 -0.6461006  0.09491185

The glm analysis:
> glmcgs <- glm(Tumor ~ probe_1 + probe_2 + probe_3 + probe_4 + probe_5 + probe_6 + probe_7 + probe_8 + probe_9 +
                  probe_10 + probe_11 + probe_12 + probe_13 + probe_14 + probe_15, data=cgshort, family = quasibinomial(link = 'logit'), maxit=100)

> summary(glmcgs)

Call:
glm(formula = Tumor ~ probe_1 + probe_2 + probe_3 + probe_4 +
    probe_5 + probe_6 + probe_7 + probe_8 + probe_9 + probe_10 +
    probe_11 + probe_12 + probe_13 + probe_14 + probe_15, family = quasibinomial(link = "logit"),
    data = cgshort, maxit = 100)

Deviance Residuals:
       Min          1Q      Median          3Q         Max
-6.227e-06  -3.066e-07   3.076e-06   4.536e-06   6.389e-06

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  23.68423    5.23171   4.527 0.001932 **
probe_1       0.41584    1.03539   0.402 0.698471
probe_2      -0.88243    0.80631  -1.094 0.305630
probe_3      -1.14642    0.60525  -1.894 0.094819 .
probe_4       0.08650    1.64350   0.053 0.959314
probe_5      -1.46564    1.38381  -1.059 0.320469
probe_6      -0.72839    1.35910  -0.536 0.606580
probe_7       2.59539    0.48714   5.328 0.000704 ***
probe_8       2.03890    1.43339   1.422 0.192700
probe_9       0.87683    1.52469   0.575 0.581041
probe_10      1.79828    0.80940   2.222 0.057028 .
probe_11      0.66033    0.93300   0.708 0.499195
probe_12    -14.75184    2.98871  -4.936 0.001141 **
probe_13      3.30891    1.31239   2.521 0.035737 *
probe_14      0.36376    0.99582   0.365 0.724368
probe_15     -0.03516    0.91771  -0.038 0.970375
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for quasibinomial family taken to be 6.771977e-11)

    Null deviance: 2.6992e+01  on 23  degrees of freedom
Residual deviance: 3.9885e-10  on  8  degrees of freedom
AIC: NA

Number of Fisher Scoring iterations: 24

PS: the reason why I am using quasibinomial here is because within the samples "Tumor", there are 2 different stages. However, there is no statistical difference in methylation levels between them (previous analysis has been performed).
And finally, the ROC curve with AUC:
> roc.final <- roc(cgshort$Tumor, fitted(glmcgs), smooth=FALSE)

Call:
roc.default(response = cgshort$Tumor, predictor = fitted(glmcgs),     smooth = FALSE)

Data: fitted(glmcgs) in 6 controls (cgshort$Tumor No) < 18 cases (cgshort$Tumor Yes).
Area under the curve: 1

My guess is because the sample size is not big enough, which would also explain the high standard error. Would that be it? And would there be any way to still evaluate the efficiency of those potential predictors in such a sample?
Comment: I think you should work a little on this question for making the example reproducible. I think that the main issues here are statistical and not on the programming side. This question should be moved to cross-validated. I doubt that lasso left all the 15 predictors in the model, I think that your model predicts exactly the tumor, in fact probe1 is enough to predict 100% accurately (probe1 below/above -2).
Comment: Thank you, @paoloeusebi. Yes, the question is mostly on statistics (sorry, if there is somewhere in the post that doesn't make it clear, despite the tags). And yes, the upstream analyses were not added here. Briefly, I ran (1) univariate linear regression first (in ~13,000 predictors), and got ~11,000 out of it (p<0.05) (PS: those ~13,000 were found among ~500,000 predictors initially, by limma). (2) Lasso and cross-validation, where I got to those 15 final targets. As for predicting "exactly" the tumor, I can totally see your point. But it does look very iffy, no? Thanks again.
Comment: so you have how many observations? and 500.000 possible predictors? if your sample is little enaugh even completely random predictors could very well have a perfect association with your response variable, if you choose it from such a large poll
Answer: If the model manages to set apart successes and unsuccesses completely, AUC will be 1. you have very little data and many predictors, and some of them are very effective in predicting outcome, so no surprise here that the model appears deterministic and ROC curve is square.
Let me guess: you used maxit parameter because model estimation woudn't converge. This means that that solution is not reliable. To get one you may use generalized LASSO, or some other kind of regularization.
This is a statistics question by the way.
Comment: Hi, @carlo. You did get that completly right: the maxit parameter was set due to no convergence of estimation. Also, I just added a brief statistical procedures to @paoloeusebi comment above. I did do LASSO, and those 15 came out from that. Unfortunately, the sample size is quite small. Would you have more suggestions on what to try? Also, does it make sense to use the `quasibinomial` family here? And thanks for the spot on comment on `maxit`.
Comment: I see that you used LASSO to select variables, ok. what I was suggesting is to use LASSO to estimate the final model, directly or after a first selection, in general there is no preferred behaviour, even if you can of course try to see what gets you better out-of-fold performance.
Comment: As I just pointed out in the comment above, the number of predictors you have is your biggest problem. Anyway, binomial quasi-likelihood (called quasibinomial in R) only makes sense if you have grouped data, while in the sample you posted I only see individual observations. So, no, quasi-likelihood here is pointless


Multiple Content Types sharing a lot of common fields

Question: I wanna have three types of Events on my website. All three types of events have common fields such as: name, date, location, time, host, price.. and many more.
Now each event type has few extra fields that do not apply to other events types.
It is very important requirement in UI administration form not to show fields that do not apply to a specific event type.
I was considering the idea of creating 3 separate Content types (one for each Event type), but somehow I feel this is not the best way to go since there is a lot of common elements.
Any suggestions?
Answer: If the content types share the majority of fields, it makes sense to keep them as a single content type.
I'd suggest adding a field for "Event type" or similar to record what sub-type of Event the content is and perhaps group the additional fields in fieldsets.
You can then show/hide the additional relevant fields with hook_field_attach_form (or equivalent) by setting '#access' => FALSE on the relevant field.
If you don't mind showing the fields to the user, you could also use a module like conditional_fields (D7 dev works ok)
Comment: Thank you David! While your solution is generally right, in my case it would not be worth doing it since I have many fields to hide. That said I'm gonna handle it as 3 independent types just to save some time since the project's budget is pretty limited.
Answer: If you want to create three different content type for the events, then you can add common fields in one content type and then can add existing field in other content type as below.

Go to Administration -> Structure -> Content types
Click on "Manage fields" link in row of content type
In the "Add existing field" section, select the your field from in "select an existing field" drop box and save the form.

I also prefer the solution which is suggested by David, but if I need to add multiple condition to hide other fields, then creating different content type would be easy solution.
Comment: Thank you Jayendra! This was my first idea but I think David's solution is the right one. Just in favour of shorter development time, I will pick my original idea and also what you suggested here.


How does the password reset model work?

Question: Email providers use secret questions as a part of the process to reset a user's password, when the user doesn't remember it, right? Generally, how does this security model work? How do the security questions identify the user?
Generally: how does the reset password model work? What is its architecture?
Comment: First of all email providers give the chance to the users to reset their passwords with a set of secret questions. The user chooses one question and ansewers it.If he forget his password he just answer the secret questi
Comment: Your question is disjointed and uses poor grammar. Please reword
Comment: My apologies for the poor grammar.
Answer: Basically on registration, the user picks and answers the questions, which are saved in the database.
When the users forgets his or her password, they are asked those questions, and the idea is that only the user would know the answer to those questions. If they answer them correctly, they can be trusted to be the actual user and a new password can be issued.

How does the password reset model work?


Fazer aplicação Java rodar como Serviço

Question: Tenho uma aplicação Java e gostaria que a mesma rode como um serviço no Windows.
Pesquisei na net e vi algumas formas de fazer sendo algumas mais práticas e outras meio confusas.
Alguém que já tenha feito algo do tipo poderia indicar qual caminho utilizou?
Comment: Da uma olhada [aqui](https://stackoverflow.com/questions/68113/how-to-create-a-windows-service-from-java-app).
Answer: Não dá para fazer uma aplicação Java rodar como serviço no Windows utilizando apenas Java.
Você terá que fazer uma outra aplicação, em outra linguagem (.Net, C++...) encapsulando a sua. Esta outra aplicação é que vai rodar como serviço e vai gerenciar a execução da sua aplicação em Java.
Se você tiver opção de usar uma ferramenta de terceiros (que nem sempre é de graça), eu já usei esta aqui e recomendo porque é flexível, funciona muito bem e poupa bastante mão de obra sua: Java Service Wrapper.

Fazer aplicação Java rodar como Serviço


Como centralizar texto rotacionado numa div?

Question: Olá amada comunidade!
Estou rotacionando um p dentro de uma div, porem não consigo centralizar ele, estou com bastante dificuldade no css, ja tentei definir um width: e height: para o p, deixei como auto, mas não funciona.

p.vertical
    {

     transform: rotate(-90deg);
     -webkit-transform: rotate(-90deg); /* Safari/Chrome */
     -moz-transform: rotate(-90deg); /* Firefox */
     -o-transform: rotate(-90deg); /* Opera */
     -ms-transform: rotate(-90deg); /* IE 9 */

     font-size: 17.5px;
     font-family: Arial;

    }

Como centralizo esse texto baseado na altura da div azul?

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

              ola
              teste

Tenho uma duvida também relativo ao CSS, porque o porque não respeita o tamanho da div azul, se ele é filho?
Answer: Primeiro coloca text-align:center; no texto.
Depois coloca essas classes no box-azul: display: flex; justify-content: center; align-items: center;
Veja como fica no exemplo abaixo:

p.vertical
    {

     transform: rotate(-90deg);
     -webkit-transform: rotate(-90deg); /* Safari/Chrome */
     -moz-transform: rotate(-90deg); /* Firefox */
     -o-transform: rotate(-90deg); /* Opera */
     -ms-transform: rotate(-90deg); /* IE 9 */

     font-size: 17.5px;
     font-family: Arial;
     text-align: center;

    }

Como centralizo esse texto baseado na altura da div azul?

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

                          ola
                          teste

Comment: To ligado como é, quando eu comecei não tinha esses frameworks, eu aprendia era no tapa haha. Cara leia muito, principalmente as documentações W3C, não fica só vendo vídeo no Youtube não! Entra nesse site e sai clicando e lendo tudo que vc puder, estude os exemplos, e vai tentando copia-los ou aplica-los em outras situações. Para trabalhar com CSS tem que ter certa criatividade... https://css-tricks.com/ se precisar de algo em português me fala. As vezes vale a pena algum curso tb, indico esse! https://www.origamid.com/
Comment: exatamente isso, aonde eu posso estudar mais css? to apanhando quando nao uso bootstrap


Phaser: Stretch background image to 100%?

Question: The easiest way to get a fullscreen background I guess is to set the dimension of the sprite as the games dimension.
var game = new Phaser.Game(800, 600, Phaser.CANVAS, '');

1. How would I give the sprite these pixel sizes?
2.If I create the game object with the string "100" in both width and height it will be as big as the screen, so what do I set the sprite to then?
Answer: optionally, you can also use these methods to get the width and height in a pixel value
var w = window.innerWidth;
var h = window.innerHeight;

Comment: my problem was that I wasn't able to set the exact pixel size of the sprite. I did however find out that it was as simple as sprite.height / width.


Security when SMTP Relay is allowed from the Private Address Blocks

Question: Is it safe to allow SMTP Relay from the private address blocks?

10.0.0.0/8
127.0.0.0/8
172.16.0.0/12
192.168.0.0/16

My gut feeling is that it's probably OK, however I'm not sure if that will not make my server susceptible to something like IP-forgery attacks or similar. Basically what are the chances that some black-hats will apply some smart techniques and will fool my MTA into thinking that it has received the envelope from the private address block, effectively turning it into the open relay?
My MTA is running inside the docker container, so I was afraid that all connections (including ones from the remote servers) will be treated as the local connections. However you can see from the following log entry that the MTA was able to work out that incoming connection is remote:
SMTP connection from [xxx.yyy.39.83]:43108 I=[172.18.0.2]:25 (TCP/IP connection count = 1)

In general how do MTAs gather such information, do they take it from the TCP connections, from the SMTP headers, something in between?
Answer: A safer setup would be to generally block unauthenticated SMTP, whitelisting only those few services that are unable to authenticate - which by now should be none or nearly none.
Comment: **Un**authenticated hosts, or IPs are **always** a bad idea. Can you say "open relay"? +1 for your assertion Mikael!
Answer: The IP addresses that an MTA users for allowing relay are usually taken from the TCP session. In this case (TCP and modern systems) they are effectively unforgeable unless the forger has access to the network infrastructure between you and the remote IP. However you should note that:

As Mikael H says you should consider authenticated SMTP.
Some network load balancers (ELB for example) will rewrite the TCP source address to its own. In that case you need to make sure that your MTA and load balancer agree on a way to communicate the real external IP (search for ELB Postfix "Proxy protocol", which would be your "in between").
If you're really set on crossing all the Ts, you may want to restrict private addresses from entering your network and/or restrict the whitelist to IPs that you are actually using.
Comment: When you say `Proxy protocol` I think you bear in mind [HAProxy Proxy Protocol](https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt)?
Comment: Yep, developed by HAProxy if I remember correctly, implemented in both ELB and Postfix.


Is it a Cauchy sequence?

Question: Let $(X,d)$ be a metric space and $(x_n)$ is a sequence in $X$. Then $\sup_{p\ge 1} d(x_n,x_{n+p}) \rightarrow 0$ as $n\rightarrow \infty$ implies  $(x_n)$ is a Cauchy sequence. Any hints or counterexample to prove or disprove this implication? Thanks in advance.
Comment: I would just go straight to the definition.  Fix $\epsilon>0$ and try to use the hypothesis to show there is some $N$ such that $|x_m-x_n|<\epsilon$ for all $m,n\ge N$.  Notice what you are given shows there exists some $M$ such that $|x_n-x_{n+p}|<\epsilon$ for all $n\ge M$, $p\ge 1$.  Is it now sufficient to take $N=M$?
Answer: Given $\epsilon>0$ there is $N$ such that $\sup_{p\ge 1}d(x_nx_{n+p})<\epsilon$ for all $n>N$. Then for all $m>n>N$, we have $d(x_n,x_m)\le \sup_{p\ge 1}d(x_n,x_{n+p})<\epsilon$.

Is it a Cauchy sequence?