Reagent batch change, sample size, results significancy

Question: We are working on a biological protocol measuring a patient's feature using a blood sample. This protocol has proven to have some variability (CV <= 10%).
During this process we sometime need to change a reagent batch. To be sure the new batch does not alter the results, we are running the protocol using the 2 reagent batches (current and new) on the same samples. We do collect the results in a spreadsheet.
So far we are using a sample size of 5 to 10 samples, with no good rational.
So far we have consider the reagent lot to be OK if the mean of the Coefficients of Variation of the N samples (current vs. new, sample by sample) to be < 10% (again, no good rational).
My first question : how can we calculate an optimal sample size that will ensure we can run with the new reagent. As the reagent are commercial and come with a CE mark quality certificate, the objective is to make sure the reagent is not bad (expired, exposed to a to low/high temperature during transportation/storage, etc.), not to make sure it has the exact same results as the current one.
Once we have collected the results for the 2 reagent for N samples:
data <- data.frame(
    sample_id=c(1,2,3,4,5,6,7,8),
    result1=c(10.83167, 17.96167, 34.97500, 37.21833, 23.19833, 29.56167, 36.32167, 40.11833),
    result2=c(14.80000, 17.71333, 37.17833, 43.74500, 24.86500, 26.80500, 40.80667, 47.52667)
    )

My second question: how can I know my second reagent batch is equivalent to the first one?
So far here is what we have done:
data <- data %>% rowwise() %>% mutate(mean=mean(c(result1, result2)), sd=sd(c(result1, result2)))
data$cv <- (data$sd/data$mean)*100

So we have data:
str(data)
Classes 'rowwise_df', 'tbl_df', 'tbl' and 'data.frame': 8 obs. of  6 variables:
 $ sample_id: num  1 2 3 4 5 6 7 8
 $ result1  : num  10.8 18 35 37.2 23.2 ...
 $ result2  : num  14.8 17.7 37.2 43.7 24.9 ...
 $ mean     : num  12.8 17.8 36.1 40.5 24 ...
 $ sd       : num  2.806 0.176 1.558 4.615 1.179 ...
 $ cv       : num  21.895 0.984 4.319 11.4 4.904 ...

We have tried:
mean(data$cv)
8.82453442580761

and
t.test(data$result1, data$result2, conf.level = 0.90, paired = T)

    Paired t-test

data:  data$result1 and data$result2
t = -2.4161, df = 7, p-value = 0.04636
alternative hypothesis: true difference in means is not equal to 0
90 percent confidence interval:
 -5.1858973 -0.6274352
sample estimates:
mean of the differences
              -2.906666

The standard deviation of the results using this protocol is expected to be 1.8.
But we are not sure how we can interpret these results.
My third question: how can I know I have done enough samples?
Once we have an answer to the equivalence between the 2 reagent batches (whatever the method), how can we make sure this result is strong/significant enough ?
We are using R for the statistical analyses.
Thanx in advance for any help.
Comment: What's the difference between your first and third question?
Comment: @StatsStudent :
Question 1: how can we anticipate how many samples we should run ?
Question 3 : now that we ran N samples, is the result significant ?
Answer: A German saying goes roughly like this: "the metall worker measures in tenth of a millimeter, a joiner measures in whole millimeters, the carpenter measures in centimeters and the brick layer - you're lucky if he stays within your real estate." Different trades/crafts require different levels of precision. A statistician will not be the one to tell you, which deviations in measurements are acceptable within your trade. As for blood samples I guess a 10% difference would often be just acceptable for blood sugar but certainly not for arterial blood pH.
You will have to define your acceptable deviation and whether you need a 95% chance of that being met or a sex-sigma chance, dependent on the impact a wrong measuremet might have.
Only after that CrossValidated and our advice come into play. You may for example use R's t.test function with paired = TRUE for paired measurements to obtain confidence intervals or use some Bayesian statistics. Using normal-normal conjugacy estimating the true mean of the differences and the expected normal distribution should be doable even within a spreadsheet.
https://statswithr.github.io/book/bayesian-inference.html#three-conjugate-families
https://statswithr.github.io/book/inference-and-decision-making-with-multiple-parameters.html#sec:normal-gamma
Edit: In your first comment on this answer you specified, that you want to go with R's t.test function and that an acceptable mean deviation is 5.4 on a 90% confidence level.
Your call to t.test gave you a p value for an irrelevant null hypothesis, so do not care to much about that. It also gave you a confidence interval from -5.1859 to -0.6274. The confidence interval of a t-test is a good estimator for a credible interval (gained with a reasonable flat prior). We are not too far off to state, that the true difference between measuremens with the old an the new reagents lies in the [-5.2 ; -0.6] interval which does not include the acceptable mean deviation of +/- 5.4. Thus the true absolute deviation is smaller then the acceptable deviation.
Edit 2: This addendum was triggered by the comment starting with "Thanx @Bernhard for this extra explanation. The test is not cheap, ..."
You have used the following function call: t.test(data$result1, data$result2, conf.level = 0.90, paired = T) A side not advice: Never use paired = T as it will stop working, once somebody enters T = 0 into your R session. Take the time and effort to write paired = TRUE. Now that is out of the way, this call performs a t test for a null hypothesis, that die true difference between the reagent is 0.000000000000000000000000000000000000000000000000000.... That is not how chemical analyses work so that obviously that is an irrelavant hypothesis . Nobody expect a difference to be perfectly zero. That is why I proposed to disregard the $p$-value of the null hypothesis altogether and concentrate on the confidence interval. Once you accept the idea, that a zero difference is not your goal, it is no longer of interest, whether zero is within the confidence interval.
However given a fixed sample size the t test can no longer detect arbitrarily small deviations from a given value. Power estimations and thereby sample size calculations depend on the concept of a null hypothesis test. For sample size computation an easy way to think about this is a one sided t test testing, whether the true difference is smaller than -5.4 and an additional one sided t test testing, whether the the difference is larger then 5.4. I do not recommend doing both these tests but one could use the idea for a sample size calculation employing the R function i refered to.
Comment: Our acceptable deviation is 1*sigma to 3*sigma (sigma=1.8) ; so say 3*sigma=5.4

We are ok with 90 or 95% confidence.

As you can read in the question, we have already done the t.test with paired=T.

We need help in interpreting the results of this t.test, and help us understand if it is significant or not.

Thanks, Olivier.
Comment: Excellent answer, IMHO.  But I'll add another when I wrap up some work here.  +1 @OlivierD.
Comment: OK @StatsStudent ; to be honest this answer didn't help much
Comment: Well it helped as much as it made you specify an acceptable deviation. Once StatsStudent posts his answer he is likely to refer to that. Meanwhile, I made an addendum to my answer, hopefully expanding usefully with the directions you gave in the first comment.
Comment: @StatsStudent Thank you. Looking forward to read yours.
Comment: @Bernhard I appreciate your addendum. It helps a lot on question 2.
Comment: @OlivierD. Great. Now we need some critical thinking on what defines an optimal size. If tests are cheap do as many as you can. That will make the confidence intervall small and thus the chance of erroneously throwing away reagents. If they are not, you will probably want to define a minimal accepted power. (to be continued)
Comment: (ctd)  The question of what sample size you need for a one sample t test to discover an deviation of exactly 5.4 (you will need to compute the effect size from that)  with a power of at least 95% can be computed via the function `pwr.t.test` after installing the package `pwr` :  https://www.rdocumentation.org/packages/pwr/versions/1.3-0/topics/pwr.t.test
Comment: Thanx @Bernhard for this extra explanation. The test is not cheap, and using patient blood is a critical resource so we need to optimize the sample size. We have used the `pwr.t.test` function already 2 months ago and found 3,5 or 10 samples depending on expectations. This guided our experiments so far. We are wondering 1/ how can we interpret the t.test result (you answered with overlapping CI - still wondering if 0 needs to be contained or not) and 2/ how can we know this result is significant and we can trust it (we thought `t.test` p-value would answer but it's not obvious for us)


IBM MQ Asynchronous fetch using .Net

Question: I have created a windows service using MQI is there a way to add asynchronous fetch to MQGet i have tried it using Message Listener.But what to do it using MQConn without threading Please find the below code
<code>         while (queueGetMessageOptions.GroupStatus != QC.MQGS_LAST_MSG_IN_GROUP)
        {
            try
            {
                inboundmsg = new MQMessage();
                queuerecieve.Get(inboundmsg, queueGetMessageOptions);
            }
       }
</code>
Is the above code correct. Do i need to set the Group Status? Because the service should be running and listening to the queue continously
Answer: Your question and code don't match.  Is the sender putting messages messages in groups?  Because your code is looking for exactly 1 group of messages then it exits the loop.
If you want to read all messages (no group) in a loop then you should do something like:
<code>MQMessage           mqMsg;
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.WaitInterval = 15000;  // wait for up to 15 seconds
gmo.Options |= MQC.MQGMO_WAIT;

bool isContinue = true;
while (isContinue)
{
   mqMsg = new MQMessage();
   try
   {
      mqQueue.Get( mqMsg, gmo );
      if (mqMsg.Format.CompareTo(MQC.MQFMT_STRING) == 0)
      {
         System.Console.WriteLine(  mqMsg.ReadString(mqMsg.MessageLength) );
      }
      else
      {
         System.Console.WriteLine( "Non-text message" );
      }
   }
   catch (MQException mqe)
   {
      // report reason, if any
      if ( mqe.Reason == MQC.MQRC_NO_MSG_AVAILABLE )
      {
         System.Console.WriteLine( "no more messages - go loop again" );
      }
      else
      {
         System.Console.WriteLine( "MQQueue::Get ended with " + mqe.Message );

         isContinue = false;
      }
   }
}
</code>
Comment: Yes.  I prefer to have each thread make their own connection to the queue manager.
Comment: Can i give the wait interval as gmo.WaitInterval = MQC.MQWI_UNLIMITED; because when I set the Wait interval to 15000; After I Stop the service the code is being executed one and i get an exception Exception while recieving the messagesSystem.Threading.ThreadAbortException: Thread was being aborted.
       at IBM.WMQ.MQDestination.Get(MQMessage message, MQGetMessageOptions gmo, Int32 maxMsgSize)
Comment: When MQ is in the middle of a Get then thread is locked. It is a bad idea to use MQC.MQWI_UNLIMITED for a service. I generally use a wait of 2 seconds for a service that way the code can check if the service has been stopped and then GRACEFULLY close the queue & disconnect from the queue manager.   Also, did you add code to handle setting the flag to false when the service is stopped?

IBM MQ Asynchronous fetch using .Net


Existence of rational roots in a quadratic equation

Question: Consider the quadratic equation $(a+c-b)x^2 + 2cx + b+c-a = 0 $ , where a,b,c are distinct real numbers and a+c-b is not equal to 0. Suppose that both the roots of the equation are rational . Then
a) a,b, and c are rational
b)$c/(a-b)$ is rational
c)$b/(c-a)$ is rational
d)$a/(b-c)$ is rational
My attempt - I used the discriminant method to find out the possible roots of the given equation.
Which for me came out to be $(-2c + a-b)/(2a -2b +2c)$ and $ ( -2c + b - a)/(2c + 2a - 2b )$
Hence according to me option a is the correct answer , while the correct answer which is given is b. Please tell me where am I going wrong , or what am I missing ?
Comment: You did not write an equation, because I don't see the $=$. Anyway, if your equation is $(a+c-b)x^2 +2cx+b+c-a =0$, then your solutions are both wrong. Because the roots are $-1$ (this is easy to check) and $(a-b-c)/(a-b+c)$. Are you sure you copied the text of the problem correctly ?
Answer: Notice that your polynomial $$(a+c-b)x^2 +2cx +(b+c-a) = (a+c-b) (x - \alpha)(x - \beta) =$$
$$=(a+c-b)x^2 - (a+c-b)(\alpha + \beta) x + (a+c-b)\alpha \beta$$
where $\alpha, \beta$ are the rational roots.
Now, the coefficient of $x$ must be equal
$$2c = -(a+c-b)(\alpha + \beta)$$
and with some algebra you get
$$\frac{c}{a-b} = -\frac{\alpha + \beta}{\alpha + \beta +2} \in \Bbb{Q}$$
Comment: Notice that you have information only about $a-b$, without any information about $a,b$. I mean, if you call $a= \pi$, $b= 1+ \pi$, their difference is rational, but these are not rational.
Answer: Note that, when $x=-1$, we get
$$
(a+c-b)-2c+(b+c-a)=0
$$
so $-1$ is a root for every choice of the parameters $a$, $b$ and $c$. Even if $a+c-b=0$, that would give $c/(a-b)=-1$.
This leads into checking option b. So, suppose $a+c-b\ne0$. The factorization of the polynomial is
$$
(x+1)\bigl((a+c-b)x+c-a+b\bigr)
$$
so the second root is
$$
\frac{(a-b)-c}{(a-b)+c}=\frac{1-\dfrac{c}{a-b}}{1+\dfrac{c}{a-b}}
$$
If this is to be rational, also $c/(a-b)$ is rational.
Answer: We know that your two roots are rational:
$$
r_1 = \frac{-2c + (a - b)}{2(a - b + c)} \in \mathbb Q \qquad\text{and}\qquad
r_2 = \frac{-2c - (a - b)}{2(a - b + c)} \in \mathbb Q
$$
Hence, their sum and difference are also rational:
$$
r_1 + r_2 = \frac{c}{a - b + c} \in \mathbb Q \qquad\text{and}\qquad
r_1 - r_2 = \frac{a - b}{a - b + c} \in \mathbb Q
$$
But then their quotient is also rational:
$$
\frac{r_1 + r_2}{r_1 - r_2} = \frac{c}{a - b} \in \mathbb Q
$$
Answer: The roots are
$$\frac{-2c\pm \sqrt{4c^2 - 4(c+(a-b))(c-(a-b))}}{2(a+c-b)}$$
$$=\frac{-c\pm (a-b)}{a+c-b}$$
$=\frac{a-b-c}{a-b+c}$ or $\frac{-a+b-c}{a-b+c}=-1$
For the first root,
$$=\frac{a-b+c-2c}{a-b+c}=1-\frac{2c}{a-b+c}$$
So $\frac{2c}{a-b+c}$ is rational, so its inverse is also rational
$\frac{a-b+c}{2c}=\frac{a-b}{2c}+\frac 1 2$
Answer: Reduce this to a monic form:
$$
x^2+\frac{2c}{a+c-b}x+\frac{b+c-a}{a+c-b}
$$
then as the roots are rational so are the sum and product of the roots, so both $\frac{2c}{a+c-b}$ and $\frac{b+c-a}{a+c-b}$ are rational and so $\frac{c}{b+c-a}$ is also rational, and you should be able to take it from there.


How to change custom blade directive value dynamically

Question: I'm trying to make a blade directive for Stichoza /google-translate-php package. But when I change the language from menu it change once. When I try to change it again it will not change. It will only work when I run php artisan view:clear command.
Here is my directive in AppServiceProvider
public function boot()
{
    Blade::directive('translate',function ($text){
        $lang =app()->getLocale();
        $changedText = GoogleTranslate::trans($text, $lang, 'en');

        return "<?php echo $changedText; ?>";
    });
}

Answer: You are generating a static string since once the blade view is compiled to PHP and cached the PHP in that file isn't going to change which is just you echoing a string (that will not change since it is a static string).
You would want the returned PHP from the directive to be getting the locale and calling GoogleTranslate::trans if you want this to actually be dynamic as the PHP in the compiled version of the blade view is what is ran every time the view is rendered, not the blade directive (there is no Blade at this point).


Spring Cloud QueueMessagingTemplate#convertAndSend Batch

Question: I'm trying to send a batch of items to Amazon SQS using Spring Cloud. I'm able to send individual items. However, the time to send it to the queue tends to be multiplied by the number of items I'm sending. I'm basically following the example of the reference doc
In the AWS documentation you can send a batch of up to 10 items at one time. So my question is does the QueueMessagingTemplate or another Spring Cloud class allow you to do this?
This code snippet shows what I want to do. I don't want to send the items as an object because I want each item placed separately on the queue.
@Service
@EnableConfigurationProperties(SqsConfigMappingProperties.class)
public class SqsServiceImpl implements SqsService {

    @Autowired
    String queueName;

    @Autowired
    QueueMessagingTemplate queueMessagingTemplate;

    @Override
    public void sendSqsMessage(List items) {
        //Can't really send a batch size here
        int batchSize = 10;
        queueMessagingTemplate.convertAndSend(queueName, items, 10);
    }
}

Comment: Hi, were you able to achieve this? Even i am looking for something like this.
Comment: No, I wasn't able to do this using the QueueMessagingTemplate. You are able to do it using the AWS SQS libraries directly. We ended up doing something else to solve our performance issues.
Comment: Oh okay. But how do you use aws methods using spring boot, I found no other way other than this?
Comment: You're just going to use the AWS Java SDK
here: https://aws.amazon.com/sdk-for-java/
Then checkout this API
here: http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/sqs/model/SendMessageBatchRequest.html
Answer: There is no dedicated convertAndSend() method or anything like that in the QueueMessagingTemplate. In fact these QueueMessagingTemplate does not define these method, it just inherts them. I would use something like a wrapper class for a collection to send it as a geenric payload in convertAndSend().
But there is more to it.
QueueMessagingTemplate's source code is located in this repo. This repo is archived (in favor of this new repo) and is no longer maintained. In a new repo QueueMessagingTemplate is removed in favor of SqsTemplate, and in SqsTemplate there is a sendManyAsync() method for instance that allows sending a batch of messages.
So it is really better for developers to migrate to a new library becuase QueueMessagingTemplate is no longer maintained (and even exist), and SqsTemplate has exactly what you want.
Hope it helped, have a nice day :)


Abrir windows explorer usando o PHP e/ou JS

Question: Bom dia a todos.
É possível abrir o Windows Explorer, na estação do cliente em uma determinada pasta de rede (compartilhamento windows) seja com o próprio PHP e/ou JS.
Já tentei com o exec() do php e com o window.open(fiel:///) do JS , mas sem sucesso.
A aplicação está rodando em linux na mesma rede das estações clientes.
Comment: Acredito que isso dependa muito mais das permissões de segurança do navegador do que da linguagem.
Comment: Os meus teste foram feitos tanto no firefox quanto no chrome, que são os mais utilizados aqui pelos meus usuários.
Comment: Em geral o explore permite isso
Answer:
É possível abrir o Windows Explorer utilizando PHP?

Não! PHP é uma linguagem que roda em server-side; Num contexto geral voce não vai conseguir interagir com recursos nativos no client-side, ou seja, no navegador do usuário;

É possível abrir o Windows Explorer utilizando Javascript?

Utilizando o Internet Explorer (provavelmente isso não é possível com outros browsers), você consegue utilizar alguns recursos do ActiveX, porem só testei fazer isso com HTML salvo na própria máquina; Usando algo como:

Não conheço o contexto ao qual você precisa utilizar esta solução, mas do ponto de vista de segurança isso não é nada aconselhável; Além do fato de a maioria dos browsers não permitirem ações como essa, você irá enfrentar diversas restrições com software de anti-virus que consideram ações como essa uma ameaça;
Recomendo pensar numa outra abordagem para resolver o seu problema; Manipular diretórios no cliente não me parece ser uma abordagem para soluções Web-based, pelo simples fato de que você não tem como garantir que determinado diretório exista no cliente;
Answer: Da pra fazer por JavaScript e ActiveX.

Para abrir usa um link/botão/etc... especificando a função:
Abrir Programa

Comment: Pelo que li está solução so vai funcionar no IE, que não seria o caso.
O ActiveXObject só é suportado pelo IE.
Nos outros navegadores da o erro "ActiveXObject is not defined".
Comment: Sim, mas eu só conheço soluções que envolva o IE. para o Firefox será com o href file:\\\\\ e no chrome \\ mas funciona mal.
Comment: obrigado pela ajuda, mas procuro algo crossbrowser, até mesmo o file:\\\ não está funcionando pois pelo que li tanto o Firefox quanto o Chrome estão bloqueando.


Alias for sublocations in nginx

Question: I have a webservice using the following routes in nginx:
/my/myservice/backend
/my/myservice/frontend

In addtion, I want the two urls
/my/myservice
/my/myname

to be aliases or redirects to /my/myservice/frontend
ow can I configure nginx to achieve this?
Comment: What have you tried? What did you expect to happen? What happened instead? What does your config look like? Do you have any log entries from the times it didn't work as expected?
Answer: Inside your server block you want something like this:
location /my/myservice {
    return 301 $scheme://$http_host/my/service/frontend;
}

location /my/myname {
    return 301 $scheme://$http_host/my/service/frontend;
}

Alias for sublocations in nginx


How to manage the allocation of many small objects being passed around?

Question: I am writing a program that tokenizes a text and transforms it based on the tokenization. The tokens are represented by a struct:
struct token {
    enum token_type type;
    size_t length;        /* as returned by strlen(token.text); */
    char text[];          /* 0-terminated */
};

The tokenizer provides an iterator interface that allocates and yields the next token when called. The caller of this function then processes the token, passes it to several functions (some of which might store the token on their own) and might store it somewhere.
At a certain point of time, token processing is finished and all tokens can be freed.
How should I go on about tracing the tokens' allocations?
I had three ideas for this:

Each token contains a pointer to the previous token; at the end, I can simply traverse the linked list to free all tokens. This gets complicated once I create tokens in more than one place.
Each token contains a reference counter. This is complicated because I need to pay close attention to where I keep a reference to a token.
Each function duplicates tokens instead of keeping references to them. If a function gets passed a token as an argument, it must not keep them. This might lead to a lot of unneccessary memory allocation.

It would be nice to have some information from more experienced programmers.
Comment: I don't think you'll find a clean implementation of smart pointers in C.
Comment: I'm pretty sure smart pointers should do the trick for you with the least amount of hassle, you don't have to worry about the reference count once its hiding inside that. Alternatively, you can register all your tokens in some global list and just traverse it to deallocate them all
Comment: @Leenor smart pointers? What's that?
Comment: Hmm. Never though of that, I guess it would be difficult without destructors. I was somehow assuming that c gurus came up with something :), still - reference counting should work
Answer: Since you say that at some point in time all tokens need to be freed at the same time, you can go with a memory pool. Write a token allocator that will malloc tokens and store the allocated pointer in some array, linked list or however you want to solve it. When you're done with all the processing, call a function that will free all the tokens at the same time.
Something like this (not tested, but you should get the idea):
struct token {
    struct token *token_next;
    enum token_type type;
    size_t length;
    char *text;
};

struct token_pool {
    struct token *token_list;
};

struct token *
token_alloc(struct token_pool *pool, size_t len, enum token_type type)
{
    struct token *t;

    if ((t = malloc(sizeof(*t) + len)) == NULL)
        return NULL;
    t->length = len;
    t->text = (char *)(t + 1);
    t->type = type;
    t->token_next = pool->token_list;
    pool->token_list = t;

    return t;
}

void
token_free_pool(struct token_pool *pool)
{
     struct token *t;

     while ((t = pool->token_list) != NULL) {
         pool->token_list = t->token_next;
         free(t);
     }
}

The advanced level here is to allocate the memory in larger slabs so that you don't need to call malloc that many times, but since you're going with dynamic sizes it's probably just overkill.
This is something that's used by apache with their apr_pool API. Many of the things that are allocated in apache have a very specific life time (per-server or per-call) so it's quite easy and efficient to avoid leaks and optimize allocations and freeing.
Answer: It depends a bit on the life span of the tokens and how much extra memory you have. Things that are doing something distinctly different with the token (creating a new string for example, or storing it for later) should probably create a copy.
For the rest I'd go with the reference counter -- but create a function (or macro) that creates the reference and updates the counter (and a counterpart that releases the reference and decrements the counter).
Then it's easier to find bad references as any time you keep a reference you must use the function -- if you don't it's unsafe. You could even put debugging logic in there to check when a reference was / created freed and have some way of tracking if a reference is safe. In debug mode you could implement reference generation as a copy to allow you to add the tracking information.
Answer: Maybe simple master list is good enough.
When you allocate token, add token pointer to master list. When you are done processing, go through the list and deallocate everything.
Edit:
This could be achieved by having a Tokenizer object (a struct), which has a bunch of functions, that manage the token life time automatically.
typedef struct {
    /* list for tokens */
} Tokenizer;

void Tokenizer_Init(Tokenizer * this); // Must be called first
void Tokenizer_DeInit(Tokenizer * this); // Must be called last
void Tokenizer_DoStuff(Tokenizer * this);

Comment: Where should I store a pointer to the master list? I dislike having global variables as they make it difficult to turn the program into a library.
Comment: @FUZxxl Not exatly sure what your program structure is, but I would probably pass the list as a pointer argument to the function/object that creates the tokens.
Comment: The problem (as stated above) is, that there are multiple functions that could create tokens.
Comment: @FUZxxl Then list would have to be passed to each function when calling, if using this approach.
Comment: I don't see why having a library precludes global memory. If all your functions are within that library then that would be good encapsulation. Memory management is, by and large, a global thing! If you need to have separate instances of a bunch of allocated memory just pass back a handle (Like `HeapAlloc`).
Comment: @nelicus A user of the library could use the code at two independent places at the same time. There would be a big problem if finishing one process would have an effect on a different, unrelated process. Thus, no global state.


Why is a region polygonally connected?

Question:
Why is a region polygonally connected ?

A region is a set, which is open and connected. Let's call the region $S$, I've seen the proof, where you take an element $z_0$ in $S$ and separate $S$ into $2$ disjoint sets, $O_1$, which are polygonally connected by $z_0$ in $S$  and $O_2$, which are not. Both sets are open, and so one concludes that $O_2$ must be empty, but why is $O_1$ not empty ?
Comment: because $z_0 \in O_1$
Comment: @cjackal then the set in the following example would be also polygonally connected or not: the set of points $z=x+iy$ with $y=x^2$.
Answer: Because $z_0\in O_1$, so it is non-empty.
Comment: but then a parabola with no thickness would be also polygonally connected ? because you can take any point $z_0$ on it and $z_0$ is always polyg. connected with $z_0$.
Comment: @implicitlee Yes, but it is not open. The theorem only says that an open, connected set is polygonally connected, not any other implication.

Why is a region polygonally connected?


Error 1017 when extending SimpleButton class in Flash/AS3

Question: I am receiving the following compile time error when attempting to extend the SimpleButton class in AS3:
1017: the definition of base class SimpleButton was not found
and the code:
<code>package com.shakti.gameState{

import flash.display.SimpleButton.SimpleButton;

public class buttonTile extends SimpleButton {

    public var id:int;
    public var quizId:int;
    public var subjectId:int;
    public var points:int;
    public var questionTxt:String;
    public var order:int;
    public var option:Array;

    public function buttonTile(newId:int, newQuizId:int, newSubId:int, newPoints:int, qtxt:String, newOrder:int, newOption:Array) {
        this.id=newId;
        this.quizId=newQuizId;
        this.subjectId=newSubId;
        this.points=newPoints;
        this.questionTxt=qtxt;
        this.order=newOrder;
        this.option=newOption;
    }
}}
</code>
This is an action script 3 file being developed in Flash.
Thanks for your help!
Kevin
Answer: Import the class.
<code> import flash.display.SimpleButton
</code>
I get this all the time from copy and paste:)


Adding HTTPS to a website

Question: I have a website (http://app4u.ml/, that resides in Ubuntu) with Tomcat installed on it. Via HTTP, everything works great.
I tried adding to the site  HTTPS.
I downloaded a self-signed certificate from http://www.selfsignedcertificate.com/ and put the '.cert' and '.key' in the server in /etc/ssl/localcerts and '.crt' file in /usr/share/ca-certificates/mozilla.
Then, I ran on Putty:
openssl req -new -x509 -sha256 -days 365 -nodes -out /etc/ssl/localcerts/app4u.ml.crt -keyout /etc/ssl/localcerts/app4u.ml.key
chmod 600 /etc/ssl/localcerts/app4u.ml*

Then, I added to the 2 files in /etc/apache2/sites-available the values of:
<VirtualHost *:443>
    SSLEngine On
    SSLCertificateFile /etc/ssl/localcerts/app4u.ml.cert
    SSLCertificateKeyFile /etc/ssl/localcerts/app4u.ml.key
    ServerAdmin firstname.lastname@example.com
    ServerName app4u.ml
    DocumentRoot /var/www/html/public_html/
    ErrorLog /var/www/html/log/error.log
    CustomLog /var/www/html/log/access.log combined
</VirtualHost>

and ran: sudo a2enmod ssl and then service apache2 restart.
This made trying to get the site in HTTPS throw a warning in chrome. If I tried to continue, I saw an empty folder list (but it had values in it if I tried to go to it in plain HTTP). Also, trying to contact the Tomcat on the server throws

javax.net.ssl.SSLHandshakeException: Handshake failed

What have I done wrong? What is missing?
EDIT2: Further problems - Now my tomcat work for GET requests, but not POST. For POST requests I get javax.net.ssl.SSLHandshakeException: Handshake failed. Why?
Comment: Purchase a proper trusted SSL cert.
Comment: Don't use self-signed certificates for public websites. Have a look at let's encrypt: https://letsencrypt.org/
To set it up with apache have a look at CertBot: http://letsencrypt.readthedocs.io/en/latest/index.html
Comment: Self-signed certificates cannot be verified by a trusted third-party. That is where the issue lies.
Comment: I tried deleting the .crt file from /usr/share/ca-certificates/mozilla, but still have problems. What should I do?
Comment: Cacerts is also a good place to have a look (i don't work for them)
Comment: I tried everything on https://certbot.eff.org/#ubuntutrusty-apache but still the HTTPS site is not loaded. Should I delete stuff from my previous try?
Comment: What does your .vhosts file looks like now?
Comment: I looked in /etc/apache2/sites-available but haven't seen any .vhost file, only two .conf files.
Comment: Also - must I purchase a certificate? Aren't there any free ones?
Comment: @Ran letsencrypt.org provide free certificates.
Comment: @Tom I tried everything on certbot.eff.org/#ubuntutrusty-apache but still the HTTPS site is not loaded. Now I try https://gethttpsforfree.com/ but on step 3 it says: Error: Account registration failed. Please start back at Step 1. { "type": "urn:acme:error:malformed", "detail": "JWS verification error", "status": 400 }. Isn't there somewhere a good guide?
Comment: Maybe https://community.letsencrypt.org/ can help you
Answer: You need to instruct Apache to forward (proxy) requests to Tomcat. The documentation is pretty complete but the following should get you in the right direction (it's not totally possible to give you cut&paste directions since it depends on exactly what you want and what you have):
Run this:
a2enmod proxy
a2enmod proxy_http

And put that in your config:
<VirtualHost *:443>
    SSLEngine On
    SSLCertificateFile /etc/ssl/localcerts/app4u.ml.cert
    SSLCertificateKeyFile /etc/ssl/localcerts/app4u.ml.key
    ServerAdmin firstname.lastname@example.com
    ServerName app4u.ml

    SSLProxyEngine on
    ProxyPass / http://localhost:8080/
    ProxyPassReverse / http://localhost:8080/

    ErrorLog /var/www/html/log/error.log
    CustomLog /var/www/html/log/access.log combined
</VirtualHost>

Comment: I have 2 files in /etc/apache2/sites-available. Should I put it in both of them? What is a command and what should be in the file?
Comment: You have to put it in the appropriate file and you have to make sure the site is enabled - `a2ensite xyz`. Sorry, I don't have your server in front of me so can't give copy/paste commands, you have to have some understanding of Apache to configure and run it.

Adding HTTPS to a website


Erro ao usar pow(a,b)

Question: <code>#include <stdio.h>
#include<math.h>

int main() {

double pi = 3.14159;
double R, A;

scanf("%lf", &R);
A = (pi)* pow(double R, int 2);
printf("%lf\n", A);

return 0;
}
</code>
Esse codigo está retornando o erro: Too few arguments to function 'pow'
por que?
Comment: Já agora: math.h já define pi: `M_PI * pow(R,2)`
Answer: Tente chamar a função da seguinte forma:
<code>A = pi * pow(R, 2);
</code>
e veja se o erro persiste.
O parenteses no pi não é necessário (mas também não causa erro), o erro era porque você estava invocando a função com os tipos de dados, o que não é preciso
Comment: Ou melhor, substitua `pow(R, 2)` por `R * R`.
Comment: Se a potência for fixa, e um valor baixo como é o caso, é melhor mais fácil fazer como @VictorStafusa mencionou, a menos é claro que seja um trabalho que obrigue a usar a função Pow ou a potência seja variável ou desconhecida...
Comment: Problema resolvido, valeu! eu queria usar a função pow pra fixar mesmo... às vezes eu esqueço que ela existe, sou iniciante.

Erro ao usar pow(a,b)


$n$th derivative of $e^{1/x}$

Question: I am trying to find the $n$'th derivative of $f(x)=e^{1/x}$. When looking at the first few derivatives I noticed a pattern and eventually found the following formula
$$\frac{\mathrm d^n}{\mathrm dx^n}f(x)=(-1)^n e^{1/x} \cdot \sum _{k=0}^{n-1} k! \binom{n}{k} \binom{n-1}{k} x^{-2 n+k}$$
I tested it for the first $20$ derivatives and it got them all. Mathematica says that it is some hypergeometric distribution but I don't want to use that. Now I am trying to verify it by induction but my algebra is not good enough to do the induction step.
Here is what I tried for the induction (incomplete, maybe incorrect)
$\begin{align*}
\frac{\mathrm d^{n+1}}{\mathrm dx^{n+1}}f(x)&=\frac{\mathrm d}{\mathrm dx}(-1)^n e^{1/x} \cdot \sum _{k=0}^{n-1} k! \binom{n}{k} \binom{n-1}{k} x^{-2 n+k}\\
&=(-1)^n e^{1/x} \cdot \left(\sum _{k=0}^{n-1} k! \binom{n}{k} \binom{n-1}{k} (-2n+k) x^{-2 n+k-1}\right)-e^{1/x} \cdot \sum _{k=0}^{n-1} k! \binom{n}{k} \binom{n-1}{k} x^{-2 (n+1)+k}\\
&=(-1)^n e^{1/x} \cdot \sum _{k=0}^{n-1} k! \binom{n}{k} \binom{n-1}{k}((-2n+k) x^{-2 n+k-1}-x^{-2 (n+1)+k)})\\
&=(-1)^{n+1} e^{1/x} \cdot \sum _{k=0}^{n-1} k! \binom{n}{k} \binom{n-1}{k}(2n x-k x+1) x^{-2 (n+1)+k}
\end{align*}$
I don't know how to get on from here.
Comment: http://mathcs.pugetsound.edu/~mspivey/Exp.pdf
Comment: Sorry I should have said that my algebra was not good enough instead of calculus. I updated the question to show how far I get.
Comment: Don't merge your two sums so early. Instead do a variable substitution in one to get a sum from $k^\prime = 1$ to $n$, then expand both sums to the range $0$ to $n$ using $\binom{n}{-1} = \binom{n}{n+1} = 0$. Expand in terms of factorials if necessary.
Comment: If your calculus was good enough to get the first few derivates, surely you can differentiate the RHS once wrt x? After that you don't need any calculus.
Comment: @Peter The problem is merging the sums by shifting the index so it fits and handling the binomial coefficients, not differentiating.
Comment: Which sum should I modify with the substitution, or doesn't it matter?
Comment: Modify the one where you have $x^{-2n+k-1}$, because you want $x^{-2(n+1)+k^\prime}$
Answer: How's this?
$$\left(\sum _{k=0}^{n-1} k! \binom{n}{k} \binom{n-1}{k} \left(-2n+k\right) x^{-2 n+k-1}\right) - \left(\sum _{k=0}^{n-1} k! \binom{n}{k} \binom{n-1}{k} x^{-2 \left(n+1\right)+k}\right) =$$
$$= \left(\sum _{k=0}^{n-1} k! \binom{n}{k} \binom{n-1}{k} \left(-2n+k\right) x^{-2\left(n+1\right)+k+1}\right) - \left(\sum _{k=0}^{n-1} k! \binom{n}{k} \binom{n-1}{k} x^{-2 \left(n+1\right)+k}\right) =$$
$$= \left(\sum _{k'=1}^{n} \left(k'-1\right)! \binom{n}{k'-1} \binom{n-1}{k'-1} \left(-2n+k'-1\right) x^{-2\left(n+1\right)+k'}\right) - \left(\sum _{k=0}^{n-1} k! \binom{n}{k} \binom{n-1}{k} x^{-2 \left(n+1\right)+k}\right) =$$
$$= \left(\sum _{k'=0}^{n} \left(k'-1\right)! \binom{n}{k'-1} \binom{n-1}{k'-1} \left(-2n+k'-1\right) x^{-2\left(n+1\right)+k'}\right) - \left(\sum _{k=0}^{n} k! \binom{n}{k} \binom{n-1}{k} x^{-2 \left(n+1\right)+k}\right) =$$
$$= \sum _{k=0}^{n} \left(\left(k-1\right)! \binom{n}{k-1} \binom{n-1}{k-1} \left(-2n+k-1\right) - k! \binom{n}{k} \binom{n-1}{k}\right) x^{-2 \left(n+1\right)+k}$$
Then
$$\left(k-1\right)! \binom{n}{k-1} \binom{n-1}{k-1} \left(-2n+k-1\right) - k! \binom{n}{k} \binom{n-1}{k} =$$
$$= \frac{\left(k-1\right)!n!\left(n-1\right)!\left(-2n+k-1\right)}{\left(n-k+1\right)!\left(k-1\right)!\left(n-k\right)!\left(k-1\right)!} - \frac{k!n!\left(n-1\right)!}{\left(n-k\right)!k!k!\left(n-k-1\right)!} =$$
$$= \frac{n!\left(n-1\right)!\left(-2n+k-1\right)k}{\left(n-k+1\right)!\left(n-k\right)!k!} - \frac{n!\left(n-1\right)!\left(n-k\right)\left(n-k+1\right)}{\left(n-k\right)!k!\left(n-k+1\right)!} =$$
$$= \frac{n!\left(n-1\right)!}{\left(n-k+1\right)!\left(n-k\right)!k!} \left(\left(-2n+k-1\right)k - \left(n-k\right)\left(n-k+1\right)\right) =$$
$$= \frac{-n\left(n+1\right)n!\left(n-1\right)!}{\left(n-k+1\right)!\left(n-k\right)!k!} =$$
$$= -\frac{\left(n+1\right)!}{\left(n-k+1\right)!} \binom{n}{k} =$$
$$= -k! \binom{n+1}{k} \binom{n}{k}$$
Comment: I just saw something nasty in the calculation. In line 5 the following expression occurs: $\sum _{k=0}^{n} ((k-1)!\ldots$ but $(-1)!$ is not defined. I think the result is still correct but this is odd
Comment: Yes, I should have been more explicit there. It's actually $(k-1)!\binom{n}{k-1}\binom{n-1}{k-1}$ so there's one $(k-1)!$ in the numerator and two in the denominator. If you take limits you can prove that the term as a whole converges to zero.
Comment: @Listing One approach is to separate out the first term and handle it separately.  In the exercise I was working through, it balances out in the end.  He doesn't show it either, but my paper and pencil checks.
https://math.stackexchange.com/questions/2111260/some-of-series-involving-factorial-in-the-denominator?noredirect=1
Answer: Peter's and Mike's answers have clearly settled this question; I'll just explain the OP's mention of "Mathematica says that it is some hypergeometric distribution". More specifically, one wonders how Mathematica might have arrived at the Kummer confluent hypergeometric function ${}_1 F_1\left({{a}\atop{b}}\mid x\right)$.
We start with the transformed Maclaurin series:
$$\exp\left(\frac1{x}\right)=1+\sum_{k=1}^\infty \frac1{x^k k!}$$
and then differentiate the series termwise, using the formula
$$\frac{\mathrm d^n}{\mathrm dx^n}x^{-k}=\frac{(-1)^n (n+k-1)!}{(k-1)! x^{k+n}}$$
to yield
$$\frac{\mathrm d^n}{\mathrm dx^n}\exp\left(\frac1{x}\right)=\frac{(-1)^n}{x^n}\sum_{k=1}^\infty \frac{(n+k-1)!}{k!(k-1)! x^k}$$
which can be reindexed like so:
$$\frac{\mathrm d^n}{\mathrm dx^n}\exp\left(\frac1{x}\right)=\frac{(-1)^n}{x^n}\sum_{k=0}^\infty \frac{(n+k)!}{(k+1)!k! x^{k+1}}$$
and rewritten in terms of Pochhammer symbols to yield
$$\frac{\mathrm d^n}{\mathrm dx^n}\exp\left(\frac1{x}\right)=\frac{(-1)^n}{x^n}\sum_{k=0}^\infty \frac{n!(n+1)_k}{(2)_k k! x^{k+1}}$$
or, expressed hypergeometrically,
$$\frac{\mathrm d^n}{\mathrm dx^n}\exp\left(\frac1{x}\right)=\frac{(-1)^n n!}{x^{n+1}}{}_1 F_1\left({{n+1}\atop{2}}\mid \frac1{x}\right)$$
It's not immediately obvious that this one can be expressed in terms of $\exp(1/x)$ multiplied by a finite sum, but we can then apply the Kummer transformation to the hypergeometric function like so:
$$\frac{\mathrm d^n}{\mathrm dx^n}\exp\left(\frac1{x}\right)=\frac{(-1)^n n!}{x^{n+1}}\exp\left(\frac1{x}\right){}_1 F_1\left({{1-n}\atop{2}}\mid -\frac1{x}\right)$$
and find that the hypergeometric function has a nonpositive numerator parameter $1-n$ for $n > 0$, which means it can be expressed as a terminating series (since the Pochhammer symbol $(1-n)_k$ is $0$ for $k \geq n$):
$$\frac{\mathrm d^n}{\mathrm dx^n}\exp\left(\frac1{x}\right)=\frac{(-1)^n n!}{x^{n+1}}\exp\left(\frac1{x}\right)\sum_{k=0}^{n-1}\frac{(-1)^k (1-n)_k}{k!(k+1)!x^k}$$
Rewriting the Pochhammer symbol in terms of factorials, we get
$$\frac{\mathrm d^n}{\mathrm dx^n}\exp\left(\frac1{x}\right)=\frac{(-1)^n n!}{x^{n+1}}\exp\left(\frac1{x}\right)\sum_{k=0}^{n-1}\frac{(n-1)!}{(n-k-1)!k!(k+1)!x^k}$$
which is equivalent to the formula you obtained.
My point here, I guess, is that hypergeometric functions are nothing to be uncomfortable with; if it helps, just consider them as shorthand for certain (in)finite sums.
Comment: Of course, the good thing about having the hypergeometric function expression is that you can then consider derivatives of $\exp(1/x)$ for positive *noninteger* $n$... $n=1/2$ for instance (the *semiderivative*) yields an expression in terms of Bessel functions.
Answer: You can get the same result using the Faà di Bruno formula and Bell polynomials.
The Faà di Bruno formula says that $$\frac{d^n}{dx^n} f(g(x)) = \sum_{k=0}^n f^{(k)}(g(x)) B_{n,k}\left(g'(x),g''(x),\dots,g^{(n-k+1)}(x)\right),$$
where $B_{n,k}(x_1,x_2,\dots,x_{n-k+1})$ is a partial Bell polynomial.
Since $f(x) = e^x$, and $g(x) = 1/x$, we have
$$\frac{d^n}{dx^n} e^{1/x} = \sum_{k=0}^n e^{1/x} B_{n,k}\left(-x^{-2},2x^{-3},\dots,(-1)^{n-k+1}(n-k+1)!x^{-n+k-2}\right).$$
It is known that $B_{n,k}(1!,2!,\dots,(n-k+1)!) = \binom{n}{k}\binom{n-1}{k-1} (n-k)!$, a Lah number (see Wikipedia on Bell polynomials or Comtet's Advanced Combinatorics, p. 135).  Thus (keeping track of signs and powers of $x$),
$$\frac{d^n}{dx^n} e^{1/x} = (-1)^n e^{1/x} \sum_{k=0}^n \binom{n}{k}\binom{n-1}{k-1} (n-k)! x^{-n-k},$$
which is just your formula with an index change (and where $\binom{n-1}{-1} = 0$).
Answer: Here's a completely elementary argument that I like better than my previous answer that uses the Faà di Bruno formula.  All that is required are the Maclaurin series for $e^x$ and the definition of the Lah numbers $L(n,k)$ as the coefficients arising when converting rising factorial powers to falling factorial powers via
$$x^{\overline{n}} = \sum_{k=1}^n L(n,k) x^{\underline{k}}.$$
First, substitute $1/x$ for $x$ in the Maclaurin series for $e^x$ and differentiate $n$ times.  This yields
$$\frac{d^n}{dx^n} e^{1/x} = (-1)^n x^{-n} \sum_{j=0}^{\infty} \frac{j^{\overline{n}} x^{-j}}{j!}.$$
Then convert rising powers to falling powers to obtain
$$\frac{d^n}{dx^n} e^{1/x} = (-1)^n x^{-n} \sum_{j=0}^{\infty} \sum_{k=1}^n L(n,k)  \frac{j^{\underline{k}} x^{-j}}{j!}.$$
Working with the summation in $j$, we have
$$\sum_{j=0}^{\infty} \frac{j^{\underline{k}} x^{-j}}{j!} = \sum_{j=k}^{\infty} \frac{j^{\underline{k}} x^{-j}}{j!} = \sum_{j=k}^{\infty} \frac{j! x^{-j}}{(j-k)! j!} = \sum_{i=0}^{\infty} \frac{x^{-i-k}}{i!} = x^{-k} e^{1/x},$$ where the last step uses, once again, the Maclaurin series for $e^x$.
Thus we have
$$\frac{d^n}{dx^n} e^{1/x} = (-1)^n e^{1/x} \sum_{k=1}^n L(n,k) x^{-n-k},$$ which is just your formula with an index change, as $$L(n,k) = \binom{n}{k}\binom{n-1}{k-1} (n-k)!.$$
(From another perspective, this is computing the rising factorial moments of a Poisson $(1/x)$ distribution.  With this in mind, converting to falling factorial powers seems reasonable, as the falling factorial moments of a Poisson distribution have a known simple expression.  See also this related answer to a previous math.SE question.)
Answer: We may obtain a recursive formula, as follows:
\begin{align}
 f\left( t \right) &= e^{1/t}  \\
 f'\left( t \right) &=  - \frac{1}{{t^2 }}f\left( t \right) \\
 f''\left( t \right) &=  - \frac{1}{{t^2 }}f'\left( t \right) + f\left( t \right)\frac{2}{{t^3 }} \\
  &=  - \frac{1}{{t^2 }}\left\{ {\frac{1}{{t^2 }}f\left( t \right)} \right\} + f\left( t \right)\frac{2}{{t^3 }} \\
  &= \left( {\frac{1}{{t^4 }} + \frac{2}{{t^3 }}} \right)f\left( t \right)
\\
\ldots
\end{align}
Inductively, let us assume $f^{(n-1)}(t)=P_{n-1}(\frac{1}{t})f(t)$ is true, for some polynomial $P_{n-1}$. Now, for $n$, we have
\begin{align}
 f^{\left( n \right)} \left( t \right) &=  - \frac{1}{{t^2 }}P'_{n - 1} \left( {\frac{1}{t}} \right)f\left( t \right) + P_{n - 1} \left( {\frac{1}{t}} \right)f'\left( t \right) \\
  &=  - \frac{1}{{t^2 }}P'_{n - 1} \left( {\frac{1}{t}} \right)f\left( t \right) + P_{n - 1} \left( {\frac{1}{t}} \right)\left\{ { - \frac{1}{{t^2 }}f\left( t \right)} \right\} \\
  &=  - \frac{1}{{t^2 }}\left\{ {P'_{n - 1} \left( {\frac{1}{t}} \right) + P_{n - 1} \left( {\frac{1}{t}} \right)} \right\}f\left( t \right) \\
  &= P_n \left( {\frac{1}{t}} \right)f\left( t \right)
 \end{align}
Thus,
\begin{align}
 f^{\left( n \right)} \left( t \right) = P_n \left( {\frac{1}{t}} \right)f\left( t \right)
 \end{align}
where, $P_n \left( x \right): = x^2 \left[ {P'_{n - 1} \left( x \right) - P_{n - 1} \left( x \right)} \right]$, $P_0=1$.
Answer: For $i\in\mathbb{N}$ and $t\ne0$, we have
\begin{equation}\label{exp-frac1x-expans}\tag{1}
\bigl(\textrm{e}^{1/t}\bigr)^{(i)}=\textrm{e}^{1/t}\frac{(-1)^i}{t^{2i}}\sum_{k=0}^{i-1}\binom{i}{k}\binom{i-1}{k}{k!}t^{k}.
\end{equation}
To the best of my knowledge, an inductive proof of the derivative formula \eqref{exp-frac1x-expans} was published on pages 123--124, Section 2.1, Theorem 2.1 of the paper [1] below. Hereafter, there have been a number of literature, for example, the papers [2, 3] below and those collected at a site on wordpress, dedicated to the investigation of the function $\textrm{e}^{1/t}$, the derivative formula \eqref{exp-frac1x-expans}, and their applications to several areas in mathematics.
References

Xiao-Jing Zhang, Feng Qi, and Wen-Hui Li, Properties of three functions relating to the exponential function and the existence of partitions of unity, International Journal of Open Problems in Computer Science and Mathematics 5 (2012), no. 3, 122--127; available online at https://doi.org/10.12816/0006128.
Siad Daboul, Jan Mangaldan, Michael Z. Spivey, and Peter J. Taylor, The Lah numbers and the $n$th derivative of $e^{1/x}$, Mathematics Magazine 86 (2013), no. 1, 39–47; available online at https://doi.org/10.4169/math.mag.86.1.039.
Khristo N. Boyadzhiev, Lah numbers, Laguerre polynomials of order negative one, and the $n$th derivative of $\exp(1/x)$, Acta Universitatis Sapientiae Mathematica 8 (2016), no. 1, 22–31; available online at https://doi.org/10.1515/ausm-2016-0002.
Comment: https://mathoverflow.net/q/405015/147732
Comment: Your second reference was actually inspired by this Math.SE question and its first few answers.  Compare the authors in the second reference with the authors of the first few answers.

$n$th derivative of $e^{1/x}$


Change form input attribute

Question: I have form with an alt attribute like the following.
<input type="text" alt="abc">

I want to replace that attribute with data-alt.
I tried the following code, but it doesn't seem to work.
function theme_form_alter(&$form, &$form_state, $form_id) {
    foreach($form["submitted"] as $newForm)
    {
        foreach($newForm as $keyid=>$frmArr)
        {
            if(isset($frmArr[]["#attributes"]["alt"]))
            {
                    $alt = $frmArr["#attributes"]["alt"];
                    unset($newForm[$keyid]["#attributes"]["alt"]);
                    $newForm[$keyid]["#attributes"]["data-alt"] = $alt;
            }
        }
    }
}

The following code is not working either.
foreach($form["submitted"] as $newForm)
    {

        foreach($newForm as $keyid=>$frmArr)
        {
            if($keyid=='#attributes'){
                $newForm[$keyid]['data-alt']=$newForm[$keyid]['alt'] ;
                 unset($newForm[$keyid]['alt'] );
                $form["submitted"]['#attributes']['alt'] = array("sss");
                form_set_value($form["submitted"]['#attributes']['alt'], array("aaa"), $form_state);
            }
        }

    }

What code should I use to achieve what I want?
Comment: isset($frmArr[]["#attributes"]["alt"])
This could never work. Isset is a check on whether something exists and [] is designed to create. Maybe all you need to do is delete those 2 characters.
Comment: i updated code that seems not working
Comment: There's numerous things wrong with the rest of the code also actually. hook_form_alter is used to alter $form and/or $form_state. What you are doing is using them to create new variables, and then not using those to manipulate $form or $form_state.
Besides that you should fix your coding style a bit. Read https://www.drupal.org/docs/develop/standards/coding-standards that and apply as much as you can.
Comment: theme_form_alter will never be called. It has to be the name of your module or theme.
Answer: function act_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the_id_of_your_form') {
    unset($form['submitted']['#attributes']['alt']);
    $form['submitted']['#attributes']['data-alt'] = 'abc';
  }
}

Won't this work?
Comment: this also not works
Comment: Any idea why? Did you alter the actual id of your form in the code sample and does the code get executed or does nothing happen or what?

Change form input attribute


Ionic 4 Consulta

Question: Boa tarde, sou novo em angular, estou tentando fazer uma pesquisa via ionic, mas não estou conseguindo, segue o fonte:

Muito Obrigado.
Answer: O seu *ngFor está definido para repetir os itens da lista chamada contact, então, ao executar o método find você precisa filtrar da forma que você quiser e depois setar esse valor na variável contact.
Ficando algo como:
find(ev: any) void {
    const val = event.target.value;

    // Movi aqui para cima, porque não faz sentido fazer essa verificação
    // depois de obter os dados, é muito trabalho jogado fora.
    if (!(val && val.trim() != ''))
        return;

    // Coloquei o método de filtrar aqui para ficar melhor a leitura do código.
    const filterMethod = data => {
        this.items = data;

        this.contact = this.items.filter(item => {
            // Aqui talvez você possa usar o método includes em vez de indexOf
            // Assim, se pesquisa Vi, você encontra a pessoa com nome Vinicius
            return item.nome.toLowerCase().indexOf(val.toLowerCase()) > -1;
        });
    };

    this.contactService.listservice().subscribe(filter);
}

Só que eu acho que ainda há espaços para melhora no código, como por exemplo, se ele digitar muito rápido, cancelar a execução do subscribe anterior e só manter a nova.
Seria algo como:
// Guardará a inscrição feita sobre pesquisa os contatos.
private findSubscription: Subscription;

find(ev: any) void {
    const val = event.target.value;

    // Movi aqui para cima, porque não faz sentido fazer essa verificação
    // depois de obter os dados, é muito trabalho jogado fora.
    if (!(val && val.trim() != ''))
        return;

    // Verifica se o findSubscription não é nulo, e depois desinscreve o método anterior
    this.findSubscription && this.findSubscription.unsubscribe();

    // Coloquei o método de filtrar aqui para ficar melhor a leitura do código.
    const filterMethod = data => {
        this.items = data;

        this.contact = this.items.filter(item => {
            // Aqui talvez você possa usar o método includes em vez de indexOf
            // Assim, se pesquisa Vi, você encontra a pessoa com nome Vinicius
            return item.nome.toLowerCase().indexOf(val.toLowerCase()) > -1;
        });
    };

    // Guarda a inscrição do método de filtrar nessa variável para que
    // posteriormente, ela possa ser excluida da memória
    this.findSubscription = this.contactService.listservice().subscribe(filter);
}

// Não esqueça de adicionar "implements OnDestroy" ao lado do nome do componente/página para que esse método seja chamado quando o mesmo for destruído da memória.
ngOnDestroy(): void {
    // Coloquei a desincrição aqui também para limpar a memória dessa inscrição
    // Se você, ao longo da sua aplicação, criar muitos subscribes sem realizar
    // o unsubscribe do mesmo, é possível que ela fica com problemas de memória.
    this.findSubscription && this.findSubscription.unsubscribe();
}

Ionic 4 Consulta


How to view traffic operating on a specific port without plugging into egress interface? (Cisco IOS)

Question: I'm trying to track down what host is infected with ZeroAccess on my network.  It runs on ports 16464-16471.  I would like to find this host without having to connect my laptop to the egress (WAN) interface. (Because it would take down the internet obviously).
I'm thinking I can create an ACL and then log violations of the ACL.  Is there any better way to go about tracking down this host?
I tried "interface gi0/2" "ip accounting" And it didn't show what ports the active connections were working on.
Hardware: Cisco 2920 Router running IOS 15 M16.
Comment: How about exporting Netflow data to track the source? Does the 2920 support Netflow?
Comment: Since all internet traffic (ingress and egress) will go through both ports I'm assuming either one would work, but I would try it on the LAN port first. You'll also need to install a Netflow collector on one of your computers to act as the destination for the Netflow export. There are a number of free Netflow collectors available. - https://www.google.com/#q=free+netflow+collector
Comment: Why not use port mirroring on your switch?
Comment: @joeqwerty I'll try to figure out the syntax of that command.  One question though:  Which interface would I apply it to? LAN/WAN?  Assuming I'm trying to find the local IP of the host, who is communicating on those ports.  I know it would seem obvious that it's the LAN.  Just want to make sure though....
Comment: @joeqwerty Thanks that worked.  For any future readers, I used "ManageEngine Net Flow".
Comment: Glad to help...
Answer: How about exporting Netflow data to track the source?
Since all internet traffic (ingress and egress) will go through both ports I'm assuming that exporting Netflow from either of the LAN or WAN ports would work, but I would try it on the LAN port first. You'll also need to install a Netflow collector on one of your computers to act as the destination for the Netflow export.
https://www.google.com/#q=free+netflow+collector


Is it possible to use two .babelrc files?

Question: I have a project that runs both a build using rollup and a build using browserify for two different outputs. Now, they are both located in the same root dir and I have separate gulp-tasks running for both of them.
My problem is that my browserify task wants a .babelrc file with the following configuration:
<code>{
  "presets": ["es2015"]
}
</code>
and my rollup task wants this configuration:
<code>{
  "presets": ["es2015-rollup"]
}
</code>
My question is, can I have two separate .babelrc files and configure which one to use in my gulp and karma config?
Answer: I looked around a lot before asking this question and right after I posted I found a possible solution:
<code>gulp.task('rollup', () => {
  return gulp.src('src/server/index.js', { read: false })
    .pipe(rollup({
      plugins: [babel({
        presets: ["es2015-rollup"],
        babelrc: false
      })]
    }))
    .pipe(gulp.dest('public/'));
});
</code>
By configuring one of the tasks to not use the babelrc I could of course configure it myself directly. This isn't a great answer and I would've preferred to just added the name of a babelrc file.


Variance of $\hat{\beta}_0$ in heteroskedastic case

Question: Stock and Watson say nothing about that, so I ask you if you know how to derive the variance of the estimator of the intercept in a simple regression, $\beta_0$, i.e. $$\sigma^2_{\hat{\beta}_0}=\frac{1}{n}\frac{var[H_iu_i]}{[E(X_{i}^{2})]^2}.$$
Answer: First, there is a mistake in your expression; it should be
$$\sigma^2_{\hat{\beta}_0}=\frac{1}{n}\frac{var[H_iu_i]}{[E(H_{i}^{2})]^2}.$$
I will depart from the general expression for the asymptotic variance covariance matrix of the OLS estimator under conditional heteroskedasticity:
\begin{equation*}
\sqrt{n}(b-\beta)\to_d N(0,\Sigma_{xx}^{-1}S\Sigma_{xx}^{-1}).
\end{equation*}
A proof of this result may be found in, e.g., Hayashi, Econometrics, Proposition 2.1.
In case of a simple linear regression with intercept
$$
\Sigma_{xx}:=E(\mathbf{x}_i\mathbf{x}_i')
$$
reduces to
$$\Sigma_{xx}=\begin{pmatrix}1&\mu_X\\ \mu_X & E(X_i^2)\end{pmatrix}$$
Next,
$$S=\begin{pmatrix}E(u_i^2)&E(X_iu_i^2)\\ E(X_iu_i^2)& E(X_i^2u_i^2)\end{pmatrix}$$
in this case.
So the task is to find the $1,1$-element of $\Sigma_{xx}^{-1}S\Sigma_{xx}^{-1}$. A tedious task, which you may speed up like this, to get
\begin{eqnarray*}
Avar(\hat\beta_0)&=&\frac{1}{\sigma^4_X}\{E(X_i^2)[E(u_i^2)E(X_i^2)-\\&&\qquad\mu_XE(X_iu_i^2)]-\mu_X[E(X_iu_i^2)E(X_i^2)-\mu_XE(X_i^2u_i^2)]\}
\end{eqnarray*}
We then need to check that this is (up to $1/n$, which results from using the asymptotic variance to approximate the finite-sample one) the same as your result.
Here,
$$
H_i=1-\left(\frac{\mu_X}{E(X_i^2)}\right)X_i.
$$
As in your related question, we may always write
$$
var(H_iu_i)=E(H_i^2u_i^2)-[E(H_iu_i)]^2
$$
Under the maintained assumption of correct specification, $E(u_i|X_i)=0$ and hence, by the law of iterated expecations, as $H_i$ only depends on $X_i$,
$$
E(H_iu_i)=E(H_iE(u_i|X_i))=0
$$
Hence,
$$
var(H_iu_i)=E(H_i^2u_i^2)
$$
Here,
$$
H_i^2=\frac{E(X_i^2)^2-2\mu_XX_iE(X_i^2)+\mu_X^2X_i^2}{[E(X_i^2)]^2}=\frac{[E(X_i^2)-\mu_XX_i]^2}{[E(X_i^2)]^2}
$$
so that
$$
E(H_i^2)=\frac{\sigma^2_X}{E(X_i^2)}
$$
and
$$
[E(H_i^2)]^2=\frac{\sigma^4_X}{[E(X_i^2)]^2}
$$
as well as
$$
E(H_i^2u_i^2)=\frac{E\{[E(X_i^2)-\mu_XX_i]^2u_i^2\}}{[E(X_i^2)]^2}
$$
giving
$$
Avar(\hat\beta_0)=\frac{E\{[E(X_i^2)-\mu_XX_i]^2u_i^2\}}{\sigma^4_X}.$$
Solving the numerator verifies that this is the same expression as the one in the above numerator of $Avar(\hat\beta_0)$.


Is using staging table and live table considered an anti-pattern

Question: a system I am working on has a number of screens where the User saves data as they move through the system.
When they save the data gets saved to a StagingTable.  When they get to the end of the user journey and Submit the Application they have filled in the Data gets copied to a Live version of the tables.  There is also corresponding Audit Tables for the Live and Staging Tables
An example of a staging table for Car would be:
CarId
Manufacturer
Model
Colour
UserId
DateModified
DateCreated

The corresponding live table for Car would be:
CarId
Manufacturer
Model
Colour
UserId
DateModified
DateCreated
StagingCarId

To me this seems like a bad design in that nearly every piece of data in the DB is duplicated.  My suggestion to an Architect would be to add a bool IsSubmitted to the table and then set it to true on submitting.
The User can submit the application multiple times - and the architect was making the point what if the User Submitted the data - in my case that would check the IsSubmitted to true.  If they then went back into the Application and did a delete and saved - that would delete the row from the table - but if they did not Submit (a valid scenario) - it would mean the actual submitted data would be wrong - it would be one row less than what they actually submitted
Just wondering is there a better approach to this scenario than using Staging and Live tables which are a mirror of each other for the most part
Comment: Your design sounds good to me. Why can't the data just be stored in the user's browser local storage or something?
Comment: I think a lot depends on the requirements we do not know about - What analysis of un-submitted data is made - is any trend analysis on un-submitted data made to understand why the user failed to submit? What purging of un-submitted data is there - if its frequent enough, its not really doubling storage.
Comment: Yeah this is one approach. Another approach would be to add a status column. Then when the user finishes you simply change the status. This of course requires that all your other queries take into account this status. But is eliminates all the duplicate data. This question is very likely to get closed as being primarily opinion based.
Comment: @SeanLange - yeah I guess I was looking for other approaches to the scenario so cheers for that
Answer: The answer to your question, as stated, is no.  You cannot reasonably object to this as an anti-pattern per se.
This is a modeling question that cannot be answered as a matter of "best practices".  For instance a "Loan Application" is something different-enough from a "Loan" that it should be in a separate table.  It depends on what you are modeling, and how your developers and users think about the domain.


Removing input formatting options and description from comment form

Question: How do I remove the input formatting options and descriptions from the comment form?
I'm not interested in a CSS and/or jquery based solution, nor am I interested in using the Better Formats module, as I am using Drupal 7 and it specifically states it is not ready for production sites (besides the fact installing a module to do this seems like overkill).  I want the html sent over the wire to not have the "input format" related text at all.
Drupal drives me nuts sometimes, because some stuff that should be simple is ridiculously complex.
I've searched but no one seems to know how to do this. Here's some things I've found:

form_alter hide Text format option
Hiding the comment form's input format selector: A zombifying experience
Drupal 7 notes - Hiding unwanted form elements in comment forms
Comment: Drupal is well Drupal..
Answer: Ok found this drupal issue discussing the matter: Node and Comment Input Format fieldset is not working (I found it by searching for "edit-comment-body-und-0-format" which html id of the fieldset that contains all the input format mumbo jumbo).
At the end of this issue is a link to the following site which gives a solution:
How To Remove Format Options / Guideliness From Comments Textarea in Drupal 7.
Here's the code I'm using on my site, in template.php of my theme (I'm using a zen subtheme):
<code>function mytheme_form_comment_form_alter(&$form, &$form_state) {

  $form['comment_body']['#after_build'][] = 'mytheme_customize_comment_form';

}

function mytheme_customize_comment_form(&$form) {
  $form[LANGUAGE_NONE][0]['format']['#access'] = FALSE;
  return $form;
}
</code>
I just tried it and it does seem to be working. Woohoo!
Comment: it should be noted that this (['format']['#access'] = FALSE) disables the Wysiwyg editor
Comment: very well. In the past I have used css on my site to hide the options
Comment: @batibolix: for me it not just disables Wysiwyg editor, it also shows warning messages like "Undefined index: format in wysiwyg_pre_render_text_format" in wysiwyg module. Removing items from #pre_render array solves my problem
Answer: Check this module https://drupal.org/project/simplify .
From the module's project page:

Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.

Very helpful to hide unnecessary tips and text format option under RTE


User having issue with site being redirected to home page from every link

Question: We have a drupal 7 site hosted on a linux machine. One of our users claims they get redirected to the home page from every link they click on the site. I'm not personally having this experience with the site nor is anyone else I work with. The user hasn't given us any more information, but I'm wondering if you guys have any idea what might be going on here?
I found this thread but it seems to be mostly a Windows-based issue: Why does my drupal 7 redirect me to the home page from any link?. Plus I have clean URLs on and like I said it works fine for everyone else.
Thoughts?
Comment: Are you using Apache? Is there an htaccess file in the drupal root?
Comment: @AyeshK yes on both counts.
Answer: It is possibly an issue with a cookie. Have that user try to use another browser to check if the same problem occurs with that browser.
Or just delete the session cookie in the browser being used, then check if the issue is resolved.
Comment: that seems a reasonable suggestion, I'll follow up with the user.
Comment: no news; user must have figured it out and not told us. We gave him your ideas though, so I'll give you credit for it.


Couldn't create a subtheme of a core theme

Question: I want to do some customization on seven administation theme, I won't to copy it in my themes folder, I want to create a subtheme of it, it doesn't work for me. this is my info file
name = SEVEN SUB
description = a Seven subtheme
base theme = seven
core = 7.x
stylesheets[all][] = style.css

when I replace Seven by a theme already exists in my sites/all/themes, my theme inherits it, but for core themes it doesn't.
I tried to specify the path of seven, themes/seven and /themes/seven doesn't fix the problem.
Comment: Your .info file looks OK, so it must be something else. Is the machine name  of the theme (the name before the .info) the same as an existing theme or module? That could cause a problem. Also, it the name should be only lower-case, digits and underscore. (No space or other punctuation.)
Comment: The same sub theme works good when I change the base theme name to a contrib theme. I'm using D7.4.1 can u please try create a seven subtheme in your drupal installation?
Answer: In Drupal 7 if subtheme is attaching CSS with exact same file name, Drupal thinks you want to override a CSS file. That seems to be the problem for you. So you are overriding the CSS from the Seven theme by attaching style.css in the info file.
Easiest way to get over that problem is to rename your CSS file into something else e.g. seven_sub.style.css.


Is it appropriate to report means and standard deviations for composite scores?

Question: Following the post here, I am wondering if reporting the mean and standard deviation is appropriate when describing a composite score.
My composite score is the total of responses on several likert scale items and count variables.
I have made sure that all are on a five point scale, based on their level of importance, so as to preserve variability.
This is the weighting system I have used to assign the scores:

0 = of no importance
1 = of some importance
2 = of medium importance
3 = of high importance
4 = of absolute importance

I have then added all scores together to arrive at the composite score. As such, this is based on a formative measurement model framework.
I am aware of issues relating to the purity of scales and I am hoping my logic of using "level of importance" as the weighing criterion would provide the necessary meaning I need to interpret the composite score. For example, if I get a composite score of 3, I know it is of high importance.
(I apologise for my non-statistical language.)
Comment: Why do you think it might not be appropriate?
Answer: This is certainly done a lot, and I don't see it as problematic. I think concerns about it are related to an over-reliance on Steven's scale of measurement. Steven's scale is useful, but it's not etched in stone.
Briefly, someone who takes the notion of ordinality literally will object to adding the scores. But if you can add the scores, then you can find the mean and sd and so on. Adding the scores implies that the Likert scale itself is interval, rather than ordinal.
I wrote more about this in this article
Comment: Thanks for the link too. I now know where the scale of measurement came from!


What to call the distribution of the square of a zero-mean normal variable plus a constant

Question: What is the name of such type of distribution/density function x which is
$x=\theta +u^2$ for $u\sim N(0,\sigma^2$)?
Comment: @Ferdi It's not the distribution that gets squared, it's the variable.
Comment: @Dothis It's a special case of a shifted gamma.
Answer: It's a special case of a shifted gamma.
$U^2\sim \text{Gamma}(\frac12,2\sigma^2)$ (shape-scale parameterization)
and so $U^2+\theta$ is shifted-gamma (or three-parameter gamma*); $\theta$ is called the shift-parameter (or sometimes the threshold parameter). You might write it as $\text{shifted-gamma}(\frac12,2\sigma^2,\theta)$.
* however it's not the only distribution to be called "three-parameter gamma"
Other names: Pearson type III, scaled-shifted-chi-squared(1).
Comment: This is very great explanation. Thank you so much. Then I have one more question. I have also such a function $f(x; \theta)=exp(-(x-\theta)) $ for $-infinite <\theta <infinite $ and $\theta \le x < infinite$ These two forms are the same, or different?
Comment: That's a shifted (standard-) exponential; it's a *different* special case of the shifted gamma. A shifted-gamma$(1,1,θ)$


Error: The operator '[]' isn't defined for the class 'Object?'

Question: return Scaffold(
appBar: AppBar(
title: Text("Demo"),
),
body: Center(
child: FutureBuilder(
future: fetchphoto() ,
builder: (ctx, snapshot){
<code>        if(snapshot.connectionState == ConnectionState.waiting){
          return CircularProgressIndicator();
        }else{
          return ListView.builder(
            itemBuilder:(_, index){
              return ListTile(
                leading: CircleAvatar(backgroundImage: NetworkImage(snapshot.data[index]['thumbnailUrl'])),
                title: Text(snapshot.data[index]['title']),
                subtitle:Text("${snapshot.data[index]??['id']}"),
              );
            },
            itemCount: 12,
          );
        }
      },
    )
  ),
   // This trailing comma makes auto-formatting nicer for build methods.
);
</code>
}
}strong text
Comment: Try correcting the operator to an existing operator, or defining a '[]' operator.
                    leading: CircleAvatar(backgroundImage: NetworkImage(snapshot.data[index]['thumbnailUrl'])),
Answer: I don't think this can work :
<code>"${snapshot.data[index]??['id']}"),
</code>
Remove '??'
Comment: i removed this"??" also the program not work
Comment: share full code please


Using strtof in a loop to parse numbers from a char buffer

Question: I have a question about allocating and releasing memory.
I want to read a char buffer in a loop and save the float values to a vector.
I get the buffer by reading an fstream.
But my approach always crashes when deleting the buffers at the end.
Is it a problem that I change the buffer during my loop?
Has anybody an idea how to fix this?
I am thankful for every hint!
char* buffer1 = new char[size]; // the size is given
char* buffer2 = NULL;

fileStream.read(buffer1,size);

while(true)
{
  // read double from buffer
  // and get pointer to the new buffer -> buffer2
  double tempDouble = strtod(buffer1, &buffer2);

  // If nothing has been read (buffer stays the same) -> break
  if (buffer1 == buffer2)
      break;
  else // change the buffer to read the next double during the next interation step
      buffer1= buffer2;

  // collect the doubles
  collectedDoubles.push_back(tempDouble);

  // if all numbers are read -> break
  if (++doubleCount == numDoubles) // termination condition
    break;
}

// delete the allocated buffer
delete[] buffer1;

// do I have th delete the 2nd buffer too?
// delete[] buffer2;

Comment: `std::copy(std::istream_iterator(fileStream), std::istream_iterator(), std::back_inserter(collectedDoubles));`
Comment: You don't need to delete buffer2. You might want to check out the example here http://en.cppreference.com/w/cpp/string/byte/strtof
Answer:
According to the docs of strtod:

The functions sets the pointer pointed to by str_end to point to the character past the last character interpreted. If str_end is NULL, it is ignored.

So your pointer buffer2 is still NULL and after you do buffer1= buffer2; - buffer1 now also is NULL (Btw, here is memory leak as the data is lost).

do I have th delete the 2nd buffer too?

In this case - no, because deleting a NULL pointer is no-operation.

Solution:
Take a look at the example provided in docs for strtod function, here is similar according to your code:
char* buffer1 = new char[size];
char* buffer2;                           // note no NULL here !
char* p = buffer1;                       // we'll modify this in loop

for (double tempDouble = std::strtod(p, &buffer2); p != buffer2; tempDouble = std::strtod(p, &buffer2))
{
    p = buffer2;
    if (errno == ERANGE){                // check if some error occured during attempt to convertion
        std::cout << "range error\n";
        errno = 0;
    }

    collectedDoubles.push_back(tempDouble);

    if (++doubleCount == numDoubles)     // termination condition
        break;
}

delete[] buffer1;

Edit 1: Take a look at an elegant and very 'C++ like' solution provided suggested by @JerryCoffin in comments to your question.


Dúvida sobre o funcionamento da classe AudioRecord

Question: Sou iniciante e estava tentando entender como gravar um áudio usando android e como ele processa esse audio. E durante as pesquisas encontrei esse site:Audio Record
O exemplo funciona perfeitamente. Porém eu não entendi de fato como que essa classe funciona para capturar o som e poder gravar esse som.
Sabe-se que no processamento digital é feita uma amostragem (numero de amostras por segundo) dos valores de tensão e depois esses valores são convertidos em códigos binarios de acordo com as faixas de tensão. Então quanto maior o número de bits mais preciso vai ser a identificação do som. No exemplo abaixo ele usa 16 bits.
Então eu estou com dúvida sobre como relacionar o que ele faz com o processamento de audio digital de fato.

No exemplo ele declara uma variável de nome samplerate = 8000. Essa variável representa o número de amostras que o microfone do celular vai captar por segundo?
A variável RECORDER_AUDIO_ENCODING é o numero de possibilidades (2¹6) que posso usar para relacionar os valores de tensão em forma digital com numeros binarios?
Em certo momento ele pega o buffer minimo com o método getminBufferSize(). Por que ele tem que fazer isso? Eu não posso usar o tamanho do buffer que eu quiser?
int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING);

Na documentação ainda diz:

Returns the minimum buffer size required for the successful creation of an AudioRecord object, in byte units. Note that this size doesn't guarantee a smooth recording under load, and higher values should be chosen according to the expected frequency at which the AudioRecord instance will be polled for new data. See AudioRecord(int, int, int, int, int) for more information on valid configuration values.
  Eu não entendi essa questão dele ter que me dar o bugffer minimo.  O que me impede de setar o buffer?

Quando ele cria o objeto recorder da classe AudioRecord ele passa alguns parametros para o construtor e dentre esses parametros ele passa "BufferElements2Rec" e "BytesPerElement". Na documentação diz que esse parametro é o "bufferSizeInBytes". E diz o seguinte:

int: the total size (in bytes) of the buffer where audio data is written to during the recording. New audio data can be read from this buffer in smaller chunks than this size. See getMinBufferSize(int, int, int) to determine the minimum required buffer size for the successful creation of an AudioRecord instance. Using values smaller than getMinBufferSize() will result in an initialization failure.
  O que representa esse parametro, sendo que primeiro ele usa o buffersize = getminbuffersize() e depois ele usa "BufferElements2Rec" e "BytesPerElement"?

No meu entendimento ele pegaria amostras do som e gravaria os niveis de tensão converidos em numero binario. Eu não entendi direito ou ele faz isso?
Se alguem puder em ajudar a entender isso ficaria agradecido!!!
            import java.io.FileNotFoundException;
            import java.io.FileOutputStream;
            import java.io.IOException;
            import android.app.Activity;
            import android.media.AudioFormat;
            import android.media.AudioRecord;
            import android.media.MediaRecorder;
            import android.os.Bundle;
            import android.view.KeyEvent;
            import android.view.View;
            import android.widget.Button;

            /**
            *
            * @author RAHUL BARADIA
            *
            *
            */
            public class Audio_Record extends Activity {
            private static final int RECORDER_SAMPLERATE = 8000;

            private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;

            private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;

            private AudioRecord recorder = null;
            private Thread recordingThread = null;
            private boolean isRecording = false;

            @Override
            public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            setButtonHandlers();
            enableButtons(false);

            int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
            RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
            }

            private void setButtonHandlers() {
            ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
            ((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
            }

            private void enableButton(int id, boolean isEnable) {
            ((Button) findViewById(id)).setEnabled(isEnable);
            }

            private void enableButtons(boolean isRecording) {
            enableButton(R.id.btnStart, !isRecording);
            enableButton(R.id.btnStop, isRecording);
            }

            int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
            int BytesPerElement = 2; // 2 bytes in 16bit format

            private void startRecording() {

            recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
            RECORDER_SAMPLERATE, RECORDER_CHANNELS,
            RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

            recorder.startRecording();

            isRecording = true;

            recordingThread = new Thread(new Runnable() {

            public void run() {

            writeAudioDataToFile();

            }
            }, "AudioRecorder Thread");
            recordingThread.start();
            }

            //Conversion of short to byte
            private byte[] short2byte(short[] sData) {
            int shortArrsize = sData.length;
            byte[] bytes = new byte[shortArrsize * 2];

            for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
            }
            return bytes;
            }

            private void writeAudioDataToFile() {
            // Write the output audio in byte
            String filePath = "/sdcard/8k16bitMono.pcm";

                    short sData[] = new short[BufferElements2Rec];

            FileOutputStream os = null;
            try {
            os = new FileOutputStream(filePath);
            } catch (FileNotFoundException e) {
            e.printStackTrace();
            }

            while (isRecording) {
            // gets the voice output from microphone to byte format
            recorder.read(sData, 0, BufferElements2Rec);
            System.out.println("Short wirting to file" + sData.toString());
            try {
            // writes the data to file from buffer stores the voice buffer
            byte bData[] = short2byte(sData);

            os.write(bData, 0, BufferElements2Rec * BytesPerElement);

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

            try {
            os.close();
            } catch (IOException e) {
            e.printStackTrace();
            }
            }

            private void stopRecording() {
            // stops the recording activity
            if (null != recorder) {
            isRecording = false;

            recorder.stop();
            recorder.release();

            recorder = null;
            recordingThread = null;
            }
            }

            private View.OnClickListener btnClick = new View.OnClickListener() {
            public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btnStart: {
            enableButtons(true);
            startRecording();
            break;
            }
            case R.id.btnStop: {
            enableButtons(false);
            stopRecording();
            break;
            }
            }
            }
            };

            // onClick of backbutton finishes the activity.
            @Override
            public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            }
            return super.onKeyDown(keyCode, event);
            }
            }

Answer: Respostas:

No exemplo ele declara uma variável de nome samplerate = 8000. Essa
  variável representa o número de amostras que o microfone do celular
  vai captar por segundo?

R: Samplerate = 8000hz quer dizer que a cada segundo 8000 amostras do microfone são capturadas, se fosse 44100hz a cada segundo 44100 amostras seriam capturadas...
O inverso é verdadeiro, depois que vc salvou e codificou ou seu áudio(mp3, wav, flac, etc) para tocar o áudio no tempo e frequências exatas é preciso despejar essas amostras na mesma amostragem em que ele foi gravado/gerado, para tocar um áudio sampleado em 8000Hz o seu player tem que jogar 8000 samples por segundo para a sua caixa de som, o que acontece se vc tem um áudio gravado em 44100hz e mandar dar play em 8000hz(mandar jogar 8000 samples por segundo para a caixa de som) ?
vai acontecer algo chamado downsample você está pegando menos amostras por segundo do que o áudio foi gerado, o áudio vai tocar bem mais lento e parecendo que veio do inferno (frequências graves).
Se existe o processo de downsample também vai existir o processo de upsample, um áudio gerado a 8000hz e tocado em 16000hz por exemplo, vai tocar duas vezes mais rápido e com as frequências oitavadas (frequências duas vezes maior) seu áudio vai ficar igual uns esquilos.
O processo digital possui algumas características do processo analógico, esse fenômeno upsample/downsample também acontecia nos discos de vinis, não sei sua idade, mas antigamente quando ia na casa da minha bizavó eu não entendia o que acontecia, ela tinha um toca discos que rodava a 78RPM ou seja 78 rotações por minuto (mecanicamente tinha um motor que girava o eixo do disco nesta velocidade) e eu ficava brincando com os discos com o dedo e alterando a velocidade da rotação do disco, o som hora ficava mais grave hora ficava mais agudo dependendo da velocidade que eu girava os discos, na verdade acontecia a mesma coisa, os discos foram gravados para serem executados a 78RPM e se vc alterar a velocidade de execução vai acontecer downsample/upsample...

A variável RECORDER_AUDIO_ENCODING é o numero de possibilidades (2¹6)
  que posso usar para relacionar os valores de tensão em forma digital
  com numeros binarios?

É realmente a maneira que você vai representar os valores de tensão, não são em binários, vão estar no formato PCM um short int ou float point, você pode mandar plotar esses valores, ele vai estar representado no formato que você escolheu, por exemplo se vc encodar um áudio em short int (ENCODING_PCM_16BIT) as representações da suas tenções vão variar entre números inteiros que vão de -32768 até 32767 para um áudio encodado em float point ENCODING_PCM_FLOAT as representações variam de -1 até 1, é só uma maneira de representação, alguns preferem short int outros float point, alguns sistemas só conseguem dar play em valores representados em float point, no android por exemplo existe diferença de desempenho, processadores ARM low-end possuem pior desempenho com áudios em float point...

Em certo momento ele pega o buffer minimo com o método
  getminBufferSize(). Por que ele tem que fazer isso? Eu não posso usar
  o tamanho do buffer que eu quiser?

O Android é um sistema conhecido por problemas de latência, o SO e o Hardware são problemáticos e trabalhar com áudio em android é preciso ser mágico rsrs, o getminBufferSize() é um parâmetro gerado pelos desenvolvedores do google que tenta garantir um tamanho mínimo e aceitável para que você consiga gravar seu áudio com menos latência possível, se você colocar um tamanho de buffer menor do que o retornado pelo getminBufferSize() vai demandar mais processamento e por esse motivo isso foi travado, e o que acontece se você quiser colocar um buffer maior ? vai funcionar? isso vai depender do seu hardware e do SO, o dispositivo possui memória suficiente para trabalhar com o buffer de sua escolha? são perguntas que eu não vou poder te responder...
Se você notar no seu código a variável bufferSize não está sendo usada em nenhum lugar, na verdade o ultimo parâmetro(int bufferSizeInBytes) usado em seu AudioRecord
AudioRecord (int audioSource,
                int sampleRateInHz,
                int channelConfig,
                int audioFormat,
                int bufferSizeInBytes)

É de 2048
int BufferElements2Rec = 1024;only 1024
int BytesPerElement = 2

veja:
BufferElements2Rec * BytesPerElement

Só lembrando que o getminBufferSize() automaticamente gera valores de buffer diferentes dependendo do dispositivo, em teoria você não precisa ficar calculando e se preocupando com isso.
Comment: Sobre a segunda questão:
A forma que ele trabalha é mais ou menos essa?
para tensões entre 1.0v e 1.5v vai ter um valor 15 do tipo short int
para tensões entre 1.5v e 2.0v vai ter um valor 16 do tipo short int
E assim por diante...
Mais ou menos dessa forma?
Comment: Sobre a terceira questão: De fato ele não usa o retorno do  getminBufferSize() (bufferSize). Então eu poderia, ou melhor , deveria usar getminBufferSize() ao criar o objeto da
classe AudioRecord? Como vc disse, se ja existe uma função que me retorna esse valor, por que a pessoa que fez esse codigo colocou 2048?
Comment: No código ele usa  "recorder.read(sData, 0, BufferElements2Rec);" para salvar os valores lidos no array sData.
Depois ele salva esse vetor no arquivo.
Se eu quiser gerar um gráfico amplitudextempo, como que eu faço para pegar a amplitude e o tempo?Como que ele faz essa indexação?
Comment: são tantas perguntas, algumas fogem da sua pergunta original, o processo de conversão das tensões é muito complexo para responder aqui, existe um processo chamado Analog-to-digital converter (ADC), envolve sampling e quantization, o ADC tenta pegar por amostragem a forma de onda analógica da forma mais fiel possível, o processo que converte esses dados para short int ou float point são os dados encodado em PCM, se o seu app for algo simples vc pode usar o getminBufferSize mas e o seu app precisar trabalhar com um buffer específico vc é livre pra escolher
Comment: vc pode usar o valor para plotar os seus dados, não existe nada indexado o tamanho do vetor é o tempo do seu áudio e os valores contidos nele representam a amplitude do seu áudio, dá pra usar o canvas do java para  plotar e ver a forma de onda, isso também é outra pergunta haha, tente segmentar os seus problema e fazer novas perguntas, assim mais pessoas podem te ajudar, uma dica tente não fazer 1000 perguntas em uma só questão, vai ser complicado alguém conseguir responder ....
Comment: Obrigado...é que uma resposta já puxa outra dúvida...rsrs.
Só uma ultima pergunta sobre sua ultima resposta: cada posição do vetor representa uma amplitude, o indice do vetor então são os segundos?Indice 2, 2 segundos, indice 10, 10 segundos e assim por diante?Ou ele usa em milisegundos, como eu posso descobrir isso?
Obrigado desde já pela ajuda!!!
Comment: não!! a posição indica o número da amostra, lembra que eu te falei sobre o processo de captura de amostras, o exemplo que dei de  44100 amostras capturadas por segundo lembra ? ou seja o índice do vetor de número 44100 indica 1 segundo de áudio, indice 88200 igual 2 segundos de áudio, ou seja para saber quantos segundos o seu áudio tem baseado na posição do vetor é só fazer `samplerate / índice desejada = tempo em segundos`, isso quer dizer que se você fizer o cálculo do samplerate divido pelo tamanho total do seu vetor você vai ter como resposta o o tempo total do seu áudio em segundos


Could somebody help me read these ACF and PACF plots?

Question: So, I have this time series that I have already forecasted using an ARMA model, but I am new to this and am therefore not at all sure whether or not I did this (somewhat) correctly.
I got the best results when differentiating the series twice, but I am not sure if it was really the right way to go.
What would your inputs be when looking at the provided ACFs and PACFs? They all are from the series. Without differences, once differentiated and twice differentiated.

Answer: Your ACF (of the undifferenced series) appears to be exponentially decaying, and your PACF has a peak at lag 1 and no other significant peaks. This suggests an AR(1) process.
I recommend the entire textbook by Hyndman and Athanasopoulos. A more modern approach to ARIMA order selection relies on information criteria. You may also want to browse through earlier threads in the box-jenkins tag, which contain many other examples of interpretation of ACF/PACF plots.


Why have AWS decided to block ICMP by default on new EC2 machines?

Question: From Why can't I ping my freshly set up amazon web service EC2 instance? it seems that the architects from Amazon's AWS have chosen to block ICMP by default.
Is there some official source stating their reasoning for that? I assume it is because of security but I'd like to be able to read their official stance on it, if possible.
Answer: That's a bit of a misunderstanding - only inbound ICMP Echo is disabled by default and you can allow it in your Security Group if you need to.
ICMP is a whole suite of Internet Control Message Protocol packet types, most of them used for various traffic flow controls, etc. Those are not blocked because they are related to other traffic initiated by the instance. Only ICMP Echo is blocked by default because you don't have control over who pings you and there is no need to have it enabled.
The reason is simple - AWS won't let any unsolicited external traffic in unless you explicitly tell it to. And that includes ICMP Echo.


Remove link from content header

Question: The website I'm building has a lot of content that I do not want linkable to the actual node. Is there a way to remove the link in the content headers?
Comment: There are a few near duplicates of this, though asked in slightly different contexts.  One of which is http://drupal.stackexchange.com/questions/324/how-do-i-hide-drupal-nodes-that-shouldnt-be-directly-accessed-from-users-and-se
Answer: There are a lot of different methods for doing this.
The basic idea is to detect the content type using one of a few methods and calling drupal_not_found().  When doing this, I typically set the pathauto for these to no-view/[nid], and then detect the request_uri in a hook.  There are some variations, but the all do something really similar.
However, there is a newish module called Rabbit Hole that eliminates the need for custom modules and provides a lot of flexability to how you hide the content.  I had been working on a general use module that did something similar, and abandoned developing it when I found this.  From the project page:

[It] works by providing multiple options to control what should happen when the node is being viewed at its own page. You have the
  ability to

Deliver an access denied page.
Deliver a page not found page.
Issue a page redirect to any Drupal path.
Or simply display the content (regular behavior).

This is configurable per content type and per node. There is also a permission that lets certain roles override Rabbit Hole completely.
Comment: I'm implementing Rabbit Hole to return them to the frontpage if anyone attempts to access the node directly, and I ended up creating some PHP directives in node.tpl.php based on the taxonomy of the content. The reason I approched it with this method is to give control to editors/content builders to either link it or not link via the content title just by entering a taxonomy term. I added a couple additional functionality like to be able to remove titles altogether, and even disable publishing information. However, rabbit hole is a fallback in case someone attempts to hack the URL to access it.

Remove link from content header


How do I return all rows of data from min date to the next possible date after current date in date column?

Question: Consider a table with multiple rows with dates:
Date
------
5/9/2022
5/27/2022
4/18/2022
6/2/2022
7/1/2022
6/6/2022
7/8/2022
7/6/2022
7/22/2022
7/19/2022
7/11/2022

current query is returning all rows DATE <= GETDATE()+1
so it would be returning all dates <=7/9/2022 when it actually needs to be <=7/11/22. This being this column never has a date that falls on a weekend or holiday. So on days like Fridays, the query should be trying to pull all rows <= to that coming Monday (the next date in the column or work day). This query has multiple where conditions as well.
WHERE (_Header.CODE IN ('10', '15')) AND (_Header.LOCATION = '89') AND (_Header.OR_NO > '0') AND (_Header.DATE <= GETDATE()+1)
Comment: reverse the order and then take the offset of 1
Answer: This would give you the next day in a date field after today. It is a simple common table expression you could use in your query. You would just request all dates be <= to the date that is retrieved from the cte.
  with cte(nextDay)
  AS (SELECT TOP 1 cal_date FROM calendar
  WHERE cal_date > GETDATE()
  ORDER BY cal_date)
  SELECT * FROM cte

Comment: Okay, I was unsure how to use this with my query but I finally found something but I'm not sure its the "best/correct" way but it works.
`SELECT _Header.DATE, _Header.LOC, _Header.JO_QT, _Header.PT_NU, _Header.JB_NU, _Header.OR_NO, _Header.OR_SE, _Header.AC_CO,
dbo.PS_TER.FAM_CODE   FROM dbo._HEADER AS _Header INNER JOIN
dbo.PS_TER ON _Header.PT_NU = dbo.PS_TER.PT_NU
Join cte b on 1=1
WHERE (_Header.CODE IN ('10', '15')) AND (_Header.LOC = '89') AND (_Header.OR_NO > '0') AND (_Header.DATE <= b.nextDay)`


" TypeError: _Fire.default.shared.addPost is not a function "'Fire.default.shared.addPost' is undefined

Question: I have been getting this error:
TypeError: _Fire.default.shared.addPost is not a function.'Fire.default.shared.addPost' is undefined
I will be glad if anyone can help
 handlePost = () => {
Fire.shared
  .addPost({
    text: this.state.text.trim(),
    localUri: this.state.image,
  })
  .then((ref) => {
    this.setState({ text: "", image: null });
    this.props.navigation.goBack();
  })
  .catch((error) => {
    alert(error.message);
  });

};
Comment: Could you provide us with relevant code (code that could be a possible reason for this error)? For example, the code that fires the function `_Fire.default.shared.addPost`.
Comment: alright sir i will post the code
Comment: i have shared the code sir
Answer: Providing the specific code snippet would be better for understanding.
If you are using the react class component, you may bind the function inside the constructor.
constructor(props)
{
  super(props);
  this.state = {};
  this.addPost= this.addPost.bind(this);
}

If you have created reference of child component inside parent and trying to access a function of the child from the parent, then you probably have used a lot of references before. React does not support more than 4 references (approximately).
Probably the _Fire.default.shared.addPost function takes arguments and you are not passing necessary and sufficient arguments.
Also, it's possible that you are accessing a function through props. Where in the main component, either the function does not exist, or you have not bound the function or you're not passing necessary arguments while calling props from the child.
PS: These are four different scenarios and the possible solutions for each.


Primary address in Address

Question: Does anybody know how to make a address primary in VendTable?
I need to make a new field (checkbox) in the Address tab of VendTable (the datasource for Address in VendTable comes from DirpartyAddressRelationship and Address).
Can anyone let me know step by step how to make a address primary?
There seems to be a lot of relations. I am not sure how this is working.
Comment: If you find the answer usefull, please accept the answer.
Answer: I assume you are asking how to set the primary address using code (not through the user interface).
Use the DirParty class:
static void DirPartyTest(Args _args)
{
    VendTable v = VendTable::find("10000");
    DirParty d = DirParty::constructFromCommon(v);
    ;
    d.getDirPartyAddress().parmIsPrimary(NoYes::Yes);
    Dirparty::updateAddressFromParty(d);
}

Using a specific address:
void setPrimary(Address a)
{
    DirParty d = DirParty::constructFromCommon(a);
    ;
    d.getDirPartyAddress().parmIsPrimary(NoYes::Yes);
    Dirparty::updateAddressFromParty(d);
}

Primary address in Address