Specifying starting values from previous class in flexmix

Question: I am using the flexmix package in R to perform latent class analysis with covariates using model with 1 to 3 classes/components.
For model with 3 classes, I'd like to use coefficients from model with 2 classes as the starting values but not sure how to do that.
I know that we can use the posterior probabilities from model with same class by specifying the cluster argument, but this is only suitable for model with same number of class/component and this uses posterior probabilities not coefficients.
m2 <- flexmix(Y ~ x1+x2+x3, data = NPreg, cluster = posterior(m1), k = 3)

Is there a way I can specify starting values of coefficients from model with 1 or 2 classes?
Detailed documentation of this package can be found here: https://cran.rapporter.net/web/packages/flexmix/vignettes/mixture-regressions.pdf
Comment: Do you have any idea about this question? I cannot add a comment so I just add an answer. And could you tell me how to define the starting values of the posterior class probabilities? There are only 'weights' argument in the flexmix function. Thanks!
Answer: It is maybe late for an answer and I am no flexmix expert, but I have been using it a little bit and here is what I came with concerning your question.
First, flexmix uses an EM algorithm to estimate the model parameters (flexmix paper sec 2.1). In the M-step, we update the coefficients using the posterior class probabilities that we have so far (and maybe the previous estimates of the coefficients as well, since this is an iterative process - see however point 2 below). In the E-step, we update the posterior class probabilities.
That being said, two things may be put into evidence:

It seems that flexmix starts by the M-step (here). That's why we have an argument allowing us to define the starting values of the posterior class probabilities, but not of the coefficients.
Moreover, the default M-step of flexmix for gaussian models (called FLXMRglm) does not need coefficients as starting value. As we can see here, this solver uses a weighted least squares formula). That being said, the "and maybe the previous estimates of the coefficients" that we mentioned above does not apply for the default case, and start values for the coefficients would not be used, even if provided...

So no, we cannot choose the start values for the coefficients, but there may be something you can do to overcome that limitation.
Supposing that by using the coefficients of a 2-class model with a 3-class model you mean, for instance, taking the coefficients of class 1 (old model) for both classes 1 and 2 (new model), and taking the coefficients of class 2 (old model) to class 3 (new model), than you may choose the posterior class probabilities to emulate that behavior. This is an idea, that I will illustrate with an example:

Let's say that there are 4 observations and that the final posterior class probabilities of the old model are [(0.8,0.2),(0.6,0.4),(0.7,0.3),(0.5,0.5)]
We would then use the following starting values for the posterios class probabilities of the new model: [(0,4,0.4,0.2),(0.3,0.3,0.4),(0.35,0.35,0.3),(0.25,0.25,0.5)]

By using this trick, class 3 (new model) would have the same probabilities as class 2 (old model), while classes 1 and 2 (new model) would be "equal" and, together, represent class 1 (old model). I could not meditate about this heuristic and what it means mathematically, but here is it as an idea anyway.


How to send cookies in websocket connection from extension's background script?

Question: I am trying to open an authenticated websocket connection to my backend from a chrome extension, for that I am using session cookies. This is my manifest file:
{
    "manifest_version": 2,
    "background": {
        "scripts": ["extension.js"],
        "persistent": true
    },
    "permissions": [
        "tabs",
        "storage",
        "http://localhost:8000/",
        "ws://localhost:8000/"
    ],
    "icons": {
        "16": "img/icon16.png",
        "48": "img/icon48.png",
        "128": "img/icon128.png"
    }
}

there I asked permission to access localhost:8000 on both HTTP and websocket schemes, but Chrome send cookies only for AJAX requests. If I try
await fetch('http://localhost:8000/checklogin', {
    method: 'GET',
    credentials: 'include'
});

from background script cookies are sent, but if I try
const ws = new WebSocket('ws://localhost:8000/');

no cookies are sent at all.
Is not that same domain, why Chrome is not sending cookies for websocket?
Answer: From my research I concluded CORS with credentials for websocket is not supported in chrome extensions, so Chrome won't inject credentials in websocket upgrade requests. A workaround for that is to use chrome.webRequest to intercept websocket upgrade request and inject the Cookie header:
class WebsocketCookie {

    constructor(websocketUrl, name, value) {
        this.name = name;
        this.value = value;
        chrome.webRequest.onBeforeSendHeaders.addListener(
            ({ requestHeaders }) => {
                requestHeaders.push({name: 'Cookie', value: `${this.name}=${this.value}`});
                return {requestHeaders};
            },
            {types: ['websocket'], urls: [websocketUrl]},
            ['blocking', 'requestHeaders', 'extraHeaders']
        );
    }
}

// you can change this cookie later by changing cookie.name or cookie.value
const cookie = new WebsocketCookie('ws://localhost:8000/', 'sessionid', 'my_session_id');
const ws = new WebSocket('ws://localhost:8000/'); // sessionid cookie will be injected

that requires websocket URL, webRequest and the webRequestBlocking permissions to be added to manifest file. Use chrome.cookies to get cookies you need to inject in websocket upgrade request.
If you would like to improve security, onBeforeSendHeaders callback takes the origin of that request as initiator member, use that to check if origin is your own extension. You can get your extension's origin using chrome.management API.
Comment: For me, it's not working. Pushing non cookie header can work while pushing cookie header will not work.


How many ways are there to prove that there is no largest prime?

Question: Is there any other proof by which I can show that there is no largest prime?
I saw an example where  it is proved with contradiction.(Idea is basically that of Euclid's proof)

Imagine that the largest prime prime is $13$.So, total number of primes we know are-$2,3,5,7,11,13$.
Now,if I do $(2\times3\times5\times7\times11\times13)+1=30031$.So, we can see that $30031$ is not divisible by $2,3,5,7,11,13$ as they leave remainder $1$. Also,as it is formed by multiplying only primes it does not have any other composite factors.We also see that $30031=59\times 509$.Which are again two primes.Thus,$13$ is not the largest prime.

What are the other ways to prove that there is no largest prime?
Thanks for any proof!!
Comment: [Different ways to prove there are infinitely many primes?](http://math.stackexchange.com/questions/50006/different-ways-to-prove-there-are-infinitely-many-primes)
Answer: Note that all Fermat Numbers are coprime to each other.
Thus, if there are a finite number of prime numbers, this is a contradiction as there are infinite number of Fermat Numbers.
Thus, there are a infinite number of prime numbers.
And so there is no largest prime.
Comment: What do you mean by all fermat numbers are co prime?Co prime to what?
Comment: @tatan co-prime to each other. The first Fermat number is $2$, the second is $5$, and the third is $17$. These numbers are all coprime to each other.
Comment: Does it necessarily mean all Fermat numbers are prime numbers?
Comment: @tatan No, it implies all Fermat numbers have distinct prime factors. Which is sufficient.
Comment: I don't find a reason to believe that there are an infinite number of Fermat Numbers unless there are an infinite number of primes.
Comment: @DhruvSomani Fermat Numbers $\neq$ Fermat Primes. Fermat Numbers are $2^{2^{n}}+1$, or $a_{n}=a_{n-1}^2+1$ & $ a_{1}=2$.
Answer: Well, the proof you have shown is not exactly the right way.
Proof:
Assume there are a finite number of primes.
Let $s$ be the set of all primes possible. And let the primes be $p_1, p_2, p_3, \dots , p_n$.
Now by the Fundamental Theorem of Arithmetic, we know that every number is a prime or a unique product of primes.
Consider the number $p_1  p_2  p_3 \cdots p_n +1$. We know that it is not divisible by any of the numbers in the set $s$. Thus we get a number which is a prime or composed of primes not in the set $s$. That's a contradiction. Thus there are an infinite number of primes.
Comment: There are two problems in this: 1. The number to be considered should be $p_1p_2p_3\cdots p_n+1$. 2. It does not necessarily follow that this number  is a prime. It follows that either this number is a prime or there is its factors contain some other primes not included in $s$. Either way the conclusion holds.
Comment: Yes. So the contradiction is you got a prime outside the set $s$. But $p_1p_2\cdots p_n+1$ is not necessarily that prime. It may also be the case that there was some other prime missed out in $s$, which leads to the same contradicton.
Comment: @GoodDeeds Thanks.
Answer: Let $p$ is the last prime. Then according to Bertrand's postulate  the interval $(p,2p)$ consists a prime number.  We get a contradiction.


Get the node title field value in the form_state

Question: Drupal version 9.3.9.
This is a process of Ajax callback, where the value of the title field is required. In the form node add, the title is displayed. It seems that the form_state does not apply to the title field. When I inspect the variables, the title field is also not reflected in the values.
<code>function my_custom_module_field_widget_process($element, \Drupal\Core\Form\FormStateInterface $form_state,$form) {
  #$element['my_field']['#default_value'] =$form_state->getFormObject()->getEntity()-
  #>label();this work, but useless in the callback

  if(!empty($form_state->getValue('title'))){
    $title = $form_state->getValue('title');
    $element['my_field']['#default_value'] = $title;
  }

  return $element;
}
</code>
Comment: What do you mean by `$form_state->getFormObject()->getEntity()->label();` works but is useless in the callback?
Comment: I mean, the value is stored after the node is been saving. I need the value in an Ajax callback. The user must see the value when entering the form so that they can change or edit the value.
Answer: This should work:
<code>    $node = \Drupal::routeMatch()->getParameter('node');
    if($node) {
        $title = $node->label();
    }
</code>


First time passage decomposition for continuous time Markov chain

Question: For discrete time finite Markov chain, the first passage time $T_j$ to visit state $j$, is determined from the recurrence equation:
$$
   p^{(n)}_{ij} = \sum_{k=0}^n f_{ij}^{(k)} p^{(n-k)}_{jj} =
      \sum_{k=0}^n \mathbb{P}(T_j = k ; X_0 = i) \mathbb{P}(X_{n-k} = j ; X_0 = j)
$$
where $p^{(n)}_{ij} = \mathbb{P}(X_n = j ; X_0 = i)$ and $f^{(k)}_{ij} = \mathbb{P}(T_j = k ; X_0 = i)$. This recurrence equation allows to find probability generating function for the first passage time distribution (exerices 1.5.3 of J.R. Norris's book on "Markov Chains", relevant chapter 1.5 is available from Norris's website).
It strikes me odd that no book I have seen discusses first passage time distribution for continuous time finite Markov chain.
Can anyone suggest a reference where this is discussed/worked-out, or hint me at how to do this for myself.
I suspect a similar integral equation would be set-up, and moment generating function for the first-passage-time distribution would satisfy some simple equation.
Thanks for reading.
Answer: First of all, I wonder if $T_j$ refers to the first return time, or to the first hitting time. Since if you're talking about the latter case then $\mathsf P\{T_j = n-k|X_0 = j\} = 1_{\{k=n\}}$.
About continuous time case some insights are the following. I know results only for first hitting time. Let us introduce CTMC (continuous time Markov Chain) through its finite state space $\mathscr X$, transition matrix $R:\mathscr X\times \mathscr X\to[0,1]$ and exit-rate function $r:\mathscr X\to[0,\infty)$. For any initial point $x\in \mathscr X$ and target point $y\in \mathscr X$, the time-bounded reachability probability (or a cumulative distribution function for the first passage time) which we denote as
$$
F(x,y,t) = \mathsf P_x\{\tau_y \leq t\}
$$
is a least solution for
$$
F(x,y,t) = 1_{\{y=x\}}+1_{\{y\neq x\}}\sum\limits_{z\in \mathscr X}R(x,z)\int\limits_0^t\mathrm e^{-r(x)s}F(z,y,t-s)\mathrm ds.
$$
Assuming that $F$ has a density $f$ and recalling that $F(y,y,t) = 1$ we obtain:
$$
f(x,y,t) = R(x,y)\mathrm e^{-r(x)t}+\sum\limits_{z\neq y}R(x,z)\int\limits_0^t\mathrm e^{-r(x)s}f(z,y,t-s)\mathrm ds
$$
for any $x\neq y$.
With regards to the references - the only person whom I've found to work on that topic is he. The equation above I saw in his paper, but I do not remember which one. The problem may be also that his paper are focused on verification of general properties, usually much more complex that just reachability and it may be not so easy to go through the notation. However, I haven't seen something I can suggest you in the classical literature on Probability Theory. If you find it, please tell me.
Regards,
Comment: Thank you very much for the post. The first passage times $T_j$ is defined by J.R. Norris in his book as Markov processes as $T_j(\omega) = \inf \{ n \ge 1 :  X_n(\omega) = j \}$.
Comment: You are welcome. So in some literature it is also called the first return time. For CTMCs you can show that it is a.s. equal to the first hitting time since the path is cadlag. I don't have an access to the whole J. Norrison's [book](http://www.statslab.cam.ac.uk/~james/Markov/), but didn't he discuss it in Ch.3.3?
Comment: In Ch.3.3, Norris defines hitting time of a subset $A$, $D^A(\omega) = \int\{t \ge 0: X_t(\omega) \int A \}$, and computes hitting  probabilities $h_i^A = \mathbb{P}(D^A < \infty; X_0 = i)$ and expected hitting times $k_i^A = \mathbb{E}(D^A ; X_0 = i)$, but does not discuss the distribution of $D^A(\omega)$.
Comment: @Sasha: your $\inf$ and $\in$ turned to integrals. Infinite horizon hitting probabilities satisfy the same equation as for DTMC (Theorem 1.3.2 in Norris) as I remember, don't they?
Comment: Too bad I can no longer edit the comment. Yes, you are correct. The infinite horizon probabilities equal to those of  the embedded Markov chain.
Comment: It occurred to me that the solution to my problem may be in discretization of the CTMC, i.e. considering state of the system only at times $t= k h$, for a fixed $h$. But the first passage time is a continuous random variable, so I'm not quite sure how adapt the pgf equality $P_{ij}(s) = \delta_{i,j} + F_{ij}(s) P_{jj}(s)$ for DTMC to the case of CTMC.
Comment: @Sasha I have to go now, could we discuss this problem tomorrow? I'll be here in 16 hours ) Maybe with some additional details I can tell you more.
Comment: @Gartaur Sure thing. See you later.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/1759/discussion-between-gortaur-and-sasha)
Comment: @Sasha: you may not receive the invitation to [chat where our discussion was moved](http://chat.stackexchange.com/rooms/1759/discussion-between-gortaur-and-sasha)
Answer: Concerning references, I've seen the problem of first passage time distributions treated in two books, unfortunately both are in German:

Nollau, V.: Semi-Markovsche Prozesse, H. Deutsch (1981).
Störmer, H.: Semi-Markoff-Prozesse mit endlich vielen Zuständen, Springer Lecture Notes in Operations Research and Math. Systems, Vol. 34 (1970).

As the titles imply, these references discuss the problem for semi-Markov processes, which of course includes the continuous time Markov chain case. For example, Nollau treats a more general problem: he provides a Markov renewal type equation, similar to the one posted by Ilya, for the probability $\Psi_{x,ABC}(t)$ of a transition from $A$ to $B$ not later than $t$, without leaving $C$, where $A$, $B$ and $C$ are subsets of states, $A\subseteq C$, and $x\in C$ is the initial state.


How can I process a node form from a custom submit handler?

Question: I have a use case where I have a custom submit button on a node edit form that will take the user off to another page to do some other editing.
If the user has made some changes to the node, such as changed the title, I need to save the current node before redirecting them off to the new page (along with some other generated ID's).
For the life of me, I cant seem to see how I can save the changes to the node in my custom submit handler.
I have tried using $formState->prepareCallback('::submitform()) but that doesn't seem to do what I expected of processing the form.
Anyone done this before or got any good ideas?
Answer: Typically, I found the answer 10 minutes after posting!
For anyone else, in your custom submit handler get the form object from the form state.
$formObj = $formState->getFormObject();

You can then call submitForm() on the form object and pass the form and form state variables.
$formObj->submitForm($form, $formState);

Then finally just simply trigger the save() function on the object.
$formObj->save($form, $formState);


showing $\sum_n a^n/n$ is convergent

Question: showing $\sum_n a^n/n$ is convergent where $0 < a < 1$. I'm pretty stuck on this. I have tried letting $ a = 1/b$ where $b > 1$ and considering $\sum_n \frac{1}{b^nn}$ but to no avail. Any hints please
Comment: just a point but its convergent for a=0 as well.
Answer: If $0<a<1$ then $\sum a^n$ converges, so the given series converges by the comparison test.
Answer: Hint: check the Taylor series of $\log(1-x)$, with $\left|x\right|
 <1$.

showing $\sum_n a^n/n$ is convergent


Drupal commerce WPS , if user not go back to the site after paypal payment?

Question: this is the problem.
The payment used in my site is WPS (With Paypal Business account) so user switch from my site to Paypal site to pay order in cart.
BUT
If User close paypal site after paypal message "Payment complete" and NOT go back in site, the status order stay on "Checkout: Complete". Drupal Commerce has no way of knowing that payment is complete so not send order email and decrease stock.
Is there a way to get around this problem?
I work with drupal commerce kickstart 2 (+ stock module)
Ty for your reply :)
Answer: I was experiencing a similar problem - no confirmation emails etc.
Apparently what was causing the problem for me was that I had created a custom Rule that fired "When an ordered is first paid in full"  and updated the order status to "Completed." This custom Rule triggered after the user used PayPal WPS to complete payment. I did this to avoid the confusion of having the default status "Pending" after the the PayPal payment was successful.
For some reason, having this custom Rule there prevented all the Rules that use the trigger "Completing the checkout process" to trigger (these default rules include all the notification emails among other things).
See this posting here for a few cases of other people who ran into this problem: https://drupalcommerce.org/discussions/1150/resolved-completing-checkout-process-not-firing
This issue was resolved (in my case) by just getting rid of the custom Rule.
I'm wondering if this is causing the problem for you too.
Answer: Usually payment processing companies display a message that the customer should not close the window and wait for him/her to be redirected to the merchant site. Paypal should display this in your case. Please ask them to do it, every other payment processing company does it.
Comment: Yes paypal display this message but often user close paypal (or browser) after paypal succesful message. User often not wait redirect to back in the commerce site. The problem is this. If not come back order status not change so not decrease stock and not send email confirmation. (rules send that after order completition)
Answer: What you're describing doesn't sound correct to me. PayPal Payments Standard does display a link back to your store, but it isn't required for a customer to click it for any processing to happen for the payment on the Drupal side. Additionally, PayPal really doesn't do much to encourage a customer to click that link - I'd be at least half of customers won't be coming back by your shop after submitting payment unless they're different than mine. : )
What sounds fishy, though, is that your orders remain in "Checkout: Complete". Technically, they should be remaining in "Checkout: Payment", because that's the status they're in when the user redirects to PayPal. However, the IPN must be coming through and triggering some order status change, which is followed by the IPN listener simulating moving the order to the next page, "Checkout: Complete." You need to look into what rules you have operating on when a payment is received in full for an order, because the IPN triggers that whether the customers comes back to the site or not. You are probably changing an order status and it is getting set back somehow.
Comment: Yes, sorry my fault the status remain in "Checkout: Payment", the problem is that: User pay with paypal and no back in the site to complete order (close paypal site). Status remain in "Checkout: Payment" so no confirm order email was send and no stock decrease action was fired. How to solve that?
Comment: Your site needs to be accessible to IPNs. It sounds like it isn't.
Comment: But there is some configuration paypal side? Like url callback or something like that?
Comment: No configuration necessary. We submit the notify_url in the redirect to PayPal, so that's where it sends the IPN regardless of whatever IPN URL you configure in your account.
Answer: I have a similar problem. I'm using drupal-commerce but not kickstart. Most of the time, Paypal WPS is working as expected. Though, Sometimes I receive a payment from a customer but the order does not move to "checkout complete". The surprizing part is that when I look to the recorded carts in the admin part ("/admin/commerce/orders/carts"), selecting the corresponding cart, looking to the "Payment" tab of that cart, the payment has been recorded in the database with the result message "The payment has completed.".
Shortly speaking, I have a cart with valid payment in my database but the order is not completed and the stock does not decrease.
Have you checked if the payment is registered in the corresponding cart ?
Any idea about what is happening ?
Comment: This seems to solve the issue :
http://drupal.org/node/1130166#comment-4813116
Comment: also here some help
https://www.drupal.org/node/2111633


Como usar um COUNT com condição?

Question: Tenho uma tabela quarto, queria retornar a quantidade de quartos que tem em cada andar (o quarto possui um atributo andar), mas não sei como fazer com que ele retorne de todos os andares
SELECT andar, COUNT(* WHERE andar = andar????? ) AS quantidade

Queria um retorno tipo
andar  quantidade
1      5
2      10
3      6

Answer: Você quer que a função COUNT() seja agregadora, quer contar todos os elementos encontrados dentro de um grupo de dados, esse grupo é definido pelo atributo andar, então use a cláusula GROUP BY.
SELECT andar, COUNT(*) AS quantidade FROM andares GROUP BY andar

Veja funcionando no SQL Fiddle. Também coloquei no GitHub para referência futura.
Comment: Isso! Valeu! Estou aprendendo e fiquei na dúvida

Como usar um COUNT com condição?


Comb space is contractible proof

Question: For each positive integer $n$, let $I_n=\{1/n\}\times I$ as a subset of $I\times I$. Let $X=(I\times 0)\cup (0\times I)\cup (\cup_{n≥1}I_n)$. I do not understand how is this space contractible. Though I saw a proof involving inclusion map from line segment joining b$(0,0)$ to $(1,0)$ to $X$, I did not understand it.
Answer: Let $h:[0,1]\times X\rightarrow X$ be defined by $h(t,x,y)=(x,(1-t)y)$. This map is continuous because it is the restriction of the continuous map $I\times I^2\rightarrow I^2$. This contracts $X$ to the line $I\times\{0\}$. But this space is also contractible, as it is homeomorphic to $I$. It follows that $X$ is contractible.

Comb space is contractible proof


tcp server does not return from accept()

Question: I am trying out with a TCP server/client program, and wonder why at server side, the program loop at accept() ....
My idea is to develop a TCP server which receive 1 request at a time from multiple clients. The connection between server and client shall close upon completing single operation. For eg
1) The TCP server shall be hearing port 30000 at all time.
2) TCP client 1 connect to TCP server, send "hello", and wait for "hello" feedback from server, and close the connection.
3) TCP client 2 connect to TCP server, send "hello", and wait for "hello" feedback from server, and close the connection.
and so on until TCP client n....
All of the operation above is executed one at a time, meaning TCP client 1 and 2 will not send message to TCP server at the same time, and, once TCP client 1 complete the operation it will not connect to server anymore (if necessary, a new connection can be triggered).
the output shows
<code>======== NW Test =======
1) Start (T)CP Server
2) Start T(C)P  Client
3) (S)end TCP Message
4) Close TCP S(O)cket
0) (Q)uit
================================
Option: t
Starting TCP server...
create socket success.
bind socket success.
listen socket success.
</code>
I am expecting also...
<code>accept socket success.
pthread_create success.
TCP server started, listening socket [tcpsocket]
</code>

<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>

struct attr {
  int tcpsocket;
};

static int nwMenu();
static void *event_start(void* param);

int tcpserver(){
    int thread_id;
    int tcpSocket;
    int listenSocket;
int nRet;
    socklen_t nLen;
struct attr atr;
    struct sockaddr_in saTCPServer, saTCPClient;

fprintf(stderr, "Starting TCP server...\n");

    listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (listenSocket < 0)
    {
  fprintf(stderr, "fail to create socket.\n");
      return -1;
    } else {
  fprintf(stderr, "create socket success.\n");
}

    saTCPServer.sin_family = AF_INET;
    saTCPServer.sin_addr.s_addr = INADDR_ANY;
    saTCPServer.sin_port = 30000;

    nRet = bind(listenSocket, (struct sockaddr *) &saTCPServer, sizeof(struct sockaddr));
    if (nRet < 0)
    {
  fprintf(stderr, "fail to bind socket.\n");
      close (listenSocket);
      return -1;
    } else {
  fprintf(stderr, "bind socket success.\n");
}

    if (listen(listenSocket, 5) < 0) {
   fprintf(stderr, "fail to listen socket.\n");
       close (listenSocket);
       return -1;
    } else {
  fprintf(stderr, "listen socket success.\n");
}

    nLen = sizeof(saTCPClient);

    tcpSocket = accept(listenSocket, (struct sockaddr *) &saTCPClient,  &nLen);
    if (tcpSocket < 0)
    {
  fprintf(stderr, "fail to accept socket.\n");
      close (listenSocket);
      return -1;
    }  else {
  fprintf(stderr, "accept socket success.\n");
}
atr.tcpsocket = tcpSocket;

    close (listenSocket);

    if(pthread_create(&thread_id, NULL, (void*) event_start, (void*) &atr) != 0){
    fprintf(stderr, "pthread_create failed.\n");
} else {
  fprintf(stderr, "pthread_create success.\n");
};

fprintf(stderr, "TCP server started, listening socket %d\n", tcpSocket);

return 0;

}

static void *event_start(void* param) {

    int quit = 0;
    int nRet = 0;
int tcpSocket;
    char szBuf[4096];

struct attr *p_atr = (struct attr* )param;
tcpSocket = p_atr->tcpsocket;

    while (!quit){

        nRet = recv(tcpSocket, szBuf, sizeof(szBuf), 0);
        if (nRet <= 0 ) // peer closed
         {
            fprintf(stderr, "receiver quit recv\n");
        quit = 1;
        break;
          }

        fprintf(stderr, "recv: %s\n", szBuf);

        send(tcpSocket, szBuf, sizeof(szBuf), 0);
    }

     close(tcpSocket);
}

int tcpclient(){
    int tcpSocket;
    struct sockaddr_in saTCPServer;

    bzero((void *) &saTCPServer, sizeof(saTCPServer));

    char* szServer = "127.0.0.1";
    int nPort = 30000;

    inet_aton(szServer, &saTCPServer.sin_addr);

    tcpSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (tcpSocket < 0){
        return -1;
    } else {
        fprintf(stderr, "client tcp socket: %d\n", tcpSocket);
    }

    saTCPServer.sin_family = AF_INET;
    saTCPServer.sin_port = htons(nPort);

    if (connect(tcpSocket, (struct sockaddr *) &saTCPServer, sizeof(saTCPServer)) < 0 )     {
        return -1;
    }

    fprintf(stderr, "TCP client started, listening socket %d\n", tcpSocket);

    return 0;
}

int send_tcp_msg(int tcpSocket){
    int nRet;
    char szBuf[4096];

    memset(szBuf, 0x00, sizeof(szBuf));

    send(tcpSocket, "hello", sizeof("hello"), 0);

    nRet = recv(tcpSocket, szBuf, sizeof(szBuf), 0);

    fprintf(stderr, "recv: %s\n", szBuf);

return 0;
}

int close_tcp(int tcpSocket){
    close(tcpSocket);

return 0;
}

static int nwMenu(){
    int ret = 0;
    int socket;
    char buff[1024];

    do{
    fprintf(stderr, "======== NW Test =======\n");
    fprintf(stderr, "1) Start (T)CP Server\n");
    fprintf(stderr, "2) Start T(C)P  Client\n");
    fprintf(stderr, "3) (S)end TCP Message\n");
    fprintf(stderr, "4) Close TCP S(O)cket\n");
    fprintf(stderr, "0) (Q)uit\n");
    fprintf(stderr, "================================\n");
    fprintf(stderr, "Option: ");
    memset(buff, 0x00, sizeof(buff));
    gets(buff);

    if (buff[0] == 't' || buff[0] == 'T'){
        ret = tcpserver();
    } else if (buff[0] == 'c' || buff[0] == 'C'){
        ret = tcpclient();
    } else if (buff[0] == 'o' || buff[0] == 'O'){
        fprintf(stderr, "Enter socket fd:\n");
        gets(buff);
        ret = close_tcp(atoi(buff));
    } else if (buff[0] == 's' || buff[0] == 'S'){
        fprintf(stderr, "Enter socket fd:\n");
        gets(buff);
        ret = send_tcp_msg(atoi(buff));
    }

    }while(buff[0] != 'q' && buff[0] != 'Q');

    return 0;
}

int main(int argc, const char* argv[]){

    nwMenu();

    return 0;
}
</code>
Comment: Your code and its messages suggest you perhaps misunderstand the purpose of accept(). You server is effectively started when you call this.  It will not (ordinarily) return until a client has connected.  Your subsequent server started message should say instead client connected.
Comment: arh... alright! the culprit is ... i set server IP address as "127.0.0.1" at client side. So when I tried to connect to server, it failed. I change it to eth0 IP (the actual: 192.168.122.1), and it works as expected. I wonder why it has to be non-loopback IP.
Answer: Your server does:
<code> saTCPServer.sin_port = 30000;
</code>
That should be
<code> saTCPServer.sin_port = htons(30000);
</code>
The port have to be specified in network order, if you're on a little endian machine , 30000 does not translate to the port 30000, but to port 12405. So your server is listening on a different port than what your client is connecting to.
Comment: To see what is happening, start your server and use something like `telnet` to connect to the port as to not rely on your own code. When that works, debug your client code.
Comment: You're supposed to use 127.0.0.1 or the actual IP of your machine as a client. 0.0.0.0 is only relevant for listening servers, it's special and means "all local IPv4 addresses"
Comment: i change it to saTCPServer.sin_port = htons(30000);  but the result is still the same.... hmmm
Comment: i got the below from netstat -tln  --> tcp        0      0 0.0.0.0:30000           0.0.0.0:*               LISTEN
Comment: hmm.. telnet dislike 0.0.0.0 :)


How to keep a shallow git clone up to date (while remaining shallow)

Question: There are some cases where its not useful to store the entire git history (a build-bot for example).
Is it possible to do a shallow clone of a git repository (with a single branch, master for example), and keep it up-to-date, while staying shallow?
Answer: Yes this is possible, the following git-commands are shell-script functions, but really they could be bat files or similar.
# clone
function git_shallow_clone() {
    git clone --depth 1 --single-branch $@
}

# pull
function git_shallow_pull() {
    git pull --no-tags $@

    # clean-up, if a new revision is found
    git show-ref -s HEAD > .git/shallow
    git reflog expire --expire=0
    git prune
    git prune-packed
}

# make an existing clone shallow (handy in some cases)
function git_shallow_make() {

    # delete all branches except for the current branch
    git branch -D `git branch | grep -v $(git rev-parse --abbrev-ref HEAD)`
    # delete all tags
    git tag -d `git tag | grep -E '.'`
    # delete all stash
    git stash clear

    # clean-up, if a new revision is found (same as above)
    git show-ref -s HEAD > .git/shallow
    git reflog expire --expire=0
    git prune
    git prune-packed
}

# load history into a shallow clone.
function git_shallow_unmake() {
    git fetch --no-tags --unshallow
}

Notes

--no-tags is important to use, otherwise you may clone tags which have sha1s pointing to blob's outside of the branch master
restricting to a single branch is also useful, assuming you're only interested in master, or a single branch at least
re-enforcing shallow after every pull seems quite a heavy operation, but I didn't find a better way

Thanks to: https://stackoverflow.com/a/7937916/432509 (for the important part of this answer)
Comment: Should the 4. example's `fetch` command be prepended with `git` instead of `g`?
Comment: Updated `git_shallow_make` so it removes all branches except the current one (no hard coded `master`)


currentUser do firebase está retornando nulo

Question: Estou fazendo um projeto que consiste em criar dois aplicativos, estou usando o firebase como base de dados e ambos estão usando a mesma base de dados, o primeiro aplicativo está funcionando normalmente, porém o segundo está dizendo que o currentUser está nulo.
Primeiro Aplicativo:
async function signUpPet(
    namePetField,
    typePetField,
    agePetField,
    racesPetField,
  ) {
    let uid = await firebase.auth().currentUser.uid;
    let key = await firebase.database().ref('pets').child(uid).push().key;

    await firebase
      .database()
      .ref('pets')
      .child(uid)
      .child(key)
      .set({
        nm_pet: namePetField,
        ds_type: typePetField,
        ds_age: parseFloat(agePetField),
        ds_races: racesPetField,
        dt_createPet: format(new Date(), 'dd/MM/yyyy'),
      })
      .then(async (snapshot) => {
        let data = {
          key: key,
          namePet: namePetField,
          typePet: typePetField,
          agePet: snapshot.val().ds_age,
          racesPet: racesPetField,
          dateCreatePet: snapshot.val().dt_createPet,
        };
        setUser(data);
      });
  }

Segundo Aplicativo:
async function signUpTimeVetSignUp(
    monday,
    tuesday,
    wednesday,
    thursday,
    friday,
    saturday,
    sunday,
  ) {
    let uid = await firebase.auth().currentUser.uid;
    let key = await firebase.database().ref('timeVets').child(uid).push().key;

    await firebase
      .database()
      .ref('timeVets')
      .child(uid)
      .child(key)
      .set({
        vetmonday: monday,
        vettuesday: tuesday,
        vetwednesday: wednesday,
        vetthursday: thursday,
        vetfriday: friday,
        vetsaturday: saturday,
        vetsunday: sunday,
      })
      .then(() => {
        let data = {
          mondayVet: monday,
          tuesdayVet: tuesday,
          wednesdayVet: wednesday,
          thursdayVet: thursday,
          fridayVet: friday,
          saturdayVet: saturday,
          sundayVet: sunday,
        };
        setTimeVet(data);
      });
  }

Answer: difícil dizer só com este código. provavelmente há algo errado com a autenticação do segundo app. lembrando que logo que recarregar a página firebase.auth().currentUser.uid costuma ser nulo. pois ainda não realizou autenticação.
tente utilizar:
let firebaseUser = null;
firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    firebaseUser = user;
  } else {
    console.log('usuário não logado');
  }
});

async function signUpTimeVetSignUp(
    monday,
    tuesday,
    wednesday,
    thursday,
    friday,
    saturday,
    sunday,
  ) {
    let uid = firebaseUser.uid;
    let key = await firebase.database().ref('timeVets').child(uid).push().key;
    // ...


evaluation of $\int\frac{1}{\sin^3 x-\cos^3 x}dx$

Question: Evaluation of $\displaystyle \int\frac{1}{\sin^3 x-\cos^3 x}dx$
$\bf{My\; Try::}$ Given $\displaystyle \int\frac{1}{\sin^3 x-\cos^3 x}dx = \int\frac{1}{(\sin x-\cos x)\cdot (\sin^2 x-\sin x\cos x+\cos^2 x)}dx$
$\displaystyle = 2\int\frac{(\sin x-\cos x)}{(\sin x-\cos x)^2\cdot (2-\sin 2x)}dx = 2\int \frac{(\sin x-\cos x)}{(1-\sin 2x)\cdot (2-\sin 2x)}dx$
Let $(\sin x+\cos x) = t\;,$ Then $(\cos x -\sin x)dx = dt\Rightarrow (\sin x -\cos x)dx = dt$
and $(1+\sin 2x)=t^2\Rightarrow \sin 2x = (t^2-1)$
So Integral Convert into $\displaystyle 2\int\frac{1}{(2-t^2)\cdot (3-t^2)}dt = 2\int\frac{1}{(t^2-2)\cdot (t^2-3)}dt$
My Question is , is there is any better method other then that
Help me
Thanks.
Comment: I think initially your method is pretty cool! I would have factored the denom in the same way. But I suspect there is a negative sign missing when you go from $cosx-sinx$ to $sinx-cosx$ in front of that $dx$ term?
Comment: I guess your method is the simplest one. For example, Weierstrass is cumbersome, $t = \sin\left(x\right)$ is quite bad, etc...
Comment: Thanks imranfat and Felix Marin..
Answer: You're missing a minus sign at one point, but other than that I think you're OK.  Next, use partial fractions:
$$
\frac{1}{(2-t^2)(3-t^2)} = \frac{A}{\sqrt{2}-t} + \frac{B}{\sqrt{2}+t} + \frac{C}{\sqrt{3}-t} + \frac{D}{\sqrt{3}+t}
$$
Answer: I had just learnt an useful technique to deal with $1+\sin x \cos x$ and want to share with you now.
$$
\begin{array}{l}
\displaystyle \because \frac{3}{\sin ^{3} x-\cos ^{3} x}=\frac{2}{\sin x-\cos x}+\frac{\sin x-\cos x}{1+\sin x \cos x}\\ \displaystyle
\therefore \int \frac{d x}{\sin ^{3} x-\cos ^{3} x}\\ \displaystyle =\frac{2}{3} \int \frac{d x}{\sin x-\cos x}+\frac{1}{3} \int \frac{\sin x-\cos x}{1+\sin x \cos x} d x\\ \displaystyle
=-\frac{2}{3 \sqrt{2}} \int \frac{d x}{\cos \left(x+\frac{\pi}{4}\right)}-\frac{2}{3} \int \frac{d(\sin x+\cos x)}{1+(\sin x+\cos x)^{2}}\\
 \displaystyle =-\frac{\sqrt{2}}{3} \ln \left|\sec \left(x+\frac{\pi}{4}\right)+\tan \left(x+\frac{\pi}{4}\right)\right|-\frac{2}{3} \tan ^{-1}(\sin x+\cos x)+C\\
\displaystyle =-\frac{\sqrt{2}}{3} \ln \left|\frac{1+\frac{1}{\sqrt{2}}(\sin x+\cos x)}{\frac{1}{\sqrt{2}}(\cos x-\sin x)}\right|-\frac{2}{3} \tan ^{-1}(\sin x+\cos x)+C\\
 \displaystyle =-\frac{\sqrt{2}}{3} \ln \left|\frac{\sqrt{2}+\sin x+\cos x}{\cos x-\sin x}\right|-\frac{2}{3}  \tan ^{-1}(\sin x+\cos x)+C
\end{array}
$$
By the way, replacing $x$ by $-x$ yields its partner integral
$$
\int \frac{d x}{\sin ^{3} x+\cos ^{3} x}=-\frac{\sqrt{2}}{3} \ln \left|\frac{\sqrt{2}-\sin x+\cos x}{\cos x+\sin x}\right|+\frac{2}{3} \tan ^{-1}(\sin x-\cos x)+C
$$


Create column of array of differences between two adjacent numbers in another column's array python/pyspark

Question: I have a column of arrays made of numbers, ie [0,80,160,220], and would like to create a column of arrays of the differences between adjacent terms, ie [80,80,60]
Does anyone have an idea how to do this in Python/PySpark? my code is df=df.withcolumn('col_array_diffs', [df.col_array.getItem[i]-df.col_array.getItem[i-1] if i else None for i in range(1,F.size(df.col_array))]) but am really struggling with the arraytype. This produces AssertionError: col should be Column...Thanks!
Comment: You can try using `.cast("Integer")` such as `df=df.withcolumn('col_array_diffs', [df.col_array.getItem[i].cast("Integer")-df.col_array.getItem[i-1].cast("Integer") if i else None for i in range(1,F.size(df.col_array))])`
Answer: You can use a UDF to do this.
import pyspark.sql.types as T

def subtract_el(x):
    return [abs(i-j) for i, j in list(zip(x, x[1:]))]

df = spark.createDataFrame(pd.DataFrame([[[0,80,160,220]]]))
df.select(F.udf(subtract_el, T.ArrayType(T.IntegerType()))("0").alias("diff")).show()

Results in :
+------------+
|        diff|
+------------+
|[80, 80, 60]|
+------------+


Get Red, Blue or Green channel from Android Color object

Question: I feel this is a pretty stupid question, but the Android Color class doesn't seem to have a method to get an int from the R, G, B channels from a Color object individually. Can I get the channels somehow like java.awt's Color can?
Answer: int color = ContextCompat.getColor(context, R.color.someColor);
        int red = Color.red(color);
        int blue = Color.blue(color);
        int green = Color.green(color);
        int alpha = Color.alpha(color);

Comment: I don't want the color from a resource file or anything, I just want to get it from a Color object I made programatically. Am I going to have to get the hex somehow and parse it to get the channels? If that's even possible cause from what I can see this class has very little knowledge.
Comment: how you made the color object then?
Comment: I just realized I never tried initializing an android.graphics.Color object, I only had a Color object in a parameter. Is there no equivalent to java's java.awt.Color on android to work with colors programatically?
Comment: In Android color values is hold as integer. And if you want to do some operation using that Color value then you have a Color class but it is helper class not actual color value container like AWT.
Answer:
Did you mean

int colorValue=Color.parseColor(#121212);
int red=Color.red(colorValue);
int green=Color.green(colorValue);
int blue=Color.blue(colorValue);

Answer: try this:
String myPassedColor = "#ffffff";
int color = Color.parseColor(myPassedColor)
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
int a = Color.alpha(color);


How to modify innerHTML by evaluating an angular expression

Question: I am trying to do something like this

    {{item.innerHTML}}

item.innerHTML contains the html that needs to go there, but since it is part of the dom, it is replaced as a string. Is there a way to just have it replace the innerHTML?
Thanks!
Answer: You need to use ngBindHtml :
http://plnkr.co/edit/n1rLzgEZQoa2tJf0qnVZ?p=preview
in the controller :
$scope.content = "this is bold content";

html :

you'll need the following module :
http://code.angularjs.org/1.0.3/angular-sanitize.js
Be sure to declare ngSanitize as a module dependancy, for instance :
var app = angular.module('angularjs-starter', ["ngSanitize"]);

Comment: I tried this, but it does not seem to work. This is what I get in the html    . Am I missing something?
Comment: the exemple works as far as i know : http://plnkr.co/edit/n1rLzgEZQoa2tJf0qnVZ?p=preview you must have forgot to do something, also dont put {{}} in ng-bind-html since it is an expression.
Comment: Thanks! That worked. I thought you use {{}} to evaluate expressions? http://docs.angularjs.org/guide/expression
Comment: @mpm 's answer works! But just as a reminder, don't forget to include "angular-sanitize.js" in your application. And also as mpm mentioned, don't forget to declare module dependancy.
Comment: Angular 4: to pass HTML as variable you can use


Active Directory - User Rights

Question: I'm building an environment in which I'm using Active Directory primarily for:

Centralized authentication and authorization for our servers (Linux and Windows)
Single Sign On for various of our services (SAML, etc)
Enterprise PKI distribution

In our company, all employees have an elevated degree of freedom. We don't care which software they install on their computer and which sites they access. So, we'd like to maintain the following:

All users can do almost anything they want in the computer they use (install software, navigate any website)
Users can't access each other files
Only infrastructure people can access the servers

Seems like this is an uncommon setup as we want to maintain all the users freedom (we even have bring your own device here).
What are the most important configurations I should do in this case? There's a lot of default GPOs that block a lot of things for standard users.
Comment: Simple: Set up standard AD, create GPO that adds authenticated users to local admin. Put servers in their own OU that does not have the GPO applied to it. http://www.dannyeckes.com/create-local-administrator-security-group-gpo/
Answer:

All users can do almost anything they want in the computer they use    (install software, navigate any website)
Users can't access each other files
Only infrastructure people can access the servers

For points (1) and (2) above, make sure to give users local admin rights just to the laptops that use.
For point (3), make sure to give infrastructure users domain admin rights.
Additionally, if as you say, laptops are used out of the office most of the time, then you may want to enable BitLocker on the laptops as well.
Answer: Under the normal and default settings/configuration standard users can't access servers administratively (if the servers and the user accounts and groups have been configured properly), standard users can't access other users files (if the files have been secured properly). If you add the appropriate standard user account to the local Administrators group on each computer then each user will have local Administrator rights on their computer only and will have no administrator rights on any other computer, server or in the domain.
Answer: Actually, what you describe here is the standard setting for users. Installing software might require local administrator privileges though. This depends on the software. Someone with local admin rights can access all files on the system though, including that of other users.
If you keep files on a NAS or similar, you can do the right management there and local admins will not have access to the files.
Accessing servers, when done through RDP, WinRM or similar will only be allowed for domain admins per default, anybody else will have to be added to the appropriate groups on the server.
Comment: We don't use an NAS. 99% of the computers are notebooks and they are used outside of our office too.

My fear is that someone grabs a random computer and use his domain account to login. As everybody would have local admin in order to install software, it could access the computer owner data.
Comment: You will have to give local admin rights on a per-machine basis in that case.

Active Directory - User Rights


Riemann $\zeta(3)$ convergence with Cauchy

Question: I'm an undergraduate freshman math student, and we were asked to prove that the sequence $a{_n} =\sum_{k=1}^{n} \frac{1}{k^3}$ converges (obviously, we weren't asked to calculate its limit.) Our teacher hinted to prove that it's a Cauchy sequence. We don't know much, only Cauchy, several sentences about sequences and limits and monotonic sequences and such (basic first few months of undergraduate freshman). I'm stuck. any hints / ideas?
Here's my attempt:
Let $\varepsilon > 0$. We need to find N, such that for all $m > n > N$, $a_{m}-a_{n} < \varepsilon$. $a_{m}-a_{n} = \sum_{k = n+1}^{m} \frac{1}{k^3}$.
$\sum_{k = n+1}^{m} \frac{1}{k^3} < \frac{m-n}{(n+1)^3}$.
But this leads nowhere.
Note: We don't have to prove it by Cauchy, any solution (from the little we have learnt) will do.
Comment: Ah man, but it's so good :D
Comment: Integral test shows that each $\sum_{k=1}^\infty \frac1{k^\alpha}$ converges for $\alpha>1$.
Comment: We haven't learnt Integral Test yet, or even functions (only sequences)
Comment: If you are interested more in the particular value, there's a whole [Wikipedia](https://en.wikipedia.org/wiki/Ap%C3%A9ry's_constant) on $\zeta(3)$.
Comment: You are allowed not to post more answers...
Comment: In the OP, you wrote "Our teacher hinted to prove that it's a Cauchy sequence."   You were on the right track.

To continue, we have the following relationships:

$$\begin{align}
\sum_{k=n}^m \frac{1}{k^3}&\le \frac1n \sum_{k=n}^m\frac1{k^2}\\\\
&\le \frac1n \sum_{k=n}^m\frac{1}{k(k-1)}\\\\
&=\frac1n \sum_{k=n}^m\left(\frac{1}{k-1}-\frac{1}{k}\right)\\\\
&=\frac1n\left(\frac{1}{n-1}-\frac1m\right)
\end{align}$$

which clearly goes to zero as $m\to \infty,n \to \infty$.  Therefore, the sequence of partial sums is Cauchy which implies that the series converges.
Answer: For $k\geq 2$ we have $k^2\geq k+1$
and
$$\frac{1}{k^3}\leq \frac{1}{k(k+1)}$$
but
$$\sum_{k=2}^n\frac{1}{k(k+1)}=\sum_{k=2}^n (\frac{1}{k}-\frac{1}{k+1})$$
$$=\frac{1}{2}-\frac{1}{n+1}\leq \frac{1}{2}$$
thus the sequence of partial sums
$S_n=\sum_{k=2}^n\frac{1}{k^3}$ is increasing and bounded, and therefore convergent.
Comment: This can be refined considerably, without much additional effort.
Comment: Another user has already posted the solution to which I refer.
Answer: Using partial fractions and telescoping from your setup, after using the inequality $$k^3=k(k^2)>k(k^2-1)=k(k-1)(k+1):$$
$
\begin{align*}\sum_{k=n+1}^m \frac{1}{k^3}&<\sum_{k=n+1}^m \frac{1}{k(k-1)(k+1)}\\
&=\sum_{k=n+1}^m \frac{1/2}{k-1}-\frac1k+\frac{1/2}{k+1}\\
&=\frac{1/2}{n}-\frac{1/2}{n+1}-\frac{1/2}{m}+\frac{1/2}{m+1},
\end{align*}
$
which you can bound above with $\dfrac1N$.  (Inspiration came from the usual telescoping way to show that partial sums of $\sum\frac1{n^2}$ are bounded, which could also be adapted to show they are Cauchy.)
Comment: This is the way forward that I would have presented.  Well done!  (+1) and Happy Holidays!  -Mark
Comment: Note that $\frac1{n}-\frac1{n+1} = \frac1{n(n+1)}$ to get a nicer expression for the bound.
Comment: @martycohen: Not sure if nicer, but you indicate a step in getting a tighter bound (which in some contexts could be more useful).  For just showing Cauchy, $\frac1N$ seems really nice, and then only requires dropping the negative terms and using $n,m>N$.  (In retrospect last 3 terms could be dropped instead of just negative ones, but either way the last step in this answer wasn't geared toward optimizing.)
Answer: Since $ b_n= \dfrac{1}{n^a} > 0 \space \forall\ n \in\mathbb N$ and $b_n>b_{n+1}$
$$\sum b_n \sim \sum2^nb_{2^n} \rightarrow \sum \dfrac{1}{n^a}\sim \sum(\dfrac{2} {2^a})^n$$ which converges for $a>1$
Comment: I'm not sure what the $\sim$ is supposed to mean, but you can bound the summation as given [here](https://en.wikipedia.org/wiki/Cauchy_condensation_test#Estimate).
Comment: Since the OP has not yet seen the integral test, I doubt that she/he has seen the Cauchy Condensation Test.
Answer: Hint
$$\frac{1}{n^3} < \frac{1}{n(n-1)(n-2)} \\
 \frac{1}{n(n-1)(n-2)}=\frac{1}{2} \left( \frac{1}{(n-2)(n-1)}- \frac{1}{(n-1)n} \right)$$
By combining these it is easy to show that your sequence of partial sums is Cauchy
Comment: I don't think this is right.  You may have meant to change the signs around a bit?  And using this answer with a bit of manipulation, it provides nice lower and upper bounds.
Comment: @SimpleArt Ty, fixed it. Ups.
Comment: This is a solid approach that relies on elementary analysis only.  Well done and Happy Holidays!  -Mark
Answer: The integral test shows us that it converges and that
$$\sum_{n=1}^\infty\frac1{n^3}<1+\int_1^\infty\frac1{x^3}\ dx=\frac32$$
And we also know that it is greater than the first term, since the partial sums are monotonically increasing, so
$$1<\sum_{n=1}^\infty\frac1{n^3}<\frac32$$
Comment: In the comments it states "We haven't [learned the] Integral Test yet, or even functions (only sequences)."  But this is one way to estimate the series.  The Euler-Maclaurin Summation Formula provides a means to generate an asymptotic expansion.
Comment: @Dr.MV Yes, but I honestly wanted to do the integral test because it's quite simple and doesn't require much.  And if the integral test is too much, the Euler-Maclaurin sum is like bringing a hammer to baseball practice.
Comment: Yes, I agree.  And you're answer is fine.  I was leaving this as a reference for other users that might be interested and you might have been posting this solution in the same spirit. ;-))
Comment: Ah, well then, thank you :-)


All the checkboxes inside a ng-repeat are getting checked when I select just one

Question: I have list of objects named rolePermissionList like this:
[{"id":1,"name":"createUser","type":"user","marked":1},{"id":2,"name":"deleteUser","type":"user","marked":1},{"id":3,"name":"editRole","type":"role","marked":0}]

and I use ng-repeat  to repeat checkboxes using the values in that list like this

    Role Permissions:

          <input type="checkbox" ng-model="idsPermission[permission .idPermission ]"
               ng-checked="permission.checked">{{permission.name}}

the ng-model of the checkboxes is named idsPermission and it's a list of numbers, those numbers are the IDS of the objects.
When I load the page the checkboxes that are supposed to be checked are checked this part works fine, but when I check another checkbox all the checkboxes gets checked, and when I uncheck a checkbox the same thing happens all the checkboxes gets unchecked.
I use that list of numbers named idsPermission to get all the IDS of the checkboxes that are checked, this worked before I used the directive ng-checked="permission.checked", but now I need to use it since now I need to show the checkboxes that are already marked.
this is my controller
angular.module('MyApp')
    .controller('RolCtrl', ['$scope', 'RolService',
        function ($scope, RolService) {
            $scope.idsPermission = {};
            $scope.getListCheckBoxesEditRole = function (idRole) {

                $scope.selectRol.descripcion;
                RolService.getListCheckBoxesEditRole(idRole)
                        .then(
                                function (d) {
                                    var userPermissionList = [];
                                    for (var permission in  d) {
                                        if (d[permission ].type === 'user') {
                                            if (d[permission ].marked === 1)
                                            {
                                                d[permission ].checked = true;
                                                userPermissionList.push(d[permission ]);
                                            } else {
                                                userPermissionList.push(d[permission ]);
                                            }
                                        }

                                    }
                                    $scope.rolePermissionList = userPermissionList;
                                },
                                function (errResponse) {
                                    console.error('ERROR');
                                }
                        );
            };
        }
        $scope.getListCheckBoxesEditRole(3);
    ]);

The RolService.getListCheckBoxesEditRole(idRole) service returns this JSON [{"id":1,"name":"createUser","type":"user","marked":1},{"id":2,"name":"deleteUser","type":"user","marked":1},{"id":3,"name":"editRole","type":"role","marked":0}]
and what I do in the controller is iterate over that list and check if the marked field is 1 if it's 1 I do this d[permission ].checked = true; I what I think that I do in that line is setting the checked value to true so I could use this directive in the html view ng-checked="permission.checked"
I tried doing this  ng-checked="idsPermission[permission.checked]" but when I do this the values that are marked=1 in the JSON that I paste above don't appear checked when I load the page, but if I put it like this ng-checked="permission.checked" they appear marked as they should, but when I click a checkbox all the checkboxes gets selected.
Comment: Create a plunker demo that reproduces problem
Answer: I came across too many issues to document but the main problem was how you are iterating through the array that is returned from the service.  It should be something like this:
Controller
    angular.forEach(d.data, function(permission) {
       if (permission.type === 'user') {
        if (permission.marked === 1) {
          permission.checked = true;
          userPermissionList.push(permission);
        } else {
          userPermissionList.push(permission);
        }
      }
    });

Then you can simplify your html like this:
HTML
 <input type="checkbox" ng-model="permission.checked" />

You can see all of the changes in this working plunk.
Answer: I can't see in your code that $scope.idsPermission is getting defined. In ng-repeat you only set the key for the object but the value is undefined. That's why the checkbox won't show the correct value.
You could use ng-init to initialize the model. Please have a look at the simplified demo below or this fiddle.
(Also defining the models in your controller would be possible.)
Only using ng-model should be enough for the checkbox to work. I think I've read somewhere that ng-checked and ng-model aren't working smoothly together.

angular.module('demoApp', [])
  .controller('mainCtrl', MainCtrl);

function MainCtrl() {
  var vm = this;

  angular.extend(vm, {
    data: [{
      id: 0,
      marked: 1
    }, {
      id: 1,
      marked: 0
    }, {
      id: 2,
      marked: 1
    }]
  })
}

    <input type="checkbox" ng-init="ctrl.idPermissions[item.id] = !!item.marked" ng-model="ctrl.idPermissions[item.id]"/>{{item.id}}

permissions: {{ctrl.idPermissions | json: 2}}
data{{ctrl.data | json: 2}}


Rewriting solution in terms of hyperbolic trigs

Question: I have to find the inverse laplace transform of:
$\mathcal{L}^{-1}(\frac{s}{-8+2s+s^2})$
I found it was
$\frac{2}{3}e^{-4t}+\frac{1}{3}e^{2t}$
But the question I'm asked is, determine $A,B,C,D$ such that $e^{At}(Bcosh(Ct)+Dsinh(Ct))$ is a solution of the inverse laplace transform.
I have no idea how to proceed. I've tried multiple things to no avail.
Any help will be greatly appreciated. Thanks.
Edit: I know hyperbolic trigs can be rewritten in terms of exponentials, but I can't figure out how to use this to my advantage.
Answer: Use the fact that
$$e^{At}(B\cosh Ct + D\sinh CT) = \tfrac{B+D}{2}e^{(A+C)t} + \tfrac{B-D}{2}e^{(A-C)t}
$$
Compare this to your expression. The coefficients give you
$$\left\{
\begin{array}{cc}\tfrac{B+D}{2}=\tfrac23 \\
\tfrac{B-D}{2}=\tfrac13
\end{array}\right.
$$
The exponents give you
$$\left\{
\begin{array}{cc}A+C=-4 \\
A-C=2
\end{array}\right.
$$
From these systems, you can easily see that
$$A=-1,B=1, C=-3, D=\tfrac13$$
so that you can write your solution as
$$e^{-t}(\cosh 3t - \tfrac13\sinh 3t)
$$
Answer: I've solved this.
One creates a system of equations out of this expression. And equate it to my simplified answer.


Como permitir que essa função receba apenas números?

Question: Bom dia gente, estou estudando JavaScript e gostaria de saber como mandar uma mensagem de erro caso o usuário insira uma string no lugar de um número, tentei fazer um código com esse intuito, ele até detecta se é um numero ou não, mas não manda a mensagem de erro.
Esse é o código que fiz:
    const aprovacao = function(nota){
    nota = Number(nota);
    if(nota !== NaN){
        if(nota >= 7){
            console.log("Aprovado.");
        } else{
            console.log("Reprovado.");
        }
    } else{
        console.log("Por favor digite um número.");
    }
    console.log(nota);
}

aprovacao(5);//mostra reprovado
aprovacao(9);//mostra aprovado
aprovacao("oi");//mostra reprovado

Comment: Basta usar [`Number.isNaN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN), exemplo: `nota = Number(nota); if(Number.isNaN(nota)) { console.log("Por favor digite um número."); } else if(nota >= 7) { console.log("Aprovado."); } else { console.log("Por favor digite um número."); }`
Answer: Utilize o operador typeof. Ele irá avaliar e retornar o tipo da variável.

const aprovacao = function(nota){
  if(typeof nota !== "number"){
    console.log("Por favor digite um número.");
    return;
  }

  if(nota >= 7){
    console.log("Aprovado.");
  } else{
    console.log("Reprovado.");
  }
}

aprovacao(5);//mostra reprovado
aprovacao(9);//mostra aprovado
aprovacao("oi");//mostra "Por favor digite um número."


Is it possible to have negative values in a simple slope analysis for dichotomous predictors?

Question: I am currently using the simple slope analysis to examine the significant interaction effects between my continuous moderator and a dichotomous predictor (values 1 & 2)on a continuous DV. I have 2 continuous covariates in the analysis.
My simple slope graph however showed negative values in the DV (i.e: moderator values at predictor value 2 accounted for negative amounts of DV - the slopes crossed the x-axis towards the bottom right direction). Is this possible, or is there some statistical error? I have seen slopes going into the negative values of DV for continuous predictors, but not for dichotomous predictors.
Comment: What are the units of each of the variables, and the dependent variable in particular?
Comment: Hello Jeromy, thanks for the below. The correlations bet the predictors was -0.035 (small) and the range of the DV was 3.00 and values were close to 0. Still working out the unusual results. But here's the units: DV: Range=3.00, Mean=1.41, SD=0.78. Unstandardised coefficients: Predictor(.71),
Comment: Apologies, here are the figures:                            DV: Range=3.00, Mean=1.41, SD=0.78.                Unstandardised coefficients: Predictor(.71),Constant(3.42), Moderator(-.04), interaction(.04).      Variances: predictor(0.02), constant(4.21), moderator(0), interaction(0). Df=92. Moderator: M=86.11, SD=8.92. Hope the above values make sense.
Comment: Given your range and mean for the DV, a predicted value a little below zero is not surprising. Of course, the more checks you apply, the better.
Answer: Overview of simple slopes analysis

The points used to generate a graph for a simple slopes analyses  are predicted values of the dependent variable given the model and various values of the predictor variables (see here for an example).

Are negative predicted values possible?

Yes. A regression equation can give rise to negative predicted values.
For example, if the equation was $Y = 1 - 2X -3Z - 1XZ$, then predicted $Y$ at $X=1$ and $Z=1$ is $Y = 1 - 2(1) -3(1) - 1(1)(1)$ or  $1 -2 -3 - 1=-5$.

Do negative predicted values imply that you've done something wrong?

Possibly.  If some or all of the following apply then negative predicted values might be a red flag on your analysis:

the range of the dependent variable is all positive, and particularly if the values are a long way from 0.
the correlation between predictors is not huge
you have chosen appropriate values of predictors.

When performing a simple slopes analysis typical values for predictor values include:

continuous predictors that are part of the moderator effect: values drawn from plus or minus one or often two standard deviations above and below the mean or something similar.
categorical predictors that are part of the moderator effect: each of the values that the categorical predictor takes
continuous covariates: the mean of the covariate
categorical covariates: one of the categories

Thus, choosing predictor values consistent with the above prescriptions will generally give rise to predictions on the dependent variable that are in the ballpark of the range of the dependent variable.
Of course, there are situations that could legitimately give rise to negative values even when the range of the dependent variable includes all positive values. This might be related to non-normal errors, correlated predictors, etc.


Fixed Position Table Row Labels

Question: I have a table in a div with overflow-x: scroll. So, you can scroll the long table left and right. The first "column" (td's in first position of each tr) should contain labels for the rows. I would like that when you scroll right or left, the contents of the table scroll, but the labels stay fixed so you can always see them.
I initially wanted to create another table to the left of this one, but the catch is the contents of each row is variable, so I don't know the height of each row until after the contents load (making it difficult to set the height of each cell in the "label column." The reason I can't dynamically just update the heights of the label column cells after the content loads is that it is really slow on FF and IE. The slowdown comes from calling clientHeight on the content tr or first td. It takes 5-6 seconds on my first clientHeight call of the content (the rest of them take 0-1ms). Regardless, I don't know of another approach.
Any suggestions?
Comment: This sort of thing has been of great interest to designers over the years, yet it remains insanely difficult to do well.  Browsers tend to be pretty weird about rendering tables ...
Comment: Maybe you could try offsetHeight instead of clientHeight? Maybe that is faster ... 5-6 seconds seems like an implementation error
Answer: You could maybe put all the contents of your other cells into the first cell as well, at offset (0,0), so that the height of the label cell is automatically set to the height of the largest component. and then put a layer above them so that they are invisible, and put the label in there.

Fixed Position Table Row Labels


como colocar um verificador de dominio em php?

Question: Bom, eu estou com um site bem desenvolvido, porém, eu quero colocar uma página para verificar se o domínio já está registrado sim ou não, pesquisei muito antes de chegar aqui, então nenhuma funcionou, o meu código em html está desta forma

                               <input type="text" placeholder="Digite o seu domínio" autocomplete="off" autofocus class="autofocus-caret-beginning" required ng-model="input.domain" name="domain" id="cart_domain_search_domain" ng-disabled="loading">

                                <input class="submit" type="submit" value="CONSULTAR" ng-disabled="searchForm.domain.$error.pattern || loading">

porém gostaria de saber, como eu poderei prossegui?
Answer: Você pode usar checkdnsrr ou gethostbyname:
Documentação:
http://www.php.net/checkdnsrr
http://www.php.net/gethostbyname
Exemplo de checkdnsrr:
<?php
 if ( checkdnsrr('example.com.', 'ANY') ) {
  echo "DNS Record found";
 }
 else {
  echo "NO DNS Record found";
 }
?>

Exemplo de gethostbyname:
<?php
 $domain = 'example.com';
 if ( gethostbyname($domain) != $domain ) {
  echo "DNS Record found";
 }
 else {
  echo "NO DNS Record found";
 }
?>

fonte: https://stackoverflow.com/a/8693519/7437072
Ou como citou o Guilherme Nascimento nessa resposta .
Talvez o que você necessita é uma consulta WHOIS.
Existe uma biblioteca chamada https://github.com/regru/php-whois que utiliza uma série de serviços pra consulta https://github.com/regru/php-whois/blob/master/src/Phois/Whois/whois.servers.json
Exemplo de uso:
<?php
require_once 'vendor/autoload.php';

$sld = 'dominio.com.br';//Dominio que quer verificar

$domain = new Phois\Whois\Whois($sld);

if ($domain->isAvailable()) {
    echo 'Domínio disponível';
} else {
    echo 'Domínio indisponível';
}

Comment: Neste caso o WHOIS me permite verificar se o domínio que o cliente quer para o site dele está disponível sim ou não igual a esta forma [link](https://www.hostinger.com.br/registro-de-dominio) ?
Comment: Sim, só utilizar a biblioteca como mostrado no exemplo


Proving A is diagonalizable only to a matrix composed of its eigenvalues

Question: I need to prove that an $n\times n$ matrix $A$ is diagonalizable only to a matrix $D$ that has its diagonal entries as a permutation of the eigenvalues of A, in order to solve a related question.
The related question is disproving that a matrix A is diagonalizable to a diagonal matrix with one of the entries not being an eigenvalue of A.
Answer: Here's a better claim: if $D$ and $E$ are similar diagonal matrices, then there's a permutation matrix $P$ with $P^{-1}DP = E$.
That'd prove your claim, for if $A$ were similar to both $D$ and $E$, then $D$ and $E$ would be similar, and hence similar via some permutation.
Why is it a better claim? Because, for instance, if your $4 \times 4 $ matrix has only $1$ and $-1$ as eigenvalues, and it's similar to
\begin{bmatrix}
1& & & & \\ & 1& & & \\
& & & 1& \\ & & & &-1
\end{bmatrix}
then it cannot be similar to
\begin{bmatrix}
1& & & & \\ & 1& & & \\
& & & -1& \\ & & & &-1
\end{bmatrix}
even though both of those diagonal matrices have entries that are all eigenvalues of $A$. This richer observation may not be needed for the thing you want to prove, but since this is no harder to prove than the other one, we might as well do it.
Now...the question is, "How do I prove that claim?"
Suppose that
$$
M^{-1} D M = E, i.e.,\\
DM = ME.
\newcommand{\be}{\mathbf e}
$$
for some pair of diagonal matrices $D$ and $E$. Note that $\be_1$ is an eigenvector corresponding to the first entry $e_{11}$ of $E$. So
$$
ME\be_1 = Me_{11}\be_1 = e_{11} M\be_1
$$
But this is the same as $DM\be_1$, by the equality above, thus $M\be_1$ is an eigenvector of $D$, with eigenvalue $e_{11}$ as well. Since $D$ is diagonal, all of its eigenvectors are standard basis vectors, so there must be some value $j$ with $D\be_j = e_{11}\be_j$. So $e_{11}$ is one of the diagonal entries of $D$.
Consider the restriction of $v \mapsto Ev$ to the subspace orthogonal to $\be_1$ (whose matrix is just $E$ with the first row and column deleted) and the restriction of $v \mapsto Dv$ to the subspace orthogonal to $\be_j$ (whose matrix is $D$ with the $j$th row and column deleted). These are still similar, (via a matrix $N$ that is simply $M$ with the first column and $j$th row deleted) and diagonal, and an inductive argument finishes the claim.
Comment: Gotcha! So disproving D and E being similar will then disprove A and E (whatever one I want to disprove) are similar. Giving it a go!
Comment: Alright I think I'm getting it. Why can't we just have $e$ as any eigenvalue of $E$ instead of just the largest one?
Comment: You can; I've written out an argument now.
Answer: The simplest explanation is that similarity transformations preserve eigenvalues, and that the diagonal entries of a diagonal matrix are exactly its eigenvalues (since the standard unit vectors are corresponding eigenvectors).
Answer: Suppose $A=P^{-1}DP$, where $D$ is diagonal, and let $d_i$ denote the $i$th diagonal entry  of $D$. Then $AP^{-1}=P^{-1}D$. Let $\mathbf{e_i}$ be the $i$th standard basis vector. Then
$$
AP^{-1}\mathbf{e_i}=P^{-1}D\mathbf{e_i}=P^{-1}d_i\mathbf{e_i}=d_iP^{-1}\mathbf{e_i}.
$$
Therefore $P^{-1}\mathbf{e_i}$ is an eigenvector of $A$, with eigenvalue $d_i$.
This proves that all the diagonal entries of $D$ are eigenvalues of $A$.


Use jQuery tab form with FormData

Question: I am using a jQuery multi-tabbed widget, but I want it all the be one form. So with inputs in all sections.

Section 1

Section 2

Section 3

  <form>

            Value 1
            <input type="text" class="form-control">

            Value 1
            <input type="text" class="form-control">

Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.

Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.

Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.

  </form>

I want all tabs to have inputs and be associated with one form. I'm just unsure how to structure it and where to place the <form></form> tags so that it knows the inputs in all the tabs belong to the one form.
Comment: Every form control element inside the form tags are members of that form, nevertheless they are wrapped in some other elements.
Comment: @Teemu I understand, so what about the edited example?
Comment: Both the inputs are "belonging" to the form. Notice, that only form control elements (input, select, textarea) are taken in a FormData object, elements like div and p are ignored. Also, it's recommended that the form control elements have the name attribute being set.
Comment: @Teemu Thank you, I just put them inputs in as examples. I will of course give them name attributes. I just wanted to make sure the structure was correct first. Thanks!
Answer: The "form" tag must wrap your entire code above
Comment: it should be like that yes

Use jQuery tab form with FormData


What is C10k in web server?

Question: I am read the wiki of the C10K problem but it confusing me.
Can any one explain about the following point

Why this problem arries
No of way we can solve this problem
Answer: Traditionally, if a webserver gets a connection, it starts a worker/thread, and the worker exists until the connection is over, even if there is no or very little data going over that connection.
Since every worker needs a certain amount of RAM, the amount of workers is limited by the amount of RAM of the server, which means the number of connections is limited by RAM. Usually, you end up way below 10000 connections.
nginx, for example does not use the thread based architecture, but an event based architecture. As such it does not use a lot of resources per connection and can handle way more connections concurrently.
More info might be found in The Architecture of Open Source Applications: nginx
Comment: RAM is just one of the issues. And the C10k problem also includes the issues with other design models. For example, if you use a big loop around `poll` or `select`, the operation gets expensive because socket discovery gets complex in the kernel/OS.
Comment: @DavidSchwartz thats a good point. I linked to an article talking about the nginx architecture since it might be too much to talk about in this format.
Comment: This issue can be mitigated by horizontal scaling (more servers, i.e. have multiple hosts serving up the same resources). In my experience this issue is something that comes up when you are scaling way up in the # of client connections.  Look at using a Load Balancer or just round-robin DNS (but be aware of how they will maintain session state for your app if it's used).

What is C10k in web server?


Como atualizar estador do Value do DropDownButton no Flutter com GetX sem utilizar o SetState?

Question: Estou tentando fazer um DropDownButton no meu projeto através de um FutureBuilder. Antes de utilizar o GetX para atualizar o estado do Value, eu utilizava o setState e funcionava. Após modificar o projeto para a utilização do GetX como gerenciador de estado não consegui atualizar e fica dando erro. Seguem os códigos:
<code>                          DropdownButton(
                          icon: Icon(
                            Icons.arrow_drop_down,
                          ),
                          iconSize: 20,
                          hint: Text("Cidade"),
                          style: TextStyle(
                            fontFamily: "WorkSansSemiBold",
                            fontSize: 16.0,
                            color: Colors.black,
                          ),
                          items: _listCidades?.map((item){
                            return new DropdownMenuItem(
                              child: new Text(item.nome),
                              value: item.id,
                            );
                          })?.toList() ?? [],
                          onChanged: (value) {
                            setState(() {
                              mySelection = value;
                            });
                          },
                          value: mySelection,
                        ),
</code>
Código com GetX para gerenciar o estado:
<code>                            FutureBuilder<List<Cidade>>(
                          future: _loginController.getCity(),
                          builder: (context,  snapshot) {
                            return DropdownButton(
                              hint: Text("Cidade"),
                                items: snapshot.data?.map((cidade) =>
                                    DropdownMenuItem<String>(
                                      child: Text(cidade.nome),
                                      value: cidade.id,
                                    )
                                )?.toList() ?? [],
                              onChanged: (newValue){
                                _loginController.setCidade(RxString(newValue));
                                mySelection = newValue;
                              },
                              value: GetX<LoginController>(
                                builder: (_)=> _.cidade,
                              ),
                            );
                          },
                        )
</code>
Código do controller:
<code>  var _selectCidade = "0".obs;
  get cidade => this._selectCidade.value;
  set cidade(value) => this._selectCidade.value = value;
</code>
Answer: Você pode instanciar o controller dentro da classe e depois usa-lo para acessar a variável cidade que está sendo observada.
Para refletir as alterações, a variavel.obs deve estar dentro de um Obx, conforme código abaixo, assim cada vez que ela for alterada, o widget será reconstruído
Existem maneira de não precisar instanciar o controller como por exemplo o uso de GetView, GetBuilder, etc...
<code>final MeuController controller = MeuController();

Obx(() => DropdownButton(
              hint: Text("Cidade"),
              items: snapshot.data
                      ?.map((cidade) => DropdownMenuItem<String>(
                            child: Text(cidade.nome),
                            value: cidade.id,
                          ))
                      ?.toList() ??
                  [],
              onChanged: (newValue) {
                _loginController.setCidade(RxString(newValue));
                mySelection = newValue;
              },
              value: controller .cidade,
            ));
</code>


Drupal Core errors and logging

Question: Looking for a way to suppress PHP errors that come from the Drupal core itself. Obviously, if the issue isn't being fixed in the core code base, we generally assume it's okay to ignore it and that it will get fixed in the core before long.
For example, we occasionally see this error in the logs:
Symfony\Component\HttpKernel\Exception\ControllerDoesNotReturnResponseException: The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned null. Did you forget to add a return statement somewhere in your controller? in () (line 98 of /var/www/html/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php).
Which comes from a core library and since we are not familiar with that particular bit of the core, we don't have plans to chase it down. Obviously, issues that originate from our own code is something we would want to see but it there a way to get the Drupal error log to ignore errors that we really can't do anything about?
Just trying to unclutter our logs a bit so we can focus on more important issues (or at least ones we have control over).
Comment: This most likely is not coming from core, but from a custom/contrib module incorrectly calling public APIs from core. Core is tested quite well, errors like this would show up on _many_ sites and would be reported.
Comment: I agree with @Hudri. There is no way that a core module is the root cause of that exception.
Comment: This error is very easy to locate. You should be able to find the controller in the stack trace attached to the error message or, if this is not available, by applying common sense where the error has happened and which module might be providing the route.
Comment: Unfortunately, there is no trace or any other information in the error logs. The line above is literally everything that is returned in the log. I assumed it was coming from the core since the error only lists one location for the error and that is in the core. If it is coming from a contrib module as you suggest, there is no indication of where it is coming from or what is triggering it. The error report itself lists no operations at all, completely empty.
Answer: If you are referring to database logging, and are comfortable with custom code, decorate the logger.dblog service, wrapping the original service with your own implementation. Override the log method of Drupal\dblog\Logger\DbLog, in which you filter messages before passing them to the wrapped object's log method.

Drupal Core errors and logging


Is there a formula for the number of k-partitions of a set?

Question: In how many ways can a set be partitioned into k non-empty subsets?
Comment: @JoeJohnson126 that is for partitions of integers, not set partitions. What OP really wants to search for are the [Stirling numbers of the second kind](http://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind).
Comment: See the section "Restricted part size or number of parts" here: http://en.wikipedia.org/wiki/Partition_%28number_theory%29#Partition_function
Comment: @Casteels: Thanks :)
Answer: If the set is non empty, it can be calculated with a recursive formula.
Let $S_{n,k}$ be the number of $k$-partitions of a set $X$ ($n\ge k \ge 1$).
Simple observations: $S_{n,1}=1,\enspace S_{n,n}=1$.
Let us now suppose $n>k>1$. Let $x_0\in X$, and consider a $k$-partition $\mathcal P$ of $X$.

Either $\{x_0\}$ is a member of $\mathcal P$. Then $\mathcal P'=\mathcal P\setminus\bigl\{\{x_0\}\bigr\} $ is a $k-1$-partition of $X'=X\setminus \{x_0\}$. These are $S_{n-1,k-1}$ in number.
Or $\{x_0\}$ is a not a member of $\mathcal P$. Then $\mathcal P$ induces a $k$-partition of $X'$, by taking the intersections of its members with $X'$. Conversely, from a $k$-partition of $X'$, you get a  $k$-partition of $X$ by  adjoining $x_0$ to one of its members. As there are $p$ choices for this adjunction, these partitions are $kS_{n-1,k}$ in number.

Conclusion: we obtain the following recurrence relation:
$$S_{n,k}=S_{n-1,k-1}+kS_{n-1,k}.$$
We can compute the values of the $S_{n,k}$s in a way very similar to Pascal's triangle. Here are the first values:
$$ \begin{array}{r|*{8}{c}}
k = &1 & 2 & 3 & 4 & 5 & 6 & 7 \\
\hline
n = 1 & 1 \\
2 & 1 & 1 \\
3 & 1 & 3 & 1 \\
4 & 1 & 7 & 6 & 1\\
5 & 1 & 15 & 25 & 10 & 1 \\
6 & 1 & 31 & 90 & 65 & 15 & 1\\
7 & 1 & 63 & 301 & 350 & 140 & 21 & 1\\
8 & 1 & 127 & 969 & 1701 & 1050 & 266 & 28 & 1
  \end{array}$$
Answer: Following the above notation, the number of non-empty $k$-partitions in a set of $n$ elements is:
$$S_{n,k} = \frac{1}{(k-1)!}\sum_{j=0}^{k-1}{(-1)^{j}\binom{k-1}{j}}(k-j)^{n-1}$$
For example:
$$S_{n,2} = \sum_{j=0}^{1}{(-1)^{j}\binom{1}{j}(2-j)^{n-1}} = 2^{n-1} - 1$$
$$S_{n,3} = \frac{1}{2}\sum_{j=0}^{2}{(-1)^{j}\binom{2}{j}}(3-j)^{n-1} = \frac{3^{n-1}-2^{n}+1}{2}$$
and so on.
The following is just an anecdotal extra, but I remember writing this formula when I played Final Fantasy VIII Remastered a while ago to calculate the number of ways to assign GF to the three active party members, which turned out to be a problem equivalent to finding out the number of distinct 3-partitions of the set of acquired GFs.


Acessar aplicação web que esta rodando no apache de um container docker dentro de um servidor linux que eu acesso por ssh

Question: Pela minha máquinha windows tenho acesso um servidor linux que está na mesma rede através de um SSH. Preciso acessar uma aplicação web que roda dentro do apache de um container docker que esta nesse servidor, alguma ideia de como fazer isso? Atualmente consigo acessa-la somente pelo navegador do servidor linux e quero acessa-la pela minha máquina windows.
Answer: Antes de mais nada você precisa saber se a rede que esse servidor está, pode ser acessada pela sua máquina direto pelo IP, voĉe pode testar isso dando um ping no ip dela.
Se a sua máquina conseguir dar um ping no servidor, significa que é possivel. Dessa forma, você precisa subir esse container mapeando uma porta que deseja, por exemplo -p 8000:8000.
Com o container ativo e a porta mapeada, você pode acessar direto pelo browser digitando o Ip da maquina junto da porta, exemplo, 172.16.108.10:8000
Answer: Depois de acessar o servidor linux por ssh, lista os containers que estão rodando no servidor executando o comando: "docker ps"
verifica o ID do container que você quer acessar e executa: docker exec -it <id_do_container> /bin/bash
Comment: Você precisa subir o container mapeando a porta para alguma porta do servidor, ex: docker run --name ``  -p 80:80 imagem:latest
Comment: Aqui tem um tutorial legal de como fazer: https://www.cloudreach.com/blog/containerize-this-php-apache-mysql-within-docker-containers/
Comment: O problema que quero acessar a página web que roda pelo apache do container, e não o container em si. Entende ?
Comment: O container vai responder na mesma porta do servidor linux, é só acessar pelo browser do windows, colocar o ip_do_servidor_linux:porta ... ai ele vai direcionar direto para o container
Comment: Vou tentar aqui. Você tem ideia de como posso linkar um container com imagem do apache à um container com a imagem do php? Tenho os dois containers rodando mas acho que preciso ligar os dois de alguma forma


Network cable keep connecting/disconnecting rapidly or so does Windows tell me

Question: Suddenly this morning one of the computer on our network keeps dropping it's network connection. The computer run an up to date Windows XP Pro and is a Lenovo 3000 J110 computer. The network card is onboard and "from" Broadcom.
As soon as the computer is started Windows report that "A network cable is unplugged". Soon after, the cable seem to be plugged in again and windows report "Acquiring network address". It then proceed to go from the first message to the second every 5-20 seconds.
If I look behind the computer the LEDs near the network plug are not lit when the computer report that the network cable in unplugged.

I've tried a new cable, same problem.
I've tried another computer on this cable, worked fine.
I've tried downloading and reinstalling the network adapter drivers, same problem afterward.
I even tried disconnecting the power from the computer for a minute, did not solve the problem.

Does anyone have any idea what might be the problem. Otherwise, what should be my next step in diagnosing this problem?
Answer: You didn't mention what happened with the other computer using that cable.
The other thing could be a problem with the switch/hub port. Try restarting the switch, if that doesn't work, change the port it's jacked into.
Comment: The other computer worked fine when plugged in this cable. I'll try to reboot the switch anyway, just in case.
Comment: What kind of switch is it? I've had SOHO router/switches start to go flaky, the ones that cost <$100. Typically last a year or two, then go nuts with the switching, the wireless function, etc. and the best solution was to chuck it. No rhyme or reason to it, they just up and died one day.
Comment: This computer and another one are connected into a cheap (definitely less than $100) 5 ports switch so they can share one wall outlet. I restarted this switch and the problem got away. Because the other computer was working correctly on the said switch I supposed it was working fine. Wrong assumption. Thanks for the help.
Comment: I've had that happen too. One port will act wonky but other systems act fine. Doesn't make much logical sense at first but a restart can clear up whatever in the firmware is going nutters.
Comment: sounds like my office multiple computers plugged into 1 wall jack :(
Comment: @Xjerx-you mean you have multiple computers going into one drop that then goes back to a low-end switch in the closet? I wouldn't be surprised if that can cause issues once in awhile with the routing of packets, or performance issues at the least.
Answer: I'd echo Bart's statements re: trying another port on the switch, etc.
You don't mention if this has ever worked before. I've seen this behavior with old, early 10/100 Ethernet switches (late 90's 3Coms come to mind) when the autonegotiation doesn't work properly. If this hasn't ever worked before I'd investigate if the switch is properly configured for autonegotiation and, if not, I'd try "hard setting" the port to a speed and duplex (reluctantly, mind you).
Edit:
Since it's been working for awhile I'd recommend looking at the switch's logs (if it has any) and, failing any error messages there, I'd consider rebooting the switch. Most switches don't have any ability to maintain persistent logs across boots and, since you really want to find a root cause (you do, don't you?), you should look at the log before you reboot it.
Trying a known-working device in the port that's acting flaky might tell you if it's the port, as well. You could do that before you reboot the switch (if you get to that point).
Comment: Beat me by 1 min.  :-)
Comment: Yes, it worked for years litteraly.
Comment: @Mathieu: I've dropped on an edit with some addt'l suggestions.
Comment: @Evan: Thanks I resolved the problem by restarting the cheap switch that was between the computer and the main office switch.
Comment: @Mathieu: Good to hear. Cheapie Ethernet switches have been the cause of more problems in my experience than you'd probably guess. They definitely can fail in strange ways (some ports working, others failng) like you saw today. I'd keep an eye on the switch because, in my experience, a partial failure like you saw today often preceeds a complete failure.
Comment: Cheapie switches are good for home, and that's about it. I know they're often marketed for SOHO use, but unless your office has five systems going through it, make the jump to a decent managed switch...SOHO switches are good for home just because they're simple enough for a couple systems to use and when they die you can buy another one as backup to switch them out. But if I relied on them to make money (in a business) no way! :-)
Answer: We had a similar problem with a broadcom card and an incompatibility with the switch.  Did you have an update to the driver that may have started this?  In any case, the solution for us was to hard code the link speed and duplex.  Try 1Gb/full duplex and work your way down from there.
Comment: Nothing changed recently, except maybe automatiques Windows updates.
Comment: Oh, and it used to work until this morning.
Comment: Check the Windows Update log to see when/if driver updates came through.


Chord theory for B5#4

Question: I have just recently Re-learned the Loverboy song "Working For The Weekend" from a score borrowed from the library. The first three chords in the intro are B5, B5#4, and Bsus4. My question only relates to the B5#4.
How do you read it: B-five-sharp-four or some other way?
What is the theory on building this chord? Is it just a power chord with a sharp fourth tone added?
Comment: It's a passing chord, between B5 and Bsus4, chromatically.
Comment: Thanks. I haven't played for about 5 years due to illness and I'm trying to remember the music theory as I relearn songs I played many years ago.
Comment: Tim's comment is the correct answer.  I think he should post it as an answer!  (Too bad we can't vote for comments!)
Answer: As @Tim said in comments the scale steps ^5 ^#4 ^4 are a chromatic embellishment over the root. I think you could say it's all just one embellished chord, no chord change.
From an expressive point of view the ^#4 is a nice spicy dissonance and the ^4 is 'unresolved' meaning the ^4 doesn't go down to the chord tone ^3. The combined dissonance and non-resolution make for a great, attention grabbing introduction.
Answer: Are you sure you've copied those chord symbols quite correctly?   B5(add#4) would make sense.   B5#4 is nonsense. B5, by definition is a two-note chord.
Here's what seems to happen, though this version is transposed to C major.
Comment: Thanks, that makes sense. The score I borrowed from the library did not have parentheses or add, just B5#4.
Comment: Transposed to Cmajor, with a Cminor key sig?
Comment: Fair point!   C minor it is.

Chord theory for B5#4


Hold the console window open using c#

Question: I have the below code to build a project using MSBuild:
string process = sourcePath + @"\Application.sln /t:rebuild";
System.Diagnostics.Process csc = System.Diagnostics.Process.Start(@"C:\WINNT\Microsoft.NET\Framework\v2.0.50727\MSBuild.exe",process);

This code worked before, I don't know why is not working any more.
If I do the same thing above by CMD it works fine, but not from VS.Net, the console window disappear fast so I can't see the error message.
If I debug the code I got this:
BasePriority = 'csc.BasePriority' threw an exception of type 'System.InvalidOperationException'
Is there any way to hold that screen so I can know what is happening here?
Comment: If it was worked BEFORE 100% you have to restart your computer...
Comment: Have you tried putting a breakpoint on the line that is throwing the error?
Comment: @valverij see the part `If I debug...`
Answer: Just start the cmd process with MSBuild.exe as an argument instead of directly starting the exe file.
string process = @"C:\WINNT\Microsoft.NET\Framework\v2.0.50727\MSBuild.exe " + sourcePath + @" \Application.sln /t:rebuild";
System.Diagnostics.Process csc = System.Diagnostics.Process.Start(@"%windir%\system32\cmd.exe", process);

Comment: =))). It is always easier to see the misteke in someone's code than in your own.
Comment: I don't understand :( My app is a console window that calls another console window app. The last one is the one I need to be active so I can see the error.
Comment: The MSBuild.exe process exits immediately when the build completes. The console you want to see is actually the cmd process window that runned the MSBuild.exe process. I do exactly this: run the MsBuild process from the newly created cmd console window. Or do you need to see the output in console windows of your own process - it would be a bit harder - you need to copy the output of that process (ran silently) and output it to your own console
Comment: Thank you @OleksandrPshenychnyy your solution made me see my issue, a space was missing between MSBuild.exe and the rest of the path
Answer: You can try to redirect the output of the msbuild you start using RedirectStandardOutput
Process compiler = new Process();
compiler.StartInfo.FileName = @"C:\WINNT\Microsoft.NET\Framework\v2.0.50727\MSBuild.exe";
compiler.StartInfo.Arguments = sourcePath + @"\Application.sln /t:rebuild";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();

Console.WriteLine(compiler.StandardOutput.ReadToEnd());

compiler.WaitForExit();

Comment: It happens when you have space in your paths.. Need double quotes around it.. See this answer http://stackoverflow.com/a/470659/158297 and also http://lajak.wordpress.com/2011/04/20/tfs-2010-msbuild-error-msb1008-only-one-project-can-be-specified/
Comment: Awesome @Amitd, that finally fixed it. I was placing the folder in path: like `Doument and Settings...` that was causing that error, so I moved it to a folder in `c:\temp\...` without spaces :)
Comment: I got an error: `MSBuild: error MSB1008: Only one project can be specified.` Why is this happening, there is only one project here. :(

Hold the console window open using c#


Running systemd units in user space in debian

Question: I'm trying to setup a unit to run on Debian Stretch under a regular user. I connect to it over ssh.
I first did this as root (username being the user in question):
# loginctl enable-linger username

And then when I run:
# systemctl --user

I get:
Failed to connect to bus: Permission denied

How do I fix this?
Comment: Logout and log back in.
Answer: There is another possible solution to this problem on Debian Stretch (at least): if the libpam-systemd package is not installed, then PAM never triggers systemd to create a systemd-user daemon.
Answer: It turns out that my in my installation of debian stretch the environment variable XDG_RUNTIME_DIR was badly configured for all non root users and was set to /run/user/0.
Instead it should be set to the id of the current user. To achieve that you can add the following to your .bashrc:
export XDG_RUNTIME_DIR=/run/user/`id -r -u`
Comment: This ought to be set automatically by the system when you login. Probably the solution is in the other answer posted today.