Passing structures to functions in C programming

Question: Declared structures:
typedef struct{
    char fname[25];
    char mname[3];
    char lname[25];

}Name;

typedef struct{

    char month[25];
    int day,year;

}Date;

typedef struct{
    Name gname;
    char addr[50];
    char cnum[11];
}Guardian;

typedef struct{
    Name sname;
    Date sbday;
    Guardian sguard;
    char gender[6];
    char addr[50];
    char cnum[11];
    char course[10];
    int year;

}Student;

Declared functions:
void input(Name name,Date date, Guardian guard, Student stud);
void display(Name name,Date date, Guardian guard, Student stud);

When input function is called, it lets me add strings being asked. Then, display function is called. It will not display the entered information.
Calling functions:
input(name, date, guard, stud);
display(name, date, guard, stud);

Display funtion:
void display(Name name, Date date, Guardian guard, Student stud)
{

    printf("   -=Student Information=-   \n");
    printf("Name: %s %s. %s\n",stud.sname.fname,stud.sname.mname,stud.sname.lname);
    printf("Birtday: %s %d, %d\n",stud.sbday.month,stud.sbday.day,stud.sbday.year);
    printf("Gender: %s\n",stud.gender);
    printf("Contact Number: \n%s",stud.cnum);
    printf("Course & Year: %s-%d \n",stud.course,stud.year);

    printf("   -=Student Guardian Information=-   \n");
    printf("Name: %s %s. %s\n",guard.gname.fname,guard.gname.mname,guard.gname.lname);
    printf("Address: %s\n",guard.addr);
    printf("Contact Number: %s\n",guard.cnum);
}

Input function:
void input(Name name,Date date, Guardian guard, Student stud)
{

    printf("Student Information \n");
    printf("First Name: ");
    gets(stud.sname.fname);
    //...
}

This will just display one set of information. It won't add new records per say. Just a simple exercise.
Comment: Problem is that C uses pass-by-value, so you just modify copies of original structs, not struct themselves. Pass addresses.
Comment: You're also passing in parameters *by value* instead of as a pointer, something that's extremely messy and wasteful.
Comment: Never ever use `gets`. It's a dangerous function which have been removed from the C specification. Use alternatives like [`fgets`](http://en.cppreference.com/w/c/io/fgets) instead.
Comment: Instead of fixed-length character fields, you're going to want to use `char*` and dynamically allocate. Some of these buffers are ridiculously short.
Comment: btw..to add.. This will just display 1 set of information.. It won't add new records per say.. Just a simple exercise
Answer: C is pass by value. So when you passed a variable as you have shown - a copy of it is given to the called function so that it can work with it. As a result the object from which the copy is made remains unchanged. The solution is to pass the address of the object and then dereferencing  the copied pointer variable which contains the address of the object - thus changing the intended object.
So in your case,
void input(Name *name,Date *date, Guardian *guard, Student *stud){
   printf("%s",name->fname); // short hand for (*name).fname
   ...
}

Call it like
input(&name, .. );

Even if you want only read those objects(you don't want to change anything) then also I would support this way of doing things - why burden things by copying those large structure instances? Just pass the address of them and work with it.
Also don't use deprecated gets - use fgets instead and when you use it (fgets) don't forget to check the return value.
Comment: since the guardian struct and student struct has a common structure which is Name.. I don't think `Name -> fname` would work since. Ill have to do `guard.gname.fname` etc.
Comment: @EricMichaelFadriga.: Hey I am giving you a example...and I wrote `name->fname` here it is a variable `name`. You get what I am saying?
Comment: ohh wow it worked!!! :D Thanks man!! :D I forgot to place a `*` in the function declaration..
Answer: Like how to modify the content of a variable througth a function, you need to give the address of the structure, because "deep down", a variable of type "int" and a variable of type "struct something", well, it's a variable.
And if you want to modify the value of your variable, you need to send his address (pointer).
Also, note that by passing the value of the struct, the value are copied. For small structure, it doesn't really matter, but for "larger" one, it will cost really huge on your program's speed.


When is something "obvious"?

Question: I try to be a good student but I often find it hard to know when something is "obvious" and when it isn't. Obviously (excuse the pun) I understand that it is specific to the level at which the writer is pitching the statement. My teacher is fond of telling a story that goes along the lines of

A famous maths professor was giving a lecture during which he
  said "it is obvious that..." and then he paused at length in thought, and then
  excused himself from the lecture temporarily. Upon his return some fifteen minutes later he said "Yes, it is obvious that...." and continued the lecture.

My teacher's point is that this only comes with a certain mathematical maturity and even eludes the best mathematicians at times.
I would like to know :

Are there any ways to develop a better sense of this, or does it just come with time and practice ?
Is this quote a true quote ? If so, who is it attributable to and if not is it a mathematical urban legend or just something that my teacher likely made up ?
Comment: @Mariano: That is obvious.
Comment: Nothing is obvious.
Comment: Your teacher's "story" isn't really a story, it's a joke.  It's meant to get across the idea that saying things are obvious is rather silly and can easily slide into pretentiousness.
Comment: [Vastly related post](http://math.stackexchange.com/questions/54431/why-do-people-use-it-is-easy-to-prove).
Comment: possible duplicate of [What does it really mean for something to be "trivial"?](http://math.stackexchange.com/questions/138112/what-does-it-really-mean-for-something-to-be-trivial)
Comment: The famous mathematics professor in the OP's story was Norbert Wiener.
Comment: In his lovely book 'Mathematics - A Very Short Introduction', Tim Gowers proposes (or possibly quotes - don't have the book with me) the idea that a statement is obvious if a proof immediately comes to mind. This is subjective of course, but I find it a very nice guide as to when the word should and shouldn't be used.
Comment: Mathematicians can only prove trivial things, because everything proven is trivial - Richard Feynman
Comment: The only obvious thing is that nothing is obvious.
Comment: @AsafKaragila, actually, I would say that that is quite non-obvious in fact! :)
Comment: I actually heard Tarski kind of do this.  Except he did not leave the room. And he scribbled for a while, but it wasn't $15$ minutes. And, most importantly, he may have been making a reference to what was probably by that time an old joke.
Comment: @Mariano: It depends on your philosophical bent, I suppose.
Comment: Obvious means 'it has been proved'.
Comment: Yes, it was Norbert Wiener.  He didn't leave the room.  He spent the 15 minutes scribbling in one corner of the board.
Comment: @MarianoSuárez-Álvarez I may have a possible counter example for the statement that there are no obvious statements. Given peano's definition of natural numbers, it is obvious that there exists at least 1 natural number.
Answer: Like Florian, I really like Gowers' definition of obvious. Of course this is a very personal definition. A proof that instantly springs to mind for one person may not spring to mind for another. I am not really sure what there is to say at this level of generality beyond that.
Really phrases like "it is obvious that..." and "clearly..." are bad habits. In a mathematical argument they are the places you should look at first for possible errors.

Perhaps another story will be illuminating: a professor of mine once made an assertion in lecture that I didn't quite see instantly. I asked him "is that obvious?" and he replied "yes." I asked him "is it obvious that that's obvious?" and, after a short pause, he replied "no."
Comment: Was the assertion correct?
Comment: @Douglas: to be honest, I don't remember. This was about a year ago now.
Answer: I really like the following definition (here given by fields medalist Timothy Gowers, and he credits his former colleague):

A statement is obvious if a proof instantly springs to mind.

However, for many mathematicians and teachers the meaning of "obvious" unfortunately is much broader.
Answer: I had an economics professor who thought one result was obvious and spent over 3 hours explaining the "obvious" result to a fellow mathematician.  After 3 hours, he realized it might not have been so obvious and found it to be, in fact, false, and published 3 papers from the counter-examples.
Comment: Care to share the obvious result and links to the papers?
Comment: I laugh every time I read this answer ... thank you!  @LogamTatham  (Update:  Because it is true!)
Answer: I believe the famous mathematician was G. H. Hardy, and I am sure he had a different view as to what is "obvious" compared to lesser mortals (like myself).
I would say that "obvious" should only ever be applied to things that the speaker believes that his listener should find "simple" ..
Comment: It is often misused to gloss over some lengthy, messy development.
Comment: Agreed - and I believe I have been guilty of this myself on some rare occasions.
Answer: The level of triviality of a mathematical is relative to the observer. That is to say, a mathematician who has worked in geometry his entire life would find a certain set of geometric statements $P$ obvious, whereas an undergraduate student learning from his/her first geometry textbook will likely only consider some subset $M \subset P$ of the statements that the mathematician does as obvious.
A good illustration of this would to consider the following statement,

Project the edges of a regular icosahedron $I$ inscribed in $\mathbb{S}^2$ onto $\mathbb{S}^2$ from the center of $I$. Then $\mathbb{S}^2$ is obviously divided into 20 equilateral triangles of area $4\pi / 20 =0.628...$

Embedded in the statement is quite a few trivial facts that an undergraduate student completely new to geometry (maybe this particular example would only be frustrating to a high school student) may not be aware of, and so upon reading this statement for the first time may be frustrated by the use of "obvious".
My answer to the question is that as you navigate your way through learning more and more mathematics over time, you are expanding the cardinality of your set $M$. There does not seem to be a way to intentionally increase your knowledge of trivial or obvious statements while not learning the other non-trivial parts of mathematics that those trivial statements hint towards.
Comment: It's my experience that usually neither of the sets $M$ and $P$ is contained in the other.
Comment: @MJD In my personal experience as an undergrad so far, $M$ usually contains many statements which are false...
Comment: Answering mathematics with the language of mathematics is always rather conducive to understanding. Thank you.
Answer: That quote is often told of G. H. Hardy. You will find it in Lion hunting & other mathematical pursuits, by Ralph P. Boas Jr:

The story is told of G. H. Hardy (and of other people) that during a lecture he said 'It is obvious… Is it obvious?' left the room, and returned fifteen minutes later, saying 'Yes, it's obvious.' I was present once when Rogosinski asked Hardy whether the story were true. Hardy would admit only that he might have said 'It is obvious… Is it obvious?' (brief pause) 'Yes, it's obvious.'
Answer: I consider this in the same vein as "it is easy to see that..." , which is probably encountered more often than "it is obvious that..." and there is a good discussion about that here.
Answer: A statement attributed to Littlewood in a footnote of Cassels' book "Geometry of numbers" says "Every equality is trivial when it is known"
Answer: Mathematical statements are only evaluated by individuals.  Since individuals differ in mathematical ability, the answer is that "something" is never obvious to everyone or to yourself.  The crux of the joke is that it was only obvious to the professor after reflection, which is deliberate irony since there would be no point in reflecting if something were explicitly obvious.  Hence, the point is that if even the expert professor had to make sure it was obvious, then students should only check axioms even more diligently, no matter how hallowed the axiom.
Answer: I have never experienced a non obvious "obviously" in a textbook in mathematics. If it wasn't obvious at first sight it became obvious after some investigations.
To me, what is really obvious is a claim that is true and can be easy proved, but that might not be that obvious from the wrong perspective.
Anybody can fail to see what is obvious and anybody with appropriate knowledge can agree after some thinking. So there is no way to develop a sense of it, but having knowledge about the subject.
Comment: Do you want to know why the downvotes? We won't tell you because it's obvious.
Comment: @Aelx - It obviously means that four users disliked my answer.

When is something "obvious"?


Let $E_1=\mathbb{Q}(\alpha)$ and $E_2=\mathbb{Q}(\beta)$ show that $[E_1E_2:E_1]=2$ where $\alpha,\beta$ be the real and complexroot of 2 respectively

Question: I am studying  lang undergraduate algebra,  field theory where this example is given.
Now I understand how $E_1 \cap E_2=\mathbb{Q}$. As we have $ \mathbb{Q} \subset E_1 \cap E_2 \subset E_1$. And we have $[E=\mathbb{Q(\alpha)}: \mathbb{Q}]=3$ since the basis of vector space $E_1$ over $\mathbb{Q}$ is ${1,\alpha, \alpha^2}$. So now $[E_1:\mathbb{Q}]=[E_1 : E_1 \cap E_2][E_1 \cap E_2 :\mathbb{Q}] \implies 3= [E_1 : E_1 \cap E_2][E_1 \cap E_2 :\mathbb{Q}]$. So that's why $[E_1 : E_1 \cap E_2] \ \vert \ 3$, since $E_1 \neq E_2$ $[E_1 : E_1 \cap E_2] \neq 1$ so $[E_1 \cap E_2 :\mathbb{Q}] =1$ and $E_1 \cap E_2 =\mathbb{Q}$.
Now $\mathbb{Q} \subset E_1 \subset E_1E_2$ so $[E_1E_2 : \mathbb{Q}]=[E_1E_2:E_1][E_1:\mathbb{Q}]$. So $[E_1E_2:E_1] =\frac{[E_1E_2 : \mathbb{Q}]}{3}$.But at the end I don't understand how they come to conclusion that $[E_1E_2:E_1]=2$. How they have calculate $[E_1E_2=\mathbb{Q}(\alpha,\beta)=\mathbb{Q}(\alpha,\sqrt(-3) : \mathbb{Q}]=6$. Any help is appreciated thanks.
Answer: Since $\alpha$ has minimal polynomial $x^3-2$ and $\sqrt{-3}$ has the minimal polynomial $x^2+3$, the combined degree of the extension is $2\times 3=6$.
This calculation implicitly uses $\Bbb Q(\alpha,\sqrt{-3})\cong\Bbb Q(\alpha)(\sqrt{-3})$ and we compute the degrees one at a time:
$$6=\underset{2}{\underbrace{[\Bbb Q(\alpha,\sqrt{-3}):\Bbb Q(\alpha)]}}\cdot\underset{3}{\underbrace{[\Bbb Q(\alpha):\Bbb Q]}}$$
Comment: Thank you very much. Basically we have to see the minimal polynomial over $\mathbb{Q}(\alpha)$
Comment: @Alexander You're welcome. Yes, $\alpha$ and $\sqrt{-3}$ do not really interact and the minimal polynomials are left unchanged


Can anyone recommend a good book about virtualisation?

Question: Can anyone recommend a good book about virtualisation, including the Popek and Goldberg virtualization requirements?
I mean a book that doesn't necessarily focus on x86 but also does comparisons to PowerPC and 68k or IA-64.
Is Smith, Jim; Ravi Nair (2005) "Virtual Machines" any good?
Comment: [Product, Service, and even *book* recommendations are off-topic on Stack Exchange sites](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/) - Virtualization being a (relatively) new technology is especially problematic as new books are being written/published and what we recommend as a great book today might be awful compared to what gets released tomorrow. Amazon or Google can help you out - they even have book reviews and ratings. Alternatively you can ask in chat.
Comment: This question was asked (and answered) years ago. And the article you point to doesn't say that book recommendations are really off-topic.
Comment: A book is a product. Years ago there was no general policy on product recommendations - now there is. If you disagree with the policy (or think books should be an exception) Please raise the issue on [Meta](http://meta.serverfault.com) - I'll be happy to discuss it further there.
Answer: This one is a mustread if you're interested in the architecture and only have basic knowledge of how virtualization works:
http://www.anandtech.com/showdoc.aspx?i=3263&p=1
Also check out the blog on http://it.anandtech.com for benchmarks and comparisons with cutting edge as well as more mainstream hardware together with virtualization.
Comment: The Dummies book is probably very good. But I am looking for something more specific to why certain instructions cannot be virtualised etc..
Comment: It's been a while since I read the article, but I thought it was mentioned in there briefly? Didn't go into detail all too much but I think it did mention and explain it.
Answer: Definitively, "Virtual Machines (Versatile platforms for Systems and processes)" By Smith & Nair is the ultimate book about virtualization in a scientific way and neutral vendor. But it covers a lot of aspect: emulation, Java virtual machine, hardware virtualisation... It is not specific about one architecture but has a lot of discussion about architecture-dependant optimization.
alt text http://img2.fkcdn.com/img/105/9781558609105.jpg
Answer: I don't have have specific book recommendations but would suggest that whatever you do find includes material from within the last year or so. Virtualisation technology has made some significant advances since 2005, that's for sure.
Answer: this is one https://dct.sun.com/dct/forms/reg_us_1404_584_0.jsp?cid=222965
Comment: Virtualization For Dummies this name of book which there to download from http://www.sun.com
Comment: Seems a little product-specific. I am not looking at the "how to use" but the "how it works".
Answer: Virtualization is really a broad topic, and I'm afraid unless you try to focus on a certain type of virtualization you won't really get much out of whatever book you choose.  There's Operating System virtualization, Profile virtualization, Hardware virtualization, Software virtualization....the lists goes on and on, and because it is so fragmented I wouldn't trust any book that covers all of them as a whole.
Comment: I think the phrase "Popek and Goldberg" already defined the field.
Answer: If you are going to use VMware, I highly recommend VMware INfrastructure 3 Advanced Technical Design & Advanced Operations Guide: http://www.amazon.com/VMware-Infrastructure-Advanced-Technical-Operations/dp/0971151083/ref=sr_1_1?ie=UTF8&s=books&qid=1244811586&sr=8-1
Comment: I find this book to be great reference, but not really a good book for a beginner trying learn the ropes.
Comment: It seems to be too high-level and product-specific. Rather a "how-to-administer" than "how-it-works".


Poor Bspline estimation for variables with short range

Question: I am recently surprised to observe a fact that, in a simple univariate regression model, the Bspline estimator performs NOT well if the range of the variable is narrow. Namely, let's consider estimating the following cross-sectional regression model
$$Y_i=m(X_i)+u_i, \ i=1,...,n,$$
where $n$ is the sample size, $Y_i$ is the dependent variable, $X_i$ is a univariate independent variable, and $u_i$ is the random error such that $E(u_i|X_i)=0$. Here, $m(\cdot)$ is an unknown conditional mean function, i.e., $m(x)=E(Y_i|X_i=x)$ for some $x$, and we assume $m(\cdot)$ is smooth.
Using Bspline estimator, we can approximate $m(X_i)\approx \sum_{l=1}^{L_{n}}\phi(X_i)\beta_l$, where $\phi(\cdot)$ is a known basis function and $\beta_l$ are unknown coefficients to be estimated. $L_n$ is the number of knots placed on the range of $X$, requiring us to specify boundary knots (knots on the boundary points of $X$) and interior knots (knots on the interior support of $X$, excluding the boundary points). For instance, if the range of $X$ is $[0,1]$, then the boundary knots are $[0,1]$, and the interior knots are, say, $(0.25,0.5,0.75)$. One can easily employ the package spline to construct $\phi(X_i)$, and estimate $\beta_l$ through OLS.
Question: The Bspline estimation is often very well by assuming the range of $X$ is relatively large, say $X\in [-1,1]$. However, I just found that the estimation becomes poor if the range of $X$ is narrow, say $X\in [0,0.3]$, which can be true in practice. I attached my code below for your reference. The poor performance remains regardless of how many interior knots we choose to place. Any suggestion on the issue here?
library(splines)
#---generating DGP by let x1~U(0,0.3):

n <- 500
x1 <- runif(n, 0, 0.3)
m1 <- x1^2

u <- rnorm(n, 0, 0.5)
y <- m1+u

Q <- cbind(x1)

#---obtain the boundary of x1:
knots.range.x=t(apply(Q, 2, range));

#---select one interior knot:
int.knots.x1 <- c(0.15)

#---create a matrix for the basis functions:
PhiX <- bs(Q[, 1], knots = int.knots.x1, degree=3, intercept = T,
           Boundary.knots = c(knots.range.x[1, 1], knots.range.x[1,
                                                                 2]))

#---estimate coefficients of beta:
ols.model <- lm(y ~ PhiX-1)
beta <- ols.model$coefficients

#---plot estimated function against the true one:
plot(x1, m1, type='p')
m1.hat <- PhiX%*%beta
points(x1, m1.hat, col='red', lty=2)
```

Comment: I see nothing here that implicates the range *per se.*  The problem is that the error sd (0.5) is huge compared to the range (0 to 0.09 for $x_1^2$), making it almost impossible to detect a relationship.  The performance of *any* model will be poor.
Comment: @whuber: You make a good point that I didn't noticed. Thank you so much.
Comment: Did you try information criteria (or cross validation?) to choose number of knots?
Comment: There is an error in your code.  Can you please ensure the code runs and generates what you expect?
Comment: @ kjetil b halvorsen: Yes, I tried. The generalized cross validation requires about 3 interior knots, but that induces more variation of estimation and thus the mean function structure still cannot be captured adequately.
Comment: @Demetri Pananos: I am sorry for the coding issue. I have revised the code, and it can be copy-paste and run in R now.
Answer: A picture says it all.

The scatter of values around any possible reasonably smooth curve through these points is so great as to obscure any underlying trend in their average value (conditional expectation).
The right hand plot shows that if data could be generated (collected) for a wider range of the explanatory values x1, the (quadratic) variation in the regression might become detectable.
If you remain limited to the original narrow range, you would need a sample of size $n\approx 100,000$ to detect this trend reliably using the least squares model $E[Y]=\beta_0+\beta_1 X_1 + \beta_2 X_1^2.$  This is neither a limitation of least squares nor of the model formulation (spline or otherwise): it merely reflects the difficulty of detecting this tiny signal amidst all the noise.
Comment: This is a very great and vivid explanation. Thank you so much for the help.


Using Azure Maps with React Native

Question: I have to build a mobile application that would work with both Android and iOS, so that's why I'm not using the Azure Maps Android SDK.
So I just wanna know if it is possible to use the Azure maps in React Native. I've tried with this repo: https://github.com/WiredSolutions/react-azure-maps which is a react wrapper for the Azure Maps. This repo is working perfectly on the web app, using react, but it doesn't seem to work on the mobile app, because when I'm trying to import these packages:
import {AzureMap, AzureMapsProvider, IAzureMapOptions} from 'react-azure-maps';
import {AuthenticationType} from 'azure-maps-control';
it's throwing an Cannot create URL for blob! exception in the react-azure-maps.umd.js and in the atlas.min.js files.
The version installed in package.json are:
    "azure-maps-control": "^2.0.31",
    "expo": "~39.0.2",
    "expo-status-bar": "~1.0.2",
    "react": "16.13.1",
    "react-azure-maps": "^0.1.4",
    "react-dom": "16.13.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-39.0.3.tar.gz",
    "react-native-web": "~0.13.7",
    "typescript": "^3.7.5"
  },
  "devDependencies": {
    "@babel/core": "~7.9.0"
  },

Comment: It might be better to raise this as an issue/question on that open source project.
Comment: I did that, and for that specific open source project, the answer is no, it can't be used for mobile applications. But my question is still not answered, is there no way of using Azure maps with React native?
Comment: You need to create a native bridge. React and React Native use different primitives. (DOM VS Native Components)
Answer: There is no solution to this problem yet, because, as the other answers said, iOS is not supported. Also, there are no libraries for react native that are supporting Azure Maps.
My workaround was to use React Native Maps as the map provider, and just do a backend call to the Azure Maps route provider.
In this way, I just draw the route provided by Azure Maps on the React Native Map.
Hopefully this will help some other people that are trying to use Azure Maps.
Comment: could you share some examples?
Answer: Here it seems, that iOS is not yet supported.  How to integrate azure-map in iOS Application
If MS will not publish library for React Native, you would need to create RN wrapper by yourself.
Comment: it is better to poste this as comment

Using Azure Maps with React Native


Is it true that (L\a + L\b,L) = 1. L=$lcm(a,b)$

Question: Suppose $a$ is  different from $b$ and $L=lcm(a,b)$.Is it true that (L\a + L\b,L) = 1$ ?
How do I approach this one? Should I write the Bezout's Theorem??
Comment: You must exclude negative $a,b,\;$ otherwise it is wrong for $b=-a; |a| > 1$
Comment: By L\a is it meant L/a?
Comment: Yes it means / sorry
Answer: It is not true: take $a=6$ and $b=10$. Then $L=30$ and $\dfrac La+\dfrac Lb=8$, which are not coprime.


Aleatório dentro de um random

Question: Galera, eu tenho esse código aqui:
<?php
// Define um array com alguns sites:
$site[] = 'google.com';
$site[] = 'facebook.com';

// Escolhe um valor aleatório (respeitando o total de sites)
$destino = rand(0, (count($site) - 1));

// Redireciona o usuario:
header("Location: " . $site[$destino]);
?>

Atualmente ele escolhe aleatoriamente entre os dois link e abre um deles. Mas queria uma alteração simples, e não sei como fazer exatamente pois não entendo muito disso. Eu queria que na segunda opção, tivesse duas opções. Mas como assim? Queria algo tipo assim?
<?php
// Define um array com alguns sites:
$site[] = 'google.com';
$site[] = 'youtube.com'  ouuu  'facebook.com';

// Escolhe um valor aleatório (respeitando o total de sites)
$destino = rand(0, (count($site) - 1));

// Redireciona o usuario:
header("Location: " . $site[$destino]);
?>

Sendo assim, um random dentro de um random. Alguém poderia me ajudar com isto?
Comment: Então a pergunta deveria ser essa xD "Como fazer para sortear um valor considerando pesos diferentes para cada valor" ou algo assim.
Comment: E por que o `facebook.com` não poderia entrar como um terceiro item no array?
Comment: Bastaria adicionar uma outra entrada de google ou fazer um array que coloca o peso de cada elemento e vê qual foi o índice baseado no range do rand (:
Comment: Por que eu queria apenas cerca de 25% dos acessos para este site. O google seria o redirecionamento principal, no caso cerca de 50% de chance. E dai esses outros 50% eu queria dividir entre os outros dois links, por isso não posso criar um terceiro array, pq se não ficaria cerca de 33% de chance de acesso em cada array
Answer: O que você quer é sortear um elemento da lista com pesos diferentes. Há uma explicação sobre isso na pergunta abaixo e não vale a pena replicar aqui:

Sorteio aleatório, mas com diferentes probabilidades

Em PHP, uma possível implementação seria:
$urls = [
    'url A' => 50,
    'url B' => 25,
    'url C' => 25
];

$x = rand(0, 100);

foreach ($urls as $url => $probability) {
    $x -= $probability;

    if ($x <= 0) {
        echo $url;
        break;
    }
}

Onde a URL A tem 50% de chance de ser sorteada, URL B tem 25% e a URL C também 25% de chance de serem sorteadas. Você pode alterar $urls livremente, desde que a soma das probabilidades seja sempre 100, por questões óbvias.
Comment: Valeu, cara. Muito obrigado!
Answer: <?php
$sites = array("siteprincipal");
$site_ind = array("siteindependente1.com", "siteindependente2.com", "siteindependente3.com", "siteindependente4.com");
$sites[1] = $site_ind;
$destino = rand(0, count($sites)-1);
if(is_array($sites[$destino])){
    $destinoind = rand(0, count($sites[$destino])-1);
    header("Location:". $sites[$destino][$destinoind]);
}else{
    header("Location:".$sites[$destino]);
}
?>

Comment: Teria como me ajudar? Não entendo muito dessas coisas :/
Comment: Você vai usar somente três sites?
Comment: Serão 6. Ai queria tipo, 4 deles independentes, e dois dentro de uma unica array. Tipo assim:

`$site[] = 'site1.com';
$site[] = 'site2.com';
$site[] = 'site3.com';
$site[] = 'site4.com';
$site[] = 'site5.com'  ouuu  'site6.com';`
Comment:
Comment: Vc só tem que quebrar as linhas pra ficar direitinho
Comment: E trocar as strings dentro dos arrays
Comment: Depois fala se deu certo
Comment: Eu segui o exemplo do outro cara ali acima. Mas muito obrigado pela força, cara.
Comment: Bruno, você pode **[edit]** sua resposta e colocar o código lá. É melhor porque fica mais organizado (toda a informação junta, assim as pessoas não precisam ficar "caçando" o código nos comentários), a além disso na resposta [é possível formatar o código](https://pt.stackoverflow.com/editing-help#code), deixando-o bem mais legível do que nos comentários
Comment: Vlw, sou novo na plataforma kk

Aleatório dentro de um random


Can double Type take parameters scala

Question: I have written the following code:
`  private def maxYinRange(minX: Double,
                              maxX: Double,
                              minY: Double,
                              node: PointerPSTNode): Double = {
       if (node == null || node.getY < minY) java.lang.Double.NEGATIVE_INFINITY
       val nodeX: Double = node.getX
       if (nodeX >= minX && nodeX <= maxX) node.getY
       val leftChild: PointerPSTNode = node.getLeftChild
       if (leftChild != null) {
       val nodeR: Double = maxX(leftChild)/*here is the error*/
       // nodeR >= points in left tree >= minX
        if (nodeR >= minX && nodeR < maxX) {
            val maxLeft: Double = maxYinRange(minX, maxX, minY, leftChild)
            val maxRight: Double =
              maxYinRange(minX, maxX, minY, node.getRightChild)
            (if (maxLeft < maxRight) maxLeft else maxRight)
          } else if (nodeR >= minX) {
            maxYinRange(minX, maxX, minY, node.getLeftChild)
          } else if (nodeR < maxX) {
            maxYinRange(minX, maxX, minY, node.getRightChild)
          }
        }
        java.lang.Double.NEGATIVE_INFINITY
      }`

but I get the following error: Double does not take parameters(the error is in this line val nodeR: Double = maxX(leftChild) )
and I don't know how to solve it.
Comment: `maxX(leftChild)` is obviously nonsense. What is it supposed to mean? What did you intend when you wrote it?
Answer: From the look of the logic it seems like you mean
val nodeR: Double = leftChild.getX

However even if this is fixed, the function is always going to return NEGATIVE_INFINITY because that is the last value in the method. The rest of the code is executed but does not affect the result (the compiler will probably warn you about this)
Even when that is fixed, the logic appears unlikely to do what you want. You should also consider using Option to hold the leaf pointers rather than using null.

Can double Type take parameters scala


Prove that $\sum_{n=0}^\infty \frac{(-1)^n}{3n+1} = \frac{\pi}{3\sqrt{3}}+\frac{\log 2}{3}$

Question:
Prove that $$\sum_{n=0}^\infty \frac{(-1)^n}{3n+1} = \frac{\pi}{3\sqrt{3}}+\frac{\log 2}{3}$$

I tried to look at $$ f_n(x) = \sum_{n=0}^\infty \frac{(-1)^n}{3n+1} x^n $$
And maybe taking it's derivative but it didn't work out well.
Any ideas?
Comment: Take $x^{3n+1}$ instead of $x^n$.
Comment: I have answered an exactly similar problem on [AoPS](http://www.artofproblemsolving.com/Forum/viewtopic.php?f=296&t=616914) & I give a complete answer, you may visit the link I give.
Comment: Change the $ x^n $ into $ x^{3n} $. Then $ f (x) $ is $\frac{1}{x}$ times the integral from $0$ to $ x$ of what series?
Comment: I talk to derivatives too sometimes, it's our secret. Also think about the natural log...
Comment: I've tried but they're just so uncouth. Now that you've edited though I sound like a weird guy
Comment: Oh and disregard the part in my first comment that actually addresses the question, I thought you could approach the problem with the $\log$ series but it seems a different solution has been shown.
Comment: Oh I actually thought about trying it but somehow gave up on that
Comment: @GPerez, You should try to have a conversation with an imporer integral then!
Comment: @Anastasiya-Romanova秀, could you explain the second equality in your answer? (the change from summation to the integral with $e$)
Comment: @AlonAlon Do you mean interchanging the integral & summation sign? It can be justified by Fubini-Tonelli theorem.
Answer: Hint
$$\sum_{n=0}^\infty\frac{(-1)^n}{3n+1}=\lim_{N\to\infty}\sum_{n=0}^N(-1)^n\int_0^1t^{3n}dt=\lim_{N\to\infty}\int_0^1\sum_{n=0}^N(-t^3)^ndt=\lim_{N\to\infty}\int_0^1\frac{1-(-t^3)^{N+1}}{1+t^3}dt$$
Now you need to prove two things:

$$\int_0^1\frac{dt}{1+t^3}=\frac{\pi}{3\sqrt{3}}+\frac{\log 2}{3}$$
$$\lim_{N\to\infty}\int_0^1\frac{(-t^3)^{N+1}}{1+t^3}dt=0$$
Comment: To prove the second point use that
$$\left|\int_0^1\frac{(-t^3)^{N+1}}{1+t^3}dt\right|\le\int_0^1 t^{3N+3}dt=\frac1{3N+4}$$
and then squeeze.
Comment: Which equality do you mean? Interchanging $\sum$ and $\int$? It's possible with finite sum.
Comment: @AlonAlon Since $0<t<1$, then as $N\to\infty$ the integrand goes to $0$
Comment: We can't interchange in general $\lim$ and $\int$ without theorems: Dominated convergence theorem, limit monotone theorem, convergence uniform theorem,... Or prove the result *by hand* as I did.
Comment: Thank you. Can you explain the second equality please?
Comment: You're welcome @AlonAlon
Comment: Is it legal: $\lim_{N\to\infty} \int_0^1 (-t^3)^{N+1} = \int_0^1 0 = 0$? (Meaning, talking the limit before evaluating the integral)
Comment: Thanks, Why doing it my way is wrong by the way?
Comment: This is a very nice approach especially I like the second part where the remainder is shown as tending to $0$. This is the way such elementary problems should be be done (i.e. without any appeal to uniform convergence, dominated convergence etc). +1
Comment: But Fubini and Tonelli's theorems justifies it for all sums/integrals less than infinity. These are less than infinity because they converge. We can directly apply that.
Answer: For a geometric series.
$$\sum_{n=0}^{\infty} (-1)^n(x^n) = \frac{1}{1+x}$$
Substitute $x \rightarrow x^3$
$$\sum_{n=0}^{\infty} (-1)^n (x^{3n}) = \frac{1}{1+x^3}$$
Integrate the sides.
$$\sum_{n=0}^{\infty} (-1)^n\frac{x^{3n + 1}}{3n + 1} = \int \frac{dx}{1+x^3}$$
The hard part is the integration. Then let $x=1$


Erro ao usar getDetails() da API googlemaps, TypeError: this is null (ionic, angular)

Question: Sou novo no ionic e angular. Estou buscando os lugares próximos usando nearbySearch() que retorna um resolve do results, deste results pego o place_id do lugar e coloco na função getDetails(), porém quando vou atribuir o resultado da getDetails(place) a uma outra para exporta-la, enfrento esse erro abaixo.

TypeError: this is null[Learn More]  js-maps.ts:48:14 init js-maps.ts:48  l3 places_impl.js:19  j3 places_impl.js:17  e
places_impl.js:4  c common.js:67
PlaceService.GetPlaceDetails:1

Segue meu codigo.
import { Injectable } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation';

declare var google;

@Injectable()
export class JsMapsProvider {

  map: any;
  places : Array<any>;
  farmaciasId :Array<any>;
  detalhesfarma: Array<object>;
  servico: any;
  farmacias :Array<any>;

  constructor(public geolocation : Geolocation) { }

  init(location, element){

    let latLng = new google.maps.LatLng(location.latitude, location.longitude);

    let opts = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    this.map = new google.maps.Map(element.nativeElement, opts);
    var service = new google.maps.places.PlacesService(this.map);

    this.getFarmas(latLng).then((place : Array<any>)=>{
      this.places = place;

      for(let i = 0 ;i < place.length ; i++)
      {
        this.createMarker(place[i]);

        service.getDetails({
          placeId:place[i].place_id
          },function (place, status){
            if (status === google.maps.places.PlacesServiceStatus.OK) {
              **this.detalhesfarma = place;**
            }
          }
        );
      }
    },(status)=>console.log(status));

    this.addMarker(this.map);

  }

  getFarmas(latLng){

    var service = new google.maps.places.PlacesService(this.map);
    this.servico = service;

    let request = {
        location : latLng,
        //radius : 2000 ,
        types: ['pharmacy'],
        rankBy: google.maps.places.RankBy.DISTANCE
    };
    return new Promise((resolve,reject)=>{
        service.nearbySearch(request,function(results,status){
              if(status === google.maps.places.PlacesServiceStatus.OK)
              {
                  resolve(results);
              }else
              {
                  reject(status);
              }

        });
    });
  }

  createMarker(place){

    let marker = new google.maps.Marker({
    map: this.map,
    animation: google.maps.Animation.DROP,
    icon: 'assets/icon/icon-29.png',
    position: place.geometry.location
    });

    let infoWindow = new google.maps.InfoWindow({});

      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent('
' + place.name + '
' +
          'Endereço: ' + place.vicinity + '
');
        infoWindow.open(this.map, this);
      });

  }

  addMarker(map:any){

    let marker = new google.maps.Marker({
      map: map,
      animation: google.maps.Animation.BOUNCE,
      position: map.getCenter()
    });

    //adicionado 18/01
    let content = "
Estou aqui !
";
    let infoWindow = new google.maps.InfoWindow({
    content: content
    });

    google.maps.event.addListener(marker, 'click', () => {
    infoWindow.open(this.map, marker);
    });
    //-----

  }
}

Comment: Seu erro está aqui `**this.detalhesfarma = place;**`?
Answer: Deduzindo que seu erro esteja aqui **this.detalhesfarma = place;**. Você tem uma função de retorno de chamada anônima que sobrescreve this, você pode atribuir this a outra variável antes de usá-la em sua função anônima ou usar Arrow Function que faz referência ao escopo pai.
Arrow Function
    service.getDetails({
      placeId:place[i].place_id
      },(place, status) => {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          **this.detalhesfarma = place;**
        }
      }
    );

Referência
    var self = this
    service.getDetails({
      placeId:place[i].place_id
      },function(place, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          self.detalhesfarma = place;
        }
      }
    );

Comment: Obrigado Marconi !!!
Comment: @WelingtonCruz por nada rs, conseguiu compreender o problema?


How does multiplication by a constant affect a Gumbel random variable

Question: Suppose $X$ is a Gumbel (Type-1 extreme value) random variable with shape and scale parameters given by ($\mu$, $\sigma$). What is the distribution of $cX$, where $c$ is a constant?
Comment: If cX is still distributed Gumbel, here's how I would answer it. Var(X) = $\frac{\sigma^2 \pi^2}{6}$ so Var(cX) = $c^2$Var(X), implying that cX must have scale parameter equal to $c \sigma$. I assume that the shape parameter becomes $c \mu$.
Answer: The distribution will still be a Gumbel distribution but with parameters $(c\mu,c\sigma)$.
That is the case for either of the usual Gumbel Type 1 distributions.  For $Y=cX$ those have density functions:
$$\frac{e^{\frac{\alpha  c-y}{\beta  c}-e^{\frac{\alpha  c-y}{\beta  c}}}}{\beta  c}$$
and
$$\frac{e^{\frac{y-\alpha  c}{\beta  c}-e^{\frac{y-\alpha  c}{\beta  c}}}}{\beta  c}$$


Return fields from different collection Mongoose

Question: Imagine a function that finds users by their name and returns them.
<code> User.aggregate(
        [
            { $sort: { userFirstName: 1, userLastName: 1 } },
            {
                $addFields: {
                    firstLastName: { $concat: ['$userFirstName', ' ', '$userLastName'] },
                    lastFirstName: { $concat: ['$userLastName', ' ', '$userFirstName'] }
                }
            },
            {
                $match: $match // Set from above with match crit
            },
            {
                $group: {
                    _id: null,
                    total: { $sum: 1 },
                    data: {
                        $push: {
                            '_id': '$_id',
                            'userFirstName': '$userFirstName',
                            'userLastName': '$userLastName',
                            'userProfileImage': '$userProfileImage',
                            'userVihorCategory': '$userVihorCategory'
                        }
                    }
                }
            },
            {
                $project: {
                    total: 1,
                    data: { $slice: ['$data', start, limit] }
                }
            }
        ]
    ).exec((errAgg, results) => {...
</code>
This works, it splices them and returns them correctly.
There is another collection that tracks user connections.
<code>{
    user: { type: Schema.Types.ObjectId, ref: 'User' },
    userConnection: { type: Schema.Types.ObjectId, ref: 'User' },
    userConnectionStatus: {
        type: String,
        enum: ['following', 'blocked', 'requested']
    }
}
</code>
Eg User: me, userConnection: 'someone', userConnectionStatus: 'following'
What I am trying to achive is to return 2 more fields,
 1. My userConnectionStatus to him
 2. His userConnectionStatus to me
And not to return users who have blocked me.
What is the best approach when it comes to this DB structure.
Thank you for your time
Comment: Use $lookup aggregate query of mongodb.
https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
Comment: @VikashSingh I understand its possibilities but is it possible to $lookup after my $group or last $project, so this way it will only populate those which are sliced and matched. I am unable to $unwind data and $lookup from there.
Or am I wrong even thinking about it like that and ignore order of actions and run $lookup before match and slice
Answer: Preventing blocked users was solved by selecting all blocked users, and adding $nin in match inside aggregate.
For connection status, I have resolved the problem by adding 2 virtual fields to User.
<code>UserMongoSchema.virtual('userConnectionStatus', {
  ref: 'UserConnection',
  localField: '_id',
  foreignField: 'user',
  justOne: true
});
UserMongoSchema.virtual('connectionStatus', {
  ref: 'UserConnection',
  localField: '_id',
  foreignField: 'userConnection',
  justOne: true
});
</code>
And populating them on results
<code>...
.exec((errAgg, results) => {
      User.populate(results[0].data, [
            { path: 'userConnectionStatus', match: { userConnection: req.userCode }, select: 'userConnectionStatus' },
            { path: 'connectionStatus', match: { user: req.userCode }, select: 'userConnectionStatus' },
        ], (errPop, populateResponse) => {
            if (errPop) { return next(errPop); }

            populateResponse = populateResponse.map((row) => {
                row['userConnectionStatus'] = row.userConnectionStatus ? row.userConnectionStatus.userConnectionStatus : null;
                row['connectionStatus'] = row.connectionStatus ? row.connectionStatus.userConnectionStatus : null;
                return row;
            });
...
</code>
Looking at the order of actions, I think this won't affect performance since I am running populate only on those matched top X (max 100) results.
I won't mark this as Answer yet. If you have any opinion about if this is bad practice or if there is a better way of doing it, feel free to comment.


A test statistic that equals a constant under $H_{0}$

Question: I was designing a hypothesis test, using the likelihood ratio test, and I found out that, under $H_{0}$, the test statistic $\Lambda$ equals the same constant $k$ no matter what the observations may be. Does that mean that the rejection region is of the following form? $$ C=\{ x, \Lambda(x)<k\}$$
Comment: Please show full details. I ask because I expect it's the same potential error as your previous question. A pity you deleted instead of responding to clarify there.
Comment: @Glen_b What I did was the following: I wrote the likelihood ratio test, I pluged in the estimators of the the parameters (Which are function of the observations), I then noticed that under $H_{0}$ the test statistic always equal the same constant $k$ no matter what the observations may be, I did a simulation on Matlab and all the values of $\Lambda$ was close to 0 (values were of the form $x,xxx \times 10^{-16}$). realising this result was always true when $H_0$ is verified, I was wondering how can I extract the p-value, and since $\Lambda$ doesn't seem to have a distribution ...
Comment: (at least to my knowledge), now that I look at my question, I can see that it's wrong
Comment: Details should go in the question, but you're omitting the very details that would let us see *why* you have a constant value under $H_0$ (we're not mind-readers). In particular I suspect you're treating the $L_0$ term (ie. the one under H0) in the LRT statistic wrong (e.g. plugging in ML estimates derived under $H_1$). Please add complete details of what you did into your question, so we can see what you are doing.  Alternatively if you know what went wrong, please add an answer.
Answer: Your rejection region is either everything or it's nothing. The test has either a 100% false positive rate or a 100% false negative rate.
Comment: @ToneyShields a likelihood ratio statistic should be a statistic. As in: it is a function of the data. If data can't change it, it's a dumb LR. You should check the assumptions of a likelihood ratio test. All kinds of problems surface when testing a hypothesis about, say, a uniform(0, $\theta$) distribution. Think about "why" and what the density function is, and so on.
Comment: Somehow I suspect the problem occurred earlier...
Comment: @eric_kernfeld what do you mean?


Formulário para edição não exibe os dados carregados

Question: Estou tentando há algum tempo fazer um formulário em CodeIgniter 3 para edição de dados exibir em seus campos os valores de cada coluna do registro selecionado. A operação update está funcionando normalmente, porém como os campos vem em branco, preciso digitar tudo novamente.
Abaixo o meu modelo MY_Model.php:
<?php

class MY_Model extends CI_Model
{
    public $table = '';
    protected $primary_key = 'id';

    public function __construct()
    {
        parent::__construct();

        $this->load->database();
        $this->load->helper('inflector');
    }

    public function get($id)
    {
        return $this->db->get_where($this->table, array($this->primary_key = $id))->row();
    }

    public function select()
    {
        $data = array();

        $this->db->from($this->table);
        $this->db->order_by($this->primary_key, 'DESC');
        $query = $this->db->get();

        foreach ($query->result_array() as $row) {
            $data[] = $row;
        }

        $query->free_result();

        return $data;
    }

    public function insert($data)
    {
        $data['date_created'] = $data['date_updated'] = date('Y-m-d');
        $data['created_from_ip'] = $data['updated_from_ip'] = $this->input->ip_address();

        if ($this->db->insert($this->table, $data)) {
            return $this->db->insert_id();
        } else {
            return false;
        }
    }

    public function update($data, $id)
    {
        $data['date_updated'] = date('Y-m-d');
        $data['updated_from_ip'] = $this->input->ip_address();

        $this->db->where($this->primary_key, $id);

        return $this->db->update($this->table, $data);
    }

    public function delete($id)
    {
        $this->db->where($this->primary_key, $id);

        return $this->db->delete($this->table);
    }

    public function count_all()
    {
        return $this->db->count_all($this->table);
    }
}

Aqui a função edit do controle Customers:
public function edit($id)
{
    if ($this->input->post()) {
        $data['name'] = $this->input->post('name');
        $data['email'] = $this->input->post('email');
        $data['address'] = $this->input->post('address');

        $this->Customers_model->update($data, $id);
        $this->session->set_flashdata('message', 'Cliente \'' . $data['name'] . '\' alterado');

        redirect('/admin/customers', 'refresh');
    }

    $data['customer'] = $this->Customers_model->get($id);
    $data['page'] = $this->config->item('admin_template_dir_admin') . 'edit_customers';
    $data['module'] = 'admin';

    $this->load->view($this->_container, $data);
}

Já tentei muita coisa para exibir os dados para edição. Do modo que está agora, fazendo um var_dump($customer) apenas mostra NULL. Como proceder?
Comment: Solucionei. Faltava um '>' na função `get` do `MY_Model`
Comment: Se tela de update fica com os campos em branco, é sinal que o select deu errado ou não retornou nada daquele id.
Comment: Cria uma resposta :)
Comment: Pronto! Parece bruncadeira.
Answer: A função get() está com um > faltando.
return $this->db->get_where($this->table, array($this->primary_key = $id))->row();

Fica assim
return $this->db->get_where($this->table, array($this->primary_key => $id))->row();

Mal dá para acreditar.


For Loop: LED's Will Not Display Correctly on Arduino

Question: Here is the code so far:
bool t1 = true;
bool f1 = false;
bool button_state = 0;
int delay_led = 100;
int led_num = 1, buzzer_delay = 75;
void setup() {
  // put your setup code here, to run once:
pinMode(2, INPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT);
pinMode(12, OUTPUT); pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalRead(2);
button_state = digitalRead(2);

if (button_state == 0)
{
  for (led_num = 10; led_num <= 13; led_num++)
  {
  digitalWrite(led_num, t1);
  delay(delay_led);
  digitalWrite(led_num, f1);
  }
}

else
{
    for (led_num >= 10; led_num <= 13; led_num++)
  {
  digitalWrite(led_num, t1);
  }
}
}

I'm trying to get the LEDs to light up at once, which is what the else statement is used for. However, our instructor specifically stated to use loops to accomplish this. Here is our assignment:
Here is an image of our assignment
I cannot figure out how to use loops instead on the if/else and I cannot get the LEDs to light up at once. Any help would be greatly appreciated!
Comment: You need an outside loop that runs forever and keeps polling the button state....

Your else doesn't need a loop, it just needs to turn all the lights on, wait, then turn them all off.
Answer: Your second foor loop init-statement of led_num >= 10 is wrong as it has no effect. Instead of:
for (led_num >= 10; led_num <= 13; led_num++)

it should probably be:
for (led_num = 11; led_num <= 13; led_num++)

Comment: Thanks, Ron! I upvoted your answer, but apparently, users under a certain level do not publically affect the answers upvotes.


Morphisms between schemes such that every point in the codomain has at most $n$ preimages.

Question: Consider a finite morphism $f:X\longrightarrow Y$ between two integral and Noetherian schemes. If $\operatorname {deg}(f)=[K(X):K(Y)]=n$,  is it true that for every $y\in Y$ then $|f^{-1}(y)|\le n$? (with the notation $|\cdot|$ I mean the cardinality). I know that $|f^{-1}(y)|<\infty$ but what about its upper bound? If the statement is false as stated here, under which other hypothesis we have that $|f^{-1}(y)|\le n$?
Thanks in advance.
Comment: On the other hand *if $Y$ is normal*, this should be true. See Shafarevich Volume 1, II.6.3 Theorem 3 for a proof in the case of varieties.
Comment: You say "I know that $|f^{-1}(y)|<\infty$", but that is false. Think about a birational map that contracts a curve: what is the degree of the field extension? Even if $f$ is finite the bound you want doesn't work: $f$ could be the normalisation of a nodal curve.
Comment: But you did not say that your morphism is finite, just that it induces a finite extension of function fields. My point is exactly that this is weaker. (Search for "generically finite".) Also, the second example is finite.
Comment: Finite morphism doesn't imply finite fibers? (finite morphisms are quasi-finite)
Comment: yeah you're right I forgot to write that $f$ is finite. Is a typo.
Comment: I've edited. Many thanks!
Comment: What is unsatisfactory about Asal Beag Dubh's comment?
Answer: This is Asal Beag Dubh's answer.
Consider the finite ring map $k[x, y]/(y^2 - xy - x^3) \to k[t]$ with $x \mapsto t(t - 1)$ and $y \mapsto t^2(t - 1)$. Take Spec of this. Then $n = 1$ but the fibre over $(0, 0)$ has two points.
If $Y$ is normal, then the result does hold, but it isn't that easy to prove. One way to do it is to reduce to the case where the extension of function fields is Galois (say with group $G$; this reduction already takes a bit of work in case of inseparability) and then to show that the fibres of $X \to Y$ are acted on transitively by $G$ (in case $X$ is normal) as in one of the proofs of going down for finite over normal.
Comment: Thanks for writing this up, @answer_bot. (I am not sure how much sense it makes to thank a bot, but never mind.)


How to pivot a Pandas Dataframe - separate row for columns

Question: I have csv file that I am reading into Pandas Data Frame in the following format:
Number|Name |v1|v2|v3|v4
100000|Name1|value1|value2|value3|value4
200000|Name2|value1|value2|value3|value4
300000|Name3|value1|value2|value3|value4

I would like to pivot it, so I have a separate row for each value with Number and Name:
Number| Name | values |
100000| Name1| value1 |
100000| Name1| value2 |
100000| Name1| value3 |
100000| Name1| value4 |
200000| Name2| value1 |
200000| Name2| value2 |
200000| Name2| value3 |
200000| Name2| value4 |
....

Comment: You can check melt
Comment: `df.set_index(["Number", "Name"]).stack()`?
Comment: https://pandas.pydata.org/docs/reference/api/pandas.melt.html
Comment: This is more *unpivot*, aka, `melt` or `unstack` as previously commented.
Answer: Try:
pd.melt(df,id_vars=['Number','Name'], value_vars=['v1','v2','v3','v4'])


Which of the following is false?

Question: Let $A^{-1} = \begin{pmatrix}1& 2\\ 2& 3\end{pmatrix}$
Which of the following statements is FALSE?
A. For arbitrary 2x2 matrices, B, C, if BA = BC then A = C.
B. $A^T$ is invertible.
C. For arbitrary 2x2 matrices, B, C, if AB = AC then B = C.
D. $AA^{-1} = A^{-1}A$
E. $A$ is a symmetric matrix.
I know for sure that B, D, E are true, but I'm stuck up on A and C. The answer key tells me A is false, but I don't understand why. It seems like A and C are asking essentially the same thing. If the first two matrices are the same, then are the other two equivalent. What makes A different than C?
Comment: In option (C), you cancel the exact matrix $A$ which is given implicitly in the beginning, $A^{-1} = \begin{pmatrix}1& 2\\ 2& 3\end{pmatrix}$. While in option (A), you cancel some other matrix $B$, but that will not necessarily work because $B$ could be singular (non-invertible), for example $B=O$.
Answer: The key is you need to be able to apply inverses on both sides. For part C, we are already given $A$ is an invertible matrix, hence $AB = AC$ implies $A^{-1}AB= A^{-1}AC$ and $B=C$. However, in part A, we do not know that $B$ is invertible. In particular, take $B$ to be the zero matrix and $C$ a different matrix from $A$.

Which of the following is false?


How prove this inequality $\frac{a^2}{b}+\frac{b^2}{c}+\frac{c^2}{a}<6$

Question: let $a,b,c\ge\dfrac{1}{3}$,and such $$a^2+b^2+c^2=a+b+c$$
show that
$$\dfrac{a^2}{b}+\dfrac{b^2}{c}+\dfrac{c^2}{a}<6$$
I try:$$a-a^2=(b^2-b)+(c^2-c)\ge-\dfrac{1}{4}-\dfrac{1}{4}=-\dfrac{1}{2}$$
so we have
$$a^2-a-\dfrac{1}{2}\le 0\Longrightarrow a\le\dfrac{1+\sqrt{3}}{2}$$
so we have
$$a,b,c\in [\dfrac{1}{3},\dfrac{1+\sqrt{3}}{2}]$$
let $f(a)=\dfrac{a^2}{b}+\dfrac{b^2}{c}+\dfrac{c^2}{a}$,and $f''(a)>0$. so $LHS$ is maximum when $a,b,c=\{\dfrac{1}{3},\dfrac{1+\sqrt{3}}{2}\}$.but I found all case this value is big $6$
Comment: Also, the following stronger inequality is true. $\frac{6(a^2+b^2+c^2)}{a+b+c}>\frac{a^2}{b}+\frac{b^2}{c}+\frac{c^2}{a}$, where $\{a,b,c\}\subset[10,41].$ All these are not for contests of course.
Comment: The following is also true (obtained by Mathematica using Lagrange multipliers): $$\frac{a^2}b+\frac{b^2}c+\frac{c^2}a\le 6-\frac{\rho}{a b c},$$ where $\rho$ is the root of $$23988055525253185536 x^8+7704497000298332160 x^7+8194057238162458665
   x^6+2668153946412058002 x^5-9159645114203751900 x^4-2417398625137389003
   x^3+270169678447885764 x^2-8530510903322967 x+85638207566543$$ near $0.0284$
Comment: If $a,b,c = \frac{1}{3}$, you don't get more than $6$....
Answer: ${a,b,c} \geq \frac{1}{3}$, where $a^2+b^2+c^2 = a+b+c$
proof that $$\frac{a^2}{b}+\frac{b^2}{c}+\frac{c^2}{a} < 6$$
say that $$m = \frac{a^2}{b}+\frac{b^2}{c}+\frac{c^2}{a} $$
therefore $$a{b}{c}{m} = a{b}{c}(\frac{a^2}{b}+\frac{b^2}{c}+\frac{c^2}{a})  $$
$${a}{b}{c}{m} = a^3c+b^3a+c^3b$$
use the fact that $a^2+b^2+c^2 = a+b+c$ , to depress the expression by eliminating $c$
$$a^3c+b^3a+c^3b - {a}{b}{c}{m} = 0$$
$$a^2+b^2+c^2-a-b-c = 0$$
so that we would take resultant of the two polynomials
$$\operatorname{Resultant} ( a^3c+b^3a+c^3b - {a}{b}{c}{m} , a^2+b^2+c^2-a-b-c , c )$$
the results is
$$ a^2b^4m^2-a^2b^3m^2+a^4b^2m^2-a^3b^2m^2+2ab^6m-4ab^5m+4a^3b^4m-5a^2b^4m+ab^4m-2a^4b^3m-4a^3b^3m+4a^2b^3m+ab^3m+2a^5b^2m-2a^4b^2m+a^3b^2m+a^2b^2m-2a^6bm+2a^5bm+b^8-3b^7+4a^2b^6-6ab^6+3b^6-2a^3b^5-6a^2b^5+9ab^5-b^5+3a^4b^4-5a^3b^4+9a^2b^4-2ab^4-4a^5b^3+2*a^4b^3+5a^3b^3-3a^2b^3+2a^6b^2+a^5b^2-a^4b^2-2a^3b^2-2a^7b+3a^6b-a^5b-a^4b+a^8-a^7 = 0$$
so where going to prove that if ${a,b} \geq \frac{1}{3}$, then $m < 6$, the maximum value of $m$ for whatsoever is always less than $6$
$$(a^2b^4-a^2b^3+a^4b^2-a^3b^2)m^2+(2ab^6-4ab^5+4a^3b^4-5a^2b^4+ab^4-2a^4b^3-4a^3b^3+4a^2b^3+ab^3+2a^5b^2-2a^4b^2+a^3b^2+a^2b^2-2a^6b+2a^5b)m+b^8-3b^7+4a^2b^6-6ab^6+3b^6-2a^3b^5-6a^2b^5+9ab^5-b^5+3a^4b^4-5a^3b^4+9a^2b^4-2ab^4-4a^5b^3+2a^4b^3+5a^3b^3-3a^2b^3+2a^6b^2+a^5b^2-a^4b^2-2a^3b^2-2a^7*b+3a^6b-a^5b-a^4b+a^8-a^7 = 0$$
but there's a problem, because of the appearance of your condition $a^2+b^2+c^2 = a+b+c$ , $m$ sometimes has a complex value, though which was not part of your statement

true test
if $a= 0.1, b= 0.2$, then $[m = 0.2857951031446771,m = 14.65420489685532]$
if $a= 0.4, b= 0.5$, then $[m = -0.04957750385466814,m = 5.129373422222015]$

the discriminate of the quadratic in $m$ gives us a condition, such that we must let the roots of $m$ to be real
$$\Delta = -a^2b^4(4b^2-4b+4a^2-4a-1)(ab^2-b^2+b-a^2+a)^2$$
$\Delta ≥ 0$ only if $-4b^2+4b-4a^2+4a+1 ≥ 0$
$$-4(b^2-b)-4(a^2-a)+1 ≥ 0$$
$$-4b(b-1)-4a(a-1)+1 ≥ 0$$
therefore $${a,b} ≤ 1$$, then $$\frac{1}{3} ≤ {a,b} ≤ 1$$
according to $$m = \frac{a^3c+b^3a+c^3b }{a{b}{c}}$$, the maximum value of $m$ happens when {a,b,c} are minimum, so setting $a=\frac{1}{3}$, $b=\frac{1}{3}$ and solving the quadratic in $m$
$$(a^2b^4-a^2b^3+a^4b^2-a^3b^2)m^2+(2ab^6-4ab^5+4a^3b^4-5a^2b^4+ab^4-2a^4b^3-4a^3b^3+4a^2b^3+ab^3+2a^5b^2-2a^4b^2+a^3b^2+a^2b^2-2a^6b+2a^5b)m+b^8-3b^7+4a^2b^6-6ab^6+3b^6-2a^3b^5-6a^2b^5+9ab^5-b^5+3a^4b^4-5a^3b^4+9a^2b^4-2ab^4-4a^5b^3+2a^4b^3+5a^3b^3-3a^2b^3+2a^6b^2+a^5b^2-a^4b^2-2a^3b^2-2a^7*b+3a^6b-a^5b-a^4b+a^8-a^7 = 0$$
gives us $m = \frac{1}{3}$ and $m = 5.75$
meaning $$m < 6$$
$$\begin{matrix}
a&b&m\\
\frac{1}{3}&\frac{1}{3}&0.333,5.75\\
1&1&3\\
\frac{1}{3}&1&-5.126,5.181\\
1&\frac{1}{3}&2.441,4.502\\
\end{matrix}$$
Comment: The maximum value of $m$ is not $5.75$. For example, $m\approx 5.8736$ when $a=1/3, b=1/2, c=(3+\sqrt{26})/6$.
Comment: @aman the community needs to look out to people who down vote others answers for no reason
Comment: Seems alright to me... no clue why you got the downvotes but it's a +1
Answer: Actually, this problem could be solved analytically or using Lagrange multipliers, but here the (Analytical solution).
show :
$\frac{a²}{b}$ + $\frac{b²}{c}$ + $\frac{c²}{a}$ ${< 6}$
s.t:
${a, b, c ≥ ⅓}$
${a² + b² + c² = a + b + c}$

Changing the problem a little
${a, b, c ≥ 1}$
$\frac{a²}{b}$ + $\frac{b²}{c}$ + $\frac{c²}{a}$ ${< 2}$

rearranging the function
${a² = a + b + c - b² - c²}$
$\frac{a + b + c - b² - c²}{b}$ + $\frac{b²}{c}$ + $\frac{c²}{a}$ ${< 2}$
then
$\frac{a}{b}$ + ${1}$ + $\frac{c}{b}$  - ${b}$ - $\frac{c²}{b}$ + $\frac{b²}{c}$ + $\frac{c²}{a}$ ${< 2}$

${b ≥ 1}$ ⇒ ${1-b}$ ≤ 0
$\frac{c}{b}$ - $\frac{c²}{b}$ = $\frac{c-c²}{b}$   ⇒ $\frac{c-c²}{b}$ ${≤ 0}$
$\frac{a}{b}$ + $\frac{c²}{a}$ = $\frac{a² + bc²}{bc}$ =   $\frac{(a + b + c - b² - c² ) + bc² }{ba}$
$\frac{1}{b}$ + $\frac{b-b²}{ba}$ + $\frac{c - c²}{ba}$ + $\frac{c²}{a}$
$\frac{1}{b}$ ${≤1}$ and $\frac{b-b²}{ba}$ ${≤ 0}$ and $\frac{c - c²}{ ba}$ ${≤ 0}$

then we need to proof that $\frac{c²}{a}$ ${≤ 1}$

$\frac{c² + a² - a² }{a}$

= $\frac{c² + a²}{a}$ - ${a}$
= $\frac{c² + (a + b + c - b² - c²)}{a}$ - ${a}$
= ${1 - a}$ +  $\frac{2c - c²}{a}$ + $\frac{b-b²}{a}$
${1-a}$ ${≤ 0}$ and
$\frac{b-b²}{a}$ ${≤ 0}$
we need to proof that $\frac{2c - c²}{a}$ ${< 1}$  or  ${2c ≤ c²}$ but ${c≥1}$
then ${2c ≤ c²}$ for all ${c≥1}$


Understanding Apache rules in  directive

Question: I have tried reading the manual although to be honest I am still finding it hard to understand and get my head around what the Order/Allow actually does.
I have the following code inside a virtual host, I'm not clear what this code inside the <directory> .....</directory>
<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    ServerName mysite.com
    DocumentRoot /var/www/mysite.com
    <Directory /var/www/mysite.com>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/mysite.com-error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/mysite.com-access.log combined
</VirtualHost>

could somebody try to explain row by row in an easier way?
I have had security problems with an older server that was using this conf code, and I would make the new server more secure. In this server I have a lot of wordpress websites so I have to use the .htaccess.
Answer: Options Indexes FollowSymLinks MultiViews
Indexes: if you try to access a directory that doesn't have a DirectoryIndex, such as index.php, the content of the directory will be shown.
FollowSymLinks: allows apache to use symbolic links. This can improve the perfomance but can be a security issue too.
MultiViews: not sure about it but, from googling a bit it looks like a security risk. Some info
AllowOverride All
Allow .htaccess files to override every configuration parameter set in apache2.conf
Order allow,deny
By default, access to a directory is forbidden.
Allow from all
Allow connections from any network.
Comment: thanks, much clear now.
If I don't want to Indexes the folder what is the value that I have to write?

my conf has some great security problem or is it ok like this?
Comment: You'd need to change it to `-Indexes`. Also, I was googling about `MultiViews` option as I didn't know what it was and out of four recommendations, two of them where "attack" and "exploit", so I guess you can have a problem there.
Comment: MultiViews is dangerous because it allows file suffixes to be anywhere in the filename. Makes it hard to predict what an uploaded file can do.

Understanding Apache rules in  directive


Absolute moment of normal distributed random variable.

Question: Let $u=(u_n)\in l^2(\mathbb{N})$ and $(Z_n)$ be an i.i.d. sequence of standard normal distributed random variables. Define $Z(u)= \sum_{n\geq 1} u_nZ_n$ and note that $Z(u)\sim \mathcal{N}(0,\|u\|_2^2)$. I'm reading a proof which simply states that $E|Z(u)|=\|u\|_2 E(|Z_1|) \, $  -  How is this seen?
Answer: The expectation of the absolute value of $\mathcal{N}(0,\sigma^{2})$ is $\sigma \sqrt{\dfrac{2}{\pi}}$, because it follows a half-normal distribution. Then $E|Z(u)|=\|u\|_2 \sqrt{\dfrac{2}{\pi}}$ and $E|Z_1|=\sqrt{\dfrac{2}{\pi}}$.
Comment: Thanks, for the quick answer. Much appreciated.


How to retrieve an image from ImageView when Click on that image?

Question: i have a ImageView in the layout, when i click on the image i want to get that image into a variable and replace with another image in this ImageView. please help me..
Answer: The onClick Listener will give you a View, that's the ImageView that was clicked. Cast it to an ImageView and do whatever you want with it.
Comment: how to get image from the view
Comment: Just as you do with every other `ImageView`, call its `getDrawable()`.
Comment: You decided to skip the part of my comment where I mention you should cast it to an `ImageView`...
Comment: Do a google search on casting then, which is a generic programming concept and not some Android related feature.
Answer: in this example i have take previous image in Drawable and replace i with new image. if you set any imageview to image which stay in drawable variable(d) then use ::   setBackgroundDrawable(d); is useful
 public void onClick(View v){
   ImageView i;
        i = (ImageView) findViewById(R.id.img);
        Drawable d = i.getBackground();
        i.setBackgroundResource(R.id.secondImage);

   }


Entityframework Core2.0 how to execute seed and migration in parallel

Question: I am using migrations and also want to use seed data. Currently getting error. what is the best way to achieve this?
My earlier query in stackoverflow:
previous post
Thanks
Comment: *Currently getting error*... so what is the error? And how would you expect migrations and seeding to work if they ran in parallel? That would almost certainly break things.
Answer: For what ever its worth migrations do not run with EnsureCreatedAsync, its in real big bold letters in the docs for EFCore, also to get around this Run  EnsureDeletedAsync with in your seed method (testing anyway right?). Then run Database.MigrateAsync();
https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/#applying-migrations-at-runtime
so....
Edit
//example method
public void Seed(IApplicationBuilder app)
{
     using(var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
     {
        var context = servicescope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        context.Database.Migrate();
         if(!context.SomeTable.Any()){
            foreach(var item in SeedData.Items){
              context.SomeTable.Add(item);
            }
            context.SaveChanges();
         }

        //for each table you need seeded data...
        //...
     }
}

Comment: Thanks. I dont want the database to get deleted if one exists. I want this seed to run only when migrate to new database.
Comment: Then don't run the delete method but the migrate call is the only way without running commands on command line to get migrations.  If it's a new dB then check using `if(!_context.SomeTable.Any()) ` loop thru seed data, for example
Comment: Using if(!_context. SomeTable.Any())  will invoked when all the migration scripts are executed? What i understand is from pmc -> update-database is executed, all migrations will be applied to new database, and the seed data is called. is that righ?
Comment: Yes this is assuming no data, i.e. new database.  Seed only needs to run once but migrations will run if one exists. Add new table then add more !Any() if logic to seed that new table if necessary.
Comment: edited for example.


Modelling using GLM

Question: I am doing species distribution modeling using GLM with 18 presence locations and 45 absence locations. Among 25 predictors (19 bioclimatic, soil moisture, distance to forest, distance to road, solar radiation, aspect, elevation), I selected eight predictors after collinearity test and fit them in a model but none of them were significant.
    Call:
glm(formula = RV ~ aspect + bio10 + bio12 + bio4 + forestdist +
    roaddist + soilmoisture + solarrad, family = binomial, data = crisfinnPA)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.1281  -0.9472  -0.6255   1.3032   1.9496

Coefficients:
               Estimate Std. Error z value Pr(>|z|)
(Intercept)  -45.201251 154.754168  -0.292    0.770
aspect         0.004206   0.004212   0.999    0.318
bio10         -0.395404   1.069799  -0.370    0.712
bio12         -0.010945   0.008885  -1.232    0.218
bio4          -0.034707   0.041306  -0.840    0.401
forestdist    -4.495176  86.868312  -0.052    0.959
roaddist       0.005171  17.123314   0.000    1.000
soilmoisture  -3.595371  12.132649  -0.296    0.767
solarrad       0.009568   0.017017   0.562    0.574

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 73.304  on 59  degrees of freedom
Residual deviance: 68.793  on 51  degrees of freedom
AIC: 86.793
Number of Fisher Scoring iterations: 4

I then tried to fit an interaction term and saw the summary, all of them were significant.This seems weird to me.
Call:
glm(formula = RV ~ aspect + bio10 + bio12 + bio4 + forestdist +
    roaddist + soilmoisture + solarrad, family = binomial, data = crisfinnPA,
    weights = bio10 * bio12)

Deviance Residuals:
   Min      1Q  Median      3Q     Max
-951.6     0.0     0.0     0.0   976.1

Coefficients:
               Estimate Std. Error    z value Pr(>|z|)
(Intercept)   1.422e+17  4.263e+07  3.336e+09   <2e-16 ***
aspect        4.495e+12  1.015e+03  4.426e+09   <2e-16 ***
bio10        -2.121e+14  2.915e+05 -7.275e+08   <2e-16 ***
bio12        -6.319e+12  2.394e+03 -2.640e+09   <2e-16 ***
bio4         -1.729e+13  1.020e+04 -1.696e+09   <2e-16 ***
forestdist   -3.578e+16  2.479e+07 -1.444e+09   <2e-16 ***
roaddist      1.298e+16  4.611e+06  2.815e+09   <2e-16 ***
soilmoisture -1.519e+16  3.133e+06 -4.850e+09   <2e-16 ***
solarrad     -1.181e+13  4.707e+03 -2.510e+09   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance:   863403  on 59  degrees of freedom
Residual deviance: 18999357  on 51  degrees of freedom
AIC: 18999421

Number of Fisher Scoring iterations: 25

Can someone please explain what may be the problem?
Comment: You are not fitting an interaction term! As @DemetriPananos notes, you are using *weights* calculated as the product of two predictors!
Comment: Why are you using the value of a predictor as the weights?
Comment: Why do you think there is a problem ? A model with interaction is completely different than a model without so it is entirely plausible for associations to become significant after including an interaction. I would be more concerned about the extremely small  and large estimates.
Comment: You have a small dataset and run the risk of absurd results if you fit over-complicated models. Detail: `aspect` is never a variable to be offered directly as a predictor; you usually need to handle it as sine and cosine terms.
Comment: That is the thing I am concerned about too and thats why I thought it has some problem. As we compare both the results, the estimates and AIC value of the model with the interaction terms are very different, also the deviance residuals.
Comment: As mentioned, they are different models, it is no surprise that the estimates, standard errors and fit statistics are completely different.
Comment: What is `RV`? The science here may guide some simpler models.
Comment: I don't see any interactions in the second model, just weights. Is it a valid way of defining interactions? I've never seen it before and I've never thought about it, but it might be.
Comment: I am actually new to all these. May be I am wrong but I tried fitting the interaction like this: m1=glm(RV~aspect+bio10+bio12+bio4+forestdist+roaddist+soilmoisture+solarrad,bio10*bio12,family=binomial,data=crisfinnPA)  and the result is posted from this model. Isn't this the correct way to fit interaction?
Comment: RV here is response variable with presence (1) and absence (0).
Answer: Your problem is not significance of any terms: it is the fact that you pass weights = bio10 * bio12 to the model.
The problem is even more evident when you look at the estimates and standard errors which are on the order of $10^{10}$ and $10^7$ in some cases respectively.
Regardless, we should expect estimates to change when new terms are added, especially interactions.  If your concern is a lack of significance, I've got news for you; adding terms to your model to get the stars to appear is p-hacking.
Please edit your question with more details about your problem.  We can then advise you on the best approach which is honest and defensible give the data and your hypothesis.
Comment: I have edited my question with details about my data.

Modelling using GLM


VirtualHost : php_value enable_post_data_reading Off : for ONE webpage

Question: I'm trying to manually parse one page on my website with multipart form data sent from a Java application. All the pages are served inside the index file in the public_html directory, and my classes for my other pages rely heavily on $_POST data being populated.
I can parse the multipart data if I set:
php_value enable_post_data_reading Off

But then my other pages error out for un-populated $_POST data.
How can I turn off $_POST reading for this one page in my content directory and leave it on for all my other pages?
My VirtualHost is as follows (only works with the one page):
<VirtualHost *:80>
    ServerName elementbox.lampllc.com

    DocumentRoot /var/element.lampllc.com/public_html

    CustomLog     /var/element.lampllc.com/access.log combined
    ErrorLog      /var/element.lampllc.com/error.log
    LogLevel info
    /*THIS IS THE FIX*/
    <If "%{QUERY_STRING} == 'mod=APIlogin'">
        php_value enable_post_data_reading Off
    </If>

    <Directory "/var/element.lampllc.com/public_html/">
        AllowOverride All
        Require all granted
        Options -Indexes
    </Directory>

    RewriteEngine on
        RewriteRule ^/index/(.+)$       /index.php?mod=$1       [PT]
</VirtualHost>

I've tried specifying the file in question with
<Files "myfile">

I've tried making an alias for a directory and setting a Directory directive for it outside of my "mod" directory (where my content is) but I get rewrite errors.
UPDATED WITH ANSWER
Answer: Try using an If condition:
<If "%{SCRIPT_URI} == '/myfile.php'">
    php_value enable_post_data_reading Off
</If>

Comment: I tried alot of IF directives, this worked for me. I appreciate it as I hadn't considered the IF directive yet.

    `
        php_value enable_post_data_reading Off
    `


Calling a Function within a secondary Function, or calling a Function defined within a larger Function

Question: I'm trying to use python to create a small look up program, that would show all the current prices of a theoretical portfolio, and then offer the option to basically refresh your portfolio, or look up a new quote of your choice.
I can get everything to work in the program, the problem I'm having is with the defined functions.
If you look at run_price1(), you'll notice that it is identical to that of run_price(); however run_price() is located within the update function.
If I take it out of the update function, the update function doesn't work.  If I don't also list it somewhere outside of the update function, the later user input doesn't work.
The question:  I am looking for either a way to call a function that is defined within another function, or a way to use a previously defined function inside of a secondary function.
My code:
import mechanize

from bs4 import BeautifulSoup

def run_price1():

    myBrowser = mechanize.Browser()
    htmlPage=myBrowser.open(web_address)
    htmlText=htmlPage.get_data()
    mySoup = BeautifulSoup(htmlText)

    myTags = mySoup.find_all("span", id=tag_id)

    myPrice = myTags[0].string

    print"The current price of, {} is: {}".format(ticker.upper(), myPrice)

def update():

    my_stocks = ["aapl","goog","sne","msft","spy","trgt","petm","fslr","fb","f","t"]

    counter = 0

    while counter < len(my_stocks):

        web_address = "http://finance.yahoo.com/q?s={}".format(my_stocks[counter])
        ticker = my_stocks[counter]
        #'yfs_l84_yhoo' - that 1(one) is really a lowercase "L"
        tag_id = "yfs_l84_{}".format(ticker.lower())
        def run_price():

            myBrowser = mechanize.Browser()
            htmlPage=myBrowser.open(web_address)
            htmlText=htmlPage.get_data()
            mySoup = BeautifulSoup(htmlText)

            myTags = mySoup.find_all("span", id=tag_id)
            myPrice = myTags[0].string
            print"The current price of, {} is: {}".format(ticker.upper(), myPrice)

        run_price()

        counter=counter+1

update()

ticker = ""

while ticker != "end":

    ticker = raw_input("Type 'update', to rerun portfolio, 'end' to stop program, or a lowercase ticker to see price: ")
    web_address = "http://finance.yahoo.com/q?s={}".format(ticker.lower())
    tag_id = "yfs_l84_{}".format(ticker.lower())

    if ticker == "end":
        print"Good Bye"

    elif ticker == "update":
        update()

    else:
        run_price1()

Comment: Why not just call `run_price1` instead of `run_price` and remove the latter altogether? You don't *have* to define it inside of `update`.
Comment: I tried that, I would prefer to do that, but it doesn't work.  I get the error - NameError: global name 'web_address' is not defined
Answer: You can simply call run_price1() from the update() function, where you now call run_price.
Functions defined at the top of a module are global in the module, so other functions can simply refer to those by name and call them.
Any value that your function needs does need to be passed in as an argument:
def run_price1(web_address, tag_id):
    # ...

def update():
    my_stocks = ["aapl","goog","sne","msft","spy","trgt","petm","fslr","fb","f","t"]

    counter = 0

    while counter < len(my_stocks):

        web_address = "http://finance.yahoo.com/q?s={}".format(my_stocks[counter])
        ticker = my_stocks[counter]
        #'yfs_l84_yhoo' - that 1(one) is really a lowercase "L"
        tag_id = "yfs_l84_{}".format(ticker.lower())

        run_price1(web_address, tag_id)

        counter=counter+1

Comment: That's how I had written it originally, it gives me - NameError: global name 'web_address' is not defined
Comment: I see what you did, I didn't notice that you added web_address to the parentheses. If I add that, I get IndexError: list index out of range
Comment: @LoWri: Ah, `tag_id` is another parameter you need to pass in.
Comment: Thanks! I passed in the ticker variable as well, and now it all works.  I think I'm beginning to understand the use of function variables, thank you!


How to access a function from within it without naming it directly

Question: I want to know how to access a function from within it without naming it directly.
def fact(n):
    this = # some code, where we don't use the name "fact"
    print(fact == this) # True
    if n < 1:
        return 1
    return n * this(n-1)

The code above should behave exactly like:
def fact(n):
    if n < 1:
        return 1
    return n * fact(n-1)

Does anyone have any ideas?
EDIT:
My question is different from Determine function name from within that function (without using traceback). I need fact == this in the code above to return True.
EDIT2:
@ksbg's answer is a good one, but consider the folowing code:
from inspect import stack, currentframe

def a():
    def a():
        f_name = stack()[0][3]  # Look up the function name as a string
        this = currentframe().f_back.f_globals[f_name]
        print(a == this)
    a()

a() # False

In this case it wont work as expected.
Comment: why do you want to do this?
Answer: This can be done by inspecting the stack trace. First we look up the function name as a string, and then we go back one frame (or level), and get the function from the module's globals:
from inspect import stack, currentframe

f_name = stack()[0][3]  # Look up the function name as a string
this = currentframe().f_back.f_globals[f_name]  # Go back one level (to enter module level) and load the function from the globals

However, I don't consider this good practice, and if possible, I would avoid doing that. As already pointed out in comments to your question, doing this without inspecting the stack trace isn't possible in Python.
Comment: That's a good one, but take a look at the `EDIT2` in my post.


ASP.NET RAZOR - Projeto WEBSITE em execução no IIS (Homologação ou Produção) não consta a TAG HEAD

Question: Estou com um problema em meu projeto WEB , que ao ser executado por um IIS de um servidor, a tag html HEAD não aparece fechada e quando executado localmente a mesma aparece corretamente. Detalhe, ao inspecionar elemento no browser a mesma aparece, porem ao pressionar ctrl+U  não encontramos a mesma.
Já foi verificado as configurações de minificação e até mesmo compactação, porem nao consigo identificar o mesmo.
Answer: Deve ser algum problema na configuração do seu IIS, você consegue rodar ou publicar no IIS o exemplo padrão de um novo projeto?
Tente colar a configuração do seu IIS no painel de controle ativar e desativar recursos do windows para compararmos se tem as mesmas configurações.


Can Power BI generate PDFs like SSRS?

Question: SCENARIO: a company is using SSRS to generate paycheck at the end of the month.
Every month SSRS generate 1 PDF per employee with the name, surname and how much he/she will be paid. the company has about 500 employees so there a re 500 PDFs that are generated.
PROBLEM: the company now wants  to move to Power BI Is it possible to generate PDFs dynamically, one for each employee, form Power BI?
Comment: in theory, yes. there's an [ExportToFile](https://learn.microsoft.com/en-us/rest/api/power-bi/reports/export-to-file) API endpoint that takes PDF as one of the options, you should probably be able to work something out with that.
Answer: I think you're looking for Paginated Reports: https://learn.microsoft.com/en-us/power-bi/paginated-reports/paginated-reports-report-builder-power-bi
Comment: Right, I think that video is even mentioning that the Export API is even better: https://learn.microsoft.com/en-us/rest/api/power-bi/reports/export-to-file#fileformat and will probably be our go-to solution.
Comment: Thank you @David. In the video I can see that I can download the report `51721` so yes, it can dynamically create reports. But if I have 500 employees do I have to input each number from the web interface with a web crawler (let's say with a python script that input the `51721` and then download each PDF) or can I input that in the URL or make an API call that generates the report and download in PDF?
Comment: This video should answer all your questions. You can download a single pdf and use a pdf splitter to split by page to get all 500 employees in one go. https://www.youtube.com/watch?v=XSIbRNXGgPQ

Can Power BI generate PDFs like SSRS?


How can I edit Custom Form API?

Question: I have created the Custom registration form module using the form API as per the requirements. I have also inserted the records in the database using form alter functions. Now I need to create an edit registration form  for the logged users.
My suggestion on this is:

Create edit_reg form module with form controls
Retrieve the records of logged users
Pass the values to defalut value of form controls

Is the above method good? May you suggest me any other method to edit the form API?
I am using Drupal 7.
Comment: There's nothing wrong with that. Do you have any specific questions?
Comment: On Drupal, the form to edit an account is very similar to the one used to register an account. Is there any reason your form to edit the registration information should be different from the form to edit an existing account?
Answer: Why not use the existing user edit form, and use hook_form_alter() to add your fields. That way, you get all the built in functionality, such as password changing etc.
It would also make sense to make the user registration alterations the same way, instead of creating your own flow, unless it for some other reason makes sense to do it that way.

How can I edit Custom Form API?


Prove that at least one of the subsets is at most size $\sqrt{n}+1$

Question: Let $X$ be an $n$-element set, and let $S_1, ..., S_n$ be subsets of $X$ such that $\mid S_i \cap S_j \mid \leq 1$ whenever $1 \leq i < j \leq n$. Prove that at least one of the sets $S_i$ has size at most $\sqrt{n}+1$
I was thinking of taking an approach by contradiction by assuming for every $S_i$ we have $\mid S_i \mid \geq \sqrt{n}+1$.
I know $\mid S_i \cap S_j \mid = \mid S_i \mid + \mid S_j \mid - \mid S_i \cup S_j \mid$. But I have no further idea about how to go about proving the claim.
Comment: This should answer your question: https://math.stackexchange.com/a/1750335.
Comment: HAve you tried INDUCTION on $n$?
Comment: @TitoEliatron I have not! So let's see, for $n=1$ the claim clearly holds for a single element set with $1$ subset. Now assume for an $n$-element set with subsets $S_1, ..., S_n$ there is a $k$ with $1 \leq k \leq n$ with $\mid S_k \mid \leq \sqrt{n}+1$
Comment: For the inductive step we consider the set $X$ but with an extra element $x_{n+1}$ and subset $S_{n+1}$ satisfying the intersection condition. We seek to prove there is now also a $k$ such that $\mid S_k \mid \leq \sqrt{n+1}+1$  But does this induction make sense? How do I know I can build a set $S_{n+1}$ to meet the criteria by adding a new element to $X$?
Comment: I think the extra element can only be part of, at most, two subsets.... (say $X_{n}$ and $X_{n+1}$). So yopu can apply Induction Hypothesis to $X_1,X_2,...X_{n-1},\tilde{X_n}$ where $\tilde{X_n}=X_n\setminus\{x_{n+1}\}$.
Answer: Let $Y$ be a random variable uniformly distributed on $X$, and let $N$ be the number of subsets $S_i$ that $Y$ is in. (Using indicator functions, $N=\sum 1_{S_i}$).
Let $f=x^2-x$, a convex function.
Then we know via Jensen's inequality that $$\mathbb E[f(N)]\ge f(\mathbb E[N]).$$
The left hand side of this is just $$\frac1n\left(\sum_{i=1}^n\sum_{j=1}^n|S_i\cap S_j|-\sum_{i=1}^n|S_i|\right).$$ Cancelling the $S_i\cap S_i$ terms with the $S_i$ gives us a trivial upper bound of $\frac1nn(n-1)=n-1$.
On the other hand, if we let $S=\sum_{i=1}^n|S_i|$, then the RHS is equal to $S(S-1)$.
Therefore we know that $n-1\ge S(S-1)$ so $$\frac12+\sqrt{n-1+\frac14}\ge S$$
But the total number of elements across all sets is $Sn$ and there are $n$ sets, so one set has at most $S$ things in it. Thus it remains to show that $$\sqrt{n}+1\ge\sqrt{n-\frac34}+\frac12$$
which is trivial as every term on the left is greater than the corresponding term on the right.
An interesting thing to note is that equality (the minimum size of a set being $\sqrt{n-\frac34}+\frac12$, not your one) is actually attainable, if you make the elements points in a finite projective plane, and sets correspond to lines containing the points they are in. Thus this shows that this bound is in fact tight :)
Answer: Let $X:=\{1,2,\dots,n\}$ and let's assume that the element $i\in X$ is in $d_i$ subsets of the list $S_1,\dots,S_n$. Then, by  the assumption $\mid S_i \cap S_j \mid \leq 1$ whenever $1 \leq i < j \leq n$, it follows that
$$\frac{1}{n}\binom{n}{2}\geq \frac{1}{n}\sum_{i=1}^n \binom{d_i}{2}\geq
\binom{\frac{N}{n}}{2}.$$
where
$$N=\sum_{i=1}^nd_i=\sum_{i=1}^n |S_i|.$$
Assume by contradiction that $|S_i|> \sqrt{n}+1$ for all $i$. Then $N>n(\sqrt{n}+1)$ and, by the above inequality, we have
$$\frac{n-1}{2}=\frac{1}{n}\binom{n}{2}\geq
\binom{\frac{N}{n}}{2}> \frac{1}{2}\left(\frac{N}{n}-1\right)^2>\frac{n}{2}$$
which is a contradiction.


What optimisation method is used in ordered logistic regression?

Question: I am using the polr function in R to create an ordered logistic model and am curious to know what its optimisation method is?
It seems to perform better than other models I have tested it against when looking at mean absolute error (MAE), but performs considerably worse when looking at MSE, so I was wondering if it optimises the model based on absolute error (as opposed to ordinary least-squares regression, for instance)?
Answer: Semiparametric ordinal regression model use the same optimization method as used for binary logistic regression: maximum likelihood.  Instead of just having simple probability elements in the calculation of the likelihood as in the binary case (for a covariate-specific P(Y=1) = p you have probability of p if Y=1 and 1-p if Y=0) you have probabilities that Y=j for a whole series of j values.  These cell probabilities are computed by differencing the ordinal model's cumulative probabilities.


Problemas para com a consulta no banco de dados (Sistema de pesquisa)

Question: Estou tentando criar um sistema de pesquisa no db no entanto esta retornando apenas um resultado, o último endereço na tabela (Eu havia conseguido fazer com que retornassem todos, no entanto depois alterando o layout eu fui testar e não deu mais, mesmo apagando tudo e retornando de quando funcionou).
<?php
$host="localhost";
$user="root";
$password="";
$db="db";
$con = new mysqli($host,$user,$password,$db);

$verifica = 0;
$city = $_POST['city'];
$bairrop = $_POST['bairrop'];

if(!empty($_POST['city']) && !empty($_POST['bairrop'])){
$result_search = "SELECT * FROM user WHERE cidade LIKE '%$city%' AND bairro LIKE '%$bairrop%'";
$resultado_search = mysqli_query($con, $result_search);
$verifica = mysqli_num_rows($resultado_search);
}elseif (!empty($_POST['city'])) {
$result_search = "SELECT * FROM user WHERE cidade LIKE '%$city%'";
$resultado_search = mysqli_query($con, $result_search);
$verifica = mysqli_num_rows($resultado_search);
}elseif (!empty($_POST['bairrop'])) {
$result_search = "SELECT * FROM user WHERE bairro LIKE '%$bairrop%'";
$resultado_search = mysqli_query($con, $result_search);
$verifica = mysqli_num_rows($resultado_search);
}

if($verifica > 0){
  while($row_search = mysqli_fetch_array($resultado_search)) {
  $nome = $row_search['nome_usuario'];
}
}else{
  echo "Nenhum resultado encontrado.";
}
?>

2:
Estou usando o bootstrap e gostaria que eles retornassem da seguinte maneira:

AQUI O NOME

DESCRIÇÃO

Answer: A função mysql_fetch_array() retorna o valor aonde o ponteiro se encontra e, após retornar o valor, move o ponteiro uma posição para a frente.
Imagine uma tabela cuja coluna é denominada de "nome_usuario" e a seta (->) é o ponteiro da lista.
-> Beltrano Tal
   Ciclano Soares
   Fulano Silva

Quando utilizamos a função mysql_fetch_array(), ele retorna a primeira linha:
   while($row_search = mysqli_fetch_array($resultado_search)) {
   $nome = $row_search['nome_usuario'];

Neste momento a variável $nome assume o valor Beltrano Tal e o ponteiro move-se uma posição para frente, e nossa lista fica da seguinte maneira:
   Beltrano Tal
-> Ciclano Soares
   Fulano Silva

Neste momento a variável $nome assume o valor Ciclano Soares e o ponteiro move-se uma posição para frente, e assim sucessivamente.

Então é por isso que no seu while na variável $nome só aparece o último nome.

Ao executar o while o valor da variável $nome está sendo sobrescrito porque você não está concatenando os valores.
Você pode por exemplo fazer assim para concatenar
$nome .= $row_search['nome_usuario'];
ou
$nome = $nome.$row_search['nome_usuario'];

É claro que do jeito que está acima os nomes retornarão todos juntos. Cabe a você decidir a forma que a variável $nome deve ser construída para posterior apresentação. Por exemplo:
`$nome .= "<li>" . $row_search['nome_usuario'] . "</li>";`

e no lugar que deva ser apresentado por exemplo:
echo "
".$nome."
";


Question mark as duplicate but reference question show 404 error page

Question: I came across one question which is marked as duplicate. So I try to open link of question provided but its shows 404 error page.
In this case How I can find solution provided?
Answer: Here what happened.
The author asked two identical questions. This happens sometimes for different reasons. Apparently one of the questions was closed as duplicate. Then the other copy of the question was closed dues to some valid reason and after some time passed was automatically purged. That's how you get 404 page.
I also deleted the question you linked in your .. question to avoid further confusion.
Comment: What if the other copy of the question has correct solution but that question deleted by user or user account deleted by any reason, in that case what will happen?
Comment: Both versions had no answers.