Nice book on geometry to gift an undergraduate in mathematics

Question: I would like some suggestions on a nice book on geometry to gift an undergraduate. I'm not searching for something that is common: I need something new and exciting. Suggestions?
Comment: There are better gifts for an undergraduate than a book on mathematics :)
Comment: I am not exactly sure what an undergraduate is - I don't know the American education system that well, but I like "The symmetries of things" by Conway et al.
Comment: @LordSoth: Glen Livet 25?
Comment: @AsafKaragila I would take it for sure, but an undergrad would waste it. Heineken $10^3$-pack would be a better option.
Comment: @LordSoth: I wouldn't touch Heineken with a poking stick, even before my undergrad years. But my Glen Livet 18 made it through my undergrad without worries, with only the occasional drink.
Comment: @AsafKaragila Haha. I am curious as to how did you manage not to devour the entire bottle during one of those heartache days (almost sure to happen in 4 years of undergrad). I commend your command on your ethanol.
Comment: @LordSoth: (1) Three years of undergrad; (2) Cheap arak, and homemade lemoncello with insane proof strength. Also, lots of beer. Great scotch is saved for great occasions.
Answer: I love this one. It is one of the most stimulating books on geometry that I have ever read: it is strikingly innovative and really enjoyable (also, it does not require a particularly advanced background).
From the book description:

New Horizons in Geometry represents the fruits of 15 years of work in
  geometry by a remarkable team of prize-winning authors—Tom Apostol and
  Mamikon Mnatsakanian. It serves as a capstone to an amazing
  collaboration. Apostol and Mamikon provide fresh and powerful insights
  into geometry that requires only a modest background in mathematics.
  Using new and intuitively rich methods, they give beautifully
  illustrated proofs of results, the majority of which are new, and
  frequently develop extensions of familiar theorems that are often
  surprising and sometimes astounding. It is mathematical exposition of
  the highest order.
The hundreds of full color illustrations by Mamikon are visually
  enticing and provide great motivation to read further and savor the
  wonderful results. Lengths, areas, and volumes of curves, surfaces,
  and solids are explored from a visually captivating perspective. It is
  an understatement to say that Apostol and Mamikon have breathed new
  life into geometry.
Comment: Wow! Thank you very much! This is really appropriate! :)
Comment: You're welcome.
Answer: I'll recommend Geometry Revisited by H. S. M. Coxeter and S. L. Greitzer.
Answer: Green Lion Press's:

Euclid's Elements: All Thirteen Books in One Volume

or

The Bones: A handy where-to-find-it pocket reference companion to Euclid's Elements

The latter is very unique; it's all the propositions and diagrams, but without the detailed proofs.
Answer: Another very nice book is Indra's pearls The vision of Felix Klein with a preview at google.
Comment: Avatamsaka Sutra
Comment: Yeah @Andrew Of course you knew the Hua-yen Sutra with a nice illustration [here](http://books.google.com/books?id=kC5kdUirHHoC&pg=PR18). Cheers!


Allocating specific logical cores to specific processes exclusively, Windows, C++

Question: If possible I do wish to allocate a logical core to a single process exclusively.
I am aware that Winbase.h contains Get/SetProcessAffinityMask and SetThreadAffinityMask.
I can get all processes running when the specific process is started and set their affinities to other logical cores, however, I do not want to check all processes in a periodic manner, for instance in order to deal with processes launched after the initiation of my process.
Furthermore there will be other processes which need to use specific logical cores only exclusively (no other process shall waste resources on that logical core). For instance my process shall run on core 15 but another shall run only on core 14.
Is there a better and more permanent way to allocate specific logical cores to specific processes than above mentioned Get/SetProcessAffinityMask scheme.
Comment: Why do you think you need to do this?
Comment: Duplicate of https://stackoverflow.com/q/40453645/103167
Comment: @1201ProgramAlarm, why I do need this is less about timing and computer science and more about contracts and customer demands.
Answer: Windows is not a real-time operating system. Windows is designed to do preemptive multitasking with isolated processes, like basically any other modern desktop OS. A process is not supposed to just lock out every other process from a particular core, therefore, there is no API to explicitly do so (at least I'm not aware of one). It's up to the OS scheduler to decide which threads get to run when and where. That's the whole idea. You can use thread priorities to tell the scheduler that certain threads should be given a chance to run over others. You can use affinity masks to tell the scheduler which cores a thread can be scheduled to. You can even set a preferred core for your thread. But you don't get to schedule threads yourself.
Note that there's apparently a way to get something a bit like what you're looking for to work on Linux (see this question for more). I don't think similar possibilities exist on Windows. Yes you could try to hack together some solution based on a background task that continuously monitors and adjusts the priorities and affinity masks of all the threads in the system to approximate the desired behavior (like the person in the question linked by Ben Voigt above has apparently tried, and failed to achieve). But why would you want to do that? It goes completely against the very nature of everything an OS like Windows is designed to do. To me, what you are asking sounds a lot like what you're really looking for is a completely different kind of operating system, or maybe even no operating system at all. Boot the CPU straight into your own image and you get to drive all the cores in whatever way you fancy…


Como apresentar somente valores pares e impares com três variáveis em C?

Question: As minhas variáveis são :
    int codigo; --> Sendo esta variável para o switch
    int numero1,numero2,numero3;

O usuário irá entrar com três variáveis :
         printf("Digite o primeiro numero inteiro: ");
         scanf("%d", &numero1);
         printf("Digite o segundo numero inteiro: ");
         scanf("%d",&numero2);
         printf("Digite o terceiro numero inteiro: ");
         scanf ("%d", &numero3);

Após isto, eu preciso fazer com que o programa verifique em cada variável, quais são seus números pares e impares.
Por exemplo, o usuário na primeira variável chamada numero1 digita o número 20, com isto, o programa terá que percorrer até chegar ao número 20 e mostrar quais números foram pares e impares.
Depois o usuário digita na variável numero2, o número 19, e novamente irá se fazer a verificação anterior.
Por fim, o usuário digita na variável numero3, o número 30 e novamente a mesma verificação.
Estou usando um switch, pois o usuário terá outras opções também. Mas como posso fazer isto então ? Usando um for junto com um do-while até conseguir pegar todos os números e fazer a verificação de quais são pares e impares ?
Answer: Não sei muito sobre C, e não sei se entendi corretamente a pergunta (não posso fazer comentários ainda então não pude perguntar, desculpa )
Fiz esse código para mostrar os números pare, eu normalmente utilizaria apenas 1 variável para isso, mas vc falou que precisava de 3 então resolvi fazer uma função para mostrar os pares dela.
caso queira que o programa liste e separe os pares dos impares, avise que eu modifico
#include<stdio.h>

int main (void){
    int numero1;
    int numero2;
    int numero3;
    int count;

    void Par(int valor){
        for(count=1 ; count <= valor ; count++){
            if (count % 2 == 0){
                printf("%d \n", count);
            }
        }
    }

    printf("Digite o primeiro numero inteiro: ");
    scanf("%d", &numero1);
    Par(numero1);
    printf("Digite o segundo numero inteiro: ");
    scanf("%d",&numero2);
    Par(numero2);
    printf("Digite o terceiro numero inteiro: ");
    scanf ("%d",&numero3);
    Par(numero3);

}

Comment: Obrigado pelo código, ele funcionou, só modifiquei a sua resposta por que o método estava dentro do main, fazendo com que desse erro.


Why would a Image Hosting website, such as Imgur, use AWS EC2 instances over S3 buckets for uploads?

Question: I was reading a Q&A with the creator of Imgur, and he went into detail explaining the server infrastructure that Imgur runs on. Here's a small quote from what he had to say:

Most of the clusters use c1.xlarge instances. The upload cluster handles all uploads and image processing requests, like thumbnails and resizing, and each instance is a huge cluster instance, cc1.4xlarge.

I understand images don't take up much space, but why even go this route? Especially, considering the significant cost different.
If you want to read the whole Q&A, you can check it our here. I found it quite interesting.
Comment: 1) The keyword is the image **processing** which takes a fair bit of CPU power, especially when you do it at scale. - 2) Large customers won't pay retail so their economics are different too.
Answer: S3 mainly offers exceptionally high durability and very low administration overhead. The service itself is not really that cheap (especially when it comes to serving requests), but at most scales the labour cost of managing alternatives blow any savings out of the water. However, at very large scales the savings start to outweigh the management overhead.
For example:
GET requests on S3 cost $0.004 per 10,000 requests.
A T2.micro can do about 180 Mbits/s and costs $0.013/h. Assuming a 500kB image size (4000 kbits), that's about 46 images/s. Assuming you can saturate that instance (which a large scale image sharing service presumably could), that's about 165k requests/hour.
So for a T2.micro it would cost you $0.013/h vs. $0.066 on S3. In practice you might hit other bottlenecks on a T2.micro so S3 would probably end up slightly ahead at this scale.
However, if you take a c4.8xlarge (with 10Gbit networking) it would cost $1.763/h. With that you could serve about 2620 images/s, or around 9.4m/hour. That would cost you $3.76/hour on S3.  Add reserved instance discounts, etc. and the difference would get even bigger.
On top of that, you can't offload processes such as resizing images to S3 and you may also want to run a WAF or DDoS protection layer to reduce bandwidth costs due to attacks.
Having said that, a common architecture is to store the originals in S3 (where they will rarely be accessed, but where durability is important) and to cache resized versions on the front end servers. I believe Netflix did or does use this technique (except they stored the cached files on their own colo hardware). It wouldn't surprise me if Imgur did that too.


How to model for independent determinants in several groups based on follow-up time

Question: I want to answer the research question which determinants are associated with long-term survival after a myocardial infarction (MI) in a prospective patient cohort study.
More precisely: I want to compare patients who have more than 10 years healthy survival after a MI compared to patients who have a new vascular event or have died in less than 10 years after the MI. What determinants are associated with >10 years healthy surival? What characterizes these patients?
I have tried to find which model is best to use, and in similar articles I have seen two different approaches: either a multivariate cox regression model or a multivariable logistic regression model.
Which method is best? Or if there is no 'best' model, but it is dependent of what exactly you are trying to answer - what is the difference between the results from the two models?
I hope the question is clear. I found similar questions on StackExchange, but the examples in those questions were so vastly different from mine that I found I could not answer my question. Thanks!
Edit:
I am now wondering if this is even the right approach at all. Like I said, the question I am trying to answer is whether patients who have a long (i.e. longer than 15 years) healthy follow-up after myocardial infarction have different characteristics than patients who did not achieve long healthy follow-up after myocardial infarction.
I do not want to use a regular Cox model, as I think this does not really answer my question (it will say, e.g. that smoking is a risk factor for mortality over time, which is really not that informative as this is generally known information). What I really want to know is what characterizes those 'healthy survivors'. Though the two questions are really close, they are not precisely the same.
The solution I have thought of for now is this: Make groups based on follow-up time and compare the determinants between those groups (e.g. a group with 0-5 year follow-up, 5-10, 10-15, 15+ years follow-up). However, I am not sure what model I can use to find out what independent determinants are for different groups compared to one another.
Alternatively, I would like to do a sort of 'reversed' Cox, where I look at the people who have the longest follow-up time first and working back, compared to a normal Cox model which is based on events throughout the follow-up time. But I have NO idea whatsoever if there is any type of model that would allow for this.
Comment: Interesting question. If the moment of death is not relevant for your research (dying after 1 year is as bad as dying after 11 years), you might opt for logistic regression. However, this is quite a statement. IMHO I think a patient would be rather interested in taking into account the expected time still alive, as I am going to die some day anyways. A cox model would do this. ...
Comment: cont'd ... Additionally, using the extended cox regression options you could also model time varying variables and effects. These would have you account for other 'death-causing' events which occur during follow-up and determinant effects which change over time. In other words, you are probably able to get closer to a more realistic 'model' when using cox regression. Do note, that interpretation of hazard ratios (the effect size in cox models) can be difficult when all these options are used.
Comment: Just to add to @IWS excellent comments if you have people lost to follow-up before 10 years (other than from death) you need Cox as you have censoring.
Comment: It is abit like the difference between (1) what predicts who can cimb to the summit of Mount Everest versus (2) what predicts how far up Mount Everest you can climb. They may be different I suppose. Incidentally if you want to ping @IWS or me you need to do that. You cannot ping more than one of us in the same comment though.
Comment: @mdewey how could I forget (one of) the most important reason(s) to do survival analysis: taking into account censoring! You are absolutely right.
Comment: I appreciate the answers. At least it gives me a lot more insight into the difference between the types of models.
(Edit as I accidentally pressed enter:) I understand that cox models take into account the time-to-event. However I'm still unsure if a cox model will actually answer my research question as to what determinants are for 'healthy survival' of more than 10 years compared to patients of an event in <10 years. As far as I know (which might be where I am wrong) a Cox model gives a hazard ratio for the entire period of follow-up, so not necessarily for long-term healthy survival.
Comment: cont'd: So how do I use a Cox model to specifically look at determinants associated with heatlhy survival and not simply at an association between determinants and length of survival (if that question makes sense)
Comment: I think this boils down to the proportionality of the predictors' effects. i.e. do you expect the effect of some baseline predictor (e.g. initial treatment of the infarction) to be *constant during the entire period of follow-up*? If your follow-up is >10 years, this is unlikely. A cox model, however, will allow you to study this. Either by certain graphics, or by modelling interactions with time ('time-varying effects', which are also a solution if there is no proportionality). Logistic regression just ignores the time aspect, leaving you with effect estimates which do so too.
Answer: Logistic regression models dichotomic (e.g. 0/1) variables, while Cox regression models survival times.
This means that logistic regression focuses on wheather a patient died within 10 years or not while Cox regression takes into account exact survival time (e.g. 11.5 years).
A simple example. Imagine you have 100 men and 100 women in your sample. All men died after 9 years and 360-364 days and all women died after 10 years and 1-5 days.
Logistic regression will tell you that sex is significant determinant of 10-years-survival (because all women survived and all men did not). Cox regression will (most probably) tell you that sex is not significant determinant (since women lived only a few days longer than men).
Note also, that in Cox regression you have determinants of survival while in logistic regression you have determinants od X-years-survival and you have to choose X.


How can I get a notification when someone edits a pipeline definition?

Question: As part of our change control process I need to get notified anytime someone edits a pipeline or release definition. I couldn't find a way to create a subscription for this type of notification. I can view the history, but also need to get notified when a new entry is added. Is this possible?
Comment: if you use yml, you can add yourself as a review when someone tries to edit it https://learn.microsoft.com/en-us/azure/devops/repos/git/branch-policies?view=azure-devops#automatically-include-code-reviewers
Comment: How about the issue? Does the answer below resolved your question,  If not, would you please let me know the latest information about this issue?
Answer: From your question I'm assuming you are using Classic Pipelines, as opposed to YAML Pipelines.  In that case I don't think you can do this out of the box.
If you were using YAML Pipelines then you can configure notifications on changes to the file in the repo or set a reviewer policy for the file in the repo.  History is then handled in the same way as history for any other file.  Two good reasons to migrate ;)
Comment: I guess there are two parts I am looking at - I have yaml defintion for the pipeline execution steps which I can view/edit from devops and are stored in our repo.  Then I also have the release definitions that show a workflow-like view of my artifacts and stages (which has a history tab).   Changes to either of these can impact what is generated and deployed to my service.
Answer:
How can I get a notification when someone edits a pipeline definition?

Sorry for any inconvenience.
I am afraid Azure devops does not support this way/feature to sent notification when someone edits a pipeline definition at this moment.
Even if our pipeline type is yaml, we cannot set notifications when someone changes the pipeline. Because the subscription can only be limited to a specific folder, and not to a specific file yaml, unless we put the yaml in a specific file, we can set notifications for it:

Besides, personally think that your request is reasonable. You could add your request for this feature on our UserVoice site (https://developercommunity.visualstudio.com/content/idea/post.html?space=21 ), which is our main forum for product suggestions. Thank you for helping us build a better Azure DevOps.

Hope this helps.


How to prove that $\gcd(m^2,m+n) = \gcd(n^2,m+n)$

Question: How can we prove that $\gcd(m^2,m+n) = \gcd(n^2,m+n)$?
My try:
$$
\gcd(m^2,m+n) = \gcd\left[m^2=m\cdot \left(m+n\right)-mn\right] = \gcd(m+n,mn)$$
But I don't think it'll help me for the future, there is another way maybe?
Comment: @Xavi Note that the central term doesn't make sense. Can you fix it to display what you want?
Comment: Why it doesn't help you for the future? It's a good solution, I think.
Comment: By [gcd mod reduction](https://math.stackexchange.com/a/95825/242) in the linked dupe: $\,\gcd(m^2,m+n) = \gcd(n^2,m+n)\,$ by $\,m^2\equiv n^2\pmod{m+n},\,$ since $\,m+n\mid m^2-n^2,\,$ or, more *arithmetically*
by  $\!\bmod m+n\!:\ m\equiv -n\Rightarrow m^2\equiv (-n)^2\equiv n^2.\  $ More generally this shows $\gcd(f(m),m+n) = \gcd(f(-n),m+n)\,$ for any polynomial $f(x)$ with *integer* coefs, since the [Polynomial Congruence Rule](https://math.stackexchange.com/a/879262/242) $\Rightarrow f(m)\equiv f(-n)\pmod{m+n}\ \ $
Answer: As @WhatsUp said, you can continue this to a solution.
$$ \gcd(m+n,mn)=\gcd(m+n,-mn)$$
$$=\gcd(m+n,-mn+n(m+n))=\gcd(m+n,n^2)$$
Comment: Or more directly from what OP has, similarly $ \gcd(n^2, m+n) = \gcd(m+n, mn) $, so these values are equal.  (I'm guessing that's why @WhatsUp said "it's a good solution" as opposed to "It's a good start".)
Comment: Please strive not to add more (dupe) answers to dupes of FAQs, cf. recent site policy announcement [here](https://math.meta.stackexchange.com/q/33508/242).


Skip validation in some cases in Vee-Validate 3.0 using ValidationProvider

Question: I have a custom text input component which I wrapped in validation provider.
Basically it looks like this:
<validation-provider :rules="rules"
                     :vid="vid"
                     :name="name"
                     v-slot="{ errors, classes }"
                     slim>

 ...

</validation-provider>

Sometimes I need to validate it, however in some cases I don't need this. If I don't need validation I don't pass rules prop.
But how can I disable the provider when I don't need to validate my component? Couldn't find any related property in the docs.
Comment: just make `rules` string empty. no rules - no validation - no errors
Comment: also, you can pass rules as object, not string. for this case, rules looks like `{ required: true, email: true }` and then you can manipulate by some of rule just toggle  true-false value. in that case you need to create variable, for example, `isRequired` and pass it to your component
Comment: Tried to pass rules as 1) undefined 2) null 3) empty string, in all cases input get "valid" class in case of focus out event..:(
Comment: that's true behavior... I wrote "no rules - no validation - no errors". so that's why input is valid when you pass empty `rules`. this is your case as you wrote " disable the provider when I don't need to validate". if you want some logic else, please, clarify.

probably, you can play around construction `:class={'invalid': errors.length}` of `div` instead of usage `classes` inside `v-slot` object.
Answer: This scrambled my brain too. The solution is to set the mode prop to passive.
You can also set the mode to a function if you need more flexibility.
https://logaretm.github.io/vee-validate/guide/interaction-and-ux.html#interaction-modes
<ValidationProvider mode="passive" rules="required" v-slot="{ errors }">

</ValidationProvider>


Codepen.io: can't do console.log() in d3.csv()

Question: I am trying to read in csv data using d3 in codepen.io and it is not printing me the data, even though it is printing console.log('hello') outside the d3.csv():
d3.csv("http://learnjsdata.com/data/expenses.csv", function(data) {
    console.log(data)
})

I added d3 cdn of course.
Whats wrong with codepen.io? How to make it working?

In the debug mode I see that codepen.io does not like that the expenses.csv is loaded over http.
Answer: I think it depends on the version of d3 you're using. In d3 v6, they changed from the signature d3.csv(<file>, <callback>) to a promise structure:

d3.csv("http://learnjsdata.com/data/expenses.csv").then(function(data) {
    console.log(data)
}).catch(function(error) {
    console.log(error)
})

Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/222672/discussion-between-ruben-helsloot-and-nikita-vlasenko).


Form a new base with two vectors

Question: I need to make a new orthonormal base in $\mathbb{R^3}$ given $(2,7,5)$ and $(4,1,3)$ so that it makes $(\widehat{e_1}, \widehat{e_2}, \widehat{e_3} )$. But $ \widehat{e_1} $ has the same direction of  $(2,7,5)$ and $\widehat{e_2}$ is in the plane formed by $(2,7,5)$ and $(4,1,3)$.
I got $ \widehat{e_1}$ by just obtaining the normal vector $\widehat{e_1} = \frac{(2,7,5)}{|(2,7,5)|}$ and $\widehat{e_3}$ would be easy by just making cross product between $\widehat{e_1}$ and $\widehat{e_2}$. My main problem is obtaining $\widehat{e_2}$ since I'm stuck obtaing a vector orthoga¡onal inside the plane.
Thanks.
Comment: Are you after an *orthonormal* basis?
Comment: Yes, I'll add that in an edit. Thanks.
Answer: Your choice for $\widehat{e_1}$ is fine. Then consider $v=(4,1,3)-\left\langle(4,1,3),\widehat{e_1}\right\rangle\widehat{e_1}$ and take $\widehat{e_2}=v/\|v\|$. And then, as you wrote, take $\widehat{e_3}=\widehat{e_1}\times\widehat{e_2}$.
Comment: Thanks, just one question $⟨(4,1,3), \widehat{e_1}⟩ \widehat{e_1}$ would be the exterior product times $ \widehat{e_1}$?
Comment: No. It's the *inner* product times $\widehat{e_1}$.
Answer: To expand on José Carlos Santos' answer, and explain why that answer works.
Let $\hat{e}_1$ be the first unit vector.
To obtain vector $\hat{e}_2$ that is in the plane spanned by $\hat{e}_1$ and $\vec{q}$, apply one step of Gram–Schmidt process to get the part of $\vec{q}$ that is perpendicular to $\hat{e}_1$, and normalize the result to unit length.
This entire process is commonly in many 3D problems, including in computer graphics where the two basis vectors are e.g. "towards" and "up", but may not be perpendicular to each other.
If we call the two vectors to be used for the base $\vec{p}$ and $\vec{q}$, then the entire process is
$$\begin{aligned}
\hat{e}_1 &= \displaystyle \frac{ \vec{p} }{ \left\lVert \vec{p} \right\rVert } \\
\vec{t} &= \vec{q} - \hat{e}_1 \left( \hat{e}_1 \cdot \vec{q} \right) \\
\hat{e}_2 &= \displaystyle \frac{\vec{t}}{\left\lVert\vec{t}\right\rVert} \\
\hat{e}_3 &= \hat{e}_1 \times \hat{e}_2 \\
\end{aligned}$$
where $\cdot$ is the dot product, $\times$ is the cross product, and $\lVert~\rVert$ Eucidean length. To remind those not familiar with basic vector algebra, given
$$\vec{a} = \left[ \begin{matrix} a_x \\ a_y \\ a_z \end{matrix} \right],
\vec{b} = \left[ \begin{matrix} b_x \\ b_y \\ b_z \end{matrix} \right]$$
the operations are
$$\vec{a}\cdot\vec{b} = a_x b_x + a_y b_y + a_z b_z , \quad
\vec{a}\times\vec{b} = \left[ \begin{matrix}
a_y b_z - a_z b_y \\
a_z b_x - a_x b_z \\
a_x b_y - a_y b_x \\
\end{matrix} \right], \quad
\left\lVert\vec{a}\right\rVert = \sqrt{a_x^2 + a_y^2 + a_z^2}$$
Answer: Since you've already used a cross product to generate $\hat e_3$, just keep going with $\hat e_2=\hat e_3\times\hat e_1$ (or $\hat e_1\times\hat e_3$, since nothing in your question said that the basis had to be right-handed). Don't forget to normalize all of these vectors.

Form a new base with two vectors


Changing units in linear regression

Question: A linear model:
$y_{i}=\alpha +\beta x_{i}+u_{i}$
was estimated using least squares and the following estimate was calculated:
$\widehat{\beta }=\frac{\sum (x_{i}-\overline{x})y_{i}}{\sum (x_{i}-\overline{x})x_{i}}$
Now we want to change the units of the independent variable from Celsius to Fahrenheit:
$z_{i}=32+1.8x_{i}$
The OLS is now:
$\widehat{\gamma }=\frac{\sum (z_{i}-\overline{z})y_{i}}{\sum (z_{i}-\overline{z})z_{i}}$
I need to show that:
$\widehat{\gamma }=\frac{5}{9}\widehat{\beta }$
And I can't do it, trying for a couple of hours. Can you please assist ? Once I prove this, I already know how to prove the equation for the new intercept.
Thank you !
Answer: Insert $z_i$ into $\hat \gamma$. For the numerator you obtain  $\sum(1.8(x_i-\bar x_i))$, as the 32 in each $z_i$ cancels with that in $\bar z$.
The same happens in the denominator, leaving you with $\sum(1.8(x_i-\bar x_i)) (32+1.8x_i)$
But as $\sum(x_i-\bar x_i) $=0, this equals $\sum(1.8(x_i-\bar x_i)) 1.8x_i$. Thus $\hat \gamma=\frac{1}{1.8}\hat\beta$.
Comment: How come you use the fact that the sum of xi-xbar is 0 if this term is multiplied by another term in the sum ?
Comment: I use this only with the 'other term' being 32 (which can be taken out of the sum). The term involving the $1.8x_i$ is kept as it is and leads to the 1/1.8.

Changing units in linear regression


Is $\{(x_n)^{1/n}\}$ convergent when $\{x_n\}$ is a positive convergent sequence?

Question: Consider $\{x_n\}$ to be a positive sequence and convergent. Is it true that the sequence $\{x_n^{1/n}\}$ is convergent?
Comment: Try $x_n=e^{-n}$ for $n$ even, and $=e^{-n^2}$ for $n$ odd.
Comment: You probably mean *convergent* ?
Answer: A simple counterexample:
$$x_n=\frac{n\bmod 2}{2^n}$$ so that
$$\sqrt[n]{x_n}=\frac{n\bmod 2}2.$$
Answer: If $x := \lim_{n \rightarrow \infty} x_n$ is positive, it is true. because there exists an $N \in \mathbb{N}$ such that $1/M<a_n<M$ for all $n \geq N$ for some fixed $M$. Thus
$$1=\liminf_{n\rightarrow \infty} M^{-1/n}\leq\liminf_{n \rightarrow \infty} a_n^{1/n} \leq \limsup_{n \rightarrow \infty} a_n^{1/n} \leq  \limsup_{n\rightarrow \infty} M^{1/n} =1.$$
Otherwise not, as the above examples show!


A pyramid in a prism - How to prove that this angle is right?

Question:
I have been struggling to prove that angle CBE in this solid is a right angle. First of all, I thought about the possibiliy that angles AED and BEC are congruent, because they "share" the same vertex and AD = BC, this does not work however, because triangles BCE and ADE have different areas. Now, I am stuck. Could you shed some light on this problem for me?
Comment: Intuitively: you can see that $\angle CBF$ and $\angle CBA$ are both right angles, so $BC$ is perpendicular to the plane $ABF$, which also includes the point $E$.
Comment: Write out the components of the vector defined by $\overbar{BC}$ and by$\overbar{BE}$ then do a dot product and see that it is $0$.
Comment: David G. Stork,
Sorry, but we haven't done the dot product or vector equations yet, it's a high-school level problem.
Answer: $CB$, by construction, is orthogonal to plane $ABFE$, thus it is orthogonal to any line in this plane, in particular to line $BE$.
Answer: The vector defined by $BC$ is $\{0,1,0 \}$ and the vector defined by $BE$ is $\{ -1,0, 1 \}$.  The "dot product" of two vectors is the sum of the products of their paired components, here:
$0 \cdot (-1) + 1 \cdot 0 + 0 \cdot 1 = 0$.
This means the vectors are perpendicular.
Comment: $BE$ lies in the plane perpendicular to $BC$, and is hence itself perpendicular to $BC$.
Comment: Thank you! Now I understand it.

Is there a way to prove it without using the dot product, straight from the diagram?


Append filter info to URL when using AJAX in 'View' module

Question: I am using the Views module and have created a view for a content type. I have added an exposed filter so that the user can filter the list of content based on a custom taxonomy.
I want to use AJAX for filtering the content.  Before I select 'yes' under 'use AJAX' in the 'advanced' tab, the filter appends the filter selection to the URL such as /content-type-view?category='selected-category'.  But once I select AJAX, I lose the update to the URL.
I want to combine the two, use AJAX but also have unique URL's so that I can direct users to pre-filtered instances of the view.
What am I doing wrong?
Comment: Are you using D7 or D8?
Comment: @CodeNext I am using D7
Comment: And are you using better exposed module also as it is listed in your tags, right?
Comment: Yes, I am using 'better exposed'.  Although the above question is not specific to the 'better exposed' module, I will eventually be using that to 'auto-submit' the filter selected in conjunction with the 'advanced' tab AJAX
Comment: @CodeNext Any help?
Comment: I tried to construct the scenario in my trial site, but I am not able to understand the URL thing. Are you want to say that, the URL is one of teh selection option and if you enable Ajax, you lose the URL link?
Comment: @CodeNext I just want to append the parameters to the URL if I select 'yes' under use AJAX.  The same way the parameters are appended to the URL if AJAX is not used.
Comment: Do I get this right: You want the URL to be updated during an AJAX call?
Comment: @CodeNext yes, just the query parameters
Answer: What you want to do is manipulate the browser's URL even though there are no page reloads, only AJAX requests taking place.
You are actually in need of the HTML5 History API.
And luckily there seems to be a module available, specific to your case:
https://www.drupal.org/project/views_ajax_history
Give this a try and good luck!
Comment: Thanks for this, I have definitely used the HTML5 History API before, but thought that there was a way to make this happen within the Views module.  I'll give the above module a shot and see how it works.  Thanks!
Comment: This worked great, highly recommend.
Comment: Worked for me like a charm, thx!!


Pegar Penúltimo registro de uma tabela com Entity Framework

Question: Como eu faço para pegar o penúltimo registro de uma tabela com Entity Framework
Answer: Você pode fazer assim:
var penultimoRegistro = db.Entidade.OrderByDescending(/*ordenação*/).Take(2).Last();

O que esse código faz é pegar os dois últimos registros conforme a ordenação especificada e salvar na variável o último registro desses dois (já que a ordenação é Descending).
Edit:
Você também pode fazer
db.Entidade.OrderByDescending(/*ordenação*/).Take(2).Skip(1).Take(1).Single();

Esse código pega os dois últimos registros conforme sua ordenação, e pula um registro o Single() serve para fazer o retorno ser um T ao invés de IEnumerable<T>.
No fim, o resultado final é o mesmo.
Veja um exemplo no dotNetFiddle
Comment: Pode usar o Skip pra não precisar retornar 2 e selecionar o último. Só trocar `Take(2).Last();` por `Skip(1).Take(1).Single();`
Comment: Também pode ser, vou adicionar essa opção.


Utilidade de referenciamento de Foreign Key (chave estrangeira) no banco de dados

Question: Tenho uma dúvida em trabalhos com bancos de dados.
Exemplificando, conforme a imagem abaixo:

Pois bem, eu sei que devo incluir na tabela agendar_consulta o usuário que precisa de uma consulta e o médico que irá consultá-lo, e isto se faz através de foreign keys referenciando a registros únicos das tabelas users e médicos.
Agora a pergunta:
Qual a utilidade de eu referenciar Foreign Keys (chaves estrangeiras) da tabela agendar_consulta a registros das tabelas users e médicos?
Não teria o mesmo efeito eu deixar a tabela agendar_consulta com os campos id_medico e id_user como campos simples (não Foreign Key) de variável Integer e só repetir os id's independentemente das outras tabelas?
Answer: Rodrigo, as chaves estrangeiras são úteis para evitar ações que destroem as ligações entre as tabelas e evita também que dados inválidos sejam inseridos numa chave estrangeira, porque o valor inserido tem de ser um valor existente na tabela que está ligada a essa.
Caso não use as chaves estrangeiras e apenas tenha uma coluna, estas regras não serão aplicadas por omissão.
Usando o seu exemplo, se eu tivesse um id_user = 1 e depois tentasse inserir na tabela agendar_consulta um user com id_user = 2 esta inserção não poderia ser feita, estaria a agendar uma consulta para um user não registado, tal como agendar uma consulta com um id_medico não existente, não pode realizar uma consulta se o id_medico não existir na sua base de dados.
Answer: Integridade e segurança.
Quando se usa Foreign Key, podemos garantir que nenhum registro será fisicamente adicionado na tabela agendar_consulta sem um id_user e um id_medico válido.
O mesmo vale na exclusão: nenhum registro poderá ser excluído das tabelas users e medicos se estes estiverem sendo usado na tabela agendar_consulta


Compilation error due to table in C++

Question: I'm trying to create a chat programm for the TI-Nspire Calc via the serial port. So I installed the ndless SDK and nspireio lib to make the communication and it kind of works because there is an infite repetition of the message so I wrote this:
if(uart_ready()) {
    char input[100] = {0};
    uart_getsn(input,100);
    if(oldinput != input) {
            nio_puts(input);
            oldinput = input;
    }
 }

But when I compile it give me this error:
root@Kali-Linux:~/TINSPIRE/Ndless/ndless-sdk/samples/uart# make
nspire-g++ -Wall -W -marm -Os -c hello.cpp
hello.cpp: Dans la fonction « int main() »:
hello.cpp:61:14: error: affectation de tableau invalide
   oldinput = input;
              ^~~~~
Makefile:33 : la recette pour la cible « hello.o » a échouée
make: *** [hello.o] Erreur 1

What I'm doing wrong?
Comment: where is defined the variable oldinput ?
Comment: Hint: use `export LANG=C LC_ALL=C`  to get your messages in English for the question
Comment: It's already declared at the top of the program
Comment: Thanks @Basile Starynkevitch
Comment: @TurtleForGaming: never comment your own question, but **edit your question** to improve it. You need to put some [MCVE] in it.
Answer: You should declare oldinput:
char oldinput[100] = {0};

memcpy(oldinput, input, sizeof(char) * 100);

Comment: It is probably already declared that way. However, you cannot assign arrays in C or C++
Answer: If oldinput is also a char array,
replace oldinput=input with
strcpy(oldinput,input);

Comment: That assumes null terminated strings. That's seldom the case for IO.
Comment: More correct:

    memcpy(oldinput, input, sizeof(char) * 100);

Compilation error due to table in C++


What is the probability of rolling at least $n$ consecutive numbers when rolling $k$ dice?

Question: I am trying to code a game that turned out to be more complicated than expected. The complication comes down to a function that attempts to calculate the chance of at least $n$ consecutive numbers out of a total of $k$ dice rolled. The function only has to work for integer values of $n$ and $k$, and $2\le n\le k\le 6$. I am looking for a formula I can use to calculate all possibilities and store them as variables, or a javaScript function that can take parameters $n$ and $k$ and then do the calculation that way. I have been trying for a while now and cannot find a way to correctly calculate these probabilities to match experimental results. I have tried a lot of different javaScript function ideas to iterate and calculate these odds, but none of my attempts works for both $n=k=2$ and $n=3, k=6$. Example combinations that work for $n=3$ and $k=6$ are $1, 2, 3, 6, 6, 6; \; 3, 5, 2, 1, 4, 6$ and 1, 2, 3, 4, 6. Thanks for any help.
Comment: Do the consecutive numbers need to appear consecutively, or do they just need to appear anywhere?  I'm not clear on whether the word "consecutive" refers to the numbers on the dice, or their positions, or both.  Can you [edit] the post to state this clearly?
Comment: Related problem of determining probability of appearing subsequence 123456 in
$$ rolls: https://math.stackexchange.com/q/4854023/1231520
Answer: There are only $6^6 \approx 50,000$ possible sequences of 6 rolls.  Just enumerate all of them, and count how many meet your requirements.  A program to do that should finish in milliseconds.
Or, precompute the answer for each $k,n$ satisfying $2 \le n \le k \le 6$.  There are only 15 pairs of values $(n,k)$, so you can precompute the answer for each pair, and hardcode all of those in your code as a lookup table, and  just look up the desired entry at runtime.
Comment: The second part would have been my answer. The first part seems to assume that the consecutive numbers need to appear on consecutive rolls. The example $3,5,2,1,4,6$ that the OP later added to the question seems to indicate that that isn't the intended interpretation.
Comment: @joriki, Oh gosh, I bet you are right.  I've edited my answer accordingly.  Shoot.  Thank you for pointing that out.


quadratic diophantine expression

Question: Can someone suggest a reference?
Also, why are there 7 answers to the question
39*c^2 + 3*c + 1 mod 49 is congruent to 0
see my Maple worksheet.

I sort of answered my own question.  If 49 divides b then so does 7.  Reducing mod 7 gives
$$4c^2 + 3c + 1 mod 7 = 0$$
Multiplying by 2 and adding 7 yields a perfect square.
$$(c+3)^2 mod 7 = 0$$
The 7 answers fall out from there.
Answer: Hint:  $39\equiv-10\mod 49$, so the quadratic can be rewritten as
$$10c^2-3c-1\equiv0\mod 49$$
Note that $10c^2-3c-1=(5c+1)(2c-1)$.
Answer: The problem is that the solution is $c =3 \pmod{7}$, you started the problem $\pmod{49}$. There are 7 residue classes modulo $49$ which can be $3 \pmod{7}$, and in this case all seven work.
To learn how to go from $\pmod{7}$ to $\pmod{49}$, or more generally from solving a polynomial equation $\pmod{p}$ to solving the same equation $\pmod{p^n}$ read on Hensel's Lemma

quadratic diophantine expression


Find the total amount of multiple products of the same type - Commerce

Question: I've created a rule that sends a thank you email to anyone who donates less-than-or-equal-to a certain amount (which works perfectly), but I cannot figure out how to pull out the total $ amount of all donations on the order and include it in the email.
If it were guaranteed there would only ever be a single donation line item the issue would be simple.  However, there is no guarantee there won't be more than one on a single order, and there will usually be at least one other line item of a different product type included in the order.  I've searched, but cannot figure out how to, for example, calculate the total donation amount for an order that has 2 donation line items of $10 & $20, plus one or more other line items of a different product type, then put the donation total into the thank you email that gets sent out.
Any / all help will be much appreciated!
Answer: Use commerce_donate module to get donation then this field use in your rules

Create a rule add events in Rule
Add condition entity has a field (your donation field)
Add variables in this you can use php field to get total amount of donation.
Add action in email section use token of variables

I am not already try this but hopefully this may work.


Bias of estimator for difference of expectations of random variables

Question: Apologize if this is a simple question, I have not been able to find a satisfactory response anywhere.
Suppose we have two random variables $X$, $Y$, and $n$ samples from each: $\{x_1,\dots,x_n\}$, $\{y_1,\dots,y_n\}$. We are interested in estimating their absolute difference of expectations, $|\mathbb{E}[X]-\mathbb{E}[Y]|$. Online, I found that an estimator for this quantity is:
$$\left|\frac{1}{n^2}\sum_{i=1}^n\sum_{j=1}^n(x_i-y_j)\right|.$$
I am curious about the bias for this estimator, in particular as a function of $n$.
When $n=1$ the estimate is clearly biased, as it produces $|x_1-y_1|$, which has expected value $\mathbb{E}\left[|X-Y|\right]$.
For $n>1$ I am having a more difficult time analyzing. It is unbiased in this case? Is it biased with a bias decreasing as $n$ increases?
Comment: The expression can also be written as $\left|\frac{1}{n}\sum\limits_{i=1}^n x_i-\frac{1}{n}\sum\limits_{j=1}^n y_j\right| = \left|\bar x -\bar y\right|$. It is biased unless $\mathbb P(X>Y=0)$ or $\mathbb P(X<Y=0)$, since otherwise you could have the sign of $\bar x -\bar y$ being opposite to $|\mathbb{E}[X]-\mathbb{E}[Y]|$.  But I would expect the probability of that to decrease as $n$ increases and so to see the bias decrease.
Comment: We have $E|X-Y| \geq | E (X-Y) |$. This inequality is strict outside of special circumstances, so if you use this inequality on your estimator, you will see that it isbiased in general. One special circumstance where we have equality is that $X-Y$ is constant. The bias decreases as $n\to \infty$. To see this intuitively, as $n\to \infty$, your estimator will become close to the constant $|E(X-Y)|$ by a law of large numbers. In the limit, this means the bias becomes $E|E(X-Y)| - | E (X-Y) |=0$.
Comment: Writing $Z = X - Y$ and $z_i=x_i-y_i$, your estimator is simply $|\overline{Z}|$, the absolute value of the sample mean of $z_i$'s. So, (1) LLN tells that $|\overline{Z}|$ converges to $|\mathbf{E}[Z]|$ as $n\to\infty$, and (2) the inequality $$\mathbf{E}\bigl[\bigl(|\overline{Z}|-|\mathbf{E}[Z]|\bigr)^2\bigr]\leq\mathbf{Var}(\overline{Z})=\frac{1}{n}\mathbf{Var}(Z)$$ can be used to quantify the concentration.
Answer: This estimator is always biased. Using Jensen's inequality:
\begin{align}
E\left| \frac{1}{n^2} \sum_{i=1}^n \sum_{j=1}^n (x_i - y_j) \right| &\geq \left| E\left(\frac{1}{n^2} \sum_{i=1}^n \sum_{j=1}^n (x_i - y_j)\right) \right| \\
&= \frac{1}{n^2}\left| \sum_{i=1}^n \sum_{j=1}^n \left(E(X)-E(Y) \right)\right| \\
&= \left|E(X)-E(Y) \right|
\end{align}
Furthermore, for Jensen, we have equality if and only if the function is affine (it is not in this case) or if $x_i - y_j$ is constant for all $i$ and $j$. As long as this is not the case, the inequality is strict.
Thus, we have that
$$
E\left| \frac{1}{n^2} \sum_{i=1}^n \sum_{j=1}^n (x_i - y_j) \right| - \left|E(X)-E(Y) \right| > 0
$$
In other words, the estimator is biased, and furthermore, the bias is always positive.
Comment: Thank you, I was looking for something just like this. I think you meant to say or if $x_i-y_j$ is constant for all $i$ and $j$ however (rather than $=0$)
Comment: Yes, you're correct, I'll correct that now.


Recebendo objeto por parâmetro

Question: Estou utilizando Spring MVC e utilizo alguns mapeamentos para receber um objeto por exemplo e acessar esse objeto específico no controller.
Por exemplo:
@GetMapping("/pessoa/{idPessoa}")
public ModelAndView editaPessoa(@PathVariable("idPessoa") Pessoa pessoa) {
.....
}

Sendo assim, caso eu tenha uma listagem, eu preciso passar por um link o href do controller passando o id da pessoa que eu queria editar por exemplo. Porém, eu queria ocultar o id da pessoa via browser, de modo que a url nao ficasse expondo os ids dos objetos
http://site.com.br/editar/pessoa/32
Existe alguma forma de apenas chamar o mapeamento sem passar o id por url e conseguir recuperar esse objeto dentro do controller ?
Answer: Sim, basta utilizar o @RequestBody e criar uma classe POJO que contenha um atributo de String id. Note que você não vai conseguir passar usado o href do link, portanto terá que criar uma request encaminhando o json via Javascript.
Por exemplo:
@GetMapping("/pessoa/")
public ModelAndView editaPessoa(@RequestBody PessoaInterface pessoa) {
.....
}

PessoaInterface.java
public class PessoaInterface {
    String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

Note que em PessoaInterface.java você pode adicionar um List e repassar inúmeros IDs numa única request.
Solução ideal
Você está utilizando o método GET para fazer uma edição. Um dos principios de REST é respeitar os códigos HTTPs e utilizar os verbos corretos, isso é, utilizar GET somente num caso em que você precise acessar algo. O ideal é que você utilizasse PUT ou PATCH para a edição (não posso afirmar qual com certeza porque não conheço o seu cenário).
Note que não é somente uma questão de respeitar os padrões, há uma longa thread sobre encaminhar body numa requisição GET (https://stackoverflow.com/questions/978061/http-get-with-request-body) e alguns servers até recusam por padrão requests GETs com body. Falando de REST, com certeza isso não é aceito.
E se quisesse obter um elemento sem ter que repassar o ID?
Supondo que o seu problema não seja uma edição de pessoa e sim obter uma pessoa repassando o ID, nesses casos continuamos repassando via path param mas é utilizado GUIDs ao invés de IDs.

Recebendo objeto por parâmetro


Fitting lognormal distribution from D10, D50, and D90

Question: I have a statistical sample where D10 = 8 (10% of population under the value 8), D50 = 11 (median), and D90 = 18 (90% of population under the value 18)
Now, I need to find the best fit, in terms of the values $\mu$ and $\sigma^2$ of a lognormal probability distribution, given these D values.
Any help is highly appreciated
Comment: The likelihood is equal to the joint density of the order statistics $D10, D50, D90$.  This density has a closed form formula, see https://en.wikipedia.org/wiki/Order_statistic#The_joint_distribution_of_the_order_statistics_of_an_absolutely_continuous_distribution.  This can in turn be maximised numerically with respect to $\mu$ and $\sigma^2$.  See https://stats.stackexchange.com/a/436621/77222 for a similar approach
Comment: You'll need to use the joint density of your three order statistics (D10, D50 and D90).  The distribution of the sample mean isn't needed.
Comment: But isn't the CLT that you use to derive the mean, only true when the sample size is large?
Comment: Ok, one more question, why do you need to use a truncated lognormal based on x1 and xn? I though x1 and xn were the sample max and min, not the max and min of the actual distribution. In my case I can have 10% of samples that are lower than 8 and larger than 18.
Comment: That's specific to the other question and doesn't apply here.
Comment: I solved it, I think, thanks!
Answer: Followin the suggestions of Jarle Tufto.
I coded the following.
<code> import numpy as np
 import matplotlib.pyplot as plt
 from scipy import special
 from scipy import optimize

 osample = [8,11,18] #ordered D10, D50, D90 sample
 num = 3

 def lnpdf(x,mu,sigma): #lognormal probability distribution function
     d = 1/(x*sigma*np.sqrt(2*np.pi))*np.exp(-0.5*(np.log(x) - mu)**2/sigma**2)
     return d

 def jpdfo(mu,sigma): #joint probability distributions of ordered statistic
     p = 1
     for i in osample:
         p *= lnpdf(i,mu,sigma)
         p = np.math.factorial(num)*p
     return p

 def nll(param): # negative log likelihood
     val = -jpdfo(param[0],param[1])
     return val

 #minimize the nll
 x0 = [10,3]
 res = optimize.minimize(nll,x0=init,method="Nelder-Mead")
 print(res)
</code>
What I obtain is the following:
<code>final_simplex: (array([[2.45588837, 0.33356707],
   [2.45592186, 0.33361764],
   [2.45597456, 0.33356375]]), array([-0.00144556, -0.00144556, -0.00144556]))
       fun: -0.001445562771159583
   message: 'Optimization terminated successfully.'
      nfev: 95
       nit: 49
    status: 0
   success: True
         x: array([2.45588837, 0.33356707])
</code>
So judging from this $\mu$ = 2.45 and $\sigma$ = 0.33. If I plot a lognormal distribution with these parameters, I obtain the following:

Which pretty much makes sense, given my sample data. I will call this good for now, thanks Jarle!


SSRS Page header

Question: Is it possible to display a page header only for the first page of a report and not have it repeat on subsequent pages?
I am trying to simple display the title of the report at the top of the first page and do not want it repeat. I know this is probably a simple question but kind of new to SSRS
Thanks in advance
Comment: See this question it should help. https://stackoverflow.com/questions/16306092/ssrs-report-builder-only-show-header-on-first-page-with-page-numbers
Comment: Possible duplicate of [SSRS Report Header](https://stackoverflow.com/questions/52715263/ssrs-report-header)
Answer: If you really want to do it, you can do it with this expression. Put a textbox in the header and write the following code:
<code>=IIF(Globals!OverallPageNumber = 1, "This is the header only for Page 1", Nothing)
</code>
Answer: I think that what you're after is a "Report Header".  Right-click in the gray area next to the report surface and select "add Page Header".

SSRS Page header


Cannot access internal android storage..?

Question: I have to access this file: file:///mnt/sdcard/DCIM/Camera/1381243874374.jpg
It should be in the internal storage.. but if I give to Android this path, it can't load the file. Any suggestions?
Thanks!
Comment: internal `storage`, not memory. memory != storage.
Comment: thanks for the comment. Question fixed :)
Comment: No, that is in what is considered the "external" storage, even if is located in flash chips permanently soldered to the board rather than a removable micro SD card.  Also, that's an explicit path to a location valid only in *some* android versions.  You really should discover the applicable mount point at runtime using the External Storage APIs.
Answer: Ok, I've fixed this like that:
<code>    String[] split = path.split("sdcard/");
    path = split[1];

    File sd = Environment.getExternalStorageDirectory();
    path = sd.getAbsolutePath() + '/' + path;
</code>
Comment: if 'path' is a Uri just do File sd = new File(uri.getPath());
Comment: @dymmeh - an important part of what is going on here is the runtime discovery of the *actual* external storage base path (mount point) on the specific device where it is executing
Comment: @ChrisStratton I assumed he was getting the path at runtime so it should be pointing to the correct storage location. If that's not true then, yes, my point is wrong.


How do I get the item count (size) of a dojo datastore?

Question: I don't see anything in the read API that provides access to this:
http://api.dojotoolkit.org/jsdoc/1.3.2/dojo.data.api.Read
Comment: With dojo.data.ItemFileReadStore you can do:

myStore._getItemsArray().length

But this is particular to that data store. I'm wondering what the correct way to get store size is.
Comment: This method is even more hackish than I initially thought. The array isn't initialized until fetch is called. So you have to make sure you fetch before checking the array length.

>>> store._getItemsArray().length
0
>>> store.fetch()
Object store=Object
>>> store._getItemsArray().length
2
Answer: An example at dojocampus demonstrates one way. Here a fetch without query parameter returns all the items in the store.
var store = new some.Datastore();
var gotItems = function(items, request){
  console.log("Number of items located: " + items.length);
};
store.fetch({onComplete: gotItems});

Answer: dojo.data.api.Read's onBegin function has the total size of the match:
function size(size, request){
  // Do whatever with the size var.
}

store.fetch({query: {}, onBegin: size, start: 0, count: 0});

From this quickstart: http://dojotoolkit.org/reference-guide/1.7/quickstart/data/usingdatastores/faq.html#question-6-how-do-i-get-a-count-of-all-items-in-a-datastore
Answer: The format of the wire-data of any data store is completely store-specific.  In order for you to get the total items count (and other metadata), it must be returned as part of the response.  This is the only way to do server-side pagination.
All the stores I have implemented expect the data to contain a totalCount attribute, like so:
{
  identifier: 'id',
  items: [
    { id: 123, name: 'aaa', ... },
    { id: 456, name: 'bbb', ... },
    ...
  ],
  totalCount: 525
}

The store saves this when the query returns (in onComplete).  The value is then exposed via a getTotalCount() method on the store.
When used in conjunction with the start and count request options, this allows you to have nice ajax pagination ("Showing 1-50 of 525").
Since this is not part of the API, the core implementations of the read API do not implement it.  A form of this technique (similar to what I have done) does seem to be implemented by the dojo.data.QueryReadStore, so you can probably look there also.
Answer: I was looking for the answer to this question using the JsonRest store, and this seems to be it:

On your server, you should look
  at the Range header in the request to know which items to return. The
  server should respond with a Content-Range header to indicate how many
  items are being returned and how many total items exist:
Content-Range: items 0-24/66

From: http://dojotoolkit.org/reference-guide/dojo/store/JsonRest.html
Answer: The following code worked for me
  // questionStoreReader is a pointer that points to and can read ask.json file

  var questionStoreReader=new dojo.data.ItemFileReadStore({url:"ask.json"});

  questionStoreReader.fetch(
   {
     onComplete:function(items,request) // items is an array
      {
        alert(items.length);// number of items in ask.json
      },
   })


Help with finding the directional derivative of a $f(x,y,z)=xy+xz+yz$ at a point and in the direction of a vector

Question: I need to find the directional derivative of $f(x,y,z)=xy+xz+yz$ at $P(1,2,3)$ in the direction of $\overrightarrow{v}=\langle 2,1,-1 \rangle$
I think I started this incorrectly and would greatly appreciate any hints!
$$f(x,y,z)=xy+xz+yz$$
$$f_x=y+z$$
$$f_y=x+z$$
$$f_z=x+y$$
Answer: Hint :-
If $f(x,y)$ is a function and $u$ is an unit vector then the directional derivative of $f$ in the direction of $u$ is $\nabla f.u$, where $\nabla f$ is the gradient of $f$.
Comment: Is my $u$ the point $P$?
Comment: @inquisitor ...no...you need to find it in direction of $u$..so $u$ is the vector $\frac {(2,1,-1)}{\sqrt{6}}$. $P$ is the point at which you will find the gradient of $f$.
Comment: That depends on the definition of directional derivative that the OP is using. Many sources don't require a unit vector.


A vertical orientation app with one view controller horizontal orientation. How to design on the storyboard?

Question: I'm currently working on a small iOS camera app and have a storyboard-related question.

(Sorry for my bad drawing) Here is what I got on my storyboard, I have two view controllers, mainVC and cameraVC, and I added table view cells to mainVC to add a segue to cameraVC. This app is a vertical orientation app, and I want to make this app horizontally only when the user gets to the cameraVC. I'm not planning to make this app rotatable, hence this app only supports the vertical orientation if the user is in MainVC and only supports the horizontal orientation if the user is in CameraVC.
I'd add several more vertical view controllers later on, so I make the app vertical on the storyboard. However, I was not sure how should I design the camera VC on my storyboard.
While the app is running and the user gets to the camera VC, I want the app orientation horizontal (and don't rotate to vertical) and display buttons on the right side, like the image below.

So my question is while all the view controllers set to vertical, should I place buttons on the cameraVC at the bottom like the first image, or is better to place buttons on the right side with assuming the VC rotates when the user gets the camera VC, like the image below?

Sorry for the confusing question.
Answer: When designing a view controller in storyboard there is no property for orientation. There are however simulated values that are applied to whole storyboard to be either landscape or portrait.
If you want to simulate these values differently I suggest that you move your camera view controller to another storyboard. I would actually do that regardless of the issue you are facing.
If this doesn't suit you for any reason then you can still simulate your view differently. You can simply select your camera view controller in storyboard and use a Freeform simulated size like on the screenshot below.
Comment: @Oblak Thank you so much for the detailed explanation! I think separating storyboard will solve this issue and I will try this today!
Once I finish solving this issue, I'll accept this answer! Again, thank you so much.


Construct a smooth function satisfying certain conditions

Question: I need to construct a smooth $C^{\infty}$ real function $f(x)$ such that
$$f(x)=0\quad x<-1$$ and $$f(x)=1 \quad x>1$$ and $$0\le f(x)\le 1 \quad \forall x$$
I know I can construct the following function: $$g(x)=\frac{\int_\infty^x dt\ \theta(t+1)\theta(1-t) \exp\left({-\frac{1}{(x+1)^2}- \frac{1}{(x-1)^2}}\right)}{\int_\infty^\infty dt\ \theta(t+1)\theta(1-t) \exp\left({-\frac{1}{(x+1)^2}- \frac{1}{(x-1)^2}}\right)} $$
where $\theta(x)$ is the Heaviside step function
But I want a more explicit function. A piecewise defined function is OK, as long as each piece has a nice "explicit" formula.
Comment: What is this $\theta?$
Comment: @zhw. https://en.wikipedia.org/wiki/Heaviside_step_function
Comment: Is your $g(x)$ smooth in the $C^{\infty}$ sense?
Comment: @Andreas Yes, because the integrand is a $C^{\infty}$ function. The integral of a $C^{\infty}$ function should also be $C^{\infty}$
Comment: the arctan answer seems the nicest. I wanted to point out that exp(-1/x) has value and all derivatives 0 at 0 on the right. A function with value and all derivatives 0, multiplied by any smooth function will also have that. Thus exp(-1/(x+1)-1/(1-x)) will have value and all derivatives 0 at -1 on the right and at +1 on the left. So we can extend it smoothly with 0 on the left and on the right of the interval [-1,+1]. If we integrate this from -1 to x, this function is a smooth step function,which you can scale and shift to the request. ie you dont need to square 1/(x+1) and 1/(1-x).
Comment: the million dollar question is whether there is a nice formula for the integral of exp(-1/x - 1/(1-x)) from -1 to x. Have tried without luck, probably there isnt. I tried simpler problem of integrating exp(-1/x) by assuming it was a power series in 1/x times exp(-1/x), but that led to a divergent power series as solution! exp(-1/x) is unusual in that value and all derivatives are 0, so the taylor series isnt equal to the function on the right!
Answer: In $-1\le x\le 1$ define $$f(x) = \frac{1+ \sin(\pi x /2)}{2}$$.
Otherwise define as in your question, $$f(x)=0\quad x<-1$$ and $$f(x)=1 \quad x>1$$.
This is "smooth" in the sense that it is continuous and the first derivatives are also continuous.
EDIT:
sorry, the "$C^{\infty}$-smoothness" was edited into the OP's question after I posted my answer.
Comment: This doesn't address the question.
Comment: The 2nd derivative of $f(x)$ at $x=-1$ is not continuous.
Comment: Thanks, I want a $C^{\infty}$ function
Comment: smooth is maths jargon to mean infinitely differentiable! you are confusing visually smooth with maths smooth! But you need to have done pure maths at uni to know this maths jargon! Your function is only smooth on each side of -1, +1, but isnt smooth at those points.
Answer: I think this has a good chance of working:
$$f(x)=\begin{cases} \dfrac{1}{2}+\dfrac{1}{\pi}\arctan (te^{1/(1-t^2)}) & |t|<1\\1& t\ge 1\\0 & t\le 1\end{cases}$$
I haven't checked all the details yet.
Comment: @user34669 I changed my answer.
Comment: I've checked, it's right. Thanks!


PDO_mysql driver doesn't work

Question: I'm using Apache server on Windows 8, XAMPP 1.8.1, PHP 5.4.7 and MySQL.
I've decided to convert my code to PDO.
Checking my phpinfo() it appears that the PDO driver for MySQL is enabled, but I still keep on getting the "could not find driver" error.
Here's the code:
<?php
//connect to database

$config['db'] = array(
    'host'           => 'localhost',
    'username'       => 'root',
    'password'       => '',
    'dbname'         => 'x'
    );

$db = new PDO("
    pdo_mysql:host=     " .$config['db']['host']. ";
    dbname=             " .$config['db']['dbname']. ";
    username=           " .$config['db']['username'].";
    password=           " .$config['db']['password']."
    ");
?>

And the error:
Fatal error: Uncaught exception 'PDOException' with message 'could not find driver'
Any suggestions?
Comment: Let me suggest you to **to post in your question exact code you tried along with exact error message you've got**. To make it possible to give you some suggestions.
Comment: Because it's a driver issue I assumed the code is irrelevant, but I've added it now, hope it will help.
Comment: It cannot be driver issue as phpinfo() says driver is installed
Comment: I'm very certain it's the way you formatted your DSN string.
Answer: Let me suggest you refer to the manual page and get the proper DSN string example from there
Answer: What happens if you change the DSN prefix from pdo_mysql to just mysql?
Comment: it obviously works. while this should be a comment, not answer.
Comment: @YourCommonSense *"Ain't that the Pot calling the Kettle black."* You often put in answers similar to this ([Just like yours](http://stackoverflow.com/a/18674400/1415724)). Although it could have been worded differently, it led to an actual "answer/solution" and that's what's "important".
Comment: @Fred-ii- I **never** ask "what happens" in the answer. Either I know what happens already, or I don't answer at all.
Comment: @YourCommonSense Yes I agree, that's why I edited my comment and added "Although it could have been worded differently".
Answer: As manual says link
You should format your dsn in this way:
DRIVER:host=YOURHOST;dbname=YOURDB
Also to create the instance you should act like this: $db = new PDO($dsn, $username, $password)
Also I forgot to say (as other users have pointed out) your DRIVER is "mysql" and not pdo_mysql
Comment: Actually it is quite different, the user is including both username and password in the DSN, while they have to be passed as parameters.
Comment: Sorry. I overlooked that.
Answer: In the end there were 2 problems with the code:
1. pdo_mysql -> mysql
2. username and password should be passed as variables and not as strings.
The correct code is:
$config['db'] = array(
    'host'           => 'localhost',
    'username'       => 'root',
    'password'       => '',
    'dbname'         => 'x'
    );

$db = new PDO (
    "mysql:host=".$config['db']['host'].";dbname=".$config['db']['dbname']."",
    $config['db']['username'],
    $config['db']['password']
);

PDO_mysql driver doesn't work


Seasonal differencing in Arima function in forecast package in R

Question: I just want to ask about the Arima function in forecast package. The usage of it is,
Arima(x, order=c(0,0,0), seasonal=list(order=c(0,0,0), period=NA),
    xreg=NULL, include.mean=TRUE, include.drift=FALSE,
    include.constant, lambda=model$lambda, transform.pars=TRUE,
    fixed=NULL, init=NULL, method=c("CSS-ML","ML","CSS"), n.cond,
    optim.control=list(), kappa=1e6, model=NULL)

My data has trend and seasonality, so I applied seasonal differencing using the codes below,
Diff1LogCP <- diff(LogChickenProd, lag = 4, differences = 1)

Now, I want to have a model SARIMA(1,1,1). Using the Arima function, I'm not sure with the order and seasonal argument. Since my model is SARIMA(1,1,1), so what I did is,
SARIMA111 <- Arima(ChickenProd, seasonal = list(order = c(1,1,1), period = 4))

Notice that I ignore the order argument before the seasonal argument. This is because I'm using a seasonal ARIMA model, and not the ordinary ARIMA. So I use the seasonal argument only. Is that correct? Or do I need to include the order argument, that makes my new codes be
SARIMA111 <- Arima(ChickenProd, order = c(1,1,1), seasonal = list(order = c(1,1,1), period = 4))

Or should it be like
 SARIMA111 <- Arima(ChickenProd, order = c(1,0,1), seasonal = list(order = c(0,1,0), period = 4))

Thank you in advance!
Answer: If you want a SARIMA(0,0,0)(1,1,1)$_4$ model, then ignore the order argument. For the notation, see http://otexts.com/fpp/8/9/
Comment: Oh ok, I will read the link you've given to me. Thank you!


Audio clip is making no sound in Unity 2d

Question: using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class Shoot : MonoBehaviour
{
public Transform shootPoint;

public GameObject Bullet;

public float BulletSpeed;
public Animator anim;

private Vector2 direction;

public float fireRate;

private float ReadyForNextShot;

public GameManager gm;

public Player player;

public bool giga;

public GameObject Bullet1;

public AudioSource source;

public AudioClip shoot;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    direction = mousePos - (Vector2) shootPoint.position;
    FaceMouse();
    if (!gm.dialogue && !player.hasTransformed)
    {
        if (Input.GetMouseButton(0))
        {
            if (Time.time > ReadyForNextShot)
            {
                ReadyForNextShot = Time.time + 1 / fireRate;
                Shooting();
            }
        }
    }
}

void FaceMouse()
{
    shootPoint.transform.right = direction;
}
public void Shooting()
{
    if (giga)
    {
        GameObject bulletins = Instantiate(Bullet1, shootPoint.position, shootPoint.rotation);
        bulletins.GetComponent<Rigidbody2D>().AddForce(bulletins.transform.right * BulletSpeed);
    }
    else if(!giga)
    {
        GameObject bulletins = Instantiate(Bullet, shootPoint.position, shootPoint.rotation);
        bulletins.GetComponent<Rigidbody2D>().AddForce(bulletins.transform.right * BulletSpeed);
    }

    source.clip = shoot;
    print(source.isPlaying);
    anim.SetTrigger("shoot");
}

}
Just so you know the curly braces aren't properly alligned after copy and pasting the code.
So in this code I tell the audio source to change its clip to shoot. I have assigned the source variable and the clip as well as everything else. Though when in the game when shooting the audio source changes its clip to shoot but nothing is heard.
Comment: you dont show any code playing the clip only setting it
Answer:
source.clip = shoot;

only assigns the clip property ... you also need to call source.Play().

Alternatively to that, specifically for bullets, I would recommend to rather use source.PlayOneShot(shoot) instead which allows to play multiple instances of the sound in parallel.


almost disjoint functions from $\aleph_{\omega+1}$ to $\aleph_\omega$

Question: Is it consistent that any collection of almost-disjoint functions $\aleph_{\omega+1}$ to $\aleph_\omega$ has size at at most $\aleph_{\omega+1}$?
"Almost-disjoint functions" are also called "eventually different functions."  $f$ and $g$ are almost-disjoint with domain $\kappa$ when $\{ \alpha : f(\alpha) = g(\alpha) \}$ is bounded below $\kappa$.
For background, there are always $\kappa^+$ many almost-disjoint functions from $\kappa^+$ to $\kappa$.  The Kurepa hypothesis for $\kappa^+$ implies there are $\kappa^{++}$ many a.d. functions.  It is consistent (from large cardinals) that there are only $\aleph_1$ almost-disjoint functions from $\aleph_1$ to $\aleph_0$.
Comment: What do you mean almost disjoint *functions*?
Comment: @AsafKaragila Yeah, I mean it says "almost-disjoint functions." By the way, what does the aleph (א) mean (in math)?
Comment: @Shahar: No, I mean, what is the definition of almost disjoint functions (I can obviously read what it says in the question and title)? The $\aleph$ is a standard notation for cardinals. $\aleph_0$ is the least infinite cardinal, $\aleph_1$ the first, and so on.
Comment: (Err, in my above comment, of course I meant that $\aleph_1$ is the second least, not the first!)
Comment: @msbq: Do you know if it follow from tree property, [failure of] stationary reflection, or other combinatorial principles like that?
Answer: I see an answer.  Thanks to Asaf for making me think about such things.  Assume there is some stationary $S \subseteq \aleph_{\omega+1}$ such that $NS_{\aleph_{\omega+1}} \restriction S$ is $\aleph_{\omega+2}$-saturated.  This is consistent by Foreman-Komjath, relative to a huge cardinal.  (So this may be a very bad upper bound for the present question.)
Suppose there is a family $F$ of $\aleph_{\omega+2}$ many almost-disjoint functions from $\aleph_{\omega+1}$ to $\aleph_{\omega}$.  For each $f \in F$, there is some stationary $S_f \subseteq S$ on which $f$ takes constant value $\alpha_f < \aleph_\omega$.  There is a $G \subseteq F$ of size $\aleph_{\omega+2}$ such that all $f \in G$ have $\alpha_f =$ some constant $\beta$.  So for $f,g \in G$, $S_f$ and $S_g$ are almost-disjoint stationary subsets of $S$.  This contradicts saturation.
It would be interesting to see this from weaker assumptions.
Comment: Huge cardinals are never tight bounds, I think. Except for the existence of huge cardinals maybe. :-)
Comment: I once read somewhere that the non stationary ideal on any regular cardinal $\kappa > \omega_1$ can never be $\kappa^{+}$-saturated (Maybe due to Gitik-Shleha?). I never knew that its restriction to some stationary set could be saturated!
Answer: Suppose $\kappa$ is a measurable cardinal that satisfies $\begin{pmatrix}
\kappa^{++} \\
\kappa^+
\end{pmatrix} \to \begin{pmatrix}
2 \\
\kappa^+
\end{pmatrix}^{1,1}_\kappa$ (this implies the non-existence of almost disjoint functions from $\kappa^+$ to $\kappa$ of size $\kappa^{++}$). Now perform Prikry forcing $\mathbb{P}$ to change the cofinality of $\kappa$ to $\omega$. We claim in the final model $\begin{pmatrix}
\kappa^{++} \\
\kappa^+
\end{pmatrix} \to \begin{pmatrix}
2 \\
\kappa^+
\end{pmatrix}^{1,1}_\kappa$ is true, where $\kappa$ is a strong limit of countable cofinality. Let $\dot{f}: \kappa^{++}\times \kappa^{+}\to \kappa$ be the name for the given coloring. Suppose $\Vdash_\mathbb{P} \neg \exists \alpha, \beta\in \kappa^{++} \exists B\in [\kappa^+]^{\kappa^+} f(\alpha, \cdot)\restriction B = f(\beta,\cdot)\restriction B$. For each $(\alpha,\beta)\in \kappa^{++}\times \kappa^+$, find $p_{\alpha,\beta}=(s_{\alpha,\beta}, A_{\alpha,\beta})\in \mathbb{P}$ that decides $\dot{f}(\alpha,\beta)$ to be $i_{\alpha,\beta}\in \kappa$. Define the following coloring in the ground: $(\alpha,\beta)\mapsto (i_{\alpha,\beta}, s_{\alpha,\beta})$. By the hypothesis, there exists $\alpha_0,\alpha_1\in \kappa^{++}$ and $B\in [\kappa^+]^{\kappa^+}$ such that the map gets constant value $(i,s)$ on $\{\alpha_0,\alpha_1\}\times B$. For each $\gamma\in B$, let $A_\gamma = A_{\alpha_0,\gamma}\cap A_{\alpha_1,\gamma}$. Fix any $\gamma\in B$, consider the following coloring on $[A_{\gamma}]^{<\omega}$:
$\bar{v}\to 0$ if for cofinally many $\nu\in B$, $\bar{v}\subset A_{\nu}$, $1$ otherwise. By normality we can shrink it down to $A'\in U$ such that for all $n\in \omega$, $[A']^n$ get the same color, which must be $0$ (otherwise, for each tuple there is a tail of $\kappa^+$ that this tuple misses. But there are only $\kappa$ many tuples). Now find $(s^*, A^*)\leq (s, A')$ and $\sigma\in \kappa^+$ such that $(s^*, A^*)\Vdash \dot{f}(\alpha_0,\cdot)\neq \dot{f}(\alpha_1,\cdot)$ past $\sigma$. Since $s^*-s\subset A'$ we can find $\mu>\sigma$ in $B$ such that $s^*-s\subset A_\mu$, then $(s^*,A^*)\leq (s,A_\mu)$. But $(s,A_{\mu})\Vdash \dot{f}(\alpha_0,\mu)=i=\dot{f}(\alpha_1,\mu)$, contradiction. To get down to $\aleph_\omega$, we can interleave Lévy collapses with Prikry forcing.
On another note (i.e. no need to measurable nonsense), if you do $Coll(\aleph_{\omega+1}, <\kappa)$ for some inaccessible $\kappa$, then you'll have the negation of Kurepa Hypothesis at $\kappa^+$, which is the same as no almost disjoint functions from $\aleph_{\omega+1}\to \aleph_\omega$ of size $\aleph_{\omega+2}$.


Jquery validation engine, Prompt doesnt appear if called by ajax

Question: I am using callback function in the sign up form to check username validity.
validate[required,funcCall[username_check]]..
Here is the javascript function
<code>function username_check(field, rules, i, options) {
    var username = $('#username').val();
    if (username == "" || username.length < 4) {
        return options.allrules.validate2fields.alertText;
    } else {
        jQuery.ajax( {
            type: "POST",
            url: "<?php echo site_url('signup/validate');?>",
            data: 'username=' + username,
            cache: false,

            success: function (response) {
                if (response == 1) {
                    return options.allrules.validate2fields.alertText;
                } else {
                    return options.allrules.validate2fields.alertError;
                }
            }
        });
    }
}
$(document).ready(function(){
    $("#signup").validationEngine();
});
</code>
The alertText is not shown during validation.
if I write the below ifelse condition outside $.ajax prompt can be seen
<code>      if (response == 1) {
          return options.allrules.validate2fields.alertText;
      } else {
          return options.allrules.validate2fields.alertError;
      }
</code>
Is this a bug or i am doing something wrong.
Comment: i think you have error in function. Can u fiddle it? http://jsfiddle.net/
Comment: No there isn't any error in function (I have double checked )
Comment: Did you find the solution? I am in the same situation...Please let me know. Thanks
Answer: Looks like you are using an asynchronous AJAX call as synchronous. The code inside success callback function most likely is not being run, even if it is the result is returned as a result of that AJAX-success-callback function. Validation Engine has specific settings for AJAX validation. See here or here: jQuery Validation Engine AJAX Protocol.


Erro de null-safety e dependência

Question: Então, comecei em um estágio recentemente onde estou dando manutenção e criando novas features em um app mobile, uma dessas features é o usuário se registrar diretamente pelo app e não pelo DB do Firebase (no momento cadastramos os usuarios dessa forma). O código não recebe manutenção desde 2019...
Na parte que eu uso a sintax (User? user) me retorna este erro: This requires the 'non-nullable' language feature to be enabled.
Try updating your pubspec.yaml to set the minimum SDK constraint to 2.12.0 or higher, and running 'pub get'
Quando atualizo o sdk para o 2.12 o erro é resolvido só que que aparece muito mais... Já olhei documentação, youtube e tudo mais, minha esperança são vcs. Grato
<code>import package:firebase_auth/firebase_auth.dart;
 import 'package:flutter/cupertino.dart';

class AuthService extends ChangeNotifier{
  FirebaseAuth _auth = FirebaseAuth.instance;
  User? usuario;
  bool isLoading = true;

  AuthService(){
    _authCheck();
  }

  _authCheck(){
    _auth.authStateChanges().listen((User? user){
      usuario = (user == null) ? null : user;

    });

}}
</code>
Gabriel.
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: Você está tendo esse problema porque o sdk 2.12 introduziu null safety. Sugiro que você veja a documentação sobre como migrar para [null safety](https://dart.dev/null-safety/migration-guide)
Answer: Isso acontece porque seu código não era null safe. Se quiser adicionar a feature da forma que você disse, deve reescrever todo o código utilizando o null safety. Ou seja, vai ter que arrumar todos aqueles problemas. Utilize o link do rosário para entender melhor

Erro de null-safety e dependência


Qual é a relevância da Teoria das Categorias para a Ciência da Computação?

Question: Estou estudando um pouco sobre programação funcional e não raro acabo me deparando com pessoas que falam sobre Teoria das Categorias, o que me faz pensar que pode ser algo com certa importância para a programação funcional.
Até onde constatei, parece ser algo do campo da Matemática que eventualmente intercepta a Ciência da Computação. De fato, a Matemática é muito comum na nossa área, portanto isso não me causa estranheza.
Gostaria de ter uma ideia em quais tipos de situação a Teoria das Categorias pode ser relevante para a computação. É realmente relevante para a programação funcional?
Comment: @Sam, "ciência da computação em geral" faz parte do escopo do site ([veja aqui](https://pt.meta.stackoverflow.com/questions/264/quais-assuntos-devem-fazer-parte-do-nosso-foco-on-topic)).
Comment: @LuizFelipe. Checa https://youtu.be/SmXB2K_5lcA?t=324 e https://youtu.be/I8LbkfSSR58. Podem ser úteis.
Comment: Tem um livro da UFRGS só sobre isso, e parece que é um dos poucos que há sobre o tema: https://www.traca.com.br/livro/885610/teoria-das-categorias-para-ciencia-computacao-vol12/
Comment: Não tenho estudo suficiente pra oferecer uma resposta completa, mas acredito que como a programação funcional se originou devido as necessidades dos matemáticos para resolução de problemas, logicamente ela anda bem junto a matemática
Comment: Ixi! Me parece uma pergunta, apesar de bonita, fora de escopo.
Comment: é usado no desenvolvimento de linguagens de programação, pra criar mecanismos de checagem de erro em tempo de compilação
Answer: A teoria da Computação caracteriza-se pelo estudo formal dos processos de computação, suas capacidades e suas limitações, além
da relação entre as teorias comportamentais e o uso dos dispositivos automatizados. A teoria da computação torna-se primordial
para a ciência na medida em que, através de um sistema equacionado pela lógica, engenharia e matemática, proporciona conceitos
para encontrar a essência de uma implementação eficiente e, ainda, serve como base de raciocínio para a compreensão de uma
gama de fenômenos computacionais. Foi proposto o estudo de diversas áreas relacionadas à teoria da computação com o intuito
de comprovar sua importância no contexto tecnológico. Tais áreas são constituídas por conceitos básicos sobre formalismos,
máquinas de Turing, funções recursivas, solucionabilidade de problemas e outros. A partir do estudo desses conceitos, percebeuse a importância dos mesmos no sentido de fornecer suporte ao desenvolvimento de inúmeras aplicações práticas tais como
problemas NP, especificação e verificação de programas, análise sintática em compiladores, criptografia, análise de algoritmos
(complexidade computacional) e projeto de linguagens de programação de alto nível. (FAPERGS)
here is a book to help you better
https://www.amazon.com.br/Teoria-Categorias-Para-Ciencia-Computacao/dp/852410662X


Como fazer um input aceitar apenas numeros Binarios

Question: como faço para que este campo aceite apenas numeros binarios que nao aceite 12 nem 13 e etc, apenas numeros 1 e 0, como  0000111 ou 1000 ou 11111??
Comment: Cara nao adiantou ele agora so ta aceitando ou 0 ou 1. tipo um numero binario 11001 ELE NAO ACEITA!! POR FAVOR ALGUEM PODE ME AJUDAR?
Comment: https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Answer:

function SomenteNumero(e){
 var tecla=(window.event)?event.keyCode:e.which;
if((tecla==48 || tecla==49)) return true;
 else{
return false;
 }
 }
<input type="text" size="10" value=""' onkeypress="return SomenteNumero(event);">

Uma função é um procedimento de JavaScript - um conjunto de instruções que executa uma tarefa ou calcula um valor. Para usar uma função, você deve defini-la em algum lugar no escopo do qual você quiser chamá-la.
O evento onkeypress ocorre quando o usuário pressiona uma tecla (no teclado) - neste caso, chama a função.
keyCode (Keyboard Codes): Representa o número da tecla que o usuário pressiona no teclado 48 é o zero e 49 é o um.
Se (if) a tecla for zero ou um, tudo bem, aceita (return true)
senão (else) não aceita.

Observei que o keyCode agora está obsoleto e será descartado:

testei com e.key

function SomenteNumero(e){
 var tecla=(window.event)?e.key:e.which;
if((tecla==48 || tecla==49)) return true;
 else{
return false;
 }
 }
<input type="text" size="70" value=""' onkeypress="return SomenteNumero(event);">

em navegadores modernos.
Comment: muito obrigado mesmo funcionou!! agora se nao for pedir muito poderia me explicar o codigo.. meu principal foco é aprender...
Comment: (window.event)?event.keyCode:e.which    essa é a parte que nao estou entendendo. o que é este WINDOW.EVENT ai pelo que entendii, se for verdadeiro ele vai pro EVENT.KEYCODE se nao for ele vai para o :e.which; ai gostaria de saber o que sao estes e porque la no INPUT passou como parametro a palavra EVENT.  agradeço se puder me explicar como disse, aprendizado é o meu foco e serei muito grato se me ajudar a compreender melhor
Comment: Alguns browsers guardam a tecla em evento.which e outros em evento.keyCode, e o qualcuno apenas está se certificando de pegar o valor, qualquer que seja o browser. Outra alternativa seria `tecla = e.which || e.keyCode`. Se as teclas apertadas forem "0" ou "1" a função retorna `true`, o que significa: "vá em frente!". Se não for "0" ou "1" retorna `false`, o que significa "aborte o evento".


Are clustered standard error still possible if no panel data structure is available?

Question: The usage of CSE is usually linked to panel data. Should one still use it if the data structure is not a panel dataset but an event type structure?
Comment: Hi. How do you define an *event type* structure? It is always important to think about *how* you're sampling observations when applying cluster-robust uncertainty estimators.
Comment: Even if the individuals occur only once in the whole sample, I could cluster them? Sampled by whom? They are selected by investors that represent the whole population.
Comment: Its like Yi,t = β0 + β∗Aftert + ui,t; and the sample is fairly small; n<500, I could cluster along the cross section.
Comment: The *after* variable is *t* subscripted so I assume you are measuring something *through time*. Right? And yes, you could cluster on individuals if you believe there is "within-cluster" dependence, but it would depend on *how* they were sampled. Is there some type of study design you have in mind?
Answer: The short answer is, yes. You can cluster outside of a panel data framework. For starters, how the standard errors are influenced by clustering should never be the reason why you cluster. Of principal importance is how the sample of individuals was selected.
Without the specifics of how investors selected individuals in the population, it is difficult to advise you how to proceed. Here is something to think about. Did investors choose participants by first randomly sampling a set of firms in a given country, and then randomly sampling individuals within those firms? Or, did investors randomly select firms, and then randomly select mid-level executives from within those firms? In the former case, you may want to make inferences about the broader population of firms. In that case, you may want to cluster on firm.
If you have aggregate data, clustering at that level of aggregation is often advised. Outside of a panel data framework, we could still have observations that are related within certain groups. Students/children nested within classrooms is a classic example. Suppose you want to investigate the effect of classroom size on academic performance (i.e., grades). The model is specified as follows
$$
\textrm{Grades}_{ig} = \gamma_{0} + \gamma_{1} \textrm{Size}_{ig} + u_{ig},
$$
where $i$ indexes individual students and $g$ indexes the students' group. Note the possibility of within-cluster (classroom) correlation across students. Let's assume independence across classrooms for the sake of this example. Think about why observations (students) within a cluster (classroom) might be related (e.g., teacher quality). The 'quality instruction' unobservable might affect students individually within a group. But, we should be more concerned about unobservables affecting collections of students in the same way (uniformly), within a group. That is, $\textrm{E}\left[u_{ig} u_{jg'}\right] = \sigma_{(ij)g}$ if $g = g'$. If the errors are positively correlated within a cluster, then a new student introduced into the cluster does not provide an independent piece of new information. Failing to account for this may result in standard errors that are too small.
Based upon your question, it doesn't appear that investors are randomly sampling from the entire population. They may want a specific type of individual, not any individual. If everyone has an equal (non-zero) probability of selection, then you shouldn't concern yourself with clustering.


Operation between rows for different columns in a stacked group data frame

Question: R experts,
I have a stacked data frame and I want to create new columns based on conditional operation between rows which will be applied to different groups in data frame. I have a simple case to try out at your end.
df<-data.frame(case=c(rep("A",6),rep("B",6)),
               cond=c(rep(1:6),rep(1:6)),
               param1=c(100,200,300,400,500,600,150,250,350,450,550,650),
               param2=c(10,20,30,40,50,60,10,20,30,40,50,60))

Here is what I want the function to achieve -
(1) I want to create new columns (for eg. dparam1 and dparam2) based on param1 and param2. dparam1 is basically ratio of param1 at given "cond" normalized by param1@cond=6. Basically for each group, all rows are divided by one particular row.
Resultant data frame with new columns will look like this -
dfnew<-data.frame(case=c(rep("A",6),rep("B",6)),
               cond=c(rep(1:6),rep(1:6)),
               param1=c(100,200,300,400,500,600,150,250,350,450,550,650),
               param2=c(10,20,30,40,50,60,10,20,30,40,50,60),
               dparam1=c(0.17,0.33,0.5,0.67,0.83,1.0,0.17,0.33,0.5,0.67,0.83,1.0),
               dparam2=c(0.17,0.33,0.5,0.67,0.83,1.0,0.23,0.38,0.54,0.69,0.85,1.0))

(2) I do not want to specify name of new column. New columns should be named as "d" followed by original column name. I think I will have to use paste function (I am not sure!). But I am interested in seeing your inputs.
(3) Finally, I want to provide list of column names for which I want normalized new columns as an argument to this new function.
Here is my current function -
param_list<-c("param1","param2")
condref<-6
fun <- function(x,list) {
for (i in list) {
if(grepl("param1|param2",i)){
x$paste(c("d",i),collapse='')<-x$i/x$i[x$cond==condref]}
else{x$paste(c("d",i),collapse='')<-x$i-x$i[x$cond==condref]}
}
x
}

dfnew<-fun(df,param_list)

And the error -
Error in x$paste(c("d", i), collapse = "") <- x$i - x$i[x$cond == condref] :
  target of assignment expands to non-language object

Thanks!
Comment: You have the desired output and a series of conditions that the code needs to meet. Where's your code do to that? Where are you stuck?
Comment: How is it not working? Is there an error? What's the difference between the observed and expected behaviors? http://stackoverflow.com/help/how-to-ask
Comment: Here is my current function -

param_list<-c("param1","param2")
condref<-6
fun <- function(x,list) {
for (i in list) {
if(grepl("param1|param2",i)){
x$paste(c("d",i),collapse='')<-x$i/x$i[x$cond==condref]}
else{x$paste(c("d",i),collapse='')<-x$i-x$i[x$cond==condref]}
}
x
}

dfnew<-fun(df,param_list)

And the error -
Error in x$paste(c("d", i), collapse = "") <- x$i - x$i[x$cond == condref] :
  target of assignment expands to non-language object
Comment: Super! Could you edit that into the question, please? That way other users can quickly see it.
Answer: Well, I have a solution, but damn is it ugly:
maxCond <- as.data.frame(t(unstack(aggregate(cond~case,df,max),cond~case)));
cbind(df,setNames(as.data.frame(do.call(rbind,lapply(unique(df$case), function(case) do.call(cbind,lapply(c('param1','param2'), function(col) round(df[df$case==case,col]/df[df$case==case&df$cond==maxCond[[case]],col],2) ))))),paste0('d',c('param1','param2'))));
##    case cond param1 param2 dparam1 dparam2
## 1     A    1    100     10    0.17    0.17
## 2     A    2    200     20    0.33    0.33
## 3     A    3    300     30    0.50    0.50
## 4     A    4    400     40    0.67    0.67
## 5     A    5    500     50    0.83    0.83
## 6     A    6    600     60    1.00    1.00
## 7     B    1    150     10    0.23    0.17
## 8     B    2    250     20    0.38    0.33
## 9     B    3    350     30    0.54    0.50
## 10    B    4    450     40    0.69    0.67
## 11    B    5    550     50    0.85    0.83
## 12    B    6    650     60    1.00    1.00

You can wrap it in a function as follows:
f <- function(df,cols) { maxCond <- as.data.frame(t(unstack(aggregate(cond~case,df,max),cond~case))); cbind(df,setNames(as.data.frame(do.call(rbind,lapply(unique(df$case), function(case) do.call(cbind,lapply(cols, function(col) round(df[df$case==case,col]/df[df$case==case&df$cond==maxCond[[case]],col],2) ))))),paste0('d',cols))); };
f(df,c('param1','param2'));
## same result as above

Comment: Actually, @user3693111, our outputs seem to have mixed up `dparam1` and `dparam2` for case B. I'm pretty sure my result is correct; for example, 150/650 should give 0.23 in `dparam1`, no? Your `dfnew` has 0.17 there. Please confirm whether my output is correct, or whether yours is.
Comment: @bgoldst...Thanks for sharing your code. Your output is correct.
Comment: Any other ideas guys?


How to delete pages in a word document dynamically

Question: I need to delete a few pages in a word document dynamically, the page numbers will be fetched from a configuration file. How can i delete a particular page.
Comment: You can find your answer here. http://stackoverflow.com/questions/3754154/interop-word-delete-page-from-document
Comment: @KosalaW - Even this link you shared also not C#. It is VB or VBA Macro (Indeed lines of code are same for Word/Office Programming)
Answer: Here is the VBA Macro for what you need. You can easily translate it to C#
Selection.HomeKey wdStory
Selection.GoTo What:=wdGoToPage, Count:=3
Selection.Bookmarks("\Page").Select
Selection.Delete

3 in the above code is the page number I want to delete. You can use a for-loop and start deleting pages in descending order (In case you use ascending order the page numbers do change and you will end up deleting something other than what are intended to be deleted).
Hope this helps.
Comment: The question is related to C#; not VBA.
Comment: @KosalaW - I do understand. I don't have Visual Studio handy. So I typed it in a word macro. Same API would be used while writing code in C#. Just that instead of **Selection** it will be **objDoc.Application.Selection**. Intellisense would definitely help.
Comment: Hi Kosala, thanks for ur help....but it is not working for C#...its not accepting (/Page).....
Comment: Thers no option wdStory in C#.instead i get objWordDoc1.Application.Selection.HomeKey(Word.WdStoryType) and for the "\Page it says bookmark cannot be used like a method.
Comment: Please check the below code in c#. objWordDoc1.Application.Selection.HomeKey(Word.WdStoryType); objWordDoc1.Application.Selection.GoTo(WordObj.WdGoToItem.wdGoToPage, WordObj.WdGoToDirection.wdGoToAbsolute, 1); objWordDoc1.Application.Selection.Bookmarks("\Page") objWordDoc1.Application.Selection.Delete();
Comment: Can you try with this? _objApp.Selection.Bookmarks[@"\Page"].Select();_
Comment: Hi Prash,thanks for the help.It worked fine,But thers a small hitch.when im trying to delete multiple pages randomly using a loop,then for every iteration it increase the page number to be deleted also... ex:-say if im inserting 3,6,9 pages from a word document.it deletes 3,7,11 pages.
Comment: Glad to hear!! Delete 9, 6, 3. Such way, numbers of the page always remains same.
Comment: Whoa it worked great Prash....but im not able to understand why it kept changing before(for 3,6,9) and how is it working now(for 9,6,3)...
Comment: Great!! Feel free to mark it as answer whenever the system allows you to do so!! - And yes, regarding the reverse order; once you delete 3rd page, then the actual 4th page becomes 3 now, likewise the 6th page that you wanted to deleted would be the 7th page before you started the operation (and it continues..). So if you remove the last page first, all the pages before that would continue to have the same page number and the pages/items that get deleted are what you wanted to have deleted.
Answer:
Its deleting pages 1,4,7.where i want to delete pages 1,3,5.

  int num = objWordDoc.ComputeStatistics(stat, ref missing);
                int[] a = { 1,3,5};
                for (int i = 0; i < a.Length; i++)
                {
                    object page_num = a[i];
                    objWordDoc.Application.Selection.GoTo(Word.WdGoToItem.wdGoToPage, Word.WdGoToDirection.wdGoToAbsolute, num, page_num);
                    objWordDoc.Application.Selection.Bookmarks[@"\Page"].Select();
                    objWordDoc.Application.Selection.Delete();

                     }

Answer:
Its deleting pages 1,4,7.where i want to delete pages 1,3,5.

this is simple: when you delete page 1 then your page 3 becomes page 2 and if you still deleting page 3 then you actually delete former page 4
and so on
just reverse array in your code and you'll be fine {5,3,1}


How to specify input_type of a widget upon declaration?

Question: Usually when defining a DateInput widget in the form, the generated html looks like this:
<input type="text" name="from_date" id="id_from_date">

the type is text instead of date or datetime.
One way to fix this is, would be setting the type in the __init__ :
class FilterCallsForm(Form):
    def __init__(self, *args, **kwargs):
        super(FilterCallsForm, self).__init__(*args, **kwargs)
        self.fields['from_date'].widget.input_type = 'date'

    from_date   = forms.DateField(localize=True, widget=forms.DateInput())

This works and I get a <input type="date" name="from_date" id="id_from_date"> as required.
However is there a way to define it right when I declare the widget? I didn't find a way other than doing it through __init__ which seems a bit odd.
Comment: This is fine. __init__ can be used for runtime modifications. However, the best practice would be to create a widget
Comment: thanks for your comment. Could you give me a tiny example what you mean by creating a widget? Do you mean extending forms.DateInput()?
Comment: https://docs.djangoproject.com/en/dev/ref/forms/widgets/  You can create custom form widgets and specify it the way you want it to be rendered.
Comment: This is something i havent tried - in a form definition, can you specify {attrs = "type: date"}
Comment: oh yeah I have tried `{attrs = "type: date"}` without any luck :)
Answer: You could subclass DateInput, and use your custom widget when you define the form:
class MyDateInput(DateInput):
    input_type = 'date'

class FilterCallsForm(Form):
    from_date = forms.DateField(localize=True, widget=MyDateInput())