In firebase login getting error "An account already exists with the same email address but different sign-in credentials" in android

Question: Here am trying to implement Google, Facebook and Twitter login using firebase.
I have faced many scenario which was not clear for me.
Each individual login is working correctly, I didn`t found any problem here.
My requirement is when the user log-in with firstname.lastname@example.com for the first time with some provider(Google,Facebook,twitter) and after success, user logged out. On second log-in the user use same id email@example.com with some other provide rather than one used before,that time We should not allow the login process. User need to log-in with the same provider from next time.
Below are the cases I found ,

For first time when in log-in using email@example.com using google, after success popup i logged out. For second time i try to log-in using same id firstname.lastname@example.com using Facebook or twitter its throws an error "An account already exists with the same email address but different sign-in credentials".
For first time when in log-in using email@example.com using twitter or Facebook, after success popup I logged out. For second time I try to log-in using same id firstname.lastname@example.com using google. It does not showing any Exception. Here I need to notify the user "email@example.com is associated with twitter or Facebook, Use same provider to login "

I don`t know whats happening in second case.
For this id xxxxx@gmail I have google, Facebook and twitter account.
Comment: Did you ever work out how to do this? i.e. to keep the default account merging behaviour where it will link the same email from Google, Apple or Email into a single account and also make it work for Facebook? I cannot seem to see how to do this other than to ask the user to "Try again with another provider that they have already used for this email" which is pretty poor Ux!
Answer: See if it helps you. Change this settings in Firebase console
Comment: I totally disagree with the answer provided. If in my app, I expects that if user login with same email address using multiple providers like google, fb...it must create a single account without any issues.
Comment: Agree with @ShreeramK, Firebase should be able to merge in the accounts. We should really avoid allowing multiple accounts per single email address!
Comment: Oh, please. He has clearly enabled that option, that is why he gets errors for facebook and twitter. I also have the same issue in my web app, where I'm implementing email, google, and github
Comment: if I active that I can log in properly but I create a new user with a new id. If I need my previous user to see (for example) my post won't work
Comment: This is not the right approach if you want to make use of Firebase's merging - i.e. I can sign in with the same email address using Google, Apple or Email and it will merge the users and provide the same UserId for each (just a different provider). However with Facebook, this is a massive pain as it doesn't do this and I don't want to have to start having different users to track for the aforementioned Apple, Google and Email users. I simply want to merge Facebook in the same way - there simply doesn't appear to be a good way to do this.
Answer: authentication->settings->user account linking
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: @DrMido I recommend to make a difference between an external link (which your comment would be appropriate for) and a picture inserted in the accepted, even recommended way, which is not considered a link-only. This post lacks some prose explanation, but it is not link-only.
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/32856830)
Comment: Problem here is that it creates a new User (and new GA tracking etc.) for each provider with the same email (whereas it will merge Google, Apple and Email by default, which is exactly what I want as they are the same person) - I just want the same behaviour with Facebook and I cannot figure out how to do this. There is a Link accounts api but for that I need to have both credentials in my hand....
Answer: To link multiple social accounts firebase have a functionality called
"Link Multiple Auth Providers to an Account"
Here's the link for reference:
Link Multiple Auth Providers to an Account


Determine if $S$ a vector space when it is a subset of $C([-1,1])$.

Question: Let $C([-1,1]$ be the set of continuous functions on the interval $[-1,1]$, and let $S$ be the subset of $C([-1,1])$ consisting of $f$ such that $f(-x)=-f(x)$ for any $x$ in $[-1,1]$. Is $S$ a vector space?
So this is one of the questions from my textbook and from the answers in the textbook, I know that $S$ is a vector space. I am having trouble with determining of how $S$ is a vector space when it involves intervals.
I know the axioms for determining whether something is a vector space but how would I apply them with the intervals?
Any help would be appreciated. Thanks.
Answer: You con show that, if $f$ and $g$ are in $S$ and $\lambda\in \mathbb{R}$ then $f+\lambda g\in S$, i.e $(f+\lambda g)(-x)=-(f+\lambda g)(x)$ $\forall x\in [-1,1]$.
Answer: Hint:
it suffices to prove that $S$  is a vectorial subspace of $\mathcal C([-1,1])$.
For this you can remark that  that $0 \in S$  and show that  if  $f,g \in S$  and $\lambda \in \Bbb R$, then $f + \lambda g \in S$
Answer: You can also show that, for any $x\in [-1,1]$, the map $h_x:x\mapsto f(-x)+f(x)$ is linear and it's Kernel is a vector subspace, and remark that $S=\bigcap_{x\in [-1,1]}\ker h_x$ which is a vector subspace.


C++ crashes when I access the next Node pointer

Question: I am creating a list container using Node.
This is how the Node structure look like; mFirst is a private data member for the List class.
struct Node{
    Node(const EType & d, Node *n = nullptr) : mData(d), mNext(n) { }
    EType mData;
    Node *mNext;
};
Node *mFirst;

There is a function which is used to delete an element from the container.
The problem happens on line temp2->mNext = temp->mNext;.
The element is deleted but the program will crash.
I have no idea what is causing the problem.
template <typename EType>
void Set<EType>::remove(const EType & x) {
    if (isElement(x)) {
        Node *temp = mFirst;
        Node *temp2 = nullptr;
        while(temp->mData != x) {
            temp2 = temp;
            temp = temp->mNext;
        }
        if (temp2 == nullptr) {
            mFirst = temp->mNext;
        } else {
            temp2->mNext = temp->mNext;
        }
    }
}

If I change the line to:
temp = temp->mNext;
temp2 = temp2->mNext;
temp2 = temp;

Nothing happens, and the function won't work.
Are both expressions not the same?
Comment: `the program will crash`: have you more information about that ? Your `remove` method seems correct, even if you could merge the `isElement` method within `remove` to avoid far assertions from their use. Note that you have not deleted `mFirst` or `temp2->mNext`.
Comment: try to use debugger to figure out what happens at the line in question, it should be either `temp2` or `temp` is `nullptr`, or try to print `temp2` and `temp` to a console to see which of those is `nullptr`. Then try to understand under which conditions it happens. And thus you will debug your problem.
Answer: For every pointer that you use, you must check is it different from 0: You check only for tmp2, but you should check for tmp too.
while(tmp && tmp->mData !=x)

You need to check if the element was found in the list
if(tmp)
{
  if(!tmp2)
  {
    mFirst = tmp->mNext;
    delete tmp;//now it is deleted
  }
  else
  {
    tmp2->mNext = tmp->mNext;
    delete tmp;//now it is deleted
  }

You also need to pay attention when creating the list: the last element must have mNext set to 0.
Answer: First of all. You're last code does nothing. Read it again.
Then you are never checking the end of your list, even in the loop.
How do you know the element has been deleted? If your program crashed at this line, nothing is deleted.
And I don't see any delete, so you're never going to delete the object,  it will still be in memory.
Can you give us the exact crash message? Using gdb maybe
Comment: The program will run then crashes. I have put a print() after I remove an element so I could see the element was gone before the program shut down. I couldn't be bothered with deleting the objects since I could not even get the program to run properly.
Comment: Then we don't know if this function is causing the crash or not.  Try using a debugger to run your code, you should get more information about the crash.


Delphi 2010 - Detect file growth in a mapped drive

Question: I'm trying to detect when a file is being written into a mapped drive. I need to wait for the file to be completely uploaded to the mapped drive before I start to process it. The problem is that the application that writes the file to the mapped location does not lock the file.
I've tried the following:
-check if file is in use => not working because file is not locked exclusively.I can rename it while it is being written to the mapped drive.
-get the last access filestamp comparison => not working. I should get an error because the file attributes change but i dont.
-get the file size => not working. it already shows me the final size of the file.
Is there any way I can detect the growth of the file so i can wait until it is over? All the tests listed above work ok on local files but not on that mapped drive where the files are written by a 3rd party tool. If is use explorer and press F5 I can see that the file size is growing.
Comment: You need to fix the root problem.
Comment: *"-get the last access filestamp comparison => not working. I should get an error because the file attributes change but i don't"* What exactly is not working specifically? Why would you expect an error querying the timestamp? If you have the file open for reading, you can use `GetFileTime()` without error. Otherwise, you can use `FindFirstFile()` or `GetFileAttributesEx()`, neither of which require you to open the file since they get metadata from the filesystem.
Comment: @David - meaning that is the only way, or that it needs fixing anyway?
Comment: Should we take it you have no control over the writer-app?
Comment: I can't really see how anyone can help here with no details provided. Any hacky workaround would surely rely on knowledge of the systems and code involved. Perhaps the writer broadcasts a message when it is done. We can only guess. Can't you be specific?
Comment: I have no control over the sender application. I was thinking on simulating the view properties from Explorer and then store the size into a variable and wait 50ms and then retrieve again the size.If they differ then it is still being copied. The application that puts the file on the shared folder it's part from an automation process i do not control. I have no settings to define there. I don't no why all the methods above fail but the explorer shows on refresh that a file is being written, it grows.
Answer: Thanks to all the suggestions received I managed to come up with a solution. Searching over the internet I managed to get a function that gets the size of the file in bytes like it is displayed in The Explorer. The problem was that in order to work i had to wait for 5 seconds before taking the second value from the file properties. This works but in order to be usable in an automation system I have to make it run in a separate thread because I need to use this in a loop(for i:=listbox1.items.count-1 downto 0 do begin) to check all the files from a listbox in order to know which can be procesed.
function GetFileSize_mmg(const FileName: string): Int64;
var
  fad: TWin32FileAttributeData;
begin
  if not GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @fad) then
    RaiseLastOSError;
  Int64Rec(Result).Lo := fad.nFileSizeLow;
  Int64Rec(Result).Hi := fad.nFileSizeHigh;
end;

function does_size_changes(filename:string; delay:integer;memo_loguri:Tmemo): boolean;
var size1,size2:int64;
begin
result:=false;
size1:=GetFileSize_mmg(filename);
sleep(delay);
size2:= GetFileSize_mmg(filename);

if size1 <> size2 then
begin
result:=true;
memo_loguri.Lines.Add(datetimetostr(now)+' - file "'+filename+'" is growing: ' +inttostr(size1)+' < '+inttostr(size2));
end

else
begin
result:=false;
memo_loguri.Lines.Add(datetimetostr(now)+' - file "'+filename+'" can be used: '+ inttostr(size1)+' = '+inttostr(size2));
end;
end;

Thanks


What are some good datasets to learn basic machine learning algorithms and why?

Question: I am new to machine learning and  looking for some datasets through which i can compare and contrasts the differences between different machine learning algorithms (Decision Trees, Boosting, SVM and Neural Networks)
Where can I find such datasets ? What should I be looking for while considering a dataset ?
It would be great if you can point to some good datasets and also tell me what makes them a good dataset?
Comment: I wonder if this question does not fit better for http://opendata.stackexchange.com/ ... As about datasets, most textbooks mention such datasets and make them available, many are already available in statistical software or in libraries for such software. You can see also https://archive.ics.uci.edu/ml/datasets.html . Of course, another question is what makes some datasets "good" for learning and some "bad" - it is an interesting question.
Comment: I think questions about data sets from a pedagogical point of view are definitely on-topic here: e.g. [What aspects of the "Iris" data set make it so successful as an example/teaching/test data set](http://stats.stackexchange.com/questions/74776/what-aspects-of-the-iris-data-set-make-it-so-successful-as-an-example-teaching); [Datasets constructed for a purpose similar to that of Anscombe's quartet](http://stats.stackexchange.com/questions/80196/datasets-constructed-for-a-purpose-similar-to-that-of-anscombes-quartet)
Comment: @Tim Because there is a *pedagogical* aspect to this question (for example, one example of a "good" data set for learning purposes is one that shows where different algorithms give very different results) I think it's better suited to CV than to OpenData.
Comment: @Silverfish: This has been discussed on Meta - ["Questions about Datasets": Possible Exceptions?](http://meta.stats.stackexchange.com/q/2096/17230) - & there seems to have been general agreement with your point of view. But I still think this q. is rather broad - what clearly distinguishes it from [Locating freely available data samples](http://stats.stackexchange.com/q/7/17230)?
Comment: You will find some datasets as packages on CRAN, like:    ElemStatLearn   and others.
Comment: @Scortchi Thanks - I  would certainly be happier with a narrower thread - one that focuses on "good" data sets for a particular pedagogical point (eg to highlight the difference between two specific algorithms). But I'm uncertain whether this is too broad to be answerable. There are certainly some "well-known data sets that learners often practise ML on" and in that respect it might differ from your link, but I sympathise with your viewpoint.
Answer: The data sets in the following sites are available for free. These data sets have been used to teach ML algorithms to students because for most there are descriptions with the data sets. Also, it's been mentioned which kind of algorithms are applicable.

UCI- Machine Learning repository
ML Comp
Mammo Image
Mulan
Answer: Kaggle has a whole host of datasets you can use to practice with.
(I'm surprised it wasn't mentioned so far!)
It's got two things (among many others) that make it a highly invaluable resource:

Lots of clean datasets. While noise-free datasets aren't really representative of real-world datasets, they're especially suited for your purpose - deploying ML algorithms.
You can also view others' ML models for the same dataset, which could be a fun way to pick up some hacks along the way. It goes without saying that the kind of exposure you get from learning from the best practitioners is, like for anything else, super helpful.
Comment: This really should be the top answer because in addition to an enormous variety of datasets, the forums for each challenge are an invaluable resource for picking up techniques and tricks, along with code examples.
Answer: First, I'd recommend starting with the sample data that is provided with the software.  Most software distributions include example data that you can use to get familiar with the algorithm without dealing with data types and wrestling the data into the right format for the algorithm.  Even if you are building an algorithm from scratch, you can start with the sample from a similar implementation and compare the performance.
Second, I'd recommend experimenting with synthetic data sets to get a feel for how the algorithm performs when you know how the data was generated and the signal to noise ratio.
In R, you can list all dataset in the currently installed packages with this command:
<code>data(package = installed.packages()[, 1])
</code>
The R package mlbench has real datasets and can generate synthetic datasets that are useful for studying algorithm performance.
Python's scikit-learn has sample data and generates synthetic/toy dataset too.
SAS has training dataset available for download and the SPSS sample data is installed with the software at C:\Program Files\IBM\SPSS\Statistics\22\Samples
Lastly, I'd look at data in the wild. I'd compare the performance of different algorithms and tuning parameters on real data sets.  This usually requires a lot more work because you will rarely find dataset with data types and structures that you can drop right into your algorithms.
For data in the wild, I'd recommend:
reddit's Dataset Archive
KDnugget's list
Comment: For those who don't have R, & don't want to download it just to get access to these datasets, the datasets & descriptions are available online [here](https://vincentarelbundock.github.io/Rdatasets/datasets.html).
Answer: In my opinion, you can should start with small datasets which do not have too many features.
One example would be the Iris dataset (for classification). It has 3 classes, 50 samples for each class totaling 150 data points. One excellent resource to help you explore this dataset is this video series by Data School.
Another dataset to checkout is the Wine Quality data set from UCI -ML repository. It has 4898 data points with 12 attributes.
Answer: The Iris data set hands down. It's in base R as well.
Comment: Please respond to the substantive part of the question: "... also tell me what makes them a good dataset?"


List of Checkbox returns false even when checked in asp.net core razor pages

Question: Student Attendance class
 public class StudentAttendance
{
    public int Id { get; set; }
    public int StudentID { get; set; }
    public bool IsPresent { get; set; }

}

View table for my attendance form
 @foreach (var student in Model.Students)
          {

                 @student.FullName
                <input type="hidden" asp-for="HiddenID" id="id" value="@student.StudentID"/>
                <input type="checkbox" name="IsPresent" >
 }

Attendance Page Model
 [BindProperty]
    public StudentAttendance studentAttendance { get; set; }

    [BindProperty]
    public List<int> StudentAttendanceList { get; set; }

    [BindProperty(SupportsGet = true)]
    public int? SearchClassID { get; set; }

    [BindProperty]
    public List<int> HiddenID { get; set; }

    [BindProperty]
    public bool IsPresent { get; set; }

    public IEnumerable<Student> Students { get; set; }

Attenadance On Post()
foreach (var id in HiddenID)
        {
            Conn.StudentAttendance.Add(new StudentAttendance
            {
                StudentID = id,
                IsPresent = IsPresent,
            });
        }

When i submit and save the IsPresent value remains false even when checked
Answer: Since the IsPresent in the form is not bound to the Model, and the default value of IsPresent in the model is false. Finally, it obtained false each time. By dynamically changing the value in the checkbox through a JavaScript function, the corresponding selected id can be submitted to the background.
In Attendance.cshtml
<form method="post">

        @foreach (var student in Model.Students)
        {

                 @student.FullName
                <input type="hidden" asp-for="HiddenID" id="id" value="@student.StudentID" />

                        <input type="checkbox" id="IsPresent" name="isPresent" value="false" onchange="changePresent(event,@student.StudentID)">

        }

    <input type="submit" name="name" value="sub" />
</form>
@section Scripts{

}

Then, in post method, get the checked id, and justify whether the id is checked.
public void OnPost(int[] isPresent)
        {
            foreach (var id in HiddenID)
            {
                new StudentAttendance
                {
                    StudentID = id,
                    IsPresent = id == isPresent[id - 1],
                };
                /*Conn.StudentAttendance.Add(new StudentAttendance
                {
                    StudentID = id,
                    IsPresent = IsPresent,
                });*/
            }
        }

result:
Comment: Thanks so much Yiyi You, i really do appreciate, but i got an exception error: IndexOutOfRangeException: Index was outside the bounds of the array
Comment: Please i will really appreciate if you can help me further i am getting   IndexOutOfRangeException: Index was outside the bounds of the array error
Comment: I think the issue you mentioned in the case can be  solved by the code,If you have a new exception,you can create a new thread,debug and tell where you get the Exception,and which data you pass to get the Exception.


Question look like the Ruzsa triangle inequality

Question: Denote $ X+Y=\{x+y:x\in X,y\in Y\} $ for two non-empty finite sets $ X,Y\subset\mathbb{R}$.
Does the following inequality always hold for any three non-empty finite sets $ A,B,C\subset\mathbb{R}$?
$$ |A|\cdot|A+B+C|\le|A+B|\cdot|A+C|.$$
Answer: No, not even for $A = B = C$. There is a standard example of a set $A$ such that $|2A| = K|A|$ and $|3A| \geq c K^3 |A|$. See the comments on this answer: https://mathoverflow.net/a/160327/20598
Comment: What about the inequality $ |A+B+C|^2\le |B+C||C+A||A+B| $ ?
I once wanted to prove it by the questioned inequality above.
The pretty counterexample doesn't work for this inequality though.
Comment: Not sure about that one.


what is the difference between L1 norm, absolute value and absolute value norm?

Question: |x| is one the most common symbol in math. it seems that this symbol means a some different computation.
per wiki

The absolute value norm is a special case of the $L1$ norm.

absolute value of a real number x is the non-negative value of x without regard to its sign.
For example, the absolute value of 3 is 3, and the absolute value of −3 is also 3.
can anyone give an simple example to elaborate the difference between L1 norm, absolute value and absolute value norm?
Answer: Absolute value and absolute value norm are defined only for numbers (usually for complex or reals). $L_1$ norm is defined for functional space with measure.
Any finite dimensional vector space $\mathbb R^n$ is functional space - it's elements can be viewed as functions from $\{1, \ldots, n\} \to \mathbb R$. We can introduce counting measure on $\{1, \ldots, n\}$ and get $L_1$ norm on $\mathbb{R^n}$: $\|(x_1, \ldots, x_n)\| = |x_1| + \ldots + |x_n|$.
$\mathbb R$ itself can be viewed as one-dimensional vector space over $\mathbb R$, and thus we will get $L_1$ norm $\|x\| = |x|$.
There is no significant difference between absolute value and absolute value norm - they are the same function(s). Term "absolute value norm" is more often used when we want to emphasize that we work with vector space, and "absolute value" when we work with just numbers.


Interpreting wording for formulating hypothesis testing

Question: I've been presented with paired data for individuals' weights before and after a dieting program (paired t-test problem).
The question being asked is "test the hypothesis that the dieting program is effective." Does this wording relate to the null hypothesis or the alternative?
Below is the  Minitab output for the paired t-test assuming that the null hypothesis is that there is no change. The descriptive statistics show that the mean weight before the dieting program (180 lbs.) is greater than the mean weight after the dieting program (170 lbs.).

Let mu1 = population mean before and mu2 = population mean after the dieting program. As can be seen in the Minitab output, I ran the paired t-test with following hypotheses...
<code> Null hypothesis: mu of difference = 0

 Alt. hypothesis: mu of difference > 0
</code>
Where "mu of difference" = mu1 - mu2. Have I interpreted "test the hypothesis that the dieting program is effective" correctly?
Comment: Please add the `[self-study]` tag & read its
[wiki](http://stats.stackexchange.com/tags/self-study/info).
Comment: In view of the two conflicting answers, it's apparent that you should justify your choice of null & alternative hypotheses with reference to the context. Where does the burden of proof lie? What does "effective" mean?
Comment: I've added Minitab output to show the descriptive statistics to make the problem more clear.
Answer: Looks like you're on the right track. When you say "Does this wording relate to the null hypothesis or the alternative?" I'm not quite sure what you mean. You're testing the effectiveness of the dieting program. So you're correct by saying the null hypothesis is that it has no effect. However, it's a little tricky with the alternative hypothesis. It's (usually) bad practice to only check for one tail when testing effectiveness like this. Most of the times, you want to check both tails, because then you'll detect if the drug is really ineffective (i.e. they gain a lot of weight while on the dieting program). If you just check for one tail like you did, and they do gain a lot of weight, the stat test won't show you that as being significant.
Answer:
"the hypothesis that the dieting program is effective."

That is the null hypothesis!!
So does "effective" mean:

No weight loss
Some weight loss
A weight gain?

Obviously you want (2).
The alternative would thus be no weight loss or a weight gain.
rb612's point was that you might want to test that the result was statistically significantly different than 0. Which is a good idea, but it isn't what the problem  is asking for.
Comment: This is incorrect. The null hypothesis in such a case is that there is no effect. The alternative hypothesis is that there is an effect.


Soma de itens em uma lista

Question: Então, esse algoritmo que eu fiz não está fazendo a subtração que deve ser feita, preciso imprimir o total
#Essas variáveis são os valores que o usuário deve atingir no dia
#no caso se faltar ou execeder deve ser avisado.
prot_total = 140.0
carbo_total = 210.0
gordura_total = 56.0
n = int(input())
for i in range(n):
    nome, proteinas, carbos, gordura=input().split()
    if float(proteinas) > 140.0:
        proteinas -= prot_total

    if float(carbos) > 210.0:
        carbos -= carbo_total

    if float(gordura) > 56.0:
        gordura -= gordura_total
print(prot_total, "gramas de proteína em falta")
print(carbo_total, "gramas de carboidrato em falta")
print(gordura_total, "gramas de gordura em falta")
#Não está sendo feita a subtraçao

Estava tentando por uma função pra fazer isso, mas não consigo pensar em algo,
obrigado desde já.
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Bom no primeiro trexo de código logo abaixo do input, temos uma condição
    if float(proteinas) > 140.0:
        proteinas -= prot_total

Ele não estar decrementando pois só irá decrementar se o valor que você definiu no input for maior que o valor total que no caso seria 141 ai sim ele faria subtração.
Vamos a melhoria que eu sugeriria para você:
# Mantenha essa váriaveis, para caso você queira mudar o valor total de consumo no dia sem
# Precisar alterar o código inteiro

prot_total = 140.0
carbo_total = 210.0
gordura_total = 56.0

Após definir isso no seu sitema você faz uma pergunta de quantos alimentos ele ingeriu, então para isso, vamos deixar mais claro o que está entrando no nosso sistema
qntd_alimentos = int(input("Informe a quantidade de alimentos: "))

Agora para termos salvo as quantidades totais vamos criar três novas váriaveis para salvar os valores totais
prot_total_usuario = 0.0
carbo_total_usuario = 0.0
gordura_total_usuario = 0.0

Agora vamos percorrer o loop que você definiu baseado na quantidade de alimentos informados, e vamos deixar mais claro que estamos informado ao sistema, e iremos adicionar esse valor informado ao valor total do usuário
for i in range(qntd_alimentos):
  proteina = float(input("Informe a quantidade de proteinas do alimento: "))
  carbo = float(input("Informe a quantidade de carbos do alimento: "))
  godura = float(input("Informe a quantidade de godura do alimento: "))

  prot_total_usuario += proteina
  carbo_total_usuario += carbo
  godura _total_usuario += godura

Quando o loop acabar veremos que todos os valores foram somados, (você pode usar um print para testar se quiser)
Agora que temos os valores totais, podemos fazer a verificação caso tenha excedido ou tenha ficado abaixo do esperado
if (prot_total_usuario == prot_total):
  print("Você atingiu o valor ideal!")
elif (prot_total_usuario < prot_total):
  print(f"Você ficou abaixo do total de proteinas por {prot_total-prot_total_usuario}")
else:
   print(f"Você ficou acima do total de proteinas por {prot_total_usuario-prot_total}")

if (carbo_total_usuario == carbo_total):
  print("Você atingiu o valor ideal!")
elif (carbo_total_usuario < carbo_total):
  print(f"Você ficou abaixo do total de carbo por {carbo_total-carbo_total_usuario}")
else:
   print(f"Você ficou acima do total de carbo por {carbo_total_usuario-carbo_total}")

if (gordura_total_usuario == carbo_total):
  print("Você atingiu o valor ideal!")
elif (gordura_total_usuario < carbo_total):
  print(f"Você ficou abaixo do total de gordura por {gordura_total-gordura_total_usuario}")
else:
   print(f"Você ficou acima do total de proteinas por {gordura_total_usuario-gordura_total}")

Assim você cosnsegue ter o valor total informado pelo usuário e o qual foi a diferença do informado para o total esperado

Soma de itens em uma lista


$\sum|a_n|^2<\infty$ and $\sum a_n<\infty$ implies $\sum\log(1+a_n)$ converges

Question: Note that all elements are complex numbers. Suppose we know $$\sum_{n=1}^\infty|a_n|^2\quad\text{and}\quad\sum_{n=1}^\infty a_n$$converge. How can we conclude $\sum_{n=1}^\infty\log(1+a_n)$ converges? This is an effort to prove that $$\prod_{n=1}^\infty(1+a_n)$$converges.
If I knew that $\sum a_n$ was absolutely convergent, then I think I'd be able to use the power series expansion of $\log(1+a_n)$ and interchange summations. However, I don't think this is the intended method of solution. Will someone help me with this homework problem?
Update: Other work I've done so far:
Disregarding finitely many terms if necessary, we can assume $|a_n|<\frac{1}{2}$ for all $n$. Thus, we know $0\leq|a_n-\log(1+a_n)|<|a_n|^2$, so by comparison, we know $\sum_{n=1}^\infty |a_n-\log(1+a_n)|$ converges. Since it is absolutely convergent, it is convergent, so now we have $$\sum_{n=1}^\infty a_n-\sum_{n=1}^\infty\left( a_n-\log(1+a_n)\right)=\sum_{n=1}^\infty\log(1+a_n),$$therefore the series is convergent. Is this correct?
Comment: [This is related.](http://math.stackexchange.com/questions/158089/infinite-products-reference-needed/158099#158099)
Comment: Note that, $\ln(1+a_n)< a_n $.
Comment: @MhenniBenghorbal: I don't think that works since $a_n\in\Bbb C$. If they were real numbers, I think you are correct.
Comment: @Clayton: $\ln(1+|a_n|)<|a_n|$.
Comment: @MhenniBenghorbal: I believe that statement, but unfortunately, we don't know $\sum|a_n|$ is convergent. Thanks for the persistence, though!
Answer: Use the fact that, for small $x$,
$$\log(1+x)=x+\epsilon(x) |x|^2, \qquad |\epsilon(x)|\le 1,$$
to express $\sum_n \log(1+a_n)$ as a sum of two convergent series.
Comment re updated question:  Yes, that's correct.
Comment: Excellent! I was about to ask about the progress of my solution when you updated (your way seems perfectly reasonable as well, I just didn't know/see that beforehand). +$1$


When running npm install in an angular project is the angular cli installed

Question: Downloaded an application built on Angular 7 from a Git repo. Then ran npm install. Is the angular cli automatically installed when doing this? Do I need to install it manually? If not will the latest angular cli work with an older version of angular? In my case v7.
Answer: When you running npm install the Angular CLI gets installed locally for your project. Then, when you run npm start or npm run ng <your command> it will kick off.
If you want to install the latest Angular CLI globally, you can do so by running npm install @angular/cli -g
Then when you run ng <command> in your project directory, for commands like scaffolding - ng g <params> or ng update the global CLI will be in use.
However you do not have to install CLI globally, as I mentioned above, you will be fine with the local one, only the downside of that you have to prefix all your CLI commands with npm run e.g npm run ng g c my-component which is a bit of inconvenient.
But if you want to play around with the latest CLI and to scaffold new projects, then you have to install it globally.
Answer: Good evening. I assume you have to install the Angular CLI. Please visit https://angular.io/guide/setup-local for detailed instructions.


How to compare a n value to the mean of n-1 ; n-2 ; ... ; n-5?

Question: My question may be silly and I apologize if it is...
I'm working on data that comes from 40 animals monitored during 6 different days at 12-time points each day. I made multiple t-tests to determine at which time points differences between d0 and d-1 to d-5 seemed to appear (not sure about this way to do my analysis as I'm accumulating type I error but it's not my point here). However, having a quite important inter-individual variability, I would like to know for which portion of my population the detected differences are statistically significant. I really don't know where to start as for each individual I'm working on only 6 points for each time point, 1 per day as described above.
I was wondering if this should have been posted on StackOverflow instead but, as I don't even know what kind of test could be used I sent my message here.
Comment: Sounds like you need a generalized linear model, with random effects for intercept and slope.
Comment: Do you mean a generalized linear model with, altogther, individuals, days studied and time points as fixed effects ? I don't really get what should be integrated as random effect nor if any is needed.
Comment: So for each animal you have a total of 6*12 observations? 6 days, 12 measurements per day? What are these measurements? Are they categorical /  ordinal / continuous? And from this you would like to check whether there exist differences between the time points for a given animal and all the days? And do this for each animal? Is this correct?
Comment: I do have 6*12 observations per animal which means I have 2,880 points in total. The datas are continous as it is body temperature measurements. I want to know if it exists a difference comparing one day to the 5 others at the different time points, which I did with t-tests. And for now, I would like to know if the "general" observed difference which appeared at 2 time points are true for my 40 animals or only 35 of them for exemple. I thought I had to take them one by one to check this but maybe there is another solution.
Hoping my issue is a bit clearer now.
Comment: But are you interested in comparing whether temperature is similar between the days without considering time points? Or are you interested in whether the temperatures are similar between the time points of the day without considering days? Or are you interested in whether the temperatures of all the animals are similar for each time point and each day separately?
Comment: I'm interested in comparing temperatures among days and if animals are similar. The question I ask myself is: "Do they all behave the same way regarding temperature variations?". As body temperature follows a circadian rhythm I already know there are differences regarding time of the day and others have described it accuratly.
Answer: If I understood this correctly, you are interested in comparing the mean temperature of each animal for each day and between the animals. If so, then this is how you would do it in R.
I do not have access to your data so I will just have to make it up. I will use the Ovary data set from the nlme package. I will artificially create two days and add measurement ids for each day. Afterwards I train a mixed model, where measurement is the random effect. Fixed effects are Animal (mare) and Day. The outcome is follicles. This will give you all the combinations for days and animals.
library(nlme)

Ovary2=do.call(rbind,
  by(Ovary,list(Ovary$Mare),function(x){
    tmp=nrow(x)
    s1=floor(tmp/2)
    return(
      cbind(x,"Day"=factor(rep(1:2,times=c(s1,tmp-s1))),
            "Measurement"=c(seq(1:s1),seq((s1+1):tmp))
      )
    )
  })
)
Ovary2$Mare=factor(as.numeric(as.character(Ovary2$Mare)),labels=LETTERS[1:11])

summary(lme(follicles~Mare*Day,random=~1|Measurement,data=Ovary2))

And this is part of the output
Linear mixed-effects model fit by REML
 Data: Ovary2
       AIC      BIC    logLik
  1611.583 1699.327 -781.7915

Random effects:
 Formula: ~1 | Measurement
        (Intercept) Residual
StdDev:    1.032887 3.274704

Fixed effects: follicles ~ Mare * Day
                 Value Std.Error  DF   t-value p-value
(Intercept)  15.874539  0.916348 271 17.323702  0.0000
MareB        -7.649660  1.262231 271 -6.060426  0.0000
MareC        -6.034276  1.262231 271 -4.780641  0.0000
MareD       -11.071429  1.237722 271 -8.945007  0.0000
MareE        -6.428571  1.237722 271 -5.193875  0.0000
MareF        -4.214286  1.237722 271 -3.404874  0.0008
MareG        -5.188122  1.262231 271 -4.110278  0.0001
MareH        -5.666310  1.218148 271 -4.651578  0.0000
MareI        -4.980727  1.290032 271 -3.860932  0.0001
MareJ        -4.000000  1.237722 271 -3.231745  0.0014
MareK        -7.111199  1.262231 271 -5.633831  0.0000
Day2         -1.199643  1.218148 271 -0.984809  0.3256
MareB:Day2    0.349304  1.754170 271  0.199128  0.8423
MareC:Day2   11.353490  1.770221 271  6.413601  0.0000
MareD:Day2    4.471429  1.720982 271  2.598184  0.0099
MareE:Day2    4.628571  1.720982 271  2.689494  0.0076
MareF:Day2    5.480952  1.720982 271  3.184782  0.0016
MareG:Day2    1.530622  1.754170 271  0.872562  0.3837
MareH:Day2    8.678914  1.695013 271  5.120264  0.0000
MareI:Day2    2.915325  1.790150 271  1.628537  0.1046
MareJ:Day2    7.866667  1.720982 271  4.571034  0.0000
MareK:Day2    1.453699  1.754170 271  0.828711  0.4080

Comment: "Do they all behave the same way regarding temperature variations?" for me this indicates that not only mean but also amplitude and phase of the circadian cycle should be compared.
Comment: @Roland So we would need to estimate a phase and cycle parameter for a sine/cosine curve also?
Comment: Yes, a cosinor model might be nice.
Comment: I think I see your point! I just have a last question, just to be sure to understand your answer. Do the measurement id you added as random effect corresponds, in my case, to the different time sets ? If so, I think I understood your answer. Anyhow, many thanks for all the time you spent helping me today.
Comment: @Roland : I've red about the cosinor method and would have been glad to use it if I've been able to understand how. If you have any nicely explained books/article/stack subject than can be of help regarding the cosinor method, I would be happy to read it!
Comment: @Blue Yes, the measurements are the time points in your case.


ListView Blank After Calling AsyncTask doInBackground

Question: i have an adapter for my listView, and the data populating from internet,
The Background Process is running good, the Result Appear in Log Cat but no in  My List View, What the problem here ? am I doing wrong? here is my Code
PortalGroup mPortalGroup;
ArrayList<PortalItemData> mItems;
PortalItemListAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_group);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    new MyPortal().execute();
        mItems = new ArrayList<PortalItemData>();
        mAdapter = new PortalItemListAdapter(getApplicationContext(), mItems);

        JazzyListView list = (JazzyListView) findViewById(R.id.listGroup);
        list.setAdapter(mAdapter);
        list.setTransitionEffect(new FlyEffect());

}

private class MyPortal extends AsyncTask<Void, Void,Void> {
    ProgressDialog pDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(GroupActivity.this);
        pDialog.setOnDismissListener(new OnDismissListener(){

            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                MyPortal.this.cancel(true);
            }
        });
        pDialog.setMessage("Loading...");
        pDialog.show();
    }

    protected Void doInBackground(Void... params) {
        Portal portal = AccountManager.getInstance().getPortal();
        try {
            PortalInfo portalInfo = portal.fetchPortalInfo();
            List<String> querys = portalInfo.getFeaturedGroupsQueries();
            for (String query : querys) {
                Log.d("Query Group", "[query] " + query);
                PortalQueryResultSet<PortalGroup> result = portal
                        .findGroups(new PortalQueryParams(query));
                for (PortalGroup group : result.getResults()) {
                    Log.d("Available Group", "[group title] " + group.getTitle());
                    PortalQueryParams queryParams = new PortalQueryParams();
                    queryParams.setQuery(PortalItemType.WEBMAP, group.getGroupId(), null);
                    PortalQueryResultSet<PortalItem> results = portal.findItems(queryParams);
                    for (PortalItem item : results.getResults()) {
                        Log.d("Group Item", "[item title] " + item.getTitle());
                        byte[] data = item.fetchThumbnail();
                        if (data != null) {
                            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                            PortalItemData portalItemData = new PortalItemData(item, bitmap);
                            mItems.add(portalItemData);

                        }
                    }
                }
            }
            pDialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
            onError(e);
        }
        return null;
    }

    public void onError(Throwable e) {
        Toast.makeText(GroupActivity.this, getString(R.string.failed_sign_in), Toast.LENGTH_SHORT).show();
        pDialog.dismiss();
    }

    protected void onPostExecute() {
         mAdapter.notifyDataSetChanged();
        pDialog.dismiss();
    }
}

private class PortalItemListAdapter extends ArrayAdapter<PortalItemData> {
    private LayoutInflater inflater=null;

    public PortalItemListAdapter(Context context, ArrayList<PortalItemData> items) {
        super(context, 0, items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_group, parent, false);
        }

        // Setup item thumbnail
        PortalItemData item = getItem(position);
        ImageView image = (ImageView) convertView.findViewById(R.id.img);
        image.setImageBitmap(item.itemThumbnail);

        // Setup item title
        TextView text = (TextView) convertView.findViewById(R.id.txt);
        text.setText(item.portalItem.getTitle());
        return convertView;
    }

}

private class PortalItemData {
    PortalItem portalItem;

    Bitmap itemThumbnail;

    public PortalItemData(PortalItem item, Bitmap bt) {
        this.portalItem = item;
        this.itemThumbnail = bt;
    }
}

Comment: onPostExecute write **mAdapter.notifyDataSetChanged()**, it will solve the issue.
Comment: There is some issues, you are setting the adapter in **onPreExecute()**, thats why the problem arising.
Comment: I have tried to put in OnCreate but the problem still same
Comment: Have you tried setting your listview in your main activity?
Comment: Yes I Have, and also i have addd mAdapter.notifyDataSetChanged() in onPostExecute(), but the problem still there.
Comment: But here in onPostExecute(), you have not specified anything.
Comment: What if you put
mAdapter = new PortalItemListAdapter(getApplicationContext(), mItems); list.setAdapter(mAdapter); in onPostExecute()?
Comment: Would You Like to give me simple code, i have add in code, i will update my Question.
Comment: Whether its working now?
Comment: Nope, same as Before
Answer: In onPostExecute you might want to populate your ListView.
Instantiate your Adapter i.e. mAdapter in doInBackground once you have fetched the values of mItems. Finally set the Adapter to the ListView in onPostExecute.
Comment: I have done that, and the result listView is Still Blank
Comment: By blank, do you mean there are no rows or the content of the rows are blank?
Answer: 2 solutions

either add mAdapter.notifyDataSetChanged() on onPostExecute()
create the adapter in onPostExecute()  and set it to the Listview

your current code can actually cause an Exception in certain scenarios
Answer: Use Below code
private class MyPortal extends AsyncTask<Void, Void,Void> {
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(GroupActivity.this);
    pDialog.setOnDismissListener(new OnDismissListener(){

        @Override
        public void onDismiss(DialogInterface dialogInterface) {
            MyPortal.this.cancel(true);
        }
    });
    pDialog.setMessage("Loading...");
    pDialog.show();
}

protected Void doInBackground(Void... params) {
    Portal portal = AccountManager.getInstance().getPortal();
    try {
        PortalInfo portalInfo = portal.fetchPortalInfo();
        List<String> querys = portalInfo.getFeaturedGroupsQueries();
        for (String query : querys) {
            Log.d("Query Group", "[query] " + query);
            PortalQueryResultSet<PortalGroup> result = portal
                    .findGroups(new PortalQueryParams(query));
            for (PortalGroup group : result.getResults()) {
                Log.d("Available Group", "[group title] " + group.getTitle());
                PortalQueryParams queryParams = new PortalQueryParams();
                queryParams.setQuery(PortalItemType.WEBMAP, group.getGroupId(), null);
                PortalQueryResultSet<PortalItem> results = portal.findItems(queryParams);
                for (PortalItem item : results.getResults()) {
                    Log.d("Group Item", "[item title] " + item.getTitle());
                    byte[] data = item.fetchThumbnail();
                    if (data != null) {
                        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                        PortalItemData portalItemData = new PortalItemData(item, bitmap);
                        mItems.add(portalItemData);

                    }
                }
            }
        }
        pDialog.dismiss();
    } catch (Exception e) {
        e.printStackTrace();
        onError(e);
    }
    return null;
}

public void onError(Throwable e) {
    Toast.makeText(GroupActivity.this, getString(R.string.failed_sign_in), Toast.LENGTH_SHORT).show();
    pDialog.dismiss();
}

protected void onPostExecute() {
    list.setAdapter(mAdapter);
    list.setTransitionEffect(new FlyEffect());
    pDialog.dismiss();
}

}
Comment: Try it once and let me know if you face any problem..!
Comment: i have tried, and `Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()` come out


Call a user control from other user control

Question: So basically I have two User Control
1.Maptab.cs
2.TransactionTab.cs
And a Main menu.
So I have a button in main menu and when click it calls the maptab.cs, and in maptab.cs I have a button named btnbuy. So what I want to do is to call the transactiontab.cs or bring to front in the main menu when the button btnbuy in the maptab.cs is clicked.
I tried it like this in maptab.cs:
<code>    private void btnBuy_Click(object sender, EventArgs e)
    {
        Mainmenu main = new Mainmenu();
        main.transactionTab1.BringToFront();
    }
</code>
and it was not working. And also I'm gonna pass some values from maptab to transactiontab.
Comment: Am I correct in guessing that you have an existing instance of `Mainmenu` somewhere, totally unrelated to the temporary one that you're calling `BringToFront()` on and discarding? If that's the case, you need to call `BringToFront()` on the real one, instead of messing with a temp that nobody can see anyway.
Answer: After creating an instance of form, just use Show() or ShowDialog() to display your desired form.
For example,
<code>private void button1_Click(object sender, EventArgs e)
{
    Form2 secondform = new Form2();
    secondform.value = 33; //"value" variable must be declared as public in Form2
    secondform.Show(); //Use secondform.ShowDialog(); to prevent user from entering main form without closing Form2.
}
</code>


Sequence defined recursively: $\sum_{k=1}^n x_k = \frac{1}{\sqrt{x_{n+1}}}$

Question: Let $(x_n)_{n \ge 1}$ defined as follows:
$$x_1 \gt 0, x_1+x_2+\dots+x_n=\frac {1}{\sqrt {x_{n+1}}}.$$ Compute the limit $\lim _ {n \to \infty} n^2x_n^3.$
MY TRY: I thought about using Stolz-Cesaro lemma, but I couldn't get to an appropriate form that leads to an easier limit.
Comment: Please use more descriptive titles. Otherwise many of your questions will just be titled "Sequence defined recursively".
Answer: Let $y_n=x_1+\ldots+x_n$ for $n\ge1$. Then, the recursion reads $y^2_n\,(y_{n+1}-y_n)=1.$ We see that $y_{n+1}-y_n>0$ for $n\ge1.$ Since $y^2$ is monotone, it follows that
$$n=\sum^n_{k=1}y^2_k\,(y_{k+1}-y_k)\le\int^{y_{n+1}}_{y_1}y^2\,dy=\frac13(y^3_{n+1}-y^3_1),$$
i.e. $$y_{n+1}\ge3^{1/3}n^{1/3}.\tag1$$ Consequently $$\frac1{y^2_n}\le3^{-2/3}\frac1{(n-1)^{2/3}},$$ and $$y_{n+1}=y_2+\sum^n_{k=2}\frac1{y^2_k}\le y_2+3^{-2/3}\sum^n_{k=2}\frac1{(k-1)^{2/3}}=y_2+3^{-2/3}\sum^{n-1}_{k=1}\frac1{k^{2/3}}.$$ Now we can estimate the RHS with a telescope: $$k^{1/3}-(k-1)^{1/3}=\frac1{k^{2/3}+k^{1/3}(k-1)^{1/3}+(k-1)^{2/3}}\ge\frac1{3k^{2/3}},$$ that means $$y_{n+1}\le y_2+3^{1/3}(n-1)^{1/3}.\tag2$$
(1) and (2) together give $$\lim_{n\rightarrow\infty}y_n\,n^{-1/3}=3^{1/3}.$$
Since $x_{n+1}=y_{n+1}-y_n=1/y^2_n,$ we have $$\lim_{n\rightarrow\infty}x_n\,n^{2/3}=3^{-2/3},$$ and thus $$\lim_{n\rightarrow\infty}x^3_n\,n^2=3^{-2}=\frac19.$$
Comment: @Giuseppe Negro That's clear from $$k^{1/3}-(k-1)^{1/3}=\frac{k-(k-1)}{k^{2/3}+k^{1/3}(k-1)^{1/3}+(k-1)^{2/3}}\ge\frac1{3k^{2/3}},$$ since $k-1<k$. Of course, an integral does the job, too.
Comment: I appreciate this answer a lot. How did you obtain the estimation $\frac1{3 k^\frac23} \le k^\frac13-(k-1)^\frac13$, if I might ask? (To estimate $\sum_{k=1}^{n-1} k^{-\frac23}$ I would have used an integral: $$1 + \sum_{k=2}^{n-1} k^{-\frac23} \le 1 + \int_2^n (x-1)^{-\frac23}\, dx=3(n-1)^\frac13-2.)$$
Comment: That's a clever trick. Thank you.
Answer: This answer will use the Stolz-Cesaro lemma.
$$L=\lim_{n \to \infty} n^2x_n^3$$
$$S_n=\sum_{k=1}^n{x_k} \quad\quad x_{n+1}=S_n^{-2}$$
We will try to find a recurrence relation that is easier to manipulate:
$$\frac{x_{n+1}}{x_n}=\frac{S_n^{-2}}{S_{n-1}^{-2}}=\frac{S_{n-1}^{2}}{S_n^{2}}=\left (\frac{S_{n-1}}{S_n}\right)^2$$
$$S_{n-1}=S_n-x_n$$
$$\frac{x_{n+1}}{x_n}=\left(\frac{S_n-x_n}{S_n}\right)^2$$
$$\frac{x_{n+1}}{x_n}=\frac{1}{x_nS_n^2}=\left(\frac{1}{\sqrt{x_n}S_n}\right)^2$$
$$\left(\frac{S_n-x_n}{S_n}\right)^2=\left(\frac{1}{\sqrt{x_n}S_n}\right)^2$$
$$\frac{S_n-x_n}{S_n}=\frac{1}{\sqrt{x_n}S_n}$$
$$S_n-x_n=\frac{1}{\sqrt{x_n}}$$
$$S_n=x_n+\frac{1}{\sqrt{x_n}}=x_n+x_n^{-\frac{1}{2}}$$
$$x_{n+1}=\frac{1}{\left(x_n+x_n^{-\frac{1}{2}}\right)^2}$$
$$x_{n+1}=\frac{x_n}{\left(x_n^{\frac{3}{2}}+1\right)^2} \quad n>1$$
Because of the limit we want to evaluate, we make the substitution: $a_n=n^2x_n^3 \quad x_n=a_n^{\frac{1}{3}}n^{-\frac{2}{3}} \quad L=a_{\infty}$
$$a_{n+1}^{\frac{1}{3}}(n+1)^{-\frac{2}{3}}=\frac{a_n^{\frac{1}{3}}n^{-\frac{2}{3}}}{\left(\frac {\sqrt{a_n}}{n}+1\right)^2}$$
$$a_{n+1}(n+1)^{-2}=\frac{a_nn^{-2}}{\left(\frac {\sqrt{a_n}}{n}+1\right)^6}$$
$$a_{n+1}=\frac{a_n(n+1)^{2}}{n^2\left(\frac {\sqrt{a_n}}{n}+1\right)^6}$$
To get rid of the square root we make the substitution: $a_n=b_n^2 \quad b_n=\sqrt{a_n} \quad L=b_{\infty}^2$
$$b_{n+1}^2=\frac{b_n^2(n+1)^{2}}{n^2\left(\frac {b_n}{n}+1\right)^6}$$
$$b_{n+1}=\frac{b_n(n+1)}{n\left(\frac {b_n}{n}+1\right)^3}$$
$$\frac{b_{n+1}}{n+1}=\frac{b_n}{n\left(\frac {b_n}{n}+1\right)^3}$$
This next substitution is somewhat obvious: $c_n=\frac{b_n}{n} \quad b_n= nc_n \quad L=\lim_{n \to \infty} (nc_n)^2$
$$c_{n+1}=\frac{c_n}{\left(c_n+1\right)^3}$$
Because we want the limit in a usable form for the Stolz-Cesaro lemma, we make the substitution: $c_n=\frac{1}{d_n} \quad d_n=\frac{1}{c_n}$
$$L=\lim_{n \to \infty} \left(\frac{n}{d_n}\right)^2=\left( \lim_{n \to \infty} \frac{n}{d_n}\right)^2$$
$$L=\left( \lim_{n \to \infty} \frac{n+1-n}{d_{n+1}-d_n}\right)^2$$
$$L=\lim_{n \to \infty} \frac{1}{(d_{n+1}-d_n)^2}$$
$$\frac{1}{d_{n+1}}=\frac{1}{d_n\left(\frac{1}{d_n}+1\right)^3}$$
$$d_{n+1}=d_n\left(\frac{1}{d_n}+1\right)^3=\frac{(d_n+1)^3}{d_n^2}$$
$$d_{n+1}=\frac{d_n^3+3d_n^2+3d_n+1}{d_n^2}$$
$$d_{n+1}=d_n+3+\frac{3}{d_n}+\frac{1}{d_n^2}$$
$$\lim_{n \to \infty} \left(d_{n+1}=d_n+3+\frac{3}{d_n}+\frac{1}{d_n^2}\right)$$
$$\lim_{n \to \infty} \left(d_{n+1}=d_n+3\right)$$
$$\lim_{n \to \infty} d_{n+1}-d_n=3$$
$$L=\frac{1}{3^2}=\frac{1}{9}$$
All of this is assuming that $d_n$ diverges to $+\infty$. Since $x_1>0$, $d_1>0$ (substitutions considered) is the only case that needs to be analyzed. We will prove that $d_{n+1}>d_n$ for $d_n>0$.
$$\frac{d_n^3+3d_n^2+3d_n+1}{d_n^2}>d_n$$
$$d_n^3+3d_n^2+3d_n+1>d_n^3$$
$$3d_n^2+3d_n+1>0$$
This is clearly true for $d_n>0$. Note that this also shows there are no solutions to $d_{n+1}=d_n$ for $d_n>0$. Therefore, we can conclude $L=\frac{1}{9}$


Get the number of empty skipped rows in pandas when parsing

Question: I noticed pandas is smart when using read_excel / read_csv, it skips the empty rows so if my input has a blank row like

Col1, Col2
Value1, Value2

It just works, but is there a way to get the actual # of skipped rows? (In this case 1)
I want to tie the dataframe row numbers back to the raw input file's row numbers.
Comment: count the number of lines in the file and compare with the rows in your dataframe
Comment: In the documentation it looks like there is an argument called `skip_blank_lines: If True, skip over blank lines rather than interpreting as NaN values`. So if it's not a large file you could read it again and compare what you have?
Answer: You could use the skip_blank_lines=False and import the entire file including the empty lines. Then you can detect them, count them and filter them out:
def custom_read(f_name, **kwargs):
    df = pd.read_csv(f_name, skip_blank_lines=False, **kwargs)

    non_empty = df.notnull().all(axis=1)
    print('Skipped {} blank lines'.format(sum(~non_empty)))

    return df.loc[non_empty, :]

You can also use csv.reader to import your file row-by-row and only allow non-empty rows:
import csv

def custom_read2(f_name):
    with open(f_name) as f:
        cont = []
        empty_counts = 0

        reader = csv.reader(f, delimiter=',')
        for row in reader:
            if len(row) > 0:
                cont.append(row)
            else:
                empty_counts += 1
        print('Skipped {} blank lines'.format(empty_counts))
        return pd.DataFrame(cont)

As far as I can tell, at most one blank line at a time will occupy your memory. This may be useful if you happened to have large files with many blank lines, but I am pretty sure option 1 will always be the better option in practice


matrix representation of relations over $A=\{1,2,3, \ldots, 1000\}$

Question: I have an exercise in discrete math about matrix representation of relations that I want to be sure I have solved properly:
How many non-zero entries does the matrix representing the following relations on $A=\{1,2,3,\ldots,1000\}$ consisting of the first $1000$ positive integers have if $R$ is:
a) $R=\{(a,b)\mid a+b=1000\}$
b) $R=\{(a,b)\mid a+b\leq1001\}$
c) $R=\{(a,b)\mid a\neq0\}$
In the c case, one million since every entry will be 1.
In the a case, every entry, from the first one to the 999-th one, excluding the 1000th row, will have one non-zero entry, so 999
In the b case the whole first row satisfies the condition, the whole second row satisfies the condition and in the third row everything but the entry (3,999) satisfies the condition. In the fourth, everything but (4,999) and (4,998) satisfies the condition.
So we will have $1000 + 1000 + 999+998+997...+1$ non-zero entries in the matrix representing the relation. $999+998+997...+1 = 99(100) / 2 $
So we have $499500 + 2000 = 501500$ non zero-entries.
Is this the right way to solve the exercise?
Thanks a lot
Answer: Your answers to parts (a) and (c) are correct.

How many non-zero entries does the matrix representing the following relations on $A=\{1,2,3,\ldots,1001\}$ consisting of the first $1000$ positive integers have if $R$ is $R=\{(a,b)\mid a+b \leq 1001\}$?

In row $k$, there are $1001 - k$ entries which satisfy the condition since we require that $k + b \leq 1001 \implies b \leq 1001 - k$.  Hence, the number of admissible ordered pairs is
$$\sum_{k = 1}^{1000} (1001 - k) = \sum_{n = 1}^{1000} n = \frac{1000 \cdot 1001}{2} = 500,500$$
where $n = 1000 - k$.
Comment: I have edited my answer accordingly.  You should have $1001 - k$ entries in the $k$th row, so your sum should be $1000 + 999 + 998 + \cdots + 3 + 2 + 1$.  Your answer is off by $1000$ since you have an extra term of $1000$ in your sum.
Comment: Thanks a lot for the answer. I have mistyped the condition for b, which actually should be a+b≤1001. But thanks for having show me that the resolution process is the correct one
Comment: Thanks, I was not  considering entry (2,1000) in the second row


Although not exceed index, I get error by the index

Question: My question is
( - Write the following method that merges two sorted lists
into a new sorted list. Write a test program that prompts the user to enter two sorted lists and displays the merged list. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list. - )
When I run this code, Eclipse give error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at single_dimension_all_arrays.Merge_two_sorted_lists.getNumber(Merge_two_sorted_lists.java:60)
at single_dimension_all_arrays.Merge_two_sorted_lists.main(Merge_two_sorted_lists.java:77)

I can't understand why give the error. I can't exceed index.

    private static void sort(int [] list3)
        {
            int temp=0;
            for (int i = 0; i < list3.length; i++)
            {
                for (int j = 0; j < list3.length; j++)
                {
                    if(list3[i]<list3[j])
                    {
                        temp=list3[i];
                        list3[i]=list3[j];
                        list3[j]=temp;
                    }
                }
            }
            for (int i = 0; i < list3.length; i++)
            {
                System.out.println(list3[i]);
            }
        }

    private static void getNumber(int [] list1,int [] list2)
    {
        Scanner scan = new Scanner(System.in);
        int [] list3 = new int[list1.length+list2.length];
        for (int i = 1; i < list1.length; i++)
        {
            System.out.println("Please, enter the number");
            list1[i] = scan.nextInt();
        }
        for (int i = 1; i < list2.length; i++)
        {
            System.out.println("Please,enter the number");
            list2[i]= scan.nextInt();
        }
        for (int i = 0; i <= list3.length; i++)
        {
            if(i<list1.length)
            {
                list3[i]=list1[i];
            }
            else if(i>list1.length)
            {
                list3[i] = list2[i];
            }
        }
        sort(list3);
    }
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please,enter the length of list1");
        int l1 = scan.nextInt();
        System.out.println("Please, enter the length of list2");
        int l2 = scan.nextInt();
        int [] list1 = new int[l1];
        int [] list2 = new int[l2];
        list1[0]=l1;
        list2[0]=l2;

        getNumber(list1,list2);
    }
}

Thanks..:)
Comment: Have you tried to debug your code? Arrays in Java are Zero based
Comment: Use a debugger to single-step through the code so you can understand it better. There are several fundamental logic errors above. For instance, in `getNumber`, you have `if (ilist1.length) { ... }` what if `i == list1.length`?
Comment: Of course. I enter the number for list3 while Program gets error.
Answer:
Although not exceed index...

Yes you do:
for (int i = 0; i <= list3.length; i++)
// ----------------^

The valid range of indexes is 0 to length - 1, so that should be < as it is in several other parts of your code.

Side note: You're also skipping the first element in arrays in a few places:
for (int i = 1; i < list1.length; i++)
// ----------^

Comment: @ArdaZaman: There may be something **else** wrong with your code, but this answers the question that was asked.
Comment: No. I find the solution. Solution is here.

else if(i>=list1.length)
   {
    list3[i] = list2[i-list1.length];
   }
. I can fixed it and the program give true reply :).
Thanks everything.


Redirect web pages from HTTP to HTTPS

Question: I need to re-direct 3 pages in a website from http to https. I need all other pages to remain http.
I've been scouring this site and the web for two days looking for a solution that works. Nothing has provided a complete solution.
Two pages that need https are in the root directory and one is in a subfolder. I've been fiddling with both .htaccess files, but I'm hoping everything can be done in the root file.
I'm new to regular expressions and .htaccess directives, so I apologize if the solution is obvious to some of you.
Here's the root .htaccess file I've put together so far. I'm open to your feedback on any part of the code. Thanks for your help!
RewriteEngine On

# redirects non-www page requests to www version
RewriteCond %{HTTP_HOST} ^mywebsite.com
RewriteRule (.*) http://www.mywebsite.com/$1 [R=301,L]

# PERTINENT CODE BLOCK BELOW

# page (order-form) has to be on https **[SEEMS TO WORK]**
RewriteCond %{HTTPS} !on
RewriteCond %{REQUEST_URI} ^/order-form/$ [NC]
RewriteRule ^(.*)$ https://www.mywebsite.com/$1 [L,R=301]

# page (employment-application) has to be on https  **[SEEMS TO WORK]**
RewriteCond %{HTTPS} !on
RewriteCond %{REQUEST_URI} ^/employment-application/$ [NC]
RewriteRule ^(.*)$ https://www.mywebsite.com/$1 [L,R=301]

# page (about/contact-us) has to be on https **[NOT WORKING]**
RewriteCond %{HTTPS} !on
RewriteCond %{REQUEST_URI} ^/about/contact-us/$ [NC]
RewriteRule ^(.*)$ https://www.mywebsite.com/$1 [L,R=301]

# All other pages have to be on http **[NOT WORKING]**
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !^/order-form/$ [NC]
RewriteCond %{REQUEST_URI} !^/employment-application/$ [NC]
RewriteCond %{REQUEST_URI} !^/about/contact-us/$ [NC]
RewriteRule ^(.*)$ http://www.mywebsite.com/$1 [L,R=301]

# END - PERTINENT CODE BLOCK

# remove .php file extensions
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/]+)/$ $1.php

# adds a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

# disables directory view on web pages
Options -Indexes

# cached pages will expire in 5 days
ExpiresActive On
ExpiresDefault "access plus 5 days"

# send 404 errors to home page
# info at http://httpd.apache.org/docs/current/mod/core.html#errordocument
ErrorDocument 404 /

Answer: Keep this .htaccess in DocumentRoot:
# cached pages will expire in 5 days
ExpiresActive On
ExpiresDefault "access plus 5 days"

# send 404 errors to home page
# info at http://httpd.apache.org/docs/current/mod/core.html#errordocument
ErrorDocument 404 /

Options -Indexes
RewriteEngine On

# redirects non-www page requests to www version
RewriteCond %{HTTP_HOST} ^mywebsite\.com$ [NC]
RewriteRule (.*) http://www.mywebsite.com/$1 [R=301,L,NE]

# adds a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

# 3 pages to be on https
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/(order-form|employment-application|about/contact-us)/ [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301,NE]

# All other pages have to be on http
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !^/(order-form|employment-application|about/contact-us)/ [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301,NE]

# remove .php file extensions
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/]+)/$ $1.php [L]

Comment: Anubhava - Thanks for taking the time. I copied your code, only changing "my website" with the actual domain. Now I'm getting a 500 Internal Server Error. Any ideas?

I noticed you escaped the website extensions in RewriteCond line, but not RewriteRule line. Should they be escaped in all instances?
Comment: Ah there was a typo. Fixed it now. Try again copy/paste
Comment: The server error is gone. The two root directory files are resolving nicely to https. However, still two problems: (1) The subfolder file doesn't resolve to https. It just stays on http. And (2), I had to remove the block of code instructing "# All other pages to be on http", because it appends .php to all files and generally messes up the whole site. If you have any more ideas please let me know. I'm very grateful for your assistance.
Comment: Do you have .htaccess in `/about/` folder or is there `/about.php` file?
Comment: Good point. There is an .htaccess file in the about folder. I have .htaccess files in all sub directories.
Comment: Not in comments, edit your question and place it there.
Comment: The .htaccess file in all subfolders is essentially the same one I had in the root folder. They are meant to remove the .php extension, add a trailing slash, re-direct 404 pages to home, add the www, etc. Let me ask you please, do you think I can remove all those? Will the file we put in the root folder apply to all subfolders in the site?
Comment: I was offline today. Yes remove all the .htaccess except the one in DocumentRoot and then retest in a new browser.

Redirect web pages from HTTP to HTTPS


Compute expectation of a random variable given the density function

Question: The probability density function is given by:
$f(t)= (8-t)^2 /9$ for $5 \le t \le 8$
Compute the mean daily CPU time. Hence state the mean of a new variable $W=T+12$ hours.
For this question, based on the information given, I would think it to be a continuous uniform distribution. I know that the mean is $b+a$.
Also, for the other part, I'm wondering how to make $T$ the subject of the formula so that $T=W-12$ hours and then put that in wherever $T$ is?
Side note, can anyone tell me how to insert actual symbols into the posts (eg. the actual 'beta' symbol and not 'b')?
Comment: You can look at the help for guidance e.g. http://stats.stackexchange.com/help/formatting I've added the tag self-study as this appears to be a homework problem or something similar. Hint on the problem: draw the curve for your density function. Is it flat?
Comment: The mean of a continuous uniform distribution $U(a, b)$ is not $a + b$. See http://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29
Answer: If I understood your question correctly, you want to compute ${\rm E}(W)$.
Here are two hints:

Use the property of lineary of the expectation to write ${\rm E}(W)$ as a function of $T$ and 12.
Compute ${\rm E}(T)$ from the definition of the expectation of a continuous random variable using the density $f(t)$.


How to use media query to change cell padding at specific resolution?

Question: When viewed in desktop view (> 480px) I need a particular  to have a left-padding of 9px but, when the resolution drops below 480px, I need this left-padding to increase to 18px.
Currently, my padding definition is inline:

@media only screen and (max-width: 480px){
  td[class=paddingControl]{
   padding-left:18px !important;
  }

    Data Here

Unfortunately, it doesn't seem to be working.
Any ideas?
Many Thanks!
Comment: yeah there are so many differences between email client preprocessors and different browser processors that it is impossible to judge if it works on a single preview or test.
Comment: what email client is it not working in? have you run it through Litmus or Email on Acid?
Comment: Hi @Gortonington; I just ran this in Litmus and it works perfectly. I think the lesson for me is: the browser lies when it comes to responsive email design! (I was testing in Chrome only), not as an actual email! My apologies.
Comment: Thanks for your help.
Answer: After having run this code in an email testing application; I realized it worked perfectly. Lesson learnt: test in email format; not just within the browser.
As was mentioned by Gortonington, "there are so many differences between email client preprocessors and different browser processors that it is impossible to judge if it works on a single preview or test".


Drupal 6 + Twitter Bootstrap 3 theme

Question: I need help in setting up bootstrap 3 theme with Drupal 6.
With a lot of research I found that we have BootStrap module that supports D7 . Can anyone tell me how I can use Bootstrap in Drupal 6?
Comment: Given that Bootstrap requires at a minimum jQuery 1.7, I think you are going to have quite an uphill battle with using it with D6
Comment: http://www.eliotdill.com/2012/06/twitter-bootstrap-theme-for-drupal-6/
see this link its may be helpful.
Comment: @MahipalPurohit it's for bootstrap v2.3 . I am looking for including bootstrap v3
Answer: Prerit,
I think there is indeed one custom port to BS3 and that can be used in Drupal 6. Follow post #3 to get the idea. However, this is a custom theme made by an Drupal developer and its not in the drupal's project yet.
FYI, it does support jQuery version 1.7.2 by un-setting the default jquery 1.2.6 version which intern may break some functionality in your site.
The link to the Github Repo.
Personally I would suggest to use Zen or Omega for a Drupal 6.x site.

Drupal 6 + Twitter Bootstrap 3 theme


How to override form error message

Question: Let's say I have a simple form with some id like myform. This form has field called Mobile number with id mobile_number.If a user enter mobile number less than 10, it will prompt error like It must be 10 digits.
Form validation snippet:
public function validateForm(array &$form, FormStateInterface $form_state) {

  if (strlen($form_state->getValue('mobile_number')) < 10) {
    $form_state->setErrorByName('mobile_number', $this->t('It must be 10 digits.'));
  }

}

On inspect I found something like below markups

Error message

                It must be 10 digits.

I want to manipulate markups in either of two scenarios:
1) For whole website
2) Only for form with id myform.
How can I achieve that?
I am using 8.1.3
Answer: You can use this twig to theme the status message:
status-messages.html.twig
{#
/**
 * @file
 * Default theme implementation for status messages.
 *
 * Displays status, error, and warning messages, grouped by type.
 *
 * An invisible heading identifies the messages for assistive technology.
 * Sighted users see a colored box. See http://www.w3.org/TR/WCAG-TECHS/H69.html
 * for info.
 *
 * Add an ARIA label to the contentinfo area so that assistive technology
 * user agents will better describe this landmark.
 *
 * Available variables:
 * - message_list: List of messages to be displayed, grouped by type.
 * - status_headings: List of all status types.
 * - display: (optional) May have a value of 'status' or 'error' when only
 *   displaying messages of that specific type.
 * - attributes: HTML attributes for the element, including:
 *   - class: HTML classes.
 *
 * @ingroup themeable
 */
#}
{% for type, messages in message_list %}

    {% if type == 'error' %}

    {% endif %}
      {% if status_headings[type] %}

{{ status_headings[type] }}

      {% endif %}
      {% if messages|length > 1 %}

          {% for message in messages %}

{{ message }}

          {% endfor %}

      {% else %}
        {{ messages|first }}
      {% endif %}
    {% if type == 'error' %}

    {% endif %}

{% endfor %}

I'm not sure, if you can get the form id in this template. But you can try to narrow down the kind of error message and make the modifications to this twig conditional.

How to override form error message


DNS nslookup query not returning all the Name Servers

Question: I have 4 DNS servers which are across two datacenters. They are also the domain servers.
When I query nslookup test.com.au, it's only returning one of the DNS servers, the other 3 servers are not listed. Any idea why?
I don't think its normal behavior as the nslookup suppose to return all the name servers.
Below is the result which returns only one DNS server 10.208.240.20
Server:  localhost
Address:  127.0.0.1

Name:    test.com.au
Address:  10.208.240.20

Below is the result of NS server query.
test.com.au nameserver = dc10.test.com.au

test.com.au nameserver = dc11.test.com.au

test.com.au nameserver = dc09.test.com.au

test.com.au nameserver = dc12.test.com.au

dc10.test.com.au    internet address = 10.208.244.10

dc11.test.com.au    internet address = 10.208.240.20

dc09.test.com.au    internet address = 10.208.240.10

dc12.test.com.au    internet address = 10.208.244.20

Answer: There is no problem here. The first two lines of nslookup are the forward and reverse records of the nameserver that nslookup is connected to. The remaining lines are the answer to the question you asked.
NSLOOKUP from a domain with 2 DC's:
C:\>nslookup -type=NS acme.com
Server:  dc11.acme.com
Address:  10.11.12.13

acme.com   nameserver = dc11.acme.com
acme.com   nameserver = dc12.acme.com
dc11.acme.com internet address = 10.11.12.13
dc12.acme.com internet address = 10.12.13.14

Comment: Hi Thanks for the reply. I expect the command "nslookup test.com.au" to return all four NS addresses, instead of one. I build 3 other identical domain/DNS environments. Only this test.com.au DNS environment is returning single NS record.
Comment: What was your exact CLI invocation and the output? You can edit the original post. What you posted so far appears to have been edited.


Logic Pro X Score creates triplets instead of a measure packed with 16th notes

Question: I have some midi in 3/4 time, and I'm trying to encode 12 16th notes in a row. It looks right in the piano roll, and sounds right on playback:

But then I look at the guitar tab score, and it turns it into three triplets with overlapping notes. Which is not at all correct. I haven't selected the triplet annotation from the parts box or anything.

Also in Piano staff:

Any idea what's going on with the display here, and how do I get the score to display as 12 individual notes with the correct timing?
Answer: Try opening your score editor then on the left hand side make sure the "region" box is opened. The second item down in the region box is "quantize". This is the quantizing of the visual written notes, not the actual recorded rhythms.
"Quantize" is a flip menu. Yours might be set to 4,12 or 8,12. Change it to 16,12 or 16 and that should do the trick.
Below are 2 examples from my program of the score and piano roll with quantize set to different values circled:


File Pointer from CreateFileAsync in Windows 8 Javascript is undefined

Question: Writing a Windows 8 app in Javascript using Visual Studio Express. I'm not sure if I am missing a chaining dependency or something else, but I am giving my game users the ability to save their progress into a file (at least that's the idea). However when I run the following code it appears that even though I can see the file out there, the file pointer is turning out to be undefined. See anything I'm missing?
var myStats = new Array();
myStats[0] = myTitle;
myStats[1] = currPage;
myStats[2] = currStep;
myStats[3] = currTune;
myStats[4] = musicon;
myStats[5] = gameComplete;

var save01File = null;

            Windows.Storage.KnownFolders.documentsLibrary.createFileAsync("Asave01.dat", Windows.Storage.CreationCollisionOption.replaceExisting).done(

                function (file) {
                    save01File = file;
                },
                function (error) {
                    WinJS.log && WinJS.log(error, "sample", "error");
                });
            Windows.Storage.FileIO.writeLinesAsync(save01File, myStats).done(
                function () {
                },
            function (error) {
                WinJS.log && WinJS.log(error, "sample", "error");
                errCount++;
            });
            if (errCount == 0) {
                fileMenuTitle.text = "File Saved - Click Cancel";
                fileMenuTitle.text = fileMenuTitle.text + "\nto Return or Select Another File to Load";
                fileMenuTitle.color = "green";
            }
            else {
                fileMenuTitle.text = "There was an error saving that file.";
                fileMenuTitle.text = fileMenuTitle.text + "\nPlease Make Another Selection.";
                fileMenuTitle.color = "firebrick";
            }

Comment: `async` - that's the key here.   Do you understand what that means?  When an async operation happens, you can ONLY use the results of that operation inside the completion function.  You can't used it in the next function you call.
Comment: I thought there was a way to chain so that the following function can "wait" until the preceding function has completed? If not, then I am not clear how I would do the "write" of my array? Do the write function inside the "function (file)" of the initial create?
Comment: Yes, you do the write inside the success handler for creating the file or in a function you call from there.  That's the ONLY place you can do it.  Javascript does not have the ability to wait for anything.  This is asynchronous programming.  You do the work in the success callback.
Answer: You need to use the promise pattern here:
var myStats = new Array();
myStats[0] = myTitle;
myStats[1] = currPage;
myStats[2] = currStep;
myStats[3] = currTune;
myStats[4] = musicon;
myStats[5] = gameComplete;

var save01File = null;

Windows.Storage.KnownFolders.documentsLibrary.createFileAsync("Asave01.dat", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) {
    save01File = file;
    return Windows.Storage.FileIO.writeLinesAsync(file, myStats);
}).done(function() {
    fileMenuTitle.text = "File Saved - Click Cancel";
    fileMenuTitle.text = fileMenuTitle.text + "\nto Return or Select Another File to Load";
    fileMenuTitle.color = "green";
}, function (error) {
    WinJS.log && WinJS.log(error, "sample", "error");
    fileMenuTitle.text = "There was an error saving that file.";
    fileMenuTitle.text = fileMenuTitle.text + "\nPlease Make Another Selection.";
    fileMenuTitle.color = "firebrick";
});

Comment: Thanks so much for this. Now if I can get the read working properly - am following the same pattern as you have above now, but suspect the line I think it has and the line I'm getting are not the same. Funny how so much of game programming is often the framework rather than the game :-)


Reflection Performance - Create Delegate (Properties C#)

Question: I'm having performance problems with using reflection.
So I decided to create delegates for the properties of my objects and so far got this:
TestClass cwp = new TestClass();
var propertyInt = typeof(TestClass).GetProperties().Single(obj => obj.Name == "AnyValue");
var access = BuildGetAccessor(propertyInt.GetGetMethod());
var result = access(cwp);

static Func<object, object> BuildGetAccessor(MethodInfo method)
{
    var obj = Expression.Parameter(typeof(object), "o");

    Expression<Func<object, object>> expr =
        Expression.Lambda<Func<object, object>>(
            Expression.Convert(
                Expression.Call(
                    Expression.Convert(obj, method.DeclaringType),
                    method),
                typeof(object)),
            obj);

    return expr.Compile();
}

The results were highly satisfactory, about 30-40 times faster than using the conventional method (PropertyInfo.GetValue (obj, null);)
The problem is: How can I make a SetValue of a property, which works the same way? Unfortunately did not get a way.
I am doing so because I can not use methods with <T> because of the structure of my application.
Comment: "I am doing so because I can not use methods with "< T >" because of the structure of my application" -- Does that mean your NETFX version < 2.0? Why can't you use generics in your application?
Comment: Also, what does creating delegates for your properties have to do with reflection, and what problem are you trying to solve using reflection?
Comment: Delegates have vastly better performance and can be used dynamically. They are the preferred option when you need to use dynamic invocation.
Comment: @JoshE, clearly not < 2.0 since he is using generics and lambdas even. But I'm with you. What are you trying to *do* here ultimately?
Comment: Yes I can (.NET 4.0), but would not be good for all the logic of my application. And there would be many changes to make. Especially the communication between WebServices, there is no point in my application that applies "" methods load, save, update, insert ...
Comment: I'd suggest to use Fasterflect, a comprehensive library that makes reflection much faster and easier to use on top. See fasterflect.codeplex.com for details and usage. Built using DynamicMethod and IL generation with built-in caching.
Comment: Or similar: FastMember - again, DynamicMethod / IL, with built-in cache
Comment: Thanks for the suggestions, I was looking a little about libraries. But most require much implementation code and many changes in my application.  If I still do not get adequate performance. I will behind...
Answer: This should work for you:
static Action<object, object> BuildSetAccessor(MethodInfo method)
{
    var obj = Expression.Parameter(typeof(object), "o");
    var value = Expression.Parameter(typeof(object));

    Expression<Action<object, object>> expr =
        Expression.Lambda<Action<object, object>>(
            Expression.Call(
                Expression.Convert(obj, method.DeclaringType),
                method,
                Expression.Convert(value, method.GetParameters()[0].ParameterType)),
            obj,
            value);

    return expr.Compile();
}

Usage:
var accessor = BuildSetAccessor(typeof(TestClass).GetProperty("MyProperty").GetSetMethod());
var instance = new TestClass();
accessor(instance, "foo");
Console.WriteLine(instance.MyProperty);

With TestClass:
public class TestClass
{
    public string MyProperty { get; set; }
}

Prints out:

foo
Answer: I think you'd be better off with CreateDelegate construct if performance is the key. Since you know the signature of the method beforehand, which here is just GetGetMethod and GetSetMethod of the PropertyInfo, you can create a delegate to execute the very method with the same signature directly. Expressions would be better suited if you need to build some logic (for which you did not have a method handle) to delegates. I did some benchmarking on different routes to this problem:
Func<S, T> Getter;
Action<S, T> Setter;
PropertyInfo Property;
public void Initialize(Expression<Func<S, T>> propertySelector)
{
    var body = propertySelector.Body as MemberExpression;
    if (body == null)
        throw new MissingMemberException("something went wrong");

    Property = body.Member as PropertyInfo;

    //approaches:

    //Getter = s => (T)Property.GetValue(s, null);

    //Getter = memberSelector.Compile();

    //ParameterExpression inst = Expression.Parameter(typeof(S));
    //Getter = Expression.Lambda<Func<S, T>>(Expression.Property(inst, Property), inst).Compile();

    //var inst = Expression.Parameter(typeof(S));
    //Getter = Expression.Lambda<Func<S, T>>(Expression.Call(inst, Property.GetGetMethod()), inst).Compile();

    //Getter = (Func<S, T>)Delegate.CreateDelegate(typeof(Func<S, T>), Property.GetGetMethod());

    //Setter = (s, t) => Property.SetValue(s, t, null);

    //var val = Expression.Parameter(typeof(T));
    //var inst = Expression.Parameter(typeof(S));
    //Setter = Expression.Lambda<Action<S, T>>(Expression.Call(inst, Property.GetSetMethod(), val),
    //                                         inst, val).Compile();

    //Setter = (Action<S, T>)Delegate.CreateDelegate(typeof(Action<S, T>), Property.GetSetMethod());
}

//Actual calls (tested under loop):
public T Get(S instance)
{
    //direct invocation:
    //return (T)Property.GetValue(instance, null);

   //calling the delegate:
   //return Getter(instance);
}
public void Set(S instance, T value)
{
    //direct invocation:
    //Property.SetValue(instance, value, null);

   //calling the delegate:
   //Setter(instance, value);
}

Results for about 10000000 calls - (Get, Set):
GetValue-SetValue (direct): 3800 ms, 5500 ms
GetValue-SetValue (delegate): 3600 ms, 5300 ms
compiled expressions:
   Get: Expression.Property: 280 ms

        Expression.Call: 280 ms

        direct compile: 280 ms
   Set: 300 ms

create delegate: 130 ms, 135 ms
direct property call: 70 ms, 70 ms

I would, in your case, write:
public static Func<S, T> BuildGetAccessor<S, T>(Expression<Func<S, T>> propertySelector)
{
    return propertySelector.GetPropertyInfo().GetGetMethod().CreateDelegate<Func<S, T>>();
}

public static Action<S, T> BuildSetAccessor<S, T>(Expression<Func<S, T>> propertySelector)
{
    return propertySelector.GetPropertyInfo().GetSetMethod().CreateDelegate<Action<S, T>>();
}

// a generic extension for CreateDelegate
public static T CreateDelegate<T>(this MethodInfo method) where T : class
{
    return Delegate.CreateDelegate(typeof(T), method) as T;
}

public static PropertyInfo GetPropertyInfo<S, T>(this Expression<Func<S, T>> propertySelector)
{
    var body = propertySelector.Body as MemberExpression;
    if (body == null)
        throw new MissingMemberException("something went wrong");

    return body.Member as PropertyInfo;
}

So now you call:
TestClass cwp = new TestClass();
var access = BuildGetAccessor((TestClass t) => t.AnyValue);
var result = access(cwp);

Isn't that simpler?? Had written a generic class here to handle the exact thing.
Answer: Use dynamic types. They use reflection under the hood, but they're a lot faster.
Otherwise...
There are tons of free faster reflection libraries out there with permissive licenses. I would link you, but there are too many, and I'm not sure which would suit you. Just search codeplex etc. When you find something you like, try it out.
But yeah, maybe before that, think if reflection really is the answer. Often there are other solutions.
Edit: As Requested...
http://geekswithblogs.net/SunnyCoder/archive/2009/06/26/c-4.0-dynamics-vs.-reflection.aspx
http://theburningmonk.com/2010/09/performance-test-dynamic-method-invocation-in-csharp-4/
http://www.mssoftwareconsulting.com/msswc/blog/post/C-40-and-dynamic-performance.aspx
It's common knowledge as far as I can tell.
Comment: I understood *dynamics* to be e.g. `dynamic foo = bar;` Dynamics is a big topic - if you are referring to building `ExpressionTree` objects, then yes - that is what *dynamics* are for. :)
Comment: Dynamics should not be used for reflection, IMO, unless there is **no other way**. Can you post some data that supports *they're a lot faster*? ...and an example of using dynamics in a way the OP requests? These might be some of the reasons for the negative votes...
Comment: There is, as far as I know, only one thing in C# properly called a `dynamic type`, and that is what I meant. The DLR is *designed* for dynamic invocation of methods and properties. Apparently, something I didn't know until now, the [DLR uses expression trees](http://msdn.microsoft.com/en-us/library/bb397951.aspx) under the hood as well (besides reflection). If you check in the links above, you will see that invoking a method using a dynamic type is faster by several orders of magnitude than using MethodBase.Invoke. It's also a lot simpler and more concise than constructing an expression tree.
Comment: From the article:
_Parts of this article are based on a prerelease version of the .NET Framework 2.0. Those sections are subject to change._
That is an obsolete article from long before `dynamic` even existed. However, I'm not disputing the fact that the DLR isn't the fastest way to invoke a method. I'm saying it's much faster than reflection, and ridiculously easy to use.
Comment: He's using dynamic invocation. E.g. setting methods, properties, etc. That's **exactly** what you're supposed to do with dynamics.
Comment: http://msdn.microsoft.com/en-us/magazine/cc163759.aspx delegate call was the most recommended....
Comment: Agree with Greg ... Reflection is a big ugly hack - period. .. use only if there is no alternative .. C# 4 dynamic and InternalsVisableTo is better in most cases.


redirect from another div

Question: From my home page am showing a popupdiv.on submiting the popup form i need my home page to redirect.but my popup form is redirecting . How to make my home page redirect, after completing controller function.
Now am using $this->redirect(home/action)
Answer: You'll need to get a reference to the homepage through java script from the pop-up win:
<code>window.opener.location.href = "new page";
</code>

redirect from another div


Angular 2: Add directive to dynamically created component(s)

Question: I came across the following Plunker to dynamically add and remove components.
According to the above link and from many other SO posts, I know how to access Input and Output properties:
this.compRef.instance.someProperty = 'someValue';
this.compRef.instance.someOutput.subscribe(val => doSomething());

And I also have a directive "appFont".
import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appFont]'
})
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.font = 'Calibri';
    }
}

How do I add this "appFont" directive to the new dynamically created component?
Comment: Does this answer your question? [How to instantiate and apply directives programmatically?](https://stackoverflow.com/questions/39563547/how-to-instantiate-and-apply-directives-programmatically)
Comment: This can be helpful. [How to dynamically add a directive?](https://stackoverflow.com/questions/41298168/how-to-dynamically-add-a-directive)
Answer: A directive is first a class.
If you can manually get your hands on the stuff the constructor needs, you can simply do something like:
const highlight = new HighlightDirective(...);

❗ Note that this is not standard Angular code. It is almost always preferable to let Angular do the work for you as you might accidentally escape its pipes and go rogue. If that happens, you might run into unexpected Angular behaviors as Angular doesn't know about what you're doing...

A 3 year old question... I wonder if anyone is still trying to achieve this.


What's the effect of standby (spindown) mode on modern hard drives?

Question: I just assembled a new Linux file server with several Samsung HD103UJ 1TB hard drives and I am currently optimizing it.
The question I can't find an answer to is: is it reasonable to set a spindown timeout (with hdparm -S) for the drives? Can the spindown/spinup be harmful to the disk in the long run?
My previous file server did not have this timeout and the hard drives have been operational for 3+ years with no problems (always on) so I am not sure if I need this optimization at all.
What are your thoughts on this?
Thanks!
Answer: I'm by no means expert on disk drive physics, but I see disproportionally many hard drives fail soon after the spinup. Probably the temperature change just does not serve them well. I would say: let them spin forever.
Comment: +1 on spin forever. We once had to shut our server room down for the air conditioner to be repaired (it was scheduled maintenance). The EMC tech we contacted told us to leave the SAN running. He said we would have fewer drives fail due to heat than if we shut down and restarted once the work was completed.
Comment: I've heard horror stories about long running SANs that had several drives with "stickage", after they powered it off then on again during maintenance. They ended up using a small sledge hammer to get them working again. *shudders*
Comment: *> I've heard horror stories about long running SANs that had several drives with "stickage", after they powered it off then on again during maintenance.*   That's probably because the drive was running for so long, the heat build up made it nice and soft, so when it turned off, the now soft materials stuck together. If the drive was kept cool enough, the metals, plastics, etc. would have remained hard.     *> Spin forever*   Data centers are probably one of the worst wasters of electricity today.
Comment: "Sticktion" is a known problem from the old days - when powering down, the heads would stick to the platters, preventing it from spinning up again.  Shaking the drive can frequently provide enough force to un-stick the heads, allowing it to spin up again.  Modern drives don't suffer from this problem - if the firmware detects stuck heads, it uses its own motors (spindle and/or head positioning) to provide the extra force to get them un-stuck.
Comment: A previous company that I worked for had a slew of HP NAS boxen (which happened to be the corporate standard for storage in the branch offices) die after shutting them down for any reason.  Someone eventually established a policy of never allowing those Nas's to be shutdown... they were simply guaranteed to die if you did so.
Answer: Is there any hard data on this phenomenon?
Frankly, this issue reminds me of my grandmother flipping out about using the phone in a lightning storm.
You always hear anecdotal accounts about how you need to keep drives spinning, but I've never seen anything based on verifiable data. I've run into a few instances where drives didn't come back after being powered down, but I've also run into many instances where everything came up just peachy.
Comment: http://www.snopes.com/horrors/techno/phone.asp Poor example, my friend.
Answer: ** Attribute #4 of S.M.A.R.T. is Start/Stop Count, which seems to indicate that start/stop count DOES play a role in disk fitness and when to expect a failure.
Answer: It's going to depend on the workload. You probably only want to spin the drive down, if it's not likely to be used for quite a while...
Answer: I'm currently looking at the Power on hours, power cycles and Start/Stop counts for my HDDs.
The drive in my desktop is set to power down whenever possible (since bought 5/6 years ago) and has had a default setting of after one minute for about 2 years. In that 2 years,  start/stop counts approx 39,000 have overtaken the power on hours approx 12,000, and the the power cycles approx 11,000.
Currently I'm checking how many power cycles, start/stop counts and power on hours occur during an hour then a two hour period (in actual time). This will tell me how many times it powers on/off just browsing the net (not watching YT vids etc), and typing in MS Word etc - but as well as this, I wish to learn if a Power On hour means an hour for which power is supplied to the drive or an hour the drive is actually spinning. I will do another test with the computer in sleep/standby (but not hibernation/safesleep) in order to see if POH also increases when the computer is in sleep mode.
If you do something similar to me, you might be able to use this to decide whether to have your hdds power down. Download a SMART utility, one I really like in Windows is 'Crystal disk info' which is free, just bing it, and on Mac, SMART Utility, or SMARTReporter are the ones I have used. Crystal also allows you to get the smart status of external drives over USB (only disks not pen drives) - i found out that the old 6GB Quantum Fireball from and 1998 iMac had 8,900 hours and only a few hundred / 1000 power cycles. All my HDDS have been reported as healthy, apart from a 2007 Seagate laptop hdd i knew was dying.
I think its worthy of note that the I often hear the drive power down and up, sometimes the down is followed immediately by an up (but it always spins all the way down before spinning up).
Answer: There even is a new trend in high-end storage : MAID (Massive Array of Idle Drives). Basically it's only big RAID arrays with support for spin down to save power... So if the big guns find it good for them, it may be good enough to you :)
Comment: HP, EMC, NetApp, DataDirect Networks, Pillar, Copan ... all propose MAID solutions now.
Comment: Who are the "big guns" you're talking about? I'm sure there are plenty of others reading this who would also be interested.