NestJS using Jest test async functions within async functions

Question: I am trying to write a test for my service, and everything is working (the service, the tests so far) but I am not able to verify a function is called, and this is failing.  However, the code coverage output from the test indicates the line is being executed, and if I run the code itself, it does delete the data.
I have tried to copy just the relevant part of the service processing to illustrate my issue.  My service maintains holiday dates from an external service.  This will remove bad entries, as well as add new holiday date records moving forward per year. I have trimmed this down to just the functions I am having the issue with.
export class UpdateService {
    constructor(
        private readonly HolidayDateDataService_: HolidayDatesService,
    ) {
        this.RemoveInvalidHolidayDateEntriesForAYear(Year);
    }

    async RemoveInvalidHolidayDateEntriesForAYear(Year: number): Promise<void> {
        let ExistingHolidayDates: Array<HolidayDatesResponseDTO>;

        try {
            ExistingHolidayDates = await this.HolidayDateDataService_.GetAllRecordsByYear(Year); // From external API
        } catch (Exception) {
            return;
        }

        ExistingHolidayDates.forEach( async (OneDateEntry: HolidayDatesResponseDTO) => {
            const HolidayIdIsActive: boolean = await this.ValidateHolidayIdActive_(OneDateEntry.HolidayId); // Validates Entry should be maintained.
            if (! HolidayIdIsActive) {
                await this.DeleteOneHolidayDateRecord_(OneDateEntry);
            }
        });
        return;
    }

    async DeleteOneHolidayDateRecord_(HolidayDateData: HolidayDatesResponseDTO): Promise<void> {
        console.log('Start DeleteOneHolidayDateRecord_');
        try {
            console.log('Start HolidayDateDataService');
            await this.HolidayDateDataService_.Delete(
                new HolidayDatesEntity(HolidayDateData.HolidayId, HolidayDateData.Name, HolidayDateData.Year),
                HolidayDateData.Key_
            );
            console.log('End HolidayDateDataService');
        } catch (Exception) {
            ; // Do nothing, try the next one
        }
        console.log('End DeleteOneHolidayDateRecord_');
        return;
    }

    async ValidateHolidayIdActive_(HolidayId: string): Promise<boolean> {
        console.log('Start ValidateHolidayIdActive_');
        try {
            console.log('Start HolidayIdDateService');

            const HolidayIdData: HolidayIdsResponseDTO = await this.HolidayIdDataService_.GetOne(HolidayId);

            console.log('End HolidayIdDateService');
            if (HolidayIdData && HolidayIdData.Active) {
                return true;
            }
        } catch (Exception) {
            ; // Do nothing as the method ends with a return false
        }
        console.log('End ValidateHolidayIdActive_');
        return false;
    }
}

As I said, all of this works.  However, I am trying to test and verify that the delete is called.
describe('UpdateService', () => {
    let service: UpdateService;
    let HolidayIdsTestService: HolidayIdsService;
    let HolidayDatesTestService: HolidayDatesService;

    const HolidayRecords: Array<HolidaysApi> = new Array<HolidaysApi>(
        { id: 31, name: 'Christmas Day', observedDate: '2022-12-27' } as HolidaysApi,
        { id: 32, name: 'Boxing Day', observedDate: '2022-12-28' } as HolidaysApi,
    );

    beforeEach(async () => {
        const mockHolidayIdsService = {
            provide: HolidayIdsService,
            useValue: {
                GetOne: jest.fn(),
            },
        };

        const mockHolidayDatesService = {
            provide: HolidayDatesService,
            useFactory: () => ({
                Delete: jest.fn(),
                GetAllRecordsByYear: jest.fn(),
            }),
        };

        const module: TestingModule = await Test.createTestingModule({
            providers: [
                UpdateService,
                mockHolidayDatesService,
                mockHolidayIdsService,
            ],
        }).compile();

        service = module.get<UpdateService>(UpdateService);
        HolidayIdsTestService = module.get<HolidayIdsService>(HolidayIdsService);
        HolidayDatesTestService = module.get<HolidayDatesService>(HolidayDatesService);
    });

    it('should delete HolidayDate records if ValidateHolidayIdActive_ returns false', async () => {
        jest.spyOn(HolidayDatesTestService, GetAllRecordsByYear').mockResolvedValue(HolidayDateRecords);
    jest.spyOn(HolidayIdsTestService, 'GetOne').mockResolvedValue(new HolidayIdsResponseDTO('Fake_Holiday_Id', false, 31, 'Christmas Day'));
    jest.spyOn(HolidayDatesTestService, 'Delete').mockResolvedValue();

    await service.RemoveInvalidHolidayDateEntriesForAYear(2022);
    expect(HolidayIdsTestService.GetOne).toHaveBeenCalledTimes(2);
    expect(HolidayDatesTestService.Delete).toHaveBeenCalledTimes(2);
});

The problem in my tests, is that the last expect fails:
expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

  532 |             await service.RemoveInvalidHolidayDateEntriesForAYear(2022);
  533 |             expect(HolidayIdsTestService.GetOne).toHaveBeenCalledTimes(2);
> 534 |             expect(HolidayDatesTestService.Delete).toHaveBeenCalledTimes(2);
      |                                                    ^

The problem I am having is the ValidateHolidayIdActive_ is called 2 times (which uses the HoldiayIdsTestService internally, which is mocked), which I expect, and as it was mocked to return a False status, the DeleteOneHolidayDateRecord_ should be called 2 times as well.  However, both .toHaveBeenCalled() and .toHaveBeenCalledTimes(2) fail when validating the internal service is called, which is again mocked.
However, with my console.log() calls in the code, I can see that the modules are called in the proper orde, and everything is started, and then completes up the chain.
Record #1
console.log Start ValidateHolidayIdActive_
console.log Start HolidayIdDateService
console.log Start ValidateHolidayIdActive_
console.log Start HolidayIdDateService

console.log End HolidayIdDateService
console.log End ValidateHolidayIdActive_
console.log End HolidayIdDateService
console.log End ValidateHolidayIdActive_

Record #2
console.log   Start DeleteOneHolidayDateRecord_
console.log   Start HolidayDateDataService
console.log   Start DeleteOneHolidayDateRecord_
console.log   Start HolidayDateDataService

console.log   End HolidayDateDataService
console.log   End DeleteOneHolidayDateRecord_
console.log   End HolidayDateDataService
console.log   End DeleteOneHolidayDateRecord_

It does appear to call and finish correctly.  However, the one function is spied as working, and the other is not.  I cannot understand my error.
Any help is appreciated, as it should be a simple mistake, but is completely frustrating me, and I cannot seem to find it.  I had the functionality a lot more together in one function originally, and have broken it out like this to test each function (which works with the same style of mocks).
Answer: My issue has to do with the processing I am doing.  await/async cannot run loops that have callbacks, such as forEach().  Use the for..of format, will correct the errors I am encountering.  It takes some restructing of the code I have written, but it does correct the issue.
...
ExistingHolidayDates.forEach( async (OneDateEntry: HolidayDatesResponseDTO) => {
    const HolidayIdIsActive: boolean = await
    this.ValidateHolidayIdActive_(OneDateEntry.HolidayId); // Validates Entry should be maintained.
    if (! HolidayIdIsActive) {
        await this.DeleteOneHolidayDateRecord_(OneDateEntry);
        }
    });
});

Change the handling to not be a callback with forEach, but to be a for..of instead:
for (OneDateEntry of ExistingHolidayDates) => {
    const HolidayIdIsActive: boolean = await
    this.ValidateHolidayIdActive_(OneDateEntry.HolidayId); // Validates Entry should be maintained.
    if (! HolidayIdIsActive) {
        await this.DeleteOneHolidayDateRecord_(OneDateEntry);
        }
    });
});

This will allow the proper processing.


pegar url do site

Question: Bom, tenho a seguinte url:
http://www.site.com.br/pasta1/pasta2/arquivo.php?parametro1=234&&parametro2=sim

Gostaria de saber qual a variável do tipo $_SERVER[] que devolve apenas
http://www.site.com.br

Comment: Relacionado [**Como obter apenas o domínio de um link?**](https://pt.stackoverflow.com/q/179155/3635) (não é dup, só comentado pra referenciar)
Answer: Tente $_SERVER['SERVER_NAME'].
Caso precise do restante da url você pode usar os argumentos 'REQUEST_URI' e 'PATH_INFO'.
Espero ter ajudado.
Documentação da função aqui.
Comment: obrigado! Falta de atenção da minha parte!
Comment: Disponha , aqui é pra isso mesmo, tirar dúvidas.

pegar url do site


Expected number of White balls followed by a Black ball?

Question: An urn has n white and m black balls that are removed one at a time in a randomly chosen order. Find the expected number of instances in which a white ball is immediately followed by a black one.
How do I approach such questions? I am clueless about where to even begin!
Comment: Calculate the probability that no white ball is immediately followed by a black one. Then calculate the probability that $1$ white ball is immediately followed by a black one. Then calculate the probability that $2$ white ball is immediately followed by a black one. Repeat this process all the way up to $n$ white balls, and then use the calculated probabilities in order to calculate the expectancy.
Comment: @barakmanos Is this a joke?
Comment: @Did: No. I answered the question of "how to approach such questions and where to begin".
Comment: @barakmanos Except that in this case, computing all these probabilities is a nightmare, with answers depending heavily and in a complicated way on n and m. Did you try to compute "the probability that 2 white ball(s) (are) immediately followed by a black one" for example?
Comment: @Did: No. I didn't.
Comment: @barakmanos Thought so. In such a case, a less authoritative tone than in your first comment would be preferable (hence my first comment).
Comment: @Did: I cannot express tones in a comment (nor in any other written form). OP asked how to approach the problem, I suggested a method which is often used for this type of problems.
Comment: @barakmanos And which fails miserably in the present case. (It is slightly unfortunate that I have to say this myself but the three upvotes on your comment and the ambiguity of your remarks make me feel I have to.)
Comment: @Did: See [here](https://en.wikipedia.org/wiki/Tone). None of the specified categories seem to be even remotely ascribed with any alphabetic (written) structures. It's all about waveform / audio, none of which appears in my comment. So whatever tone you've detected there is your personal interpretation (I respect it BTW, but in this specific case it is plain wrong, I wasn't thinking in any "authoritative tone" whilst writing it).
Comment: @barakmanos I am slightly surprised that you see fit to extend this thread beyond reason (perhaps are you doing this as some kind of damage control operation to hide the fact that your first comment is *false* and *misleading*), but here we go: *as you should be well aware*, the imperative usually indicates that the author is sure that the route they indicate leads to the desired result, otherwise one adds caveats such as "perhaps", "it might work to do so and so", and the like. Your second comment confirms that you were convinced your first was of value, probably because you did not even ...
Comment: ... bother to check it was leading anywhere. Next time, I suggest to think more about the "hints" you want the OP to spend some time on before posting them. Or, add the suitable caveats.
Comment: @Did: As am I (surprised, for the exact same reason).
Comment: @barakmanos I can see that you are willing to discuss everything except the mathematics, hence indeed there is no point in continuing this.
Answer: For $k=1,\ldots,m+n-1$ let $X_k$ be $1$ if the $k$-th ball is white and the $(k+1)$-st ball is black, and $0$ otherwise. There are $\binom{m+n}m$ possible sequences of white and black balls, all of which are equally likely. If we specify that the $k$-th and $(k+1)$-st balls are white and black, respectively, there are $\binom{m+n-2}{m-1}$ possibilities for the remainder of the sequence; why? This means that
$$\Bbb E[X_k]=\frac{\binom{m+n-2}{m-1}}{\binom{m+n}m}=\frac{(m+n-2)!\,m!\,n!}{(m+n)!\,(m-1)!\,(n-1)!}=\frac{mn}{(m+n)(m+n-1)}$$
for $k=1,\ldots,m+n-1$. Now express the number of white balls that are immediately followed by a black ball in terms of the random variables $X_k$, and use linearity of expectation to get the desired result.
Answer: Label the white balls $w_1$ to $w_n$. Let random variable $X_i$ be equal to $1$ if white ball $w_i$ is immediately followed by a black ball, and $0$ otherwise. Then the number $Y$ of instances in which a white is immediately followed by a black is given by $Y=X_1+\cdots+X_n$.
By the linearity of expectation we have $E(Y)=\sum_1^n E(X_i)=nE(X_1)$.
To find $E(X_1)$, we find $\Pr(X_1=1)$. We have $X_1=1$ if white ball $w_1$ is not chosen last, and is followed by a black. The probability it is not last is $\frac{m+n-1}{m+n}$. Given that it is not last, the probability it is followed by a black is $\frac{m}{m+n-1}$. It follows that $\Pr(X_1=1)=\frac{m}{m+n}$.
Thus $E(X_1)=\frac{m}{m+n}$ and $E(Y)=\frac{mn}{m+n}$.


rsync secure configuration running as daemon

Question: The uid is set to nobody (which should be default anyway), chroot and read only are both enabled. The rsync service is being started over /etc/init.d/rsync. This is the full rsrync.conf:
motd file = /etc/rsync/rsyncd.motd
max connections = 4
timeout = 30
uid = nobody
use chroot = true
address = my-ip

[ubuntu-releases]
   path = /usr/share/nginx/example.com/cdn/ubuntu-releases
   log file = /etc/rsync/rsync.log
   read only = true
   list = true

So my question is, if this is secure or did I miss anything?
I heard about rsync over ssh but I am not sure if this is only for private access.
Answer: Depends on what you mean with secure. It's not encrypted, so susceptible to traffic sniffing. It is 'secure' in the sense that, barring rsync bugs, users only have access to what's in /usr/share/nginx/example.com/cdn/ubuntu-releases
Comment: Thank you, yes I should have better explained what I mean by secure. And another short question: What does the string inside the [] brackets relate to?
Comment: That's the name of the exported rsync module. It doesn't need need to match the directory name.


Whats the most efficient way to access another forms controls in .NET?

Question: I'm creating a reporting application, and our customers are going to need to generate some pretty big reports which require quite a bit of memory.  Ive been in a re-factoring mood lately, so I was wondering what the best way to access the properties of another open form would be(The reporting viewer opens in a new form.)  So far I have:
Dim form As MainSelections

form = My.Application.OpenForms(2)
yay or nay.
Thanks
*Edit - I should probably mention that what I need is a label, two date time pickers, 5 datagridviews and a few datasets. Those cotrols have the info I use for my parameters
Answer: First, don't access a form's controls directly, its considered a bad practice, access dependent data through an interface instead:
(Warning: untested code and my VB-fu is rusty, but you should get the general idea)
public interface ILoginScreen
    Property Username as String with Get
    Property Password as String with Get
end interface

Implement the interface on your Form. (And make sure your interface does not return datatypes like TextBox, ComboBox, etc, that would defeat the purpose of the interface abstraction.)
Second, don't access dependencies through global state like the OpenForms collection, pass your dependencies to your objects through a constructor instead.
So if your Reports form depends on your login screen (or any other screen), you should have a constructor which accepts an ILoginScreen implementation:
public sub New(loginScreen as ILoginScreen)
    me.LoginScreen = loginScreen
end sub

And instantiate your reports form as such:
dim reportScreen as new ReportScreen(Me)
'passes self as ILoginScreen implementation

According to the OP in the comments:

Actually what I need is a label, two
  date time pickers, 5 datagridviews and
  a few datasets. Those cotrols have the
  info I use for my parameters.

Evidently the OP is passing these controls as report parameters. Probably creating and implementing an interface is excessive for his needs, but the general principle of dependency injection is correct.
Pass your data into your Report form's constructor:
class Report
    public sub New(start as DateTime, end as DateTime, label as String, _
        etc as Whatever)
end class

Please ensure you pass things like DateTimes, Strings, Integers, DataSets, etc -- or a typed object representing your parameters.
Don't pass DateTimePickers, TextBoxes, Comboboxes, DataGridViews, etc. Your report form shouldn't know or care that its start and end dates come from a DateTimePicker or not, it should only care that it actually has dates of some kind. Lazily passing form controls is a surefire way to enrage the next person who works on your code.
Comment: I'm still a little new at this, so should i have a module containing the varibles then pass them into the Report form's constructor? I'm kinda confused.
Comment: @broke: no, you don't need another module. Just create the ReportForm from your MainSelections form, make sure you call the constructor which takes your parameters: `new ReportForm(dtStartTime.SelectedDateTime, dtEndTime.SelectedDateTime, lblReportName.Text, [whatever other properties]).Show()`.
Comment: Sorry for being a pest, but i think i got it now.

In my MainSelections i have:

Dim reportscreen As New ReportForm(lblNumber.Text)
        reportscreen.ShowDialog()

Then in my ReportForm i have

 Public Sub New(ByVal reportnum As String)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub

I can fill in the rest of the requirements like the datasets and all that.  Am I on the right track?


If $A$ is idempotent and $B=(I-A)$, then $BA'=I$

Question: Given that $A$ is idempotent and         $B=(I-A)$, then prove that $BA'=I$.
I try this by taking two idempotent matrices..but i am confused
Comment: The question is wrong.  If $A$ is an idempotent matrix other than $0$, $I - A$ has less than full rank, so you certainly can't have $B A' = I$.
Comment: Just plug the formula for $B$ into the thing you want to prove.
Comment: 1) So, what is your question? 2) What do you mean by $A'$?
Comment: $A'$ generally means $A^T$. However the question is wrong.
Comment: Actually this question is asked in university exam ..and A' means A transpose
Answer: Given $A^2=A$ and $B=I-A$, you want to prove
$$BA^T=I$$
$$(I-A)A^T=I$$
$$A^T-AA^T=I$$
Left multiplying by $A$ (if $A\neq O$), what you have to prove comes down to
$$AA^T-A(AA^T)=I$$
$$AA^T-(AA)A^T=I$$
$$AA^T-AA^T=I$$
$$O=I$$
Hence the identity is invalid for $A\neq O$.
For $A=O,B=I$, $BA^T=O$. Hence it is not valid for any $A$.
Answer: As it stand, this is not correct.
For instance, take
$A = \begin{bmatrix} 1 & 1 \\ 0 & 0 \end{bmatrix}.$
This is an idempotent matrix, but the expression
$(I-A)A'$
will be equal to the matrix
$\begin{bmatrix} -1 & 0 \\ 1 & 0 \end{bmatrix},$
as shown in wolfram alpha.


duktape use common c function for multiple bound js functions

Question: I'm trying to bind a common c function to multiple javascript functions using the duktape engine.
My problem is that i need to find out the name of the calling function inside the common c function. I feel like it's possible to implement this using the often referred javascript stack.
However i have no concrete idea on how to implement it. Does anybody have an idea on how to do this?
Below You can find my mwe. The function duk_get_invoking_function is meant to be pseudo code that emphasizes my intent.
<code>#include "duktape.h"

duk_ret_t common_function(duk_context * ctx) {
    const char * function_name;

    //
    // function_name = duk_get_invoking_function(ctx);
    // e.g. function_name is "func_01"
    //

    return 0;
}

int main() {
    duk_context * ctx;

    ctx = duk_create_heap_default();
    if (!ctx) {
        return 1;
    }

    duk_push_c_function(ctx, common_function, DUK_VARARGS);
    duk_put_global_string(ctx, "func_01");

    duk_push_c_function(ctx, common_function, DUK_VARARGS);
    duk_put_global_string(ctx, "func_02");

    duk_push_c_function(ctx, common_function, DUK_VARARGS);
    duk_put_global_string(ctx, "func_03");

    duk_eval_string(ctx, "func_01('abc'); func_02(123); func_03();");

    duk_destroy_heap(ctx);

    return 0;
}
</code>
Answer: If I understood correctly you want multiple Ecmascript function objects to bind to the same native function -- and when that native function is called, figure out which Ecmascript function object was used in the call.
If so, you don't need to look at the call stack to do this: each duk_push_c_function() creates a new Ecmascript function object that points to the same native function. When the native function is called, you can use duk_push_current_function() to get access to the Ecmascript function used in the call. You can then distinguish between the Ecmascript function objects based on e.g. their properties which you set when you create them.
Comment: Thanks a lot! It works perfectly.  I have used
 `duk_push_c_function(...);  duk_push_string(ctx, "name");
 duk_push_string(ctx, "func_01");  duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE);  duk_put_global_string(ctx, "func_01");`
 to define the functions property "name" during registration. In the handler i am accessing this property with the following code
`duk_push_current_function(ctx);  duk_get_prop_string(ctx, -1, "name");
 function_name = duk_get_string(ctx, -1);`


Transformation of normal distribution

Question: Suppose I have a normal distribution $A \sim \mathcal{N}(\mu,\sigma^{2})$ with a known cuttof point (percentile) on this distribution called $o$. Based on this point the distribution needs to be transformed which leads to a new distribution called $W$. Next, suppose $s$ equals a deterministic value. $o$ and $s$ are known in advance and do not need to be estimated.
 The first part of $A \in [-\infty,o]$ becomes deterministic and equal to $o+s$, the second part $]o,+\infty]$ remains stochastic and is equal to a transformation of $A$ more specifically $\mathcal{N}(\mu+s,\sigma^{2})$
So summarised:
$W = \begin{cases}o+s & \text{if } A \leq o \\ A+s & \text{if } A > o \end{cases}$
I want to find an expression for the pdf of $W$.
More specifically in my application A represents the arrival time distribution at a customer and $o$ represent the opening time at that customer. If you arrive to early you will have to wait before you can serve (service time is equal to $s$) the customer.
My current (unsuccesfull) solution approach for the case in which $\mu=10,\sigma=1,o=11,s=1$ is as follows
I think W is the component mix:
$W= P(A\leq o)*(o+s)+ P(A>o)*(A+s),$
I entered this in mathematica (see picture below)
Furthermore, I programmed a monte carlo simulation executing 100000 iterations. The new distribution has a mean equal to $12.08$ and a standard deviation equal to $0.26$.
Comment: In the definition of $W$, what is the relationship between "$\mathcal{N}(\mu+s,\sigma^{2})$" and "$A$"?  Do these represent independent variables--as the notation suggests--or is the former indeed some "transformation" of $A$?  If the latter, exactly how is $A$ being transformed?
Comment: $W$ has a censored Normal distribution (censored below at $c$). Then, the pdf of $W$ has a discrete mass at the point $c$, and a continuous component for $A > c$. This is not reflected in your plot above, and so your plot and working are faulty.
Comment: @cevertje400 very well. However, please answer: are either $o$ or $s$ known here or must they be estimated from data? For instance, in the case of screening for CD4 count in HIV positive persons, we *know* that values lower than 400 are returned as "indeterminable", so the thresholding level is known.
Comment: Also, how can you run a simulation (or make a plot) without specifying a value for $c$?
Comment: thanks for the remark, this was an error, there should be no $c$ variable only an $o$.
Comment: Instead of calculating the mean and standard deviation based on my simulation samples I now added a histogram of the actual samples to the post.
Comment: I don't actually see much of a question in here... but I presume your interest lies in estimating $\mu$ and possibly $\sigma^2$ for the original untruncated, untransformed $A$. I am also somewhat confident that in your formulation of $W$ you meant to write that $A=W$ when lower limit of detection is not reached. The pertinent question is whether you know $s$ in which case you can just add $s$ to $W$ and make this a simple EM algorithm application.
Comment: I understand the confusion because of my wrong notation. I meant a transformation of $A$ as the mean of $A$ is increased with $s$.
Comment: I don't know the correct notation. But it should be impossible to have a value smaller than $o+s$ as can be seen in the histogram.
Comment: Both $o$ and $s$ are known in advance. $o$ is the opening time of a customer and $s$ is the service which is assumed to be known in advance in my application.
Answer: I can't bring myself to use an 'a' or $A$ for a random variable (or an 'o' for a constant), so will swap for $X$ and $c$.
The problem
Let $X \sim N(\mu,\sigma^2)$ with pdf $f(x)$, and let $c$ and $s$ denote constants.

(source: tri.org.au)
Then, random variable $W$ has a censored distribution, where:
$$W = \begin{cases}c+s & \text{if } X \leq c \\ X+s & \text{if } X > c \end{cases}$$

(source: tri.org.au)
The tail of $X$ to the left of $c$ becomes the discrete mass at $c+s$, with mass $P(X \leq c)$ (the blue point). The tail of $X$ to the right of $c$ gets shifted to $X+s$.

As to computation of $E[W]$:
Define:

(source: tri.org.au)
Then, $E[W]$ is:

(source: tri.org.au)
where I am using the Expect function from the mathStatica package for Mathematica to automate the computation, and Erf denotes the error function.
For the given parameter values:
{$\mu$ -> 10, $\sigma$ -> 1, c -> 11, s -> 1}
... this yields:  $\frac{1}{2} \left(\text{erf}\left(\frac{1}{\sqrt{2}}\right)+23\right)+\frac{1}{\sqrt{2 e \pi }} \approx 12.0833$ as per OP's simulation.
Suggestion
The inclusion of constant $s$ is an unnecessary distraction. A neater way of modelling this is to define:
$$Y = \begin{cases}c & \text{if } X \leq c \\ X & \text{if } X > c \end{cases}$$
and $$W = Y + s$$
Comment: Thanks for the solution, I bought mathstatica now and copied your solution. But how did you draw the pdf of the censored distribution $W$ ?
Comment: Go to Chapter 2, Section 2.5 C - _Censored Distributions_ of the Rose/Smith book: see Figure 20. Figure 20 plots the distribution of $Y$ in my answer above. I just adapted that for your case (+s). To view the code that generated the figure, click on the little triangle under the diagram, ... |> Fig. 20  ... and the code will appear. If you want the actual code to generate the plot above, let me know and I can send it to you.

Transformation of normal distribution


Why are my fields are out of order when viewing?

Question: I have a content type called 'article'.  I create custom fields and drag-n-drop them in the order I want.  My user fills out the fields in the order that I prefer.  User then clicks SAVE.  Now the fields are out of order when this content type 'article' is being viewed.  When user clicks EDIT, then everything is back in order, just not when viewing.  Why is this and how do I fix it?
Answer: Reordering the fields for the content type only affects the edit/add form. To change the order of how they display (and other things, such as label display/placement) you need to go to Structure -> Content Types -> [Your content type name] -> Manage Display -> Default.
Comment: Excellent! I did not notice the "manage display" setting. duh! :(

Thank you for your help


How to redirect HTTP traffic to HTTPS without using .htaccess file in laravel 5.2

Question: I want to redirect the HTTP traffic to HTTPS without using .htaccess file in laravel 5.2?
How can i do that, Any solution will be appreciated.
Answer: if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off"){
    $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
}

For Laravel 5.2 you can do this:
create new middleware (you can do it by command php artisan make:middleware nameMiddleware, eg. php artisan make:middleware forceSSL
In this middleware (/app/Http/Middleware/nameMiddleware.php) put this:
<?php

namespace App\Http\Middleware;

use Closure;

class nameMiddleware {

    public function handle($request, Closure $next) {

        if (!$request->secure() && env('APP_ENV') === 'prod') {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }

}

Register your middleware in /app/http/Kernel.php
$middlewares = [
...
'\app\Http\Middleware\nameMiddleware'
];

Add the middleware to $routeMiddleware array.
After this, you can add the middleware directly into Route::get('/', ['middleware' => 'nameMiddleware'] ...);
Comment: Thanks brother, your code is running in core php, but i need to run it in laravel where it is not working ?
Comment: You can create a filter:

`Route::filter('f.ssl', function()
{
    if( ! Request::secure())
    {
        return Redirect::secure(Request::path());
    }

});`
Comment: How to create a filter ? can you pleae elaborate
Comment: Brother i am using laravel 5.2
Comment: and there are no filters in laravel 5.2 as far i know
Comment: your answer is also right, but the proper procedure is described here which i have follow and worked.
http://stackoverflow.com/questions/28402726/laravel-5-redirect-to-https


Access callback evaluated on every page

Question: I have a custom module with a menu entry that has a page callback and a access callback. However, every time I visit any page, the access callback is evaluated. Could somebody enlighten me?
function foo_menu() {
  $items = array();

  $items['foo'] = array(
    'page callback' => 'foo',
    'access callback' => 'foo_access_callback',
  );

  return $items;
}

function foo() {
  //...
}

function foo_access_callback() {
  error_log('This gets evaluated on every page.');
  return TRUE;
}

Comment: Confirmed this is happening on a blank installation with just the required core and 'Foo' modules enabled. Only on front end pages though, the callback is _not_ fired for admin pages. Interesting...
Comment: Is your function called exactly `foo_access_callback`? If not, is it possible in naming your function you've inadvertently implemented a system/contrib hook that's being called on every page?
Comment: I've tried renaming it to something else (foo_ac), doesn't help.
Comment: And it's fired 4 times on the '/foo' page.
Answer: Something just dawned on me...if you have a menu on the page that links to the '/foo' page, Drupal will query the access callback to find out if the menu link can be shown.
Since you're not providing a type in your menu item, it will default to MENU_NORMAL_ITEM which will place it in the site's Navigation menu.
I would guess that's what's causing the function to be run at least once on every front end page, but not for the admin pages (where you probably won't have the same menus).
It's definitely what was causing the issue on the test installation I just set up for this.
Comment: I have changed the type to MENU_CALLBACK, but the access callback is still evaluated. I have no link to the menu item anywhere.
Comment: I was thinking along similar lines though.
Comment: I've just done a backtrace and it's definitely coming from the menu module. As soon as I remove the Navigation menu from the sidebar the callback stops getting evaluated. Do you have a link to the site per-chance?
Comment: Quick debugging exercise: install the Devel module and run `dpm(debug_backtrace());` in your access callback. Then you'll be able to see where the function was invoked from
Comment: Even with MENU_CALLBACK: function _menu_check_access ... menu_name (String, 10 characters ) navigation.
Comment: I deleted the menu entry in the menu_link table, cleared the cache and the callback seems to work. Looks like changing the type of the menu entry to MENU_CALLBACK and clearing the cache didn't clear the record in menu_link, so it was still bound to "navigation" menu.
Comment: Ah yeah that makes sense (I think!) Glad you got it sorted
Comment: Does it qualify as Drupal Core bug you think?
Comment: I wouldn't have thought so...from Drupal's point of view either the admin or the module implementer should probably clean up any menu link that's added. I might be wrong though

Access callback evaluated on every page


Solve definite Integral with given substitution

Question: I've been given the following integral
$$\int_a^b f(x) \,dx,$$
where $f(x) = \sqrt{16 - x^2}$ and $[a, b] = [-4, 4]$
I've been given the instruction to solve the definite integral with the following substitution:
$$
x = 4\sin u
$$
Various attempts of mine have failed. Help is very much appreciated.
Comment: It might me more instructive for you if you type in your work.
Comment: @GitGud what do you mean?
Comment: I meant 'it might **be**'. Typo, sorry.
Answer: $$\int_{-4}^4 \sqrt{16 - x^2}\,dx$$
Putting $x = 4 \sin \theta \implies dx = 4 \cos \theta$. And note that $\theta = \sin^{-1}\left(\frac x4\right)$.
Then $x = -4\implies \sin\theta = -1 \implies \theta = -\pi/2$, and $x = 4 \implies \sin\theta = 1 \implies \theta = \pi/2$.
$$\begin{align}\int_{-4}^4 \sqrt{16 - x^2}\,dx & = \int_{-\pi/2}^{\pi/2} \sqrt{16 - 16\sin^2 \theta}\,4\cos
\theta\,d\theta\\ \\
& = 16\int_{-\pi/2}^{\pi/2} \sqrt{1 - \sin^2 \theta}\,\cos\theta\,d\theta \\ \\  \end{align}$$
Now you can use the identity that $1 - \sin^2 \theta = \cos^2\theta$.


css Multiple parents with childs

Question: Currently I have the current HTML:

 text

 text

         text

I want all my header in this class to be white so I made this in CSS:
.row.text-center > h1 h3{
color: #FFFFFF;
}

But the H1 and H3 are still the default colour.
Is this not supported in CSS or am I doing something wrong?
Comment: @Hashem Qolami Your mark is incorrect the child/descendants work, the parents don't.
Comment: It completely matches the question. `I want all my header in this class to be white` this means you want to group the `` and `` which are descendants of the `div.row.text-center`. The question is not about the parent/ancestor. Anyway, you could simply set the color on the `` element itself. All the descendants would inherit that value.
Answer: in your code, you assign at h3 inside h1.
you have to use:
.row.text-center > h1,.row.text-center > h3{
  color: #FFFFFF;
}

Comment: Why do .row.text-center > h1 and .row > h1 h3 work, but does .row.text-center > h1 h3 not?
Comment: if you don't divide rules with a "," it consider all selectors nested.
So  .row.text-center > h1 h3 means the color white is applied at the h3 that is son of h1 that is son of .row.text-center

css Multiple parents with childs


How to statistically distinguish between two types of time series (bimodal vs. not bimodal)?

Question: I have two different types of time series. The first group of series is much more bimodal, and the second group is much flatter. For a given time series, I want to test whether it more likely belongs with the first group or the second group.  I don't really care about the specific values of the time series. It is the shape of the time series that matters and how much of a difference there is between the higher part of the series and the lower part of the series. Are there any specific tests for this? I think ARIMA modeling requires a stationary timeseries, which these are not.
Ones that look like this:

And ones that look like this:
Comment: They look different, but bimodality usually refers to modes in a frequency distributions, not peaks in a (seasonal?) time series. You might find it interesting and possibly even helpful to plot on logit scale, i.e. log[reflectance / (1 - reflectance)].
Comment: Hi Nick, thanks for the help. I suppose I was thinking 'bimodal' if you ignore the time component, and just look at the distribution of the reflectance values, but perhaps that is not correct. Unfortunately, if I plot using logit (with reflectance on the x, and log[reflectance / (1 - reflectance)] on the y), they all look pretty linear unfortunately. Would testing for similarities in the variance of timeseries (like an F test) be advisable?
Comment: The point of a logit scale is that they are more similar in that space, suggesting that distinguishing the two is not necessarily a good idea. What is the underlying physical or biological idea? (I am guessing wildly at data from satellite or drone sensing.)
Comment: I am suggesting logit reflectance versus doy (day of year, presumably). But it is true that logit $y$ does not bend much outside (0.1, 0.9).
Comment: It is studying surface reflectance (from satellite data) over time of ice melting to determine ice breakup dates. It is much easier to see when ice has broken up in the first group of timeseries, but much more difficult to be as confident in the breakup detection in the second group. I'm trying to find a way to flag timeseries that look more like the second set, so that we might be more skeptical of ice breakup dates from those time series if that makes sense.
Comment: So, I'd look for the steepest segment.
Comment: Ah gotcha. They do look much more similar plotting the logit function against doy. So perhaps any distinguishing between the them might require a more arbitrary metric than a statistical test?
Comment: Just saw your steepest segment comment. I am fairly new to statistics (if that isn't clear already!). So Just to clarify. Using logit sort of stretches out different timeseries to the same y axis scale so that they can more easily be compared? And then we could therefore compare the slopes during the breakup period to see if they are similar. Is that the correct way of thinking about it?
Comment: Indeed. I've looked a little at seaice data myself and think in terms or more or less continuous spatial variation within each region.
Comment: Are you looking for break-up date in each year or typical break-up date across a number of years?
Comment: Great, thank you! It is for multiple years. So the first plot is for multiple years of the same area, and the second plot is for multiple years of a different area. The idea is that we are better able to detect breakup in some areas than others. In the full data set, there are over a thousand different areas, so we need a concise way to test for a given area whether or not we are reliably seeing a time series whose shape reflects ice breakup.
Comment: One idea for hunting a breakpoint (change in level, rather than steep slope) is to look for regimes, as in https://stats.stackexchange.com/questions/67571/how-can-i-group-numerical-data-into-naturally-forming-brackets-e-g-income/67586#67586 Presumably you only care about say the warmer 6 months of the year or so.
Answer: You can expand the time series on some functional basis. You can do this for example with the fda package in R. Now each time-series is represented as a vector of numbers. You could try a classification with these coefficient as input.
If its testing, and not classification that you want to do, then first you could model the coefficients of the more stable time-series with some random variable. And once you see a new time-series, you expand it out on the functional basis and check whether the coefficient values is something unlikely to be obtained. This will be multiple comparison.
If you don't want to do multiple comparison, you could do a PCA on the coefficients of the time-series from the class of less changing time-series. Just take the first principle component. Look at the distribution of the eigenvalue for this component. Try to model this with some suitable distribution. Then for a new time-series, expand to the coefficient vector, take an inner product of that with the first principal component vector. You will get a single number. Calculate how unlikely this number is under the distribution you used to model the eigenvalue. If it very unlikely, reject that it is from the class of less changing time-series.


Set default admin order for shop order

Question: I'm looking for a way to sort, by default, shop order in descending order:
edit.php?post_type=shop_order&orderby=date&order=desc

There is a solution for ordering product using default_catalog_ordering_desc (https://stackoverflow.com/a/47629492/858782) but I can't find the equivalent for the shop order.
Thanks
Answer: woocommerce using Wordpress WP_List_Table and in order to modify the order by you can use the following function:
function set_orderby_in_admin($wp_query)
{

    global $pagenow;
    if (is_admin() && 'edit.php' == $pagenow && !isset($_GET['orderby']) && isset($_GET['post_type']) == 'shop_order') {

        $wp_query->set('order', 'DESC'); //You can change it to ASC
    }
}

add_filter('pre_get_posts', 'set_orderby_in_admin', 5);

Test it and working :)
Comment: no problem did you tried to increase the priority ?
Comment: Thank you @kashalo for this code! sadly it is not working, I'm trying to check what can be wrong with my theme.
Comment: The code is ok, sorry, problem came from the plugin "Intuitive Custom Post Order" overriding the sort-ability. Thanks!

Set default admin order for shop order


Como saber se um registro foi adicionado ao banco de dados?

Question: Olá, eu estou trabalhando em um sistema de alertas, quando um dado maior que o normal é cadastrado no banco de dados um alerta tem que aparecer na página em que o usuário estiver navegando. O problema é que eu não sei como checar se um elemento foi adicionado ao banco.
Estou pegando meus dados automaticamente de uma PCD (estação meteorológica), se algum desses dados passar do limite cadastrado pelo ADM, um alerta será mostrado ao usuário.
Tenho as seguintes tabelas no meu banco:
CREATE TABLE PARAMETROS_DE_ALERTAS (
    PRA_ID INTEGER AUTO_INCREMENT PRIMARY KEY,
    PRA_VALOR_MAXIMO INTEGER(5) NOT NULL,
    PRA_VALOR_MINIMO INTEGER NOT NULL,
    PRA_COR_MINIMA VARCHAR(30) NOT NULL,
    PRA_COR_MAXIMA VARCHAR(30) NOT NULL,
    SEN_ID INTEGER NOT NULL
);

Está tabela é o parametro para os alertas, onde será cadastrado o minimo e o máximo da medição vinda da PCD para ela ser um alerta.
CREATE TABLE MEDICOES (
    MED_ID INTEGER AUTO_INCREMENT PRIMARY KEY,
    MED_DADO VARCHAR(10) NOT NULL,
    MED_DATA_HORA_MEDICAO DATETIME NOT NULL,
    API_ID INTEGER,
    SEN_ID INTEGER NOT NULL
);

Está é a tabela de medições, onde guardará os dados vindos da PCD.
CREATE TABLE ALERTAS_CRITICOS (
    ALC_DATA_HORA_ALERTA DATETIME NOT NULL,
    ALC_ID INTEGER AUTO_INCREMENT PRIMARY KEY,
    ALC_VALOR_MEDICAO FLOAT NOT NULL,
    SEN_ID INTEGER NOT NULL
);

O sistema deverá adicionar um registro desta tabela caso o dado da medição seja maior ou menor que os parâmetros. Após que este alerta critico seja cadastrado, o sistema deverá mostrar um alerta ao usuário que esteja navegando em qualquer página de meu site.
O problema é que eu não sei como checar se um registro foi adicionado ao banco.
Comment: Isso, um jeito que eu pensei de realizar essa ação foi de criar um script que verificaria se um alerta critico foi adicionado ao banco de dados de tempos em tempos. Acredito que se eu guardar em uma var qual foi o último id inserido à tabela alertas críticos, e verificar de tempos em tempos se o último registro inserido for > à variável que guardei, ai acionaria o alerta. Acha que isso funcionaria?
Comment: Que tipo de elemento vc se refere ?
Comment: Uma tabela mesmo, por exemplo, vou pegar meus dados de um PCD (uma estação meteorológica), que irá me mandar dados como o nível da água de um rio, se o nível passar do limite cadastrado pelo ADM, deverá mostrar um alerta ao usuário.
Comment: Bota um exemplo na sua pergunta, esse trecho que define o limite.
Comment: Qual linguagem está usando, na aplicação ?
Comment: PHP para conectar ao banco e ajax para controlar as funções do php.
Comment: Como está recebendo esses dados, pode colocar um trecho do código php?
Comment: Ainda não cheguei na parte de integrar meu projeto ao PCD, por enquanto estou adicionando os registros diretamente por código SQL.
Comment: Então, imagino que terá de fazer uma comparação na hora de inserir no banco do tipo if(x > y || x < z){echo "foi adicionado";} algo assim... è tipo iso que procura? Mas pode fazer fazer consultas sql oara verificar...
Comment: Sim, essa parte irá adicionar um registro de alerta critico ao banco de dados, mas eu gostaria que aparecesse um alerta para o usuário que está navegando em qualquer página de meu site, então imagino que eu teria que usar um método que verificaria se um um registro de alerta critico foi adicionado ao banco. Ou quando o sistema adicionar o alerta critico mandar algo que dispare um listener na páginas que irá mostrar o alerta.
Comment: Tipo, se vai ter um script que vai ficar atualizando as informações do PDC,, ou seja esse script terá de ser executado automaticamente, de tempos em tempos, e no momento que o retorno estiver dentro dos parâmetros ele alerta para qualquer usuário em qualquer página, é isso?
Comment: Acho que sim, existem vários meios para se atingir o que vc quer. Acho que um diagrama de blocos, pode de ajudar a decidir o melhor momento de fazer a verificação. Ela pode ser no ato da consulta no PDC, na hora de inserir no banco, ou através de consultas periódicas. O mais importante (eu acho) é vc planejar bem esses passos e ir construindo conforme seu objetivo.
Comment: Sim, muito obrigado MagicHat, agora eu tenho mais ou menos a ideia de como irei fazer isso formulado!
Comment: Talvez, isso ajude ou complique, não é minha intenção,complicar.
https://dev.mysql.com/doc/refman/5.5/en/signal.html
Answer: Voce pode usar uma função de banco para dar esse insert. Dentro dessa função voce faz o INSERT necessario e pode dar um SELECT logo em seguida retornar true ou false para a aplicação saber se foi com sucesso.
Comment: Dependendo do sistema que ele está fazendo, uma `trigger` ao inserir dados na tabela que ele quer resolveria.
Answer: Nicolas, pelo que entendi da sua necessidade, não exste um método que fará tudo o que você precisa, então vou sugerir aquilo que eu faria na sua situação:

Insert do alerta no banco
Read em um arquivo json salvo na sua aplicação
Geraria um array, ou adicionaria no array já existente de alertas
Criar um middleware para toda a sua aplicação que realiza a leitura deste JSON e exibria os alertas no load da página e ou um js na página com um looping infinito que faz essa leitura através da url do json
Excluir os alertas (caso faça parte da sua regra) e salvar esse arquivo após edição

As vantagens de usar json são, você pode editar facilmente o conteúdo (utilizando as funções json_encode e json_decode) e a leitura é extremamente rápida, pois não precisa consultar o banco e não é um volume grande de dados.
Answer: Precisa criar uma api que acessa o banco e poderá fazer chamada a ela via ajax.
Essa api consulta o banco e trás os dados e no get de seu ajax ao receber o callback dessa chamada poderá implementar o alerta
Comment: Sim, mas existe um método que verifica se um registro foi adicionado ao banco de dados?


Recovering data from a poorly-formatted source

Question: I've been given a stack of demographic data to look over by the small nonprofit I work for, though as the original electronic files have been misplaced by a predecessor I'm having to reverse-engineer it from a strangely-formatted hardcopy. The data is currently of the form;

00001
Name
Address 1
Postcode
Etc
00002
Name
Address 1
Postcode
Etc

with each individual a paragraph and each line a field.
While I've managed to scan and OCR the text into Notepad++ as well as strip out the printer's markings and other non-data, I'm struggling to get it transformed into excel (ie each para from the txt forms a new excel row, with lines within each para seperated horizontally into adjacent cells). There are enough entries that copy-pasting them across line by line is infeasible.
Could anyone suggest a better way of doing this?
Comment: Issues like these sometimes require creativity to resolve.  The optimal solution can depend on how much hardcopy you have, how consistently it is formatted, how accurately OCR can perform, whether there are additional data, how redundant the information might be, and much more.  As @Silverfish indicates, the Excel issues are not on topic here (and arguably Excel is one of the last tools you should consider using for this task), but there might be interest in helping out with the overall problem of converting your hardcopy reliably into electronic data--can you supply some specifics?
Comment: I think such a question is only marginally on-topic here - it is straying a bit into the territory of "how to do X in Excel" (or some other software), but the issue of how to deal with poorly formatted data is one that crops up in statistical analysis. When you say "with each individual a paragraph and each line a field", what is splitting the lines? And is there any difference between how lines and paragraphs are separated?
Answer: Assuming you have a regular arrangement of rows, i.e. every set of   four rows should be split across 4 columns, then put your data in one column. The following VBA code: Transpose every 5 or n rows from one column to multiple columns does the job, changing 5 to 4, or the number of lines required. Here is the input and output:

Alternatively, you can use How to convert multiple rows and columns to columns and rows in Excel, which I did not try.


Retrieve Object From Nested List Spring JpaRepository

Question: I do have a repository
public interface GroupRepository extends JpaRepository<Group, Integer> {
}

The Group does have a list of items
private List<Item> items;

Each Item has a position property
private int position;

How can I retrieve a group by knowing the position of an item
  present in one of the lists?

Item.java
public class Item extends PersistedBean{
 private int position;
 private Group group;

 @Column(name = "Position")
  public int getPosition() {
    return position;
  }

  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "GroupId", referencedColumnName = "Id")
  public Group getGroup() {
    return group;
  }
}

Group.java
public class Group extends PersistedBean {
 private int position;
 private List<Item> items;

  @Column(name = "Position")
  public int getPosition() {
    return position;
  }

  @OneToMany(cascade = CascadeType.ALL, mappedBy = "group", orphanRemoval = false)
  public List<Item> getItems() {
    return items;
  }

}

Comment: Could you show your entity classes?
Comment: i edited the question
Comment: So position is unique for all the *items*? Otherwise you will retrieve all the groups having any of their items(position = *X*);
Comment: yes, the position is unique for all
Comment: Have you tried *findByItemsPositionIn(int pos);* ?
Answer: You could add query to your JpaRepository<Group, Integer> repository, something like should work:
@Query("SELECT g FROM Group g " +
       "JOIN g.items i ON i.position IN :p")
List<Group> getGroupsWhenPositionMatchAnyRelatedItem(@Param("p") Integer p);

Comment: This is gr8. I'll mark it as accepted. One more thing. Could here be added a WHERE statement where a Cart could be specified as parameter? Thank you
Comment: Shure you can add where statement, but it is JPQL not SQL, remember.


How to upgrade R in linux Mint?

Question: I am using Linux mint 18.3. I have installed R. My current R version is 3.4.4 But I want to upgrade it to version 3.5.
How can I do it?
Answer: Add an R apt-repository
https://www.r-bloggers.com/how-to-upgrade-r-in-ubuntu-12-04/
It's for an older version, but the process is the same across versions

How to upgrade R in linux Mint?


Linear span- geometric interpretation in $\mathbb R^3$

Question: Prove that Span({$x$})={$ax: a\in F$} for any vector $x$ in a vector space. Interpret this result geometrically in $\mathbb R^3$
My attempt at the first part:
By definition of Span, Span({$x$}) is the set that contains all linear combinations of $x$. So, for any $a\in F$, Span({$x$})={$ax: a\in F$}
I'm confused about the second part. I think it geometrically represents all the points on the $x$-axis.
Am I correct about both the parts?
Comment: Not necessarily: try a concrete example, with $x=(1,1,1)$. Is span($\{x\}$) the $x$-axis?
Comment: The span of $\{x\}$ is equal to the set $\{ax\}$ as you have proved: and this is precisely the set of points that lie on the line through the vector $x$ and the origin.
Comment: The first part is correct btw .
Comment: No. Then Span is all points coplanar with $x$?
Comment: The span is the line through the given vector.
Comment: I don't understand how. Can you please elaborate a bit?
Answer: See any vector space must contain the zero element. The geometrical equivalent of the span of $\{x\}$ is the line passing through $x$ and $0$


What is a line prall?

Question: I am composing a melody for piano in Musescore, and after experimenting on a particular note with various ornaments (i.e. trills, mordents, etc.) I decided to use a 'line prall'. It sounded good, so I Googled it, hoping to find some information about it.
Nothing. Not a single relevant hit for "line prall", nor for "prall". Google has failed me.
What is a line prall (i.e. how does one play it) and are there any notable pieces in which at least one is featured?
Answer: About three years too late for you, but this maybe helpful to others. I have found that pralls are really just the same thing as trill lines. Uppralls do a slide up into the trill notes, and the opposite for downpralls. A prallprall line is exactly the same as a trill line, except I don't think musescore has updated the sound, because all the pralls sound pretty bad in M4. As far as I can tell, it's like the difference between all the pedal lines. They might look different, but they do virtually the same thing.
Hope this helps!
Answer: Could that be another name for upper mordent? Or inverted mordent?

In music, a mordent is an ornament indicating that the note is to be played with a single rapid alternation with the note above or below. (wikipedia).

The precise meaning of mordent has changed over the years. In the Baroque period, a mordent was a lower mordent and an upper mordent was a pralltriller or schneller.

Edit
Here is a portion of the source code of MuseScore (sorry :/), which tells you how MuseScore interprets ornamentation:
    //  articulation type            set of  duration       body         repeatp      suffix
//                               styles          prefix                    sustainp
{ SymId::ornamentTurn,                any, _32nd, {},    { 1,0,-1,0 },   false, true, {} },
{ SymId::ornamentTurnInverted,        any, _32nd, {},    { -1,0,1,0 },   false, true, {} },
{ SymId::ornamentTrill,           baroque, _32nd, { 1,0 }, { 1,0 },        true,  true, {} },
{ SymId::ornamentTrill,          defstyle, _32nd, { 0,1 }, { 0,1 },        true,  true, {} },
{ SymId::brassMuteClosed,         baroque, _32nd, { 0,-1 },{ 0, -1 },      true,  true, {} },
{ SymId::ornamentMordentInverted,     any, _32nd, {},    { 0,-1,0 },     false, true, {} },
{ SymId::ornamentMordent,        defstyle, _32nd, {},    { 0,1,0 },      false, true, {} },// inverted mordent
{ SymId::ornamentMordent,         baroque, _32nd, { 1,0,1 },{ 0 },         false, true, {} },// short trill
{ SymId::ornamentTremblement,         any, _32nd, { 1,0 }, { 1,0 },        false, true, {} },
{ SymId::ornamentPrallMordent,        any, _32nd, {},    { 1,0,-1,0 },   false, true, {} },
{ SymId::ornamentLinePrall,           any, _32nd, { 2,2,2 },{ 1,0 },       true,  true, {} },
{ SymId::ornamentUpPrall,             any, _16th, { -1,0 },{ 1,0 },        true,  true, { 1,0 } },// p 144 Ex 152 [1]
{ SymId::ornamentUpMordent,           any, _16th, { -1,0 },{ 1,0 },        true,  true, { -1,0 } }// p 144 Ex 152 [1]

,{ SymId::ornamentPrecompMordentUpperPrefix, any, _16th, { 1,1,1,0 }, { 1,0 },    true,  true, {} },// p136 Cadence Appuyee [1] [2]
{ SymId::ornamentDownMordent,         any, _16th, { 1,1,1,0 }, { 1,0 },    true,  true, { -1, 0 } },// p136 Cadence Appuyee + mordent [1] [2]
{ SymId::ornamentPrallUp,             any, _16th, { 1,0 }, { 1,0 },        true,  true, { -1,0 } },// p136 Double Cadence [1]
{ SymId::ornamentPrallDown,           any, _16th, { 1,0 }, { 1,0 },        true,  true, { -1,0,0,0 } },// p144 ex 153 [1]
{ SymId::ornamentPrecompSlide,        any, _32nd, {},    { 0 },          false, true, {} }

 // [1] Some of the articulations/ornaments in the excursions table above come from
// Baroque Music, Style and Performance A Handbook, by Robert Donington,(c) 1982
// ISBN 0-393-30052-8, W. W. Norton & Company, Inc.

// [2] In some cases, the example from [1] does not preserve the timing.
// For example, illustrates 2+1/4 counts per half note.

(rendermidi.cpp)
It has the same body as the trill which seems to indicate an excursion of 1 semi-tone up repeated, but I have to say I do not get the prefix/ suffix part, which are different… Wild guess: excursion of two semi-tones before for the line prall? Anyway, this is just MuseScore interpretation…
Comment: Found the correlation using DuckDuckGo ;)
Comment: Except Musescore has an up prall, a down prall, a prall prall, a line prall, and more. I would specifically like to know what a line prall is. Thanks anyway, though.
Comment: Isn't it another way of writing it?

What is a line prall?


Acessar o conteúdo de um iframe via javascript

Question: Eu tenho um documento html com o nome frame.html com o seguinte código:

    <title>frame</title>

    teste

E um outro documento html com o nome index.html:

    <title>index</title>

eu pretendo acessar o conteúdo de dentro do iframe a partir de um script no index.html como por exemplo:
document.getElementById('teste').style.backgroundColor = "#f00";

Answer: Cada janela tem seu document, então o document do iframe é outro. No caso do seu exemplo:
var iframe_document = document.getElementById('frameq').contentWindow.document;

A partir desse document você consegue fazer a alteração de estilo – mas apenas se os dois documentos forem do mesmo domínio, caso contrário há restrições de segurança.
iframe_document.getElementById('teste').style.backgroundColor = "#f00";


How to loop through comments using the Rules module?

Question: I have created a rule (using the Rules module) using Rules Event "After updating existing comment" and some comment fields must be changed.
Loop node:comments is used but nothing happens when component is used to change a field (list_item is considered as Any entity (parameter) to use it in the component). node:comments doesn't work in that case. What can be done?
Answer: How to loop through comments using Rules
Have a look at this rule (in Rules export format, you should be able to import it in your own site if you have the Rules UI enabled):
{ "rules_change_a_comment_field" : {
    "LABEL" : "Change a comment field",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_update" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "An update to some comment has been discovered ... Some more details about this updated comment:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\u003Cbr \/\u003E\r\nComment body (before) = [comment-unchanged:comment-body:value]\u003Cbr \/\u003E\r\nComment body (after) = [comment:comment-body:value]\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\u003Cbr \/\u003E\r\nComment author (before) = [comment-unchanged:author]\u003Cbr \/\u003E\r\nComment author (after) = [comment:author]\u003Cbr \/\u003E\r\n" } },
      { "LOOP" : {
          "USING" : { "list" : [ "comment-unchanged:node:comments" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "drupal_message" : { "message" : "Now processing comment with cid=[list-item:cid] and body = [list-item:comment-body:value] ..." } },
            { "entity_fetch" : {
                "USING" : { "type" : "comment", "id" : [ "list-item:cid" ] },
                "PROVIDE" : { "entity_fetched" : { "comment_fetched" : "Fetched comment" } }
              }
            },
            { "data_set" : {
                "data" : [ "comment-fetched:author" ],
                "value" : [ "site:current-user" ]
              }
            },
            { "entity_save" : { "data" : [ "comment-fetched" ], "immediate" : "1" } }
          ]
        }
      }
    ]
  }
}

In this rule, for the sake of simplicity, I intentionally did not use a Rules Component (I just included my entire Rules logic in a single rule). Here is a summary of what the above rule does:

Rules Event: After updating an existing comment.
Rules Actions: Loop over each of the comments, and perform these actions for each of them:

Show a message on the site (just for demo purpose, to know what the rule is processing).
Fetch entity by id, to retrieve all data about the comment entity being processed in the loop.
Set a data value, to change the author of the comment being processed to the current user (this may seem a bit bizarre, I know, but consider it as just a demo sample, to illustrate you can update EACH comment processed in the loop).
Save entity, for the comment entity being processed in the loop. If you don't perform this action, then I'm pretty sure the updated value won't have been saved in the end (which is probably also what you experienced in your nothing happens).

Disclaimer: there may be more refined (optimized) solutions to get such rule to work, but using the above Rules actions (and meaningful variables ...) should help to understand what's happening if you're not experienced enough with Rules (yet).
Attention: be careful if you import the above rule (and leave it active) ... because this rule really works (and will change all comment authors to the last user who updated any comment).
Plan B
If what's above doesn't help, then something that will help you find the answer to your question, is to have a look at Rules debugging ... Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).
Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your node:comments).
Refer to the (great!) video "Debugging rules configuration" for way more details about these 2 variations.


Estimating coefficients of an interaction in a GLMM

Question: I fitted a Generalized Linear Mixed Model with a Gamma distribution of errors on lme4. I included an interaction between two continuous variables (x:z). How can I estimate the coefficients (beta, Standard Error) of the first variable (x) for different values of the second (z)? I would like to report changes in the slope of x in a paper.
Answer: This is really a general question about linear models. Suppose that your linear predictor is
$$
\eta = \beta_0 + \beta_1 x + \beta_2 y + \beta_3 xz
$$
that is, $\beta_3$ is the interaction parameter.  I think what you mean by "the coefficient of $x$ for different values of $z$" is $\beta_1 + \beta_3 z$, i.e. rewriting the expression as
$$
\beta_0 + (\beta_1 + \beta_3 z) x + \beta_2 z .
$$
In other words, $\beta_1 + \beta_3 z$ gives the expected change in the response (on the linear predictor scale) caused by a 1-unit increase in $x$ at a particular value of $z$.
If you know the variances of $\beta_1$ and $\beta_3$ and their covariance, you can also calculate the variance (and hence standard deviation) of this value. Suppose you have a contrast vector: in this case it would be $c=(0~1~0~z)$, since you're interested in the expression
$$
\beta_1 + \beta_3 z = 0\cdot \beta_0 + 1 \cdot \beta_1 + 0 \cdot \beta_2 + z \cdot \beta_3
$$
then the variance of the expression is $c \mathbf V c^\top$.
Given that you can specify a focal value of z you're interested in, in R code, you would use
z <- ?? ## a focal value
coefs <- fixef(model)
cc <- coefs["x"] + coefs["x:z"]*z
varcov <- vcov(model)
vv <- varcov[c("x","x:z"),c("x","x:z")]
res_var <- c(1,y) %*% vv %*% c(1,z)  ## variance of the result
res_sd <- sqrt(res_var)

Comment: Thanks ! However, I'm trying to do something easier than writing down the formula: I would just write down the betas expressing the relationships between y and x at different levels of z (e.g "while the relationship between y and x is negative at low levels of z (beta=XXXX±XXXX), it gets negative at high levels of z (beta=XXXX±XXXX)". I would like just to estimate those betas and their standard errors. The change is pretty clear from plots, however I would like to add some text.
Comment: I thought that was the question I answered ... just changed y to z to make it match your question better/hopefully make it clearer.
Comment: I'm sorry. I understood later on...
Comment: stack exchange deprecates the use of comments to say "thank you"; if the answer solved your problem, you're encouraged to click the check-mark to accept it ...


Sending Prometheus data to local and remote storage

Question: Having a PI running to monitor internet connectivity locally is good, but it also comes with the drawback of having limited storage, especially when other stuff is running on it, too.
I am looking for a way to store metrics not only locally but remotely, too.
Since the internet monitoring it also running if the internet connection is broken, the transmission of metrics needs to happen even if the internet connection is not working.
Just delayed when the internet connection is back online.
Since the remote_write functionality is discarding after two hours of non-reachability, this is not ideal.
I was thinking about running a cron or something, that syncs the local storage to the remote and then deletes the local copy of the metrics, since I do not need them there.
Maybe Prometheus can not do that and I am just missing something?
Answer: This is described in the documentation
I would make a NAS with some disks and try to configure that as an extra path to store the metrics. Based on your requirements I feel that remote storage is not an option, because you internet doesn't have 24/7 uptime.
Comment: Appreciate the answer, but it does not answer my question. I do not want to buy a whole new NAS and let it running 24/7 just to collect some data, when I already have remote storage available. :)
Comment: What maybe could do is some caching or queuing when the internet is not available. Or make sure you have a backup internet, in a corporate environment a fallback uplink is quite common
Comment: That is what the question is about. What would be a strategy to cache this for some time and sent it when internet is available. Sorry, if that was not clear.


How can I redraw or resize the rectangle in html?

Question: I wanted to redraw and resize the rectangle which is drawn to detect objects. And initially i am able to fetch the data through JSON file and able to draw rectangle based on JSON's x,y,width & height data.
Now I wanted to redraw or resize it. How can i do that?
Approach : Once user press EDIT button all the rectangle bounding box will converts in to dotted box and later as per user requirement, user can access that any particular rectangle & it can be resize or re drawable.Once it is done user has to press the save button and whatever new changes we made it automatically reflect to same json file with new Json data.
Here is the fiddle for drawing an object.
Json file format:
{
    "Frame_count":1,
    output:[
        {
        "Objects_classname":"car1",
            "x_val":82.9883,
            "y_val":197.56245,
            "width":316.03088,
            "height":197.45451
        },

        {
        "Objects_classname":"car2",
            "x_val":522.4823,
            "y_val":170.47263,
            "width":64.66687,
            "height":61.78085
        },

        ],
        "Total_objects_detected":2,
},
{
    "Frame_count":2,
    output:[
        {
        "Objects_classname":"car1",
            "x_val":78.9991,
            "y_val":189.48058,
            "width":327.41028,
            "height":198.80226
        },

        {
        "Objects_classname":"car2",
            "x_val":506.45404,
            "y_val":170.87161,
            "width":67.57983,
            "height":52.28577
        },

        ],
        "Total_objects_detected":2,
}

In image you see the rectangle boxes around pedestrian
Comment: Let me know if I am missing anything in above question
Comment: you assingment of new values is probably wrong as the rectangle is drawn from objetos in actualizar not from objetoActual
Comment: ya you are right but how can i update it?
Comment: This is my code which gets the data from JSON and draws a Rectangle : https://jsfiddle.net/kypq28uz/1/
Answer: try

Click the button to send JSON Size

<button type="button" onclick="newSize()">new size</button>

Comment: Here main problem is that First I m drawing a rectangle using JSON data and later I wanted to edit it. So How can I select particular rectangle first, if I am able to select I can resize it.
Comment: check this link :(https://jsfiddle.net/tetut91e/74/)  Here I am giving rectangle height and width in CSS but in my case It is coming from JSON file so how can I apply same mechanism to my code?
Comment: How can I put JSON's x,y,w,h instead of #main in above jsfiddle?
Comment: not sure how your fiddler works with pure js looks like some library is used. However changed the code example
Comment: In example code I am not able to resize or drag using mouse events
Comment: no that's done through your javscript library which makes the code aware of $


If $x$ is the limit point of a finite union then is $x$ a limit point of some set in the union?

Question: Background
This question arose from the following problem:
If $B_n=\bigcup_{i=1}^{n}A_i$ then prove that $\overline{B_n}=\bigcup_{i=1}^n \overline{A}_i$ for $n=1,2,3...$. By $\overline{X}$ we mean the closure of $X$, by $X'$ we mean the set of limit points of $X$ and by $N_r(x)$ we mean the neighborhood of $x$ of radius $r$.
Question and Attempt
I have done this problem before by induction but today I wanted to try doing it directly.
Here is what I did:
We have to show that $$\left( \bigcup_{i=1}^n A_i \right)\bigcup\left( \bigcup_{i=1}^n A_i \right)'= \bigcup_{i=1}^n \left(A_i \cup A'_i \right) .$$ If $x \in \left( \bigcup_{i=1}^n A_i \cup A'_i \right)$ Then it is not too hard to show $x \in \left( \bigcup_{i=1}^n A_i \right)\bigcup\left( \bigcup_{i=1}^n A_i \right)'$. On the other hand though, suppose $x \in \left( \bigcup_{i=1}^n A_i \right)\bigcup\left( \bigcup_{i=1}^n A_i \right)'$ and consider the case when $x \in \left( \bigcup_{i=1}^n A_i \right)'.$ Then for all $r$, $N_r(x) \bigcap \left(\bigcup_{i=1}^n A_i \right)$ is not empty (in fact it contains infinitely many points since $x$ is a limit point). So for any $r$, this intersection contains infinitely many points of some $A_j$  ($1 \leq j \leq n$).
How do we then conclude that $x$ is a limit point of some $A_j$, bearing in mind that as $r$ is changed, $N_r(x)$ may intersect a different set $A_k$?
Answer: Yes.
Suppose not. Let $x$ be a limit point of $ A\cup B$, but not a limit point of $A$ nor $B$. Then exist $r_1,r_2>0$, s.t. $B_{r_1}(x)\setminus \{x\}\cap A =\emptyset$ and $B_{r_2}(x)\setminus \{x\}\cap B =\emptyset$. Then take $r=\min \{r_1,r_2\}>0$, we get  $B_{r}(x)\setminus \{x\}\cap (A\cup B) =\emptyset$. Contradiction.
This does not generalize to infinite union. For example, $0$ is a limit point of $\bigcup [\frac{1}{n},1]$, but it's not a limit point for any of them.
You can also prove the theorem you want by using closure of $E$ is the smallest closed set containing $E$. Hence $\overline{B_n} \subset \bigcup_{i=1}^n \overline{A}_i$ since finite union of closed set is closed. You can easily get the other side inclusion.
Answer: Let it be that $x\notin\bigcup_{i=1}^{n}\overline{A}_{i}$.
Then for each
$j\in\left\{ 1,\dots,n\right\} $ there is some $r_{j}>0$ such that
$N_{r_{j}}\left(x\right)\cap A_{j}=\emptyset$.
For $r=\min\left\{ r_{1},\dots,r_{n}\right\}>0$
we then find: $N_{r}\left(x\right)\cap\left(\bigcup_{i=1}^{n}A_{i}\right)=\emptyset$.
This allows the conclusion that $x\notin\overline{B}_{n}$.
Proved is now: $x\in\overline{B}_{n}\Rightarrow x\in\bigcup_{i=1}^{n}\overline{A}_{i}$.


Issues declaring variable name in C++

Question: I'm having a weird issues declaring variable names in C++. When I tried declaring the two variables;
double hoursWorked;
double hourlyWage;

the variable name (hoursWorked, hourlyWage) would change colours in my IDE and the program would not compile, citing the names as "unused variables". This issue only happens with those two words when used as identifiers for 'double' variables. I checked the reserved word checklist and nothing seems out of the ordinary in my naming conventions.
I should also note that the variable name will be white (good) right until I type the final 'd' in 'Worked' and the final 'e' in 'Wage', at which it turns blue. This leads me to believe I'm trampling on some kind of keyword, since the "main" in the programs main function is of the same blue colour.
Any help would be appreciated!
Comment: It's really not a problem.  You have a program that declares two variables and does nothing.  Your IDE is letting you know this might be a problem in realtime.  You haven't finished your program yet.  You haven't compiled.  Unless it's set to treat warnings as errors, this will be fine.  Also, please keep your language clean in here.
Comment: @programBABYlover Put the code in the question, not in comments.
Comment: You should probably show us your code as a minimal, complete, verifiable example (http://stackoverflow.com/help/mcve). Also since this seem to be dependent on the behavior of your IDE you should tell which one you use (and which compiler you use). Unused variables are perfectly legal in C++ so that should only be a compiler warning.
Comment: The error is quite explicit about the variables are unused.  So use them before you try to compile.  Maybe assigning a value will help?
Comment: I tried to use them and no error occurred. please show us your code.
Comment: 'Unused variables' is not a compilation error and does not prevent compilation. It is a warning.
Answer: No errors with this code. Please bear in mind that your unused variables are not errors, simply warnings and your program will still compile and run correctly regardless.
#include <iostream>

int main()
{
    double hoursWorked, hourlyWage;
    hoursWorked = 2.4;
    hourlyWage = 3.5;

    std::cout << "Hourly wage holds: " << hourlyWage << "\n";
    std::cout << "Hours worked holds: " << hoursWorked << "\n";
    return 0;
}

Issues declaring variable name in C++


Erro ORA-12571 encountedred em Serviço do Windows

Question: Tenho um sistema em C# rodando como serviço do windows, com Windows Server 2012R2.
Eventualmente quando o serviço tenta se comunicar com o banco de dados(para realizar uma consulta ou fazer um insert, por exemplo) a comunicação entre o servidor windows e o host onde está rodando o banco de dados "caí" e então é gerado o erro oracle ORA-12571.
Já sabemos que isto não é um problema no banco de dados, mas na comunicação entre os host.
Para resolver, simplesmente rodo novamente o serviço e tudo acontece sem problemas.
O pior é que o registro de eventos do windows não captura nada que possa nos ajudar ou dá uma pista sobre o problema.
Se precisarem de mais detalhes, é só pedir!
Desde já agradeço.
Comment: Talvez seja o caso de implementar um exception handling no ponto onde o erro ocorre e tentar uma reconexão?
Answer: No seu sqlnet.ora
Procure por --> SQLNET.AUTHENTICATION_SERVICES= (NTS)
Altere para --> SQLNET.AUTHENTICATION_SERVICES= (NONE)
Comment: Prezado, muito obrigado pelo retorno, vou testar neste momento e retorno o resultado assim que souber.
Comment: Obrigado Otto! Até o momento não tivemos mais ocorrências deste erro :)


Set Azure FileShare Size - ARM Template

Question: I'm looking for a way to set the quota size (ex, 100gb) for the file share I am deploying using Azure ARM Templates. As of now when I deploy it defaults to 5TB which is not ideal. Ideally I would just add a setting to my template.json or parameter.json files that would adjust this setting but I haven't come across anything yet. I'd appreciate any help/guidance on this.
<code>
{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "188.8.131.52",
    "parameters": {
        "location": {
            "type": "string"
        },
        "storageAccountName": {
            "type": "string"
        },
        "fileShareName": {
            "type": "string",
            "minLength": 3,
            "maxLength": 63
        },
        "fileShareName1": {
            "type": "string",
            "minLength": 3,
            "maxLength": 63
        },
        "fileShareName2": {
            "type": "string",
            "minLength": 3,
            "maxLength": 63
        },
        "accountType": {
            "type": "string"
        },
        "kind": {
            "type": "string"
        },
        "accessTier": {
            "type": "string"
        },
        "supportsHttpsTrafficOnly": {
            "type": "bool"
        }
    },
    "variables": {},
    "resources": [
        {
            "name": "[parameters('storageAccountName')]",
            "type": "Microsoft.Storage/storageAccounts",
            "apiVersion": "2018-02-01",
            "location": "[parameters('location')]",
            "properties": {
                "accessTier": "[parameters('accessTier')]",
                "supportsHttpsTrafficOnly": "[parameters('supportsHttpsTrafficOnly')]"
            },
            "dependsOn": [],
            "sku": {
                "name": "[parameters('accountType')]"
            },
            "kind": "[parameters('kind')]",
        "resources": [
        {
            "type": "Microsoft.Storage/storageAccounts/fileServices/shares",
            "apiVersion": "2019-04-01",
            "properties": {
                "shareQuota": "100"
            },
            "name": "[concat(parameters('storageAccountName'), '/default/', parameters('fileShareName'))]",
            "dependsOn": [
                "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]"
            ]
        },

        {
            "type": "Microsoft.Storage/storageAccounts/fileServices/shares",
            "apiVersion": "2019-04-01",
            "properties": {
                "shareQuota": "100"
            },
            "name": "[concat(parameters('storageAccountName'), '/default/', parameters('fileShareName1'))]",
            "shareQuota": "100",
            "dependsOn": [
                "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]"
            ]
        },

        {
            "type": "Microsoft.Storage/storageAccounts/fileServices/shares",
            "apiVersion": "2019-04-01",
            "properties": {
                "shareQuota": "100"
            },
            "name": "[concat(parameters('storageAccountName'), '/default/', parameters('fileShareName2'))]",
            "shareQuota": "100",
            "dependsOn": [
                "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]"
            ]
        }

    ]
}
    ],
    "outputs": {}

}

</code>
Answer: The ARM resource for creating file shares supports providing a quota size using the shareQuota property, this value is in GB.
<code>{
  "name": "string",
  "type": "Microsoft.Storage/storageAccounts/fileServices/shares",
  "apiVersion": "2019-04-01",
  "properties": {
    "shareQuota": "100"
  }
}
</code>
Comment: Thanks for the response. I tried adding the "shareQuota" property to my template.json file and I get the following error - "The request content was invalid and could not be deserialized: 'Could not find member 'shareQuota' on object of type 'TemplateResource'. Path 'properties.template.resources[0].resources[0].shareQuota'
Comment: Can you show the whole template?
Comment: added it above to the initial question
Comment: My apologies, I forgot to remove some previous settings from my code above when I posted it. I was able to get it working by adding the setting you mentioned. I have the following for each share:                                                                                {
            "type": "Microsoft.Storage/storageAccounts/fileServices/shares",
            "apiVersion": "2019-04-01",
            "properties": {
                "shareQuota": "100"
            },

Set Azure FileShare Size - ARM Template


checking collinearity in a glm

Question: I'm new to checking the VIF value for a glm model so I just want to make sure i"m understanding this correctly.
I have 4 predictors for my count model and the model looks like this:
model1<-glm(Number~dts+dss+dtn+dsn, family=poisson, data=birds)

I then checked the collinearity on the model using the car::vif function and got this output;
dts         dss         dtn       dsn
2.261840    2.281326    2.016644  2.073556

so from my understanding and reading online, due to all 4 being below vif of 3, then there is no multicollinearity and I can now proceed with finding the "simplest" model.
After I did this, i then performed the "summary" function, and found 3 out of the 4 to be significant, the model would then become;
dts, dss, dsn

Would that therefore mean that my best model would be;
glm(Numer~dts+dss+dsn, family=poisson, data=bird)

or am i completely misunderstanding the car:vif function
Comment: What is your interest in multicollinearity or even in building this model?
Comment: I'm trying to see if any of those 4 predictors influence the number of birds being present. So i wanted to make sure those 4 predictors did not have any collinearity
Comment: Well then why not test the full model against a null model with just an intercept?
Answer: From what you describe, there's no reason to abandon the full four-predictor model.
Unless it's extreme, VIF isn't much of a criterion for evaluating a model. It describes the correlations among the coefficient estimates. A high VIF just means some imprecision in those estimates. See this page among many other for discussion on implications of VIFs. Things like goodness of fit and predictive performance are much more important.
There's little to be gained and potentially a lot to be lost if you remove the nominally "insignificant" predictor. There's a problem even in ordinary least-squares regression with omitted-variable bias: if you omit from a model any predictor that is correlated both with outcome and with another predictor, then the estimates of the coefficients for the retained predictors will be biased. In other types of regressions like logistic regression, you can have this problem even if the omitted predictor isn't correlated with the retained predictors.
So I don't see much reason to omit dtn from your model.

checking collinearity in a glm


limit of a sequence relative to a norm

Question: Assume we have some vector space $ V$ and a norm $ ||•|| $.
If I hve a sequence $ v_n $  that converge to a vector relative to the norm, that is, $ lim ||v_{n}-v || =0 $.
How can I show that $lim ||v_{n}||=||v|| $?
I tried to use the squeeze theorem and wrote:
$ ||v_n||=||v_n -v+v|| \leq ||v_n-v|| + ||v || $
This gives me the the limit is smaller or equals to ||v||.
What can I do in order to show the other direction?
Comment: Equivalently, the "reverse triangle inequality" tells you that
$$
\|v_n - v\| \geq |\,\|v_n\| - \|v\|\,|
$$
Comment: Use the same trick: $\|v\| = \|v - v_n + v_n\| \leq \|v - v_n\| + \|v\|$
Comment: @BenGrossmann I need something smaller than $ ||v_n|| $
Answer: From $\|v_n\| \leq \|v_n-v\|+\|v\|$ one has $\|v_n\|-\|v\| \leq \|v_n-v\|$, and from $$ \qquad \|v\| = \|\!-\!v\| = \|(v_n-v)-v_n\| \leq \|v_n-v\|+\|v_n\|$$ one has $-\|v_n-v\| \leq \|v_n\|-\|v\|$. Thus $$-\|v_n-v\| \leq \|v_n\|-\|v\| \leq \|v_n-v\|$$ and then taking the limit as $n \to \infty$ we conclude that $\lim_n (\|v_n\|-\|v\|) = 0$.
Comment: That's great. Thanks!

limit of a sequence relative to a norm


All jQuery mobile events firing twice

Question: I have a very simple use case on my index page.

For some reason this event is firing 2 times. Now I am sure I haven't binded another event on the body tag as this is the first page. I have tried other simple events also like touchstart etc. They all are firing twice. What am I doing wrong ?
Update :-
I have modified the answer I marked as correct in the following way and it worked. The events on this page are not firing twice.

Comment: @Floradu88 : You are right sorry for that. I was trying out a few solutions but haven't got the exact answer yet. But I will mark the one I am working on .
Comment: You should mark only correct answers, do not mark an answer which is not correct
Comment: Yes, but the one I have marked correct worked with some changes to it. I will update the answer accordingly.
Answer: There are few ways of avoiding this problem. Like CodeJack told you this is a know issue but it is not an error, mainly because of the jQM unique way of handling pages.

Easiest one is to unbind an event before binding it again, like this:
$("body").off().on("swipeleft", function(event) {
    alert('hello');
    /*window.location.href = "html/first.html";*/
});

In case you have other events bound to same object use this:
$("body").off("swipeleft").on("swipeleft", function(event) {
    alert('hello');
    /*window.location.href = "html/first.html";*/
});

There is an alternative to using event bind/unbind, live/die and on/off. Instead of unbinding before you bind it again use jQuery event filter, it can be used to identify if event is already been bind. Don't forget to download it from link posted below (it is not a standard part of jQM).
http://www.codenothing.com/archives/2009/event-filter/
This is my usage example:
$('#carousel div:Event(!click)').each(function(){
    //If click is not bind to #carousel div do something
});

I am using each because my carousel div has many inner blocks but principle is the same. If #carousel inner div elements don't have click event add them that event. In your case this will prevent multiple event binding.

Additional solutions can be found here.
Answer: You should try using document ready event to attach events to body. Also you may want to attach an event only once to body.
$(document).ready(function(){
    $("body").off().on("swipeleft", function(event) {
        alert('hello');
    });
});

In case you have other events bound to same object use this:
$(document).ready(function(){
    $("body").off("swipeleft").on("swipeleft", function(event) {
        alert('hello');
    });
});

Answer: This is known issue...i found it to avoid by moving the js code inside  tag..i donno the reason..but that avoided the problem...

All jQuery mobile events firing twice


Rails: Dynamic Select with Active Record

Question: I need to create a dynamic SQL select statement to get the city, state combination from a table called Metros with the least distance from a set of passed in GPS coordinates. Note the set of passed in GPS coordinates are variables that will pull from a list. In order to calculate the distance I need to be able to pass in a latitude and longitude, and using the the haversine formula, calculate the distance between the present row and all 291 cities in the table Metros, then select the minimum City,state.
In rails the issue I am running into is how to properly create the select statement with the Metros table to allow for passing in the variable GPS coordinates but also using Active Record instead of conventional SQL.
At present, this is how far I have gotten:
    Metros.select(
        "major_city
        , major_state
        ," haversine(row[latitude], row[longitude], lat2, long2)" as 'distance'")
           .group("major_city,major_state").limit(1).order('distance')

row[latitude], row[longitude] are the passed in variable latitude and longitude (the present row I am comparing all 291 cities/states GPS coordinates in the Metros table and need to select the one with the least distance outputted by the Haversine function). As for lat2, long2, they need to refer to the latitude and longitude columns in the Metros table.
In building this query I am unaware of how to input the Haversine function as well as pull those records from the database with Active Record and calculate.
Is there a better way to do what I am trying to do?
Answer: You should implement haversine as a SQL function and then call in ActiveRecord like so:
Metros.select("major_city, major_state, haversine(?, ?, lat, long) as 'distance'", lat, long).
  group("major_city,major_state").
  limit(1).
  order('distance')


ruby on rails 5 server-side CSV validation ERROR

Question: In my lib/csv_validation.rb file I got my validate method:
def self.validate(file, delimiter, columns)
  return false unless File.exist?(file)
  content = File.read(file, encoding: 'utf-8')
  return false unless content.valid_encoding?
  content.each_line do |line|
    return false if line.count(delimiter) < columns - 1
  end
  true
end

when I send a CSV file via ajax post request I get the following error:
Started POST "/students/import" for 127.0.0.1 at 2017-12-20 01:03:43 +0100
Processing by StudentsController#import as */*
Parameters: {"file"=>#<ActionDispatch::Http::UploadedFile:0x007fd0a228ca38 @tempfile=#<Tempfile:/tmp/RackMultipart20171220-4516-or6qi3.csv>, @original_filename="students_fail.csv", @content_type="text/csv", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"students_fail.csv\"\r\nContent-Type: text/csv\r\n">}
Completed 500 Internal Server Error in 19ms (ActiveRecord: 0.0ms)

TypeError (can't convert ActionDispatch::Http::UploadedFile to IO (ActionDispatch::Http::UploadedFile#to_io gives Tempfile)):

app/models/student.rb:114:in `exist?'
app/models/student.rb:114:in `import'
app/controllers/students_controller.rb:50:in `import'
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.text.erb
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.text.erb (0.4ms)
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.4ms)
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.6ms)
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb (14.4ms)
DEPRECATION WARNING: Accessing mime types via constants is deprecated. Please change `Mime::HTML` to `Mime[:html]`. (called from acceptable_content_type? at /var/lib/gems/2.4.0/gems/web-console-2.3.0/lib/web_console/middleware.rb:58)

I was searching for can't convert ActionDispatch::Http::UploadedFile to IO but I just find something like can't convert ActionDispatch::Http::UploadedFile into String.
I am not sure how to handle this error or where I can find someone with the same problem.
sorry for my bad english and thx for help.
Answer: You'll want to use the ActionDispatch::Http::UploadedFile#tempfile method.
Documented here.
So you can call it like this:
File.read(file.tempfile, encoding: 'utf-8')
That will allow the object to transform to an actual file as opposed to an ActionDispatch object.
See this SO Article: Reading in file contents rails


How many assists did Pele make for Brazil?

Question: Someone asked "how many assists did Maradona make for his national team" (Argentina)? and the answer was "National team assists (including u-20 assists) 33+22 = 55.".
Therefore, as a small part of the GOAT debate I would like this compared to Pele.
How many assists did Pele make for Brazil?
Comment: At the time of his career, assists weren't officially recorded ...
Answer: There are many people claiming at the time Pelé was playing many of his matches werent recorded so it's impossible to know.
However, there are also many well known soccer websites claiming assist statistics for particular sections of his career, such as the world cup, which were likely all recorded in tv and can be counted.
For all the world cup editions he played in, it's stated that he scored 10 assists
Top 5 players with the highest numbers of assists in the FIFA World Cup
List of international goals scored by Pelé (it also mentions World Cup assists)
Transferkmarkt which is several times mentioned in sports networks and media mentions 8 assists in Copa Libertadores and international cup Pelé assists in Copa libertadores and international cup
This verified Twitter account and other soccer website news claim Pelé had
47 assists in Brazil national team . They dont clarify however if it includes friendly unofficial matches or not, since this figure conflicts another.
Neymar has now surpassed Pelé in Brazil
This other source claims 18 assists in New York Cosmos in 1976
Pelé assists in 1976 in Cosmos
So, I dont have the full detail of how all Pelé assists were obtained, but spanish Wikipedia claims 305 (69 in first division, 192 in regional division, 11 for international cup and 33 in national team) . Pelé assists spanish Wikipedia  , and this figure equals the figure given in this english Quora answer which adds up to the same number but with a different breakdown (245 assists in 656 games for Santos; 27 assists in 64 games for New York Cosmos; 33 assists in 92 games for Brazil.) How many assists did Pelé have
Even though this last source isnt considered reliable and it's unsourced, considered both different breakdowns, by different persons, in different languages (one by clubs and the other by tournaments) add up to the same number, and in the first case the figure it's a breakdown reviewed by many, I think it's needed to mention it and the best answer we can have up to today.


javascript check if string contains any symbols

Question: I have the following set of symbols:
var a = '|\/~^:,;?!&%$@*+';

How can I check is the following string contains any of those symbols?
var b = 'avguybdf';

Comment: with a regular expression
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Comment: Duplicate [javascript code to check special characters](http://stackoverflow.com/questions/11896599/javascript-code-to-check-special-characters)
Answer: As suggested, regular expressions will work.
b.match(/[|\\/~^:,;?!&%$@*+]/);

EDIT: I originally used the method here https://stackoverflow.com/a/6969486/2044733 to escape the string but because of the grouping, only the backslash character needs to be escaped.
The "/" at the beginning and end of the string are the delimiters for regular expressions in javascript, and "[]" are used to group the characters. In case you're wondering how this works.
Answer: Use RegEx
Check the how to use regex @ Javascript RegEx
Answer: Try one of the following examples that use regular expressions:
http://www.webdeveloper.com/forum/showthread.php?264705-Best-way-to-check-for-multiple-characters-in-a-string
http://tjvantoll.com/2013/03/14/better-ways-of-comparing-a-javascript-string-to-multiple-values/
Answer: Use RegEx. You can use test() or exec(). Read more here: http://www.w3schools.com/jsref/jsref_obj_regexp.asp