Wrap mat-select options to fit to control's width

Question: I use below css to wrap mat-select options and working fine.
The same css is also applying to few auto-complete options so auto-complete not properly wrapping that means, option is hiding with other option of upside and downside.
.mat-select-panel mat-option.mat-option {
  height: unset;
}

.mat-option-text.mat-option-text {
  white-space: normal;
}

What changes are required in this code?
Comment: See this:https://stackblitz.com/edit/angular-lnr1yt
Comment: also this:https://stackblitz.com/edit/angular-oggceh
Comment: mat option's text should wrap to next line whenever text is long.
Comment: it will be shown as `your-text-is-too-long` as `your-text-is...`
Comment: Check this:https://stackblitz.com/edit/angular-material2-issue-ndtstg
Comment: Yes, it is default but I want to wrap this. The above css code works well with other mat-select options but with mat-autocomplete
Comment: Yes, your 3rd link css and my code both are same and works with mat-select but not with mat-autocomplete
Comment: yes got that....
Comment: You can also use a tooltip to show the full text?
Comment: ha but my client does not like it, he wanted text to be wrapped. Because, tooltip will show even for short text.
Comment: Okay! i am investigating will update once done
Answer: Set width for <mat-form-field></mat-form-field> wrapper tag like:
<mat-form-field class="example-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of options" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
</mat-form-field>

CSS:
.example-width {
   width: 50%; -- or the width you want for auto-complete
}

Working-Demo


Name of study design for 2 samples measured at different times

Question: I am trying to figure out the name for a design study in the following scenario. Imagine a hospital where patients with a certain condition (say bacteria infection) are treated with a certain medication (say antibiotic A). At some point in time, there was a decision to change the antibiotic used to treat the condition to another medication (Antibiotic B). A sample were drawn from time1 (with use of Antibiotic A) and another sample from time2 (after change to Antibiotic B). The samples can be considered independent and differences can be investigated using either Independent samples t-test or chi-square. I am not sure what type of study design this is:
The following are my thoughts so far:

Causal-Comparative or Ex post facto [but since I can change the treatment (antibiotic), I am not sure this is right].
Quasi-experimental - My doubt with this is that this is an observational study and the change in practice (antibiotics) was not due to experimentation but change in operation.
A combination of retrospective and prospective study as stated here, however, the page and every example of this that I saw seems to suggest that this design is used on THE SAME cohort.

I saw similar design here but there was no mention of the study design. All assistance are welcome.
Answer: I would consider this to be a natural experiment. While sometimes the separation into groups is geographic (see, e.g., https://en.wikipedia.org/wiki/Natural_experiment#History), other times the separation into groups is temporal (e.g., https://en.wikipedia.org/wiki/Natural_experiment#Smoking_ban) or otherwise. You could also see this as a quasi-experiment (or not) depending on how you define that term (compare https://en.wikipedia.org/wiki/Quasi-experiment#Ethics and https://en.wikipedia.org/wiki/Quasi-experiment#Advantages).
Comment: This is a useful framing: one advantage of "naming" study designs is to think about their common sources of bias. Here the gold standard design would be a randomised controlled trial (RCT) for the two treatments; having a before-after design that is separated on treatment opens up questions of confounding and influence from broader contextual factors (e.g. admission procedures for in-patient vs. community treatment)
Comment: @adejames2000  This paper discusses quasi-experimental designs in the evaluation of interventions for infectious disease.  https://academic.oup.com/cid/article/38/11/1586/285372
Comment: @JamesStanley That is right, naming the study design help to put a lot of things in better perspective.
Comment: @JamesStanley, I appreciate your contribution. I do agree that from a statistical point of view, there are concerns for confounding and bias, however, I am not focusing of the statistical ramifications at this moment. I am more focused on the design, which I have seen in a few study set-ups particularly healthcare but haven't been able to pinpoint its appropriate study design name.
Comment: @adejames2000 -- that's all good, I appreciate my comment didn't address your direct question (hence a comment rather than an answer). My comment point was that most of the utility in naming a study design is in what this tells us as researchers/readers about the pros/cons of that design and how to deal with them (i.e. the design name is shorthand for what to consider when drawing conclusions based on that evidence)
Comment: @DianaPetitti, that seems to explain it. Thank you.


Excel Power Query How to add new column determining most recent and 2nd most recent dates (current vs prior)

Question: I have a data set that has Report Date with some fields. I would like to add a column (ex. Status) using excel power query that determines the most recent date (ex. 3/1/2022) and assigns "Current", and the second most recent (ex. 2/1/2022) and assigns "Prior". Any help would be greatly appreciated. Thanks!

Report Date
Company
Number
Status

1/1/2022
Apple
7

1/1/2022
HP
4

2/1/2022
Apple
8
Prior

2/1/2022
HP
9
Prior

3/1/2022
Apple
10
Current

3/1/2022
HP
10
Current
Comment: you didnt specify if it needs to be done within company. @David provided an example where company matters, mine is when it doesnt matter
Comment: Did any of these answer your question?
Answer: Here you go.
let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMtQ31DcyMDJSUNJRciwoyEkFMcwVlGJ1UOU8AkCkCUTCCJsmC0w5iCZLiIQxNk2GBpiSEF1gmVgA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Report Date" = _t, Company = _t, Number = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Report Date", type date}, {"Company", type text}, {"Number", Int64.Type}}),
    #"Grouped Rows" = Table.Group(#"Changed Type", {"Company"}, {{"All", each _, type table [Report Date=nullable date, Company=nullable text, Number=nullable number]}}),
    #"Added Custom" = Table.AddColumn(#"Grouped Rows", "Custom", each
        let a = Table.Sort([All], {{"Report Date", Order.Descending}}),
        b = Table.AddIndexColumn(a, "index"),
        c = Table.AddColumn(b, "Status", each if [index] = 0 then "Current" else if [index] = 1 then "Prior" else null )
        in c
        ),
    #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Company", "All"}),
    #"Expanded Custom" = Table.ExpandTableColumn(#"Removed Columns", "Custom", {"Report Date", "Company", "Number", "index", "Status"}, {"Report Date", "Company", "Number", "index", "Status"}),
    #"Removed Columns1" = Table.RemoveColumns(#"Expanded Custom",{"index"})
in
    #"Removed Columns1"

Answer: In powerquery, try below (which ignores company)
To get all values in the Report Date column use
Table[ReportDate]
Sort it to get it in date order
List.Sort(Table[ReportDate],Order.Descending)
Since there are repeating dates, we remove duplicates
List.Distinct(List.Sort(Table[ReportDate],Order.Descending))
Then if you take the first row, that is the latest date
List.Distinct(List.Sort(Table[ReportDate],Order.Descending)){0}
and the date prior to that one is
List.Distinct(List.Sort(Table[ReportDate],Order.Descending)){1}
Then just add a custom column that compares ReportDate on each row to those
let  Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Report Date", type date}, {"Company", type text}, {"Number", Int64.Type}}),
LastDate=List.Distinct(List.Sort(#"Changed Type"[Report Date], Order.Descending)){0},
NextDate=List.Distinct(List.Sort(#"Changed Type"[Report Date], Order.Descending)){1},
#"Added Custom" = Table.AddColumn(#"Changed Type", "Status", each if [Report Date]=LastDate then "Current" else if [Report Date]=NextDate then "Prior" else null)
in  #"Added Custom"

Comment: I don't think this works on a per company basis. i.e. Try changing sample data so only Apple's latest date is 04/01/22. I'm not sure if that is what OP intended though...
Comment: Agreed. But that wasn't in the question
Comment: Fair point. OP should have been explicit.


C Programming Binary Tree Insertion Recursively (Not Binary Search Tree)

Question: This is my code here. I want to insert the items recursively into the binary tree. It's not a binary search tree (left child need not be < parent or right child need not be > parent).
It's simply a binary tree where there can be at most two children for each node. When I execute the traversal, it just prints out the starting node endlessly in an infinite loop (5-> 5-> 5->....). Please help me out.
I've searched through Stack Overflow and nothing is based on this. Most are binary search trees. I'm sorry if this is a bad question.
struct node {
    int info;
    struct node* left;
    struct node* right;
}*temp, *ptr, *prev;

struct node *root, *start=NULL;

void insert(struct node*);
void inorder(struct node*);

void insert(struct node* ptr)
{
    int ch;

    if(start==NULL)  // if start is null, new node is made as start node.
        start=ptr;
    else
    {
        temp=(struct node*)malloc(sizeof(struct node)); //new node created
        temp->left=NULL;
        temp->right=NULL;
        puts("Enter value");
        scanf("%d", &temp->info);
        ptr=temp;     //ptr is set as new node
    }

    printf("Does %d have a left node? (1/0)\n", ptr->info);
    scanf("%d", &ch);
    if(ch==1)
    {
        prev=ptr;
        if(ptr==start)
            insert(start->left); //start->left will be the new 'ptr' in the next insertion scenario
        else
            insert(ptr->left);  //same principle as above
    }

    printf("Does %d have a right node? (1/0)\n", ptr->info);
    scanf("%d", &ch);
    if(ch==1)
    {
        prev=ptr;
        if(start==ptr)
            insert(start->left);
        else
            insert(ptr->right);
    }

}

void inorder(struct node* ptr)
{
    while(ptr!=NULL)
    {
        inorder(ptr->left);
        printf("%d -> ", ptr->info);
        inorder(ptr->right);
    }
}

void main(){
    int ch;
    do{
        puts("1. Insert 2.Traverse 3.Exit");
        scanf("%d",&ch);
        switch(ch){
            case 1:
                puts("Enter root node");
                root=(struct node *)malloc(sizeof(struct node));
                root->left=NULL;
                root->right=NULL;
                scanf("%d", &root->info);
                insert(root);
                break;
            case 2:
                inorder(start);
        }
    }while(ch!=3);
}

Thanks in advance, guys.
Comment: @Eregrith The traversal function does not look ok — it loops forever if `ptr != NULL`.
Comment: Your traversal function looks ok, but your insertion code is all over the place. I would suggest two things : 1. stop with the globals. This is generally bad practice, especially when dealing with chained lists. 2. Use a function (or functions) to manipulate your tree and add/insert nodes.
Comment: If you have never used a debugger before, this looks like a great opportunity to learn.  See http://www.thegeekstuff.com/2010/03/debug-c-program-using-gdb/ if you have gdb available on  your system.
Comment: @CiaPan wow indeed sorry I think I need to sleep more >_<. Did not see the `while`
Answer: your traversal create infinite loop, you should change the while to if
void inorder(struct node* ptr)
{
    if (ptr != NULL)
    {
        inorder(ptr->left);
        printf("%d -> ", ptr->info);
        inorder(ptr->right);
    }
}

in insert(struct node* ptr) when you do ptr=temp; it's only changing ptr inside the function scope, so actually you never assign left and right nodes for the root
Comment: Thanks for pointing out the traversal function's mistake. Also about the insertion function, what you said makes sense. What would be an apt solution?
Answer: Try this way of adding nodes:
struct node *createTree()
{
    struct node *node;
    int resp;

    node=malloc(sizeof(struct node)); //new node created
    node->left=NULL;
    node->right=NULL;
    puts("Enter value");
    scanf("%d", &node->info);

    printf("Does %d have a left node? (1/0)\n", node->info);
    scanf("%d", &resp);
    if(resp==1)
        node->left = createTree();

    printf("Does %d have a right node? (1/0)\n", node->info);
    scanf("%d", &resp);
    if(resp==1)
        node->right = createTree();

    return node;
}

then in main() do:
root = createTree();

Note the resp variable is of type int if you scan it with "%d" format. For type char you should use format "%c".
Answer: I have found the solution for this. Sorry for wasting your time. The problem with my code was:
1) The while instead of if in the traversal function
2) Secondly, when I pass the argument ptr, it doesn't know where to link that ptr to. All I'd been doing was ptr=temp.  It must link to the previous node's left/right, right?
@huxley's explanation along the lines of function scope was wrong. It must point to the same object - that's why we use pointers, right? However, it rang a bell in my head. So here's the solution below:
void insert(struct node* ptr, int side)
{
    int ch;

    if(start==NULL)  // if start is null, new node is made as start node.
        start=ptr;
    else
    {
        temp=(struct node*)malloc(sizeof(struct node)); //new node created
        temp->left=NULL;
        temp->right=NULL;
        puts("Enter value");
        scanf("%d", &temp->info);
        ptr=temp;
        if(side==1)
            prev->left=ptr;
        else
            prev->right=ptr;
    }

    printf("Does %d have a left node? (1/0)\n", ptr->info);
    scanf("%d", &ch);
    if(ch==1)
    {
        prev=ptr;
        insert(ptr->left, 1);
    }

    printf("Does %d have a right node? (1/0)\n", ptr->info);
    scanf("%d", &ch);
    if(ch==1)
    {
        prev=ptr;
        insert(ptr->right, 2);
    }

}

void inorder(struct node* ptr)
{
    if(ptr!=NULL)
    {
        inorder(ptr->left);
        printf("%d -> ", ptr->info);
        inorder(ptr->right);
    }
}

I explained it detailedly because there's not a proper insertion code for binary tree using recursion. I hope everyone understands.
Thanks everyone who helped.
Cheers,
Akhil


FBSDKLoginManager fails with error code - 308

Question: We are using FBSDKLoginManager with our own UI for login to facebook. However sometimes the login fails with the error code 308.
As per docs the reason is - FBSDKLoginBadChallengeString, I have searched all over the internet to find out the reason for this but have had no luck.
Any explanation as to why this error occurs and how to resolve it?
Comment: have you looked at this? http://stackoverflow.com/questions/30643122/ios-parse-facebook-login-error-308-fbsdkloginbadchallengestring
Comment: .. and this? http://stackoverflow.com/a/31480026/383919
Answer: The reason I had this error was that my login and logout code used two different instances of the FBSDKLoginManager.
see my answer here https://stackoverflow.com/a/32659830/4068264
(I do not have the reputation for comments so apologies to the community if this response does not fall in the category of "Answer")
Answer: This is how I reproduced and solved the com.facebook.sdk.login error 308.
User A logs to Facebook, then logs into my app, finally logs out of my app using the popular:
func logOutFromFacebook(){

   if (FBSDKAccessToken.currentAccessToken() != nil){

           let loginManager = FBSDKLoginManager()
           loginManager.logOut()
    }
}

Now User B logs into Facebook, logs into my app and com.facebook.sdk.login error 308 shows up.
If I reinstall the app the new user can login without problems but certainly I don't want people reinstalling the app every time there is an account switch.
The solution that has solved this problem was to use  FBSDKAccessToken.setCurrentAccessToken(nil) as below:
func logOutFromFacebook(){

   if (FBSDKAccessToken.currentAccessToken() != nil){

     FBSDKAccessToken.setCurrentAccessToken(nil)

        By itself I had no use for it, maybe you might want to uncomment.
        //   let loginManager = FBSDKLoginManager()
        //   loginManager.logOut()

    }
}

Hope it helps someone!
Answer: How to fix issue in iOS10 for Facebook Login
Error OSStatus -10814 occures when canOpenURL: can't find any application, that can open this URL (actually, Facebook trying to find their application by calling canOpenURL: with argument "fbauth2:/"). Printing happens inside of function, so you can't do anything with that. But if you will run your application on device with installed Facebook app, you will not see this error.

Error 308 occures because of the situation, when value, stored in keychain is not equal to value, that is stored in facebook completion parameters (for more information you can check -[FBSDKLoginManager completeAuthentication:expectChallenge:]).

It happens because Apple changed the way of working with keychain in iOS 10. To fix this issue you simply should go to **Targets**->**Capabilities** and **enable keychain sharing** (it enables access to keychain for your app):

After that you can get the data for Facebook.
Hopefully, it will helps you.
Thanks Mandeep Singh
Comment: I have enabled keychain access in xcode but still getting 308 error. I have tried a lot. Please help.
Comment: @EktaPadaliya, yes mam how may I help you. Can you give me brief description about your issue
Comment: I am getting "The operation couldn't be completed. (com.facebook.sdk.login error 308.)" when try to login with facebook.
I am using SDK 4.22.1.
Comment: Can you share your project with me so that I can review it properly and will provide you update asap.
Answer: Use the following pods
  pod 'FacebookCore', '~> 0.5.0'
  pod 'FacebookLogin', '~> 0.5.0'
  pod 'FacebookShare', '~> 0.5.0'
  pod 'FBSDKCoreKit', '~> 4.37.0'
  pod 'FBSDKLoginKit', '~> 4.37.0'
  pod 'FBSDKShareKit', '~> 4.37.0'

Also call logOut() on FBSDKLoginManager before login
Answer: Use the following pods
 pod 'FacebookCore', '~> 0.5.0'
 pod 'FacebookLogin', '~> 0.5.0'
 pod 'FacebookShare', '~> 0.5.0'
 pod 'FBSDKCoreKit', '~> 4.37.0'
 pod 'FBSDKLoginKit', '~> 4.37.0'
 pod 'FBSDKShareKit', '~> 4.37.0'

Also call logOut() on FBSDKLoginManager before login


Upper bound a binomial-like summation

Question: I am attempting to prove a non-trivial upper bound on the following expression.
Let $0 < r \leq 1$, and let $p$ be a positive integer.
My summation is the following:
$$\sum_{k=0}^\left\lfloor \frac{p}{2} \right\rfloor {p \choose 2k}r^{2k} = 1 + {p \choose 2}r^2 + {p \choose 4}r^4 + \ldots$$
Note that when $r = 1$, I think that it is easy to see that this summation is $2^{p-1}$, as we are essentially counting the number of even subsets of a set of size $p$ (right?).
I'm not sure how to bound it as a function of $r$ and $p$, however.
Any help is greatly appreciated.
Comment: Why do you need an upper bound when the sum is given by $\frac{(1+r)^p + (1-r)^p}{2}$?
Comment: @user6312: No problem. Let your answer stay on so that this questions gets an answer
Comment: @user6312: No problem. It doesn't really matter as long as both our answers are the same.
Comment: Thank you for this quick reply.  If it's not too much to ask, can you tell why this is true?  (I suppose I could probably convince myself by induction?)
Comment: You don't even need induction, just the binomial formula.  $(1+r)^n=\sum \binom{n}{k}r^k$ and $(1-r)^n=\sum \binom{n}{k}(-r)^k$.  If you add them, all the terms where $k$ is even are the same in both sums, and all the terms where $k$ is odd cancel each other out.
Answer: I'll flesh out the details from the comments:
Recall from the binomial theorem that $(1+x)^n = \displaystyle \sum_{k = 0}^{n} {n \choose k}x^k$. Similarly, $(1-x)^n = \displaystyle \sum_{k = 0}^{n} {n \choose k}(-x)^k$. If we add these two together, we get:
$$\begin{align}
(1+x)^n + (1-x)^n &= [1 + x {n \choose 1}  + x^2  {n \choose 2}  + x^3  {n \choose 3}  + x^4  {n \choose 4}  + ...] + \\
&\; + \, [1 - x  {n \choose 1}  + x^2  {n \choose 2}  - x^3  { n \choose 3 }  + x^4  { n \choose 4}  + ...]
\end{align}$$
So we see that all the odd-powered terms cancel, while the even-powered terms reinforce. So the exact sum is $\dfrac{(1+x)^n + (1-x)^n}{2}$.
But there is one distinction between this solution and the problem you asked: since your question only goes up to $\lfloor \frac{p}{2} \rfloor$, if $p$ is odd then we see that the last term of the expansion is left out. But this is minor - and is easily remedied.
Comment: Thanks a lot for this explanation!  I guess it is quite simple, now that I see the answer.
Comment: @Tom: no problem! I didn't really do any of the work, it all came from the comments.

Upper bound a binomial-like summation


Is it possible to write a phase-shifted pattern that obeys the rules of classical counterpoint?

Question: Is it possible to write a phase-shifted pattern in the style of Minimalist phased looping on Gibson Echoplex Digital Pro that obeys all the classical counterpoint rules? Each note of the pattern will eventually play against every other note.
If it is possible, which diatonic scale degrees are permissible?
Comment: nb Reich uses the word "counterpoint" in a lot of his works. Maybe the point is that a broader use of the word just involves "point against point," as the shifting phases bring points into contact with other points, creating a new "counterpoint" with every shift. Meanwhile, sure, I imagine just about any challenge is *possible*. Retrograde canons, duets that can be executed by two people facing one sheet of music from either end, etc. It's kind of a "negative-proof" question; it's hard to prove an impossibility.
Answer: Yes.

One part that repeats a single pitch for the entire tune, and another part repeats a pitch a major or minor third away.

One part oscillates between the root and third of a major or minor chord, and another part oscillates between the third and fifth.

I think the "real" question is whether a musically "interesting" counterpoint can be written. And in this case, I believe the answer is no.
In this particular case, we're talking about a canon: a single pattern that plays against itself. So we need to construct a musically interesting melody that can be phase shifted against itself and remain a classically rule-adherent canon.
The melody, in this case, will be required to include seconds — a classical melody entirely of skips would not be aesthetically acceptable. Further, to avoid just oscillating between the same two pitches (which wouldn't meet the "rules"), there will have to be a passage with at least two consecutive seconds, either both ascending or both descending. Let's make them both ascending, since the descending case will lead to the same problem.
In classical counterpoint, when two voices form a second, the should either resolve to a third or a unison. However, there will be phases in which the seconds between the two voices do not resolve properly: for example when the first and second notes in one voice overlap with the second and third notes in the other voice.

There is a related topic that might be of interest: tiling rhythmic canons. These are rhythmic patterns which, when presented in canon with themselves, fill the entire metric space. For more see: What is rhythmic counterpoint? and What's "species counterpoint"? Are there any other types of counterpoint?.
Comment: Thank you for your detailed answer! I'm not sure what you mean by part here. Are you referring to two parts of the same phrase? In the phase-shifting I'm thinking about, the phrase is identical in both parts except that one part has a simple 8/8 time signature, and the other part has an 8/9 time signature with same phrase but with an extra eighth note or eighth note rest tacked on.
Comment: @empty My answer actually shifts between two separate voices and a single voice that is phase shifted with itself in the manner of Steve Reich. The 8/8 vs. 9/8 case would have similar problems, but it wasn't clear that's what your question referred to. As a side note, it's not reasonable to expect people to read the entire web page you linked to, which is why this site asks for videos, for example, to be summarized. (Also because links go dead.)
Comment: I just wanted a quick disambiguating link for answerers. Do you think I should add a full explanation of phased-shifted loops?
Comment: @empty I don't think a full explanation is necessary (for that, you can include the link), but a clearer explanation of your question would help. What you're describing in your comment sounds like polymeter rather than phase shifting, so the specific kind of phasing you'rr asking about should be clarified.
Comment: Thanks, I've changed the link to an MSE link with an appropriate example.
Comment: That makes things much more clear. However, I've going to post in chat. I have some questions about what exactly you're looking to do.


How to apply django @transaction decorator to celery task

Question: In my project I use transactions by default. I want to disable them for few celery tasks. But when I use:
https://docs.djangoproject.com/en/2.0/topics/db/transactions/#django.db.transaction.non_atomic_requests
from django.db import transaction

@transaction.non_atomic_requests
@app.task(bind=True, name='my_task')
def tasks_monitor(task):
    m = MyModel.objects.get(id=1)
    m.value = 5
    m.save()
    time.sleep(40)

My celery task is still do transactions. And looks like @transaction.non_atomic_requests and @transaction.atomic_requests not applying.
UPD: Trying to swap order, not working too.
When i disabled DATABASES['default']['ATOMIC_REQUESTS'] = False it works as expected
Comment: Try using a context manager (`with transaction.non_atomic_requests`) inside the function.
Comment: @Arti What is your evidence that your celery task is still using transactions even when you use `@transaction.non_atomic_requests`?
Comment: What if you swap the order of the decorators?
Comment: I tried, not working too @WillemVanOnsem
Comment: @stefanw AttributeError at __enter__
Comment: @Louis when I do loop: ```for x in range(0, 10): m = MyModel.objects.filter(value=4).first()
    m.value = 5 m.save()
Comment: in next iteration I get the same object
Comment: or if I do time.sleep for 2 minutes, and in this time check database, that have old value
Comment: When i disable `DATABASES['default']['ATOMIC_REQUESTS'] = True
` it works as expected
Comment: @Arti Please include in your question the code that launches your celery task and the code that uses the results of the task.
Answer: The transaction.non_atomic_requests is meant to decorate a view, it won't have any effect on a Celery task. But here is the thing: the setting ATOMIC_REQUESTS shouldn't have any effect either! The only place it is evaluated in Django is in core.handlers.base.make_view_atomic, which wraps views.
Therefore, my assumption is that you run your application with CELERY_TASK_ALWAYS_EAGER=True (CELERY_ALWAYS_EAGER in older versions of Celery). In this case, the transaction of the view is active. If you set it to False and run your tasks in a worker, each DB operation should be autocomitted.
Comment: yes, you were right, I missed `CELERY_ALWAYS_EAGER` and also yes, `transaction.non_atomic_requests` is useless


Generate pdf on the fly and email with webmatrix

Question: I have a web application which at the moment generates certificates using a template. Since I original wrote it in php, I used the str_replace built in function to replace values in my template with values from the query.
Now I have changed to asp.net web pages and my aim is to generate certificates in pdf and mail them.
I am using iTextSharp and  webmatrix.
Below is part of my code :
<code> var sql = "SELECT CustomerID, CompanyName, ContactName, Address, City, Country, Phone FROM Customers WHERE CustomerID = 'ALFKI'";
var data = db.Query(sql);

  foreach(var item in data){ var companyname = item.CompanyName;}

PdfPCell certify1 = new PdfPCell(new Phrase("companyname"));
certify1.Colspan = 2;
certify1.Border = 0;
certify1.PaddingTop = 40f;
certify1.HorizontalAlignment = 1;//0=Left, 1=Centre, 2=Right
table.AddCell(certify1);
</code>
From this code I am trying to show the data from database table. The code above is not working. I am trying to grab the query values and have then in certify1 cell.
How can I do this?
Comment: Thanks for your question! However, this is not really the kind of question that Stack Overflow is here to answer. [Read this for more information](http://stackoverflow.com/faq#dontask) Once you have a specific question about a specific problem you are having with code you are writing, feel free to return.
Comment: @Mike-Brind  I have added code and interested in showing values from query. The  query returns a single value.
Answer: Try this:
<code>var sql = "SELECT CustomerID, CompanyName, ContactName, Address, City, Country, Phone FROM Customers WHERE CustomerID = 'ALFKI'";
var data = db.Query(sql);

foreach(var item in data){
    var companyname = item.CompanyName;
    PdfPCell certify1 = new PdfPCell(new Phrase(companyname));
    certify1.Colspan = 2;
    certify1.Border = 0;
    certify1.PaddingTop = 40f;
    certify1.HorizontalAlignment = 1;//0=Left, 1=Centre, 2=Right
    table.AddCell(certify1);
}
</code>


Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times?

Question: When I write the following program and use the GNU C++ compiler, the output is 1 which I think is due to the rotation operation performed by the compiler.
#include <iostream>

int main()
{
    int a = 1;
    std::cout << (a << 32) << std::endl;

    return 0;
}

But logically, as it's said that the bits are lost if they overflow the bit width, the output should be 0. What is happening?
The code is on ideone, http://ideone.com/VPTwj.
Comment: @awoodland I too think so. According to latest draft: "The behavior is undefined if the right operand
is negative, or greater than or equal to the length in bits of the promoted left operand." (5.8) N3291
Comment: @xanatos How do you know that this is a "wrong" question?!
Comment: @Arak Before speaking, at least follow the link and watch the history. His original message was: `when i write the following program on GNU C++ compiler http://ideone.com/VPTwj it shows me an output of 1` then please follow the link and look at the upper left: `language: C++ (gcc-4.3.4)`. I think it's as much clear as it can be.
Comment: You might want to show exactly what command line (switches) you have used, what version of GCC and also on which platform.
Comment: The problem is that, as given by the OP, the question was illogical. He said "look here, it gives me 1", but the example he gave returned 0 :-)
Comment: @xanatos I see your point, but it is not enough because his code is exhibiting "Undefined Behavior", and in that case you have to check the rules of the language because the compiler is allowed to do anything!
Comment: @AraK No. If he gives us a specific implementation of the compiler (the one of IdeOne), then we can look at the rules used by GCC, and probably discover that on GCC it's defined. He gave a SPECIFIC example on a SPECIFIC compiler. It's different than asking "what shoud I have?"
Comment: I see output "0" on the linked page; am I missing something?
Comment: yup! 0 http://ideone.com/elyN0
Comment: @ all I get the output as 1 and it appears as if it is performing the rotation operation
Comment: @xanatos its a genuine doubt man I am not here for free points :) simple I have a doubt and I wanna clear it
Comment: if `int` is 32bits isn't it undefined or implementation defined?
Comment: why the close votes? a proper question
Comment: @everyone Because before someone edited the question, he posted a link on ideone? I have reedited the question. Please feel free to check the history!
Comment: @AnkitSablok Could you run it with `g++ -S` to show the output?
Comment: @xanatos He didn't provide the version nor the options used to compile the code.
Comment: @xanatos Duh! I didn't see the link, sorry.
Comment: Possible duplicate of [What does the C standard say about bitshifting more bits than the width of type?](https://stackoverflow.com/questions/11270492/what-does-the-c-standard-say-about-bitshifting-more-bits-than-the-width-of-type)
Comment: Possible duplicate of [Left shift an integer by 32 bits](https://stackoverflow.com/questions/33058340/left-shift-an-integer-by-32-bits)
Comment: Does this answer your question? [GCC left shift overflow](https://stackoverflow.com/questions/3871650/gcc-left-shift-overflow)
Answer: This is caused due to a combination of an undefined behaviour in C and the fact that code generated for IA-32 processors has a 5 bit mask applied on the shift count. This means that on IA-32 processors, the range of a shift count is 0-31 only. 1
From The C programming language 2

The result is undefined if the right operand is negative, or greater than or equal to the number of bits in the left expression's type.

From IA-32 Intel Architecture Software Developer's Manual 3

The 8086 does not mask the shift count. However, all other IA-32 processors (starting with the Intel 286 processor) do mask the shift count to 5 bits, resulting in a maximum count of 31. This masking is done in all operating modes (including the virtual-8086 mode) to reduce the maximum execution time of the instructions.

1 http://codeyarns.com/2004/12/20/c-shift-operator-mayhem/
2  A7.8 Shift Operators, Appendix A. Reference Manual, The C Programming Language
3 SAL/SAR/SHL/SHR – Shift, Chapter 4. Instruction Set Reference, IA-32 Intel Architecture Software Developer's Manual
Comment: Could you please include the essence of that blog post in your answer (cf http://meta.stackexchange.com/a/8259/244745)?
Answer: In C++, shift is only well-defined if you shift a value less steps than the size of the type. If int is 32 bits, then only 0 to, and including, 31 steps is well-defined.
So, why is this?
If you take a look at the underlying hardware that performs the shift, if it only has to look at the lower five bits of a value (in the 32 bit case), it can be implemented using less logical gates than if it has to inspect every bit of the value.
Answer to question in comment
C and C++ are designed to run as fast as possible, on any available hardware. Today, the generated code is simply a ''shift'' instruction, regardless how the underlying hardware handles values outside the specified range. If the languages would have specified how shift should behave, the generated could would have to check that the shift count is in range before performing the shift. Typically, this would yield three instructions (compare, branch, shift). (Admittedly, in this case it would not be necessary as the shift count is known.)
Comment: @Beta: "Don't pay for what you don't need" principle. **You** can do the check, if your code needs it. But if the check was automatic, you could not _not_ do it.
Comment: @Beta - it's undefined so as not to encumber implementations with the burden of emulating in software what was "the norm" in hardware at the point in time when the standard was conceived.
Comment: @Beta: interesting question ! Most of those undefined operations map directly to processor instructions. The behavior is generally *undefined* because doing otherwise would require checks prior to the operations that would not be implemented efficiently on most architectures. Typical safety/speed tradeof.
Comment: @Beta, Imagine the instruction for shift in a certain computer takes 5 bits. No matter what you do, you just can't shift a variable by 32! (Something like 01011 (shift) 010 (to register 2) 110 (from register 6) ????? (shift amount) (This is an imaginary but very possible instruction))
Comment: But... *why* is this undefined behavior? Why couldn't the low-level code perform the subtraction, determine that it need consider only the lowest *zero* bits, and return 0 without inspecting the value at all?
Comment: Nice example of specifications being "optimized" for existing CPUs, but made counter intuitive in process. Damn.
Comment: @MSalters Pascal had a nice alternative to pretty much the same problem - keep everything as defined as possible, *but* give an option to opt-out (using preprocessor directives). It's much more multi-platform friendly.
Answer: It's undefined behaviour according to the C++ standard:

The value of E1 << E2 is E1
  left-shifted E2 bit positions; vacated
  bits are zero-filled. If E1 has an
  unsigned type, the value of the result
  is E1 × 2^E2, reduced modulo one more
  than the maximum value representable
  in the result type. Otherwise, if E1
  has a signed type and non-negative
  value, and E1×2^E2 is representable in
  the result type, then that is the
  resulting value; otherwise, the
  behavior is undefined.
Comment: that's some mighty quick standard searching!
Comment: @awoodland Yes, Google is seriously impressive!
Comment: @Ankit The answer should not be 0. The answer is undefined. The answer could be anything. This is the essence of undefined behaviour.
Comment: @AnkitSablok Undefined behavior means that any behavior can happen ;) check: http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior
Comment: @AnkitSablok - it DOES justify the behaviour. The point is that when behaviour is undefined the compiler is allowed to do anything it pleases. At best guess the compiler has simply decided to do nothing (which is perfectly valid according to the standard)
Comment: That's not the best part to quote.  The preceding paragraph states "The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand" so `n << 32` is an UB regardless of the signedness of the left operand
Comment: your answer doesnt justify the query sir i am interested in knowing y arent the bits lost and the answer should be 0 as per me but it does some sort of rotation and puts the last bit in the 1st position and u can confirm this with other numbers as well
Comment: Oh I see. I'd fired up a PDF reader and got about as far as the table of contents.
Comment: @Ankit - but it does exactly answer it. That's the beauty of undefined behaviour, *anything* goes!
Answer: The answers of Lindydancer and 6502 explain why (on some machines) it happens to be a 1 that is being printed (although the behavior of the operation is undefined). I am adding the details in case they aren't obvious.
I am assuming that (like me) you are running the program on an Intel processor. GCC generates these assembly instructions for the shift operation:
movl $32, %ecx
sall %cl, %eax

On the topic of sall and other shift operations, page 624 in the Instruction Set Reference Manual says:

The 8086 does not mask the shift count. However, all other Intel Architecture processors
  (starting with the Intel 286 processor) do mask the shift count to five bits, resulting in a
  maximum count of 31. This masking is done in all operating modes (including the virtual-8086
  mode) to reduce the maximum execution time of the instructions.

Since the lower 5 bits of 32 are zero, then 1 << 32 is equivalent to 1 << 0, which is 1.
Experimenting with larger numbers, we would predict that
cout << (a << 32) << " " << (a << 33) << " " << (a << 34) << "\n";

would print 1 2 4, and indeed that is what is happening on my machine.
Answer: It doesn't work as expected because you're expecting too much.
In the case of x86 the hardware doesn't care about shift operations where the counter is bigger than the size of the register (see for example SHL instruction description on x86 reference documentation for an explanation).
The C++ standard didn't want to impose an extra cost by telling what to do in these cases because generated code would have been forced to add extra checks and logic for every parametric shift.
With this freedom implementers of compilers can generate just one assembly instruction without any test or branch.
A more "useful" and "logical" approach would have been for example to have (x << y) equivalent to (x >> -y) and also the handling of high counters with a logical and consistent behavior.
However this would have required a much slower handling for bit shifting so the choice was to do what the hardware does, leaving to the programmers the need to write their own functions for side cases.
Given that different hardware does different things in these cases what the standard says is basically "Whatever happens when you do strange things just don't blame C++, it's your fault" translated in legalese.
Comment: A bit more precisely, at least in the case of older versions of gcc, a<>33 was faster and generated equivalent code to a>>1 (due to some implementation details of the 80486 CPU).  Of course in retrospect I realize how foolish it was to do that, but I was young and inexperienced, and it DID give me a significant speed increase in an often-run inner loop.
Comment: @fluffy: It's not gcc, it's the processor. Given that the standard doesn't require any specific behavior what the guys from gcc did was just to use the assembler instruction for the shift not caring about what to do in case the counter was too big or negative. If you check the manual I pointed to you will see that indeed the x86 family uses the low 5 bits of the counter, ignoring the others... in their words "The count is masked to five bits, which limits the count range
to 0 to 31". The standard wanted to leave this exact freedom, so that shift can become just one asm instruction.
Comment: Yes, but in this case it's a matter of how the code is generated by the compiler.  It was a case of `shr eax` vs. `shr eax,1`, and the fact that gcc had a design facet in which `shr eax,33` would AND the immediate operand with 31 to ensure that it fit into the 5-bit parameter slot in the instruction.  Immediate-mode `shr` has the shift amount encoded *directly in the instruction*, at least on x86 and most other CISC architectures.  i.e. it's a matter of how the compiler is doing the masking TO SUPPORT THE CPU. It's a fine distinction but important.
Comment: @fluffy: The reason for which the standard doesn't mandate a behavior when counter is bigger than the bit size of the value is to avoid a performance penality in case of a **parametric** shift. In case of a constant shift (e.g. 33) a compiler could just simplify to a constant 0 without any performance penality. That gcc decided to keep uniform behavior to the parametric case is a reasonable choice but not the only one (I hope at least a warning was emitted tho). If you need control on the asm instruction generated just use asm... using a non-specified behavior is looking for trouble.
Comment: At the time, gcc didn't emit a warning, but this was in the gcc 2.x days. Nowadays it does emit a warning, which is why I'd even remembered I was doing this terrible thing since I was dusting off old code for nostalgia's sake. :)  And yes, I am fully aware that the behavior was unspecified and that to rely on it is a bad idea. I was just adding more to your answer about one of the particular ways it can behave that is different than the way you were stating. I should have been more precise that I was using immediate-mode >> rather than register-mode >> though.
Answer: Shifting a 32 bit variable by 32 or more bits is undefined behavior and may cause the compiler to make daemons fly out of your nose.
Seriously, most of the time the output will be 0 (if int is 32 bits or less) since you're shifting the 1 until it drops off again and nothing but 0 is left. But the compiler may optimize it to do whatever it likes.
See the excellent LLVM blog entry What Every C Programmer Should Know About Undefined Behavior, a must-read for every C developer.
Comment: IMO it's not the compiler in this case, it's the hardware that doesn't handle shifts bigger than registers. The standard simply didn't want to specify something that would require fatter and slower code for all parametric shifts on some CPUs.
Answer: Since you are bit shifting an int by 32 bits; you'll get: warning C4293: '<<' : shift count negative or too big, undefined behavior in VS. This means that you're shifting beyond the integer and the answer could be ANYTHING, because it is undefined behavior.
Comment: It doesn't mean the answer could be 0 or 1, it means that **absolutely anything** could happen
Answer: You could try the following. This actually gives the output as 0 after 32 left shifts.
#include<iostream>
#include<cstdio>

using namespace std;

int main()
{
  int a = 1;
  a <<= 31;
  cout << (a <<= 1);
  return 0;
}

Comment: This doesn't explain *why* there's a difference between a shift of 32 places, and two shifts that add up to 32 places.
Answer: I had the same problem and this worked for me:
f = ((long long)1 << (i-1));
Where i can be any integer bigger than 32 bits. The 1 has to be a 64 bit integer for the shifting to work.
Answer: Try using 1LL << 60. Here LL is for long long. You can shift now to max of 61 bits.


Can Most Beatles and Carpenters songs be played on a 61 key keyboard?

Question: I would like to know if there will be restriction in playing most of the Beatles and Carpenters songs on a 61 key keyboard due to limitation of the keys.
Comment: You can play any song in a Western key (no semitones) on any keyboard. It just takes a little arranging if you run out of octaves.  Same as a bass singer being able to sing a number written for a soprano.
Comment: @CarlWitthoft - 'Western key', 'no semitones'? What's it mean?
Comment: @Tim - he probably means microtones used in other musical
 systems outside of the european tradition: https://en.wikipedia.org/wiki/Microtonal_music : _Microtonal music or microtonality is the use in music of microtones—intervals smaller than a semitone, which are also called "microintervals". It may also be extended to include any music using intervals not found in the customary Western tuning of twelve equal intervals per octave..._
Comment: @Stinkfoot - it more than likely means almost the opposite - though when a question is asked, it's good to receive an answer. If he says 'you can play any song' that wouldn't include microtones. It *would* include diatonic notes, which comprise lots of pop type songs, although they can, and do modulate,. However, all normal keyboards are capable of coping with that, using the other five notes available. But 'Western key (no semitones)' seems to be an oxymoron.
Comment: @Tim _You can play any song in a Western key (no semitones) on any keyboard_  I think that means you can't play in an "in between" key.  For example, I believe there is an Indian or middle eastern system that divides an octave in 16 tones, instead of 12 - "microtones". You won't be able to play Paperback Writer in  that system in the key that comes after our G, "G 3/4#" for example, on our piano, which only supports 12 tones per octave, not the in between tones - "microtones" - relative to our twelve tone chromatic octave as represented on our piano. (You could conceivably play it on a violin)
Comment: @Stinkfoot - I've never noticed that Paperback Writer was anything but 'ordinary' notes. Just checked it out and it's a 3 chord trick. Probably in Mixolydian, but that still makes it playable on any keyboard.
Comment: @Tim - no argument - that's exactly what Paperback Writer is. I just took that as an example of a popular, simple Beatles song - same applies to everything, Beatles to Bach. Point is, if you wanted to change the key from G to "G + 3/4#"  (or something like that) - a note **between** G and G#  ( like when you bend on a guitar ) and play it on a piano - you couldn't, just like you can't really bend on a piano. But you could play that on certain instruments that use that 16 note scale - imagine you had a piano with 16 keys to span octave - or on a violin that allows you to play anything.
Answer: Yes, you'll be able to set a piano sound and play the printed song copies with little, if any, modification.  Or you could use more of the capabilities of a keyboard - maybe split the lower half to play a bass sound - and interpret the music more freely.
Answer: Even though Karen Carpenter (still my most favourite) had a range of over four octaves, she didn't use it all in any song! Most songs that can be sung will have a range of a twelfth or so (octave and a half), leaving plenty of notes above and below to play the accompaniment.
So, yes, it's easily possible to do. Eventually you may feel the need to octave notes in the bass and top parts, but until you actually start doing that, 61 keys will suffice. It's five octaves in total, so even given the restriction of root notes/ highest tonic notes in some keys, it's plenty to go on. And, you'll find on a lot of keyboards with 61 notes, there is an octave button to go up or down 2 or 3 octaves, and coupled with a key change button, the range is as good as an 88 noter.
Answer: I use a 61 key keyboard and am usually annoyed that it doesn't have ~5 more keys. That said, it's totally possible. You can play the song with probably even a 41 key keyboard, that doesn't mean you'll get the perfect balance of octaves, or any bass and treble mix at all. Replicating all of the songs by them perfectly on a 61 key keyboard probably can't be done unless you have really cool foot pedals, or a third hand and super high intellect.


Installing specific git releases via composer

Question: I'm trying to install a specific release version of a library (pdf.js) into my D9 site, to which I've followed this example, and I have this in my composer file
"repositories": [
    {
        "type": "package",
        "package": {
            "name": "mozilla/pdf.js",
            "version": "v2.14.305",
            "type": "drupal-library",
            "extra": {
                "installer-name": "pdf.js"
            },
            "dist": {
                "type": "zip",
                "url": "https://github.com/mozilla/pdf.js/releases/download/v2.14.305/pdfjs-2.14.305-dist.zip"
            }
        }
    }
...
...
"require": {
    "mozilla/pdf.js": "v2.14.305",
    ...

Except every time I run composer install it just gets the current master branch (eg, everything from here), how do I make it get that specific zip I've specified?
Answer: Turns out... this is fine, I'd been directly updating the composer.json file after my initial attempt to download it failed to get the correct version, and I was just being stupid by only running composer install and kept removing the folder manually each time it didn't download what I wanted.
I removed it from composer properly using composer remove "mozilla/pdf.js", and re-ran the require line again, and this time it has worked.
I'll leave it up in case anyone wants to see how to download a specific version


Executar o próximo passo sem passar por um anterior a esse

Question: Tenho o seguinte problema, se o usuário não digitar nem 'S' ou 'N' irá retorna a mensagem de erro que tratei, no entanto irá continuar o loop, mais eu queria uma forma de não pedir novamente pra digitar o número novamente e se digitar a resposta da variável 'pergunta'.
def caractere(resposta):
    # false
    if resposta == 'N':
        return 'Encerrando programa...'

    # true
    elif resposta == 'S':
        return 'Ok, vamos continuar...'

    # true
    elif resposta not in 'SN':
        return 'Caractere inválido. Digite novamente'

def main():
    while True:
        try:
            numero = float(input('Digite um número: '))
            print(f'O cubo do numero {numero} é igual {numero ** 3}')
            pergunta = str(input('Deseja continuar[sim - S/não - N]: ')).upper()[0]
            resultado = caractere(pergunta)

            if pergunta == 'S':
                print(resultado)

            elif pergunta == 'N':
                print(resultado)
                break

            elif pergunta not in 'SN':
                print(resultado)

        except:
            print('Valor inválido, tente novamente.')

if __name__ == "__main__":
    main()

Answer: def caractere(resposta):
    # false
    if resposta == 'N':
        return 'Encerrando programa...'

    # true
    elif resposta == 'S':
        return 'Ok, vamos continuar...'

    # true
    elif resposta not in 'SN':
        return 'Caractere inválido. Digite novamente'

def continuar():
    pergunta = ""
    while (pergunta == "S" or pergunta == "N") == False:
        pergunta = str(input('Deseja continuar[sim - S/não - N]: ')).upper()[0]
        print(caractere(pergunta))

    return pergunta

def main():
    while True:
        try:
            numero = float(input('Digite um número: '))
            print(f'O cubo do numero {numero} é igual {numero ** 3}')
            pergunta = continuar()

            if pergunta == "N":
                break

        except:
            print('Valor inválido, tente novamente.')

if __name__ == "__main__":
    main()


Almost surely convergence of the sequence

Question:
Let ${X_n}$ be a sequence of independent and identically distributed, square integrable random variables.
  Write $ u = E(X_n)$. Study the almost sure convergence, as $n \rightarrow \infty$, $$S_n = (X_1X_2 + X_2X_3 + ... + X_{n-1}X_{n})/n$$

Since $X_iX_{i+1}$ are not independent, it seems we cannot directly use law of large number for that, so anyone can give me some idea?
Comment: Before $u=E(X_n)$ you had a symbol that I could recognize. Is the editing I did correct? Please let me know!
Comment: @Stef yes it should be correct
Comment: Slightly related: https://math.stackexchange.com/q/430930/66096
Answer: You need to consider separately two terms:
$$S_n^1 = \frac{X_1 X_2 + X_3 X_4 + \ldots + X_{2n - 1} X_{2 n}}{n}$$ and
$$S_n^2 = \frac{X_2 X_3 + X_4 X_5 + \ldots + X_{2n} X_{2 n + 1}}{n}.$$
Then
$$S_{2 n + 1} = S_n^1 + S_n^2$$
and for $S_n^1$ and $S_n^2$ you can apply Law of large numbers. Then you can proceed sum of two random variables by definition of almost sure convergence.
Answer: Hint: define $Y_j:=X_{2j-1}X_{2j}$ and $Z_j:=X_{2j}X_{2j+1}$. Notice that the sequence $(Y_j)_{j\geqslant 1}$ is independent, as well as $(Z_j)_{j\geqslant 1}$. After having expressed $S_{2n}$ and $S_{2n+1}$ in terms of $Y_j$ and $Z_j$, apply the strong law of large numbers.


how to calculate VIF in logistic regression?

Question: No book told me that...
Using McFadden's Pseudo-R2 ? OR do traditional linear regression to get VIF?
Answer: The variance inflation factor is only about the independent variables. You can calculate it the same way in linear regression, logistic regression, Poisson regression etc.
Whether the same values indicate the same degree of "trouble" from colinearity is another matter. For this, I like to use the perturb package in R which looks at the practical effects of one of the main issues with colinearity: That a small change in the input data can make a large change in the parameter estimates.
Comment: "That a small change in the input data can make a large change in the parameter estimates"            Is it because of the variance is usually very large for highly correlated variable? By changing the observation matrix X a little, we artificially create  a new sample and hope the new estimation will be differ a lot from the original one?
Comment: Someone else can give the math, if you need it. Intuitively, it's because the variance doesn't know where to go.
Comment: The Wikipedia article on VIF mentions ordinary least squares and the coefficient of determination. If you were doing a logistic regression and wanted to find the VIFs of the independent values, does this mean you perform an auxiliary standard linear regression?


Closed-form solution to $y = \frac{\ln(a+x)}{\ln(b+x)}$?

Question: I'm trying to solve the following equation for $\delta$:

$$-0.01 = \frac{\ln(1+\delta)}{\ln{\delta}}$$

And I found that while Wolfram Alpha and Mathematica can give me numerical estimates ($\delta = 0.034300977...$), they cannot give me a closed form solution (even including the non-elementary functions that they'll sometimes use.)

Is there a closed-form solution to the problem above, or the more general version below?
  $$y = \frac{\ln(a+x)}{\ln(b+x)}$$

Or is this a case where there isn't a solution and moreover determining one would require a new function unrelated to those already established (such as the Lambert W function).
I have not taken Complex Analysis, or any other math higher than Differential Equations; however, depending on the complexity I may be able to follow along.

Full context and motivation:
A problem from my undergrad Nuclear Detection course: Given exponentially decaying signals of the form $f(t) = K\mathrm{e}^{-\mu t}$ that are generated periodically with period $x$.  We can find the smallest $x$ such that signal pileup is less than 1%, we can see that $1.01 = \sum_n^\infty{\mathrm{e}^{-\mu n x}}$ which yields $x = \frac{\ln{101}}{\mu}$ after some massaging.
However, I noticed that in this instance, neglecting all but the first two terms of the series (ie, 1 and $\mathrm{e}^{-\mu x}$), gave the result $x^{\prime} = \frac{\ln{100}}{\mu}$ for an error percentage between $x^{\prime}$ and $x$ of only 0.216%.  So I wanted to figure out what percentage of pileup was required before more than just these terms were required.  I selected 1% as my threshold.  So I had $$\frac{x}{x^{\prime}} = \frac{\ln(1+\delta) - \ln{\delta}}{-\ln{\delta}}$$ which gives the first formula of the question.
Comment: I think a numerical solution is as good as you can expect to do in this sort of situation.
Comment: The specific case described can, by exponentiating both sides appropriately, be brought to the form $\delta(1+\delta)^{100}=1$. So this is in fact a polynomial of high degree, and one is looking for its real roots (of which there is but one in this case). More generally, if $y$ is rational in the second equation, then the problem amounts to solving some polynomial equation. My guess is that this isn't going to have a closed-form solution in any reasonable sense.
Comment: A numerical solution certainly is useful, and it's all I really need.  I was merely curious if there was some sort of closed form solution to this more interesting than let `$OMG(x; a, b) = \frac{\ln{a+x}}{\ln{b+x}}$`.
Comment: Not really an answer, but I suspect that (depending on your choices for $a, b, x$) you'd most likely get a transcendental equation which would only be solvable numerically.
Answer: Hint:
We have $$y=\frac{\ln(a+x)}{\ln(b+x)}\implies (b+x)^y=a+x\implies x=(b+x)^y-a$$
$$\implies x=(b+(b+(b+......+(b+x)^y-a)^y.....-a)^y-a)^y-a)$$
The actual solution may come differently in different values of a ,b and y.
Now we come to the specific problem:
$$\frac{-1}{100}=\frac{\ln(1+\delta)}{\ln \delta}$$
let $f(\delta)=\ln \delta$ then $$\frac{-1}{100}f(\delta)=f(\delta+1)$$
When you would solve this recurrence you would get something like this:-
$$f(\delta)=(-1)^{(n+1)}\frac{f(\delta-n)}{100^{(n+1)}}$$
Now put the value of $f(\delta)$ and put $\lim_{{\delta-n}\to 0}$ such that $n \to 0$
Comment: I apologize, I ought to have been slightly more specific and formal with my terminology. I was seeking a closed form solution. I'm well aware of how to obtain this recurrence relation.
Comment: Try to solve the recurrence. No need to apologize
Comment: I have tried so solve the recurrence @OmnipotentEntity. Check the modified answer.
Comment: I have given the correct numerical solution in my original post, and it does not seem to match.


Retornando dados do BD com PHP e AJAX

Question: Sou iniciante com PHP e estou tendo um problema ao retornar dados do BD para apresenta-los no Front-End com AJAX e JS. Creio que não estou sabendo tratar os dados, pois até o console do navegador, os dados são retornados corretamente, mas ao tentar coloca-los no front, tenho um "undefined" como resposta. Alguém sabe me dizer onde estou errando ?
Meu código no index.php:
<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Testando API</title>

Meu código que puxa os dados:
<?php
$servidor = 'localhost';
$usuario = 'root';
$senha = '';
$dbname = 'testevip';

$connect = mysqli_connect($servidor, $usuario, $senha, $dbname);

$result = "SELECT nome from fornecedores ORDER BY nome ASC LIMIT 30";
$query = mysqli_query($connect, $result);

foreach ($query as $key => $fornecedorNome) {
    print_r(json_encode($fornecedorNome));
}
?>

Meu código no JS / AJAX:
function loadDados() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
            if (xmlhttp.status == 200) {
                var data = xmlhttp.responseText;
                console.log(data);

                var html = "";
                for (var i = 0; i < data.length; i++){
                    var fornecedorNome = data[i].nome;
                    html += "
" + fornecedorNome + "
";
                }
                document.getElementById("fornecedorNome").innerHTML = html;
            }
            else if (xmlhttp.status == 400) {
                alert('There was an error 400');
            }
            else {
                alert('something else other than 200 was returned');
            }
        }
    };

    xmlhttp.open("GET", "API.php", true);
    xmlhttp.send();
}
loadDados();

E por fim a resposta que tenho no meu navegador:
http://prntscr.com/nqxvyf
Agradeço desde já a qualquer ajuda fornecida, muito obrigado !
Comment: Você consegue dar um print no retorno do console? As vezes a resposta esta vindo aninhada de forma que seu for não esteja percorrendo os índices de forma correta. Aparentemente você tem um array de arrays contendo os nomes que você precisa, no seu código PHP tenta utilizar json_encode somente após interar toda sua massa de dados.
Comment: Acredito que o erro é devido ao loop de print_r que você está fazendo. Tenta assim troca o foreach ($query as $key => $fornecedorNome) {print_r(json_encode($fornecedorNome));}  por echo json_encode($query) e verifica se dá certo; assim você receberá o objeto completo para fazer suas interações no loop do JS.
Answer: Faça o seguinte: retorne o JSON numa array no PHP:
foreach ($query as $key => $fornecedorNome) {
    $json[] = $fornecedorNome;
}

print_r(json_encode($json));

E no JavaScript faça o parse:
var data = JSON.parse(xmlhttp.responseText);

O resultado será como o print abaixo, onde você poderá iterar:

Do jeito que está fazendo está retornando um JSON inválido. Note que no seu print não há separação dos objetos por vírgula. Retornando em forma de array, as vírgulas são adicionadas automaticamente, pois cada objeto é um item da array.
Comment: Não esqueça de alterar na linha var fornecedorNome = data[i].nome; para  var fornecedorNome = data[i]; Já que você não atribuiu uma chave para os elementos do array; Para continuar com o loop atual você deverá fazer  $json['nome'][] = $fornecedorNome; no php
Comment: Não precisa. Cada item do JSON tem um índice (adicionei um print na resposta), logo `var fornecedorNome = data[i].nome` será o valor da chave `nome` de cada índice.
Comment: Bom dia Sam, consegui fazer a resposta aparecer corretamente em minha TAG . Só que, se eu tentar alterar para um  ou um , já não tenho mais a funcionalidade. Para eu conseguir jogar esse resultado em um select ou em um input com autocomplete, tenho que mudar algo no código ?
Comment: Bom dia. Dependendo do que vc quer fazer, basta alterar a forma de tratar o resultado. No caso de um select, vc criaria `option` em vez de ``, tipo assim: `html += "" + fornecedorNome + ""`
Comment: Entendi. Por fim, há alguma forma de eu fazer uma "sincronia" com os dados ? Por exemplo, ao invés de eu trazer apenas os "nomes", trazer também os dados de "id" e "cnpj", e assim que eu selecionar o nome do fornecedor, por exemplo, o seu ID e CNPJ mudam automaticamente para os deste fornecedor selecionado.
Comment: Sim, basta trazê-los tb no JSON do PHP. Mas aí vc precisa fazer uma nova pergunta para outro caso.

Retornando dados do BD com PHP e AJAX


Como obter o retorno (value) de uma Promise em JavaScript / TypeScript?

Question: Estou iniciando com Ionic 2, que utiliza o Angular 2, e estou tentando entender como funcionam promises, pois algumas libs que estou utilizando trabalham possuem funções que retornam promises e gostaria de obter o valor retornado, porém o retorno é sempre undefined:
Ex.:
'classe' Storage:
public get(key: string) {
    localforage.getItem(key).then(function (value) {

      console.log(value); // exibe o value normalmente, ex.: {nome: 'Joao', idade: '20'}
      return value;

    }).catch(function (err) {
      console.log(err);
    });
}

'classe' Page1:
recuperarItem() {
    var object = this.storage.get('pessoa1');

    console.log(object); // undefined
}

Como faço para obter o retorno desta forma? Grato pela atenção.
Comment: Não seria nessa parte `localforage`? O correto é localStorage
Comment: Estou utilizando a biblioteca localforage neste exemplo - https://mozilla.github.io/localForage/ - mas a dúvida se aplicaria a qualquer Promise
Answer: Isso acontece pois a sua função get não retorna nada, repare que o seu return está dentro de uma função anonima e não na função get
Em geral as Promises são usadas em programação assíncrona, é basicamente uma alternativa aos callbacks, onde na verdade você ainda está usando callbacks, uma forma de corrigir o seu problema seria retornando o Promise na função get
public get(key: string) {
    return localforage.getItem(key).catch(function (err) {
        console.log(err);
    });
}

E então na função recuperarItem você espera o promise ser resolvido
recuperarItem() {
    this.storage.get().then(function (value) {
        console.log(value);
    })
}

Agora dependendo se o target do TypeScript for es6/es2015 você tem a opção de usar o async/await, seu código ficaria assim
public get(key: string) {
    return localforage.getItem(key).catch(function (err) {
        console.log(err);
    });
}

E então na função recuperarItem nós deixamos o TypeScript fazer sua mágica com o async await
async recuperarItem() {
    var object = await this.storage.get();
    console.log(value);
}

Porém lembrando que es6/es2015 ainda não é suportado pela maioria dos navegadores e não sei dizer no caso do Ionic 2 como está o suporte ou se precisa usar algum transpiler como o Babel
Comment: O problema era justamente o que você falou. Naquela época não sabia trabalhar com promises ainda, e você esclareceu bem, obrigado! Desculpe a demora pelo retorno.
Answer: Tente desta forma:
...
localforage.getItem(key).then((value) => {
...


Solutions of $2^a - 7 = 27b$

Question: How can I find the solutions of the equation $2^a - 7 = 27b : a, b \in \mathbb{N}$? I can see this is also of the form $2^a - 7 \equiv 0 \mod 27$.
Comment: the question in the title seems easier than that in the body
Comment: I edited the title.
Answer: you want $2^a\equiv 7\bmod27$.
Compute all powers of $2 \bmod 27$ to get
$2,4,8,16,5,10,20,13,-1,-2,-4,-8,-16,-5,-10,-20,-13,1$. So $2$ has order $18$ mod $27$
Notice $-20\equiv7\bmod 27$ thus you want $2^{16+18k}$
Answer: $$2^2\cdot7\equiv1\pmod{27}\implies7\equiv2^{-2}$$
Using Prove that a primitive root of $p^2$ is also a primitive root of $p^n$ for $n>1$., $2$ is a primtive root $\pmod{3^n},n\ge1$
So modulo order ord$_{(3^n)}2=\phi(3^n)=3^{n-1}(3-1)$
$\implies7\equiv2^{-2}\equiv2^{-2+18}$
Proof :  $2$ is a primitive root $\pmod9$
ord$_32=2$
Using Number of consecutive zeros at the end of $11^{100} - 1$.,
$2^2\not\equiv1\pmod9\implies$ord$_{3^2}2\ne2\implies$ord$_92=3(3-1)=\phi(9)$
Answer: Note that $ 2^a - 7 \equiv 0 \pmod {27} \iff 2^a \equiv 7 \pmod {27} $.
Note that the only $a$ such that this is true and $ 0 \le a \le \phi(27) = 18 $ is $ 2^{16} \equiv 7 \pmod {27} $. Do you see why all $a$ such that $ a \equiv 16 \pmod {18} $ are solutions and they are the only ones? Hint: look back at Euler's theorem.
Comment: $a\equiv 16\pmod{18}$, where $18=\phi(27)$.
Comment: @vadim123 Yes, sorry and thanks. Edited!
Comment: I have the system $$2^a \equiv 7 \mod 27$$ and $$2^{18} \equiv 1 \mod 27$$ How can I solve this system?
Answer: Hint: all $a$ are of the form
$$a=16+18k,\,k\in \mathbb{N}\cup \{0\}$$
Can you prove this by induction?
Comment: This may be harder to prove with induction than you expect.  How would you inductively prove $$\bigg(2^{16 + 18k} \not \mid 27 \bigg) \Rightarrow \bigg(2^{16 + 18(k+1)} \not \mid 27\bigg)$$ ?  It is a good exercise to prove that the equation is sufficient, but not that it is necessary.
Comment: Well, I agree. I should be possible though :P.

Solutions of $2^a - 7 = 27b$


Why can't I append to the end of an array recursively in Ruby?

Question: I'm brand new to ruby and I've run into an error that I haven't been able to find the answer to in google, or stack overflow.
I'm trying to put the first 10 values of the fibinachi sequence into an array like so:
#@fib=[] #Maybe try creating the array differently?
@fib=Array.new
foo=42
puts "foo is of type #{foo.class}"
@fib.push(42) #Testing the array

puts @fib #Show the test

def find_fib(anumber)
    return anumber if anumber <= 1
    ( find_fib(anumber - 1) + find_fib(anumber - 2 ))
    #@fib.push(anumber.to_i) #Maybe I need to specify it is an integer http://stackoverflow.com/questions/11466988/ruby-convert-string-to-integer-or-float
    puts "anumber is of type #{anumber.class}"
    puts "They array is of type #{@fib.class}"
    puts "a number is #{anumber}"
    @fib.push(anumber) #<= this line fails
end

puts find_fib(10)

I am getting the following error:
...`+': no implicit conversion of Fixnum into Array (TypeError)
.......
foo is of type Fixnum
42
anumber is of type Fixnum
They array is of type Array
a number is 2
[Finished in 0.3s with exit code 1]

Can someone explain to me what is different between foo and anumber that prevents me from appending to the array? After all, they are both 'Fixnum' datatypes.
Comment: By the way, it's the convention in Ruby to use 2-space indent, not 4-space indent.
Comment: `@fib.push(number) #<= this line fails` looks like a typo. It should be `@fib.push(anumber)`.
Comment: Johnsyweb Thanks for pointing that out. The typo only exists on SO, not on my local copy. I fixed it in the question.
Comment: @spuder by the way, I think one of the problems with your original algorithm might be that each recursive call returns an array that represents the additive operands for a Fibonacci number, instead of just the summed Fibonacci number for that sub-sequence. That's just a hunch though, I'm not 100% sure that that's the problem.
Answer: For the error you posted, that's because the terminate condition of the find_fib method returns anumber, which is of type Fixnum. This return value is used in your former recursion:
( find_fib(anumber - 1) + find_fib(anumber - 2 ))

Here you are going to call Array + Fixnum, which causes the type check error. Change the terminate condition to the following may remove that error.
def find_fib(anumber)
  return [anumber] if anumber <= 1
  ...

BTW, you find_fib won't work as expected, you may need further tweak on the algorithm implementation.
Comment: You are right on both accounts, changing anumber to [anumber] got rid of the error. There still is something wrong with the algorithm that I can look into now. https://gist.github.com/spuder/9885656
Answer: There are a number of problems with your method:
def find_fib(anumber)
  return anumber if anumber <= 1
  (find_fib(anumber - 1) + find_fib(anumber - 2)) # 1
  # ETC...
  @fib.push(number) # 2 and 3
end

You're calculating a Fibonacci number here, but you don't assign the value to a variable,
so you're basically throwing away the number.
The last statement evaluated in a Ruby function gets returned, unless you make an
explicit return statement like in your first line. As Arie Shaw points out,
that last line returns an array object, while the first line returns a number, so you're
trying to call Array + Fixnum, which is not a defined operation.
You're pushing number into your @fib array, but that variable isn't assigned a
value anywhere.

If you want a method that generates an array of the first n Fibonacci numbers, here's one Ruby way to do it:
def fib(n)
  (n == 1) ? [0] : (2..(n-1)).each_with_object([0,1]) { |i,a| a[i] = a[i-2] + a[i-1] }
end


Deserialize JSON string into a C# complex class object containing a reference of itself inside

Question: have class whose structure is like
class QuestionNode
{
    public String Value { get; set; }
    public int? QId { get; set; }
    public String QuesDiscription { get; set; }
    public String QuesType { get; set; }
    public String Editable { get; set; }
    public int? PrevQues { get; set; }
    public String UserResponse { get; set; }
    public int UserSelected { get; set; }
    public int Progress { get; set; }

    public List<QuestionNode> OptionSet { get; set; }
    public QuestionNode(int? QId,int? PreQues, String Value){}
    public QuestionNode(int? PreQues, String Value){}
    public QuestionNode (String Value,int? QId,string QuesDiscription,string QuesType ,string Editable ,int?  PrevQues,int? NextQues,int Progress ){}
    public QuestionNode(String Value, int? QId, string QuesDiscription, string QuesType, string Editable, int? PrevQues, int UseResponse, int UserSelected, int Progress, List<QuestionNode> OptionSet){}

}

I am able to convert this structure into json using NewtonSoft.Json.
but while Deserializeing it using
Newtonsoft.Json.JsonConvert.DeserializeObject<QuestionNode>(json);
I am getting this exception:

Unable to find a constructor to use for type TestingJson.QuestionNode.
   A class should either have a default
  constructor, one constructor with arguments or a constructor marked
  with the JsonConstructor attribute. Path 'Ques', line 2, position 10.
Comment: Try commenting last line  public QuestionNode(String Value, int? QId, string QuesDiscription, string QuesType, string Editable, int? PrevQues, int UseResponse, int UserSelected, int Progress, List OptionSet){} and check if it works
Comment: Please add the JSON content to your question, because creating and filling and serializing an instance of this is not easy. The error message says it all by the way, The problem is probably not the class containing a reference to itself, it is with it's constructors. Please add full source code of QuestionNode class
Comment: I am creating a tree like structure with QuestionNode . After creating the structure I am able to create a json string using Newtonsoft.Json .I am converting the same string back to QuestionNode Object..at that time it is giving the exception..i tried commenting the line of                QuestionNode(String Value, int? QId, string QuesDiscription, string QuesType, string Editable, int? PrevQues, int UseResponse, int UserSelected, int Progress, List OptionSet){}  .it is not working .after adding default constructor it is creating object with all the fields having  null values
Answer: As the exception states you have to add a default constructor:
class QuestionNode
{
    QuesionNode(){} //Empty default constructor for deserializer

    public String Value { get; set; }
    public int? QId { get; set; }
    //More properties....
}

Comment: Although it is the case in your answer, I would explicitly point out, that this ctor can be made `private` which leaves the encapsulation as desired by the OP.
Comment: after adding the default constructor ,it create a json with all the fields null..


Is a busy-loop the best way for my async function to not complete until bluetooth scan completes?

Question: I have an async function in my Flutter app that scans for bluetooth devices. I would prefer that the async function does not complete, until the bluetooth scan completes.
I have implemented this with a busy-loop that block until the scan is complete, and checks every 500ms if this is the case.
Is this the best way to do this in dart? Is this problematic?
var stream = FlutterBlue.instance.scan(timeout: Duration(seconds: 10));
stream.listen((ScanResult result) async {
  if (result.device.name == _expectedName) {
    try {
      await result.device.disconnect();
      await result.device.connect();
      _scannedDevice = result.device;
    } catch (error) {
      print(error);
    }
  }
});

while (_scannedDevice == null && await FlutterBlue.instance.isScanning.first) {
  await Future.delayed(Duration(milliseconds: 500));
}

if (_scannedDevice == null) {
  return DeviceConnectResult.deviceNotFound;
}

Answer: What I was looking for was 'await for' loop.
An 'await for' loop will process each event in a stream, and synchronously suspend execution until the stream is complete.
var stream = FlutterBlue.instance.scan(timeout: Duration(seconds:10));
await for (var scanResult in stream) {
  if (scanResult.device.name == _expectedName) {
    try {
      await scanResult.device.disconnect();
      await scanResult.device.connect();
      device = scanResult.device;
      await FlutterBlue.instance.stopScan();
    } catch (error) {
      print(error);
    }
  }
}

Answer: When browsing the API documentation for FlutterBlue I came across the startScan method that seems to be a good solution for your problem.

Starts a scan and returns a future that will complete once the scan
has finished. To observe the results while the scan is in progress, listen to the scanResults stream

FlutterBlue.instance.scanResults.listen((ScanResult result) async {
  if (result.device.name == _expectedName) {
    try {
      await result.device.disconnect();
      await result.device.connect();
      _scannedDevice = result.device;
    } catch (error) {
      print(error);
    }
  }
});
await FlutterBlue.instance.startScan(timeout: Duration(seconds: 10));


App crash on using NSPredicate in iphone App?

Question: When i am using the NSPredicate while fetch the unique user data from Coredata Entity the app getting crash. But, no error logs. This is the code am using,
if (managedObjectContext == nil)
{
    managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Name==%@",selectedUserName];
NSFetchRequest *fectchreq = [[NSFetchRequest alloc] init];
NSEntityDescription *entitydes = [NSEntityDescription entityForName:@"ALLData" inManagedObjectContext:managedObjectContext];
[fectchreq setEntity:entitydes];
[fectchreq setPredicate:predicate];

NSSortDescriptor *sortdes = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES];
NSArray *sortdesarray = [[NSArray alloc] initWithObjects:sortdes, nil];
[fectchreq setSortDescriptors:sortdesarray];
[sortdes release];
[sortdesarray release];
NSError *error = nil;
//NSMutableArray *storeddata = [[[managedObjectContext executeFetchRequest:fectchreq] error:&error] mutableCopy];
NSArray *storeddata = [managedObjectContext executeFetchRequest:fectchreq error:&error];
//[fectchreq release];
NSLog(@"StoreData : %@, count : %d",storeddata, [storeddata count]);

Can anyone please help to solve this problem? THanks in advance.
Comment: The second parameter to `executeFetchRequest:error:` is a pointer-to-a-pointer of error object. You should pass it with ampersand like this: `... executeFetchRequest:request error:&error]`.
Comment: @Eimantas Yes i have tried your words in my code. Still the app getting crash. Can you please help me? THanks.
Answer: NSError *error;
NSMutableArray *storeddata = [managedObjectContext executeFetchRequest:fectchreq error:error];

You need to change this code to:
NSError *error = nil;
NSArray *storeddata = [managedObjectContext executeFetchRequest:fectchreq error:&error];

Reasons:
The error argument should be passed as a pointer because the declaration is -executeFetchRequest:(NSFetchedRequest *)request error:(NSError **)error;
Also this method returns NSArray, not NSMutableArray - you must be getting compiler warning about this...
Comment: Yes i have changed the code as per your advice. Still the app getting crash in the executeFetchRequest: line. Could you please help me? I will post the recent code in question. Thanks.
Comment: No errors in log. When the app come to the executeFetchRequest: line the app crashed. No error logs. Can you please help me? Thanks.
Comment: There is no way to help you without providing me some error. And there is no way you're not getting an error, at least you should see the signal which is a start... The posted code is correct.
Comment: Ya the posted code is currently am working on. sharedlibrary apply-load-rules all
(gdb) This is only am getting in my log. Please help me. Thanks.
Comment: Yes thanks a lot Mr.Graver. Really this is my mistake. I put a wrong column name in NSPredicate. Thanks a lot for your helping hand.
Comment: Is the attribute correct: `Name` and the entity name: `ALLData`
Comment: I changed the attribute name in my code. Now it is working fine. Can you please help me to delete a selected person record from the entity? Please see this question and help me.http://stackoverflow.com/questions/11305590/how-to-get-unique-values-retrieve-from-coredata-iphone-app. Thanks


What does 'echo 0 > foo' mean?

Question: I would like to know what does this code mean?
echo 0 > foo

Completely new to Unix and Bash commands. Lots of stuff to learn, but need a quick answer to this question.
Comment: The answer below is correct. Here is a link for additional reading on this topic: http://www.tldp.org/LDP/abs/html/io-redirection.html
Comment: Now that you have accepted an answer, your question will be marked as solved. You don't need to edit the title.
Comment: You can use `man echo` or google to find what commands do. For syntax like `>`, you can search `man bash` or use the "name syntax" feature on [shellcheck.net](http://www.shellcheck.net).
Answer: It echoes 0 to a file named foo. In other words, it redirects the output, 0, to a file named "foo", instead of showing it on the screen.
From a basic Wikipedia example on redirection:

command1 > file1
executes command1, placing the output in file1, as opposed to
  displaying it at the terminal, which is the usual destination for
  standard output.
Comment: Just to make it a little clearer for someone new to shell scripting: Here, 'echo' means 'print'.
Answer: The command echo 0 > foo overwrites whatever content is in the file foo - or creates it if it doesn't exist - and replaces it with 0.
The command echo 0 >> foo will add 0 to the end of the file foo, or create a file containing 0 if it doesn't exist.

What does 'echo 0 > foo' mean?


Does the central limit theorem imply the law of large numbers

Question: Assuming that the distribution has finite variance (a condition not required for the LLN), then doesn't the LLN follow from the CLT?
Comment: Possibly of interest: [central-limit-theorem-versus-law-of-large-numbers](http://stats.stackexchange.com/questions/22557/).
Answer: WLLN, yes.
Here is a general claim: Suppose $\{ f_n \}$, $f$, and $g$ are random variables, and
$$
\sqrt{n} (f_n - f) \stackrel{d}{\mapsto} g.
$$
Let's say the CDF of $g$ is continuous everywhere. Then $f_n \rightarrow f$ in probability. This is because $\sqrt{n} (f_n - f)$ is bounded in probability/uniformly tight.


d3 animate path by arc

Question: I started to work with d3. And have a question, how can I animate properly triangle along the filling path? I created a base for the gauge chart and animated it.

var chart = d3.select("#speedometer");

const arc = d3
    .arc()
    .outerRadius(120)
    .innerRadius(90)
    .startAngle(-Math.PI / 2);

chart
    .append("path")
    .datum({
        endAngle: Math.PI / 2
    })
    .attr("transform", "translate(160, 180)")
    .attr("class", "background")
    .style("fill", "#495270")
    .attr("d", arc);

const triangle = chart
.append('g')
.attr('transform', 'translate(30, 180) rotate(90)')
.style('width', '100%')
.append("path").attr("d", "M3.937,0,7.873,14H0Z");

const newAngle = (70 / 100) * Math.PI - Math.PI / 2;

const foreground = chart
    .append("path")
    .datum({ endAngle: -Math.PI / 2 })
    .style("fill", "rgb(50, 188, 228)")
    .attr("transform", "translate(160, 180)")
    .attr("d", arc);

foreground
    .transition()
    .duration(3000)
    .attrTween("d", function (d) {
        const interpolate = d3.interpolate(d.endAngle, newAngle);
        return function (t) {
            d.endAngle = interpolate(t);
            return arc(d);
        };
    });

triangle
    .transition()
    .duration(3000)

function pathTween(path) {
    const length = path.node().getTotalLength(); // Get the length of the path
    const r = d3.interpolate(0, length); // Set up interpolation from 0 to the path length
    return function (t) {
        const point = path.node().getPointAtLength(r(t)); // Get the next point along the path
        d3
            .select(this) // Select the circle
            .attr("transform", `translate(${point.x}, ${point.y})`);
    };
}
.main-wrapper{
  max-width: 80%;
  margin: 20px auto;
}

.element{
  display: flex;
  flex-flow: column nowrap;
  margin-bottom: 20px;
    border: 1px solid rgba(0,0,0,.4);
    padding: 20px;
    border-radius: 6px;
}

.title{
  margin-bottom: 4px;
  font-weight: 500;
}
.description{
  margin-bottom: 10px;
  color: rgba(0,0,0,.4);
}

#speedometer {
    width: 300px;
    height: 300px;
}

canvas{
    width: 100%;
    height: 100%;
}

        Speedometr

        <svg id="speedometer" viewbox="0 0 300 300"></svg>

The question is, how can I link the triangle to the edge of the animating arc like in the picture?
I know I should use
tween('path'....)

but not sure
Answer: I'd use SVG transform: rotate, because it allows you to specify relative to what you should rotate, and because you can chain transformations. In this case, I transform the angle to the centre of the arc, then rotate it into the right direction, and then move it up a little bit more than the outer radius so it follows the line smoothly.
It's not pixel perfect, which I think is because the triangle is not a whole number of pixels wide.

var chart = d3.select("#speedometer");

const arc = d3
    .arc()
    .outerRadius(120)
    .innerRadius(90)
    .startAngle(-Math.PI / 2);

chart
    .append("path")
    .datum({
        endAngle: Math.PI / 2
    })
    .attr("transform", "translate(160, 180)")
    .attr("class", "background")
    .style("fill", "#495270")
    .attr("d", arc);

const triangle = chart
  .append('g')
  .datum({ endAngle: -Math.PI / 2 })
  .style('width', '100%')
  .append("path").attr("d", "M3.937,0,7.873,14H0Z");

const newAngle = (70 / 100) * Math.PI - Math.PI / 2;

const foreground = chart
    .append("path")
    .datum({ endAngle: -Math.PI / 2 })
    .style("fill", "rgb(50, 188, 228)")
    .attr("transform", "translate(160, 180)")
    .attr("d", arc);

foreground
    .transition()
    .duration(3000)
    .attrTween("d", function (d) {
        const interpolate = d3.interpolate(d.endAngle, newAngle);
        return function (t) {
            d.endAngle = interpolate(t);
            return arc(d);
        };
    });

triangle
    .transition()
    .duration(3000)
    .attrTween("transform", function (d) {
        const interpolate = d3.interpolate(d.endAngle, newAngle);
        return function (t) {
          const angleRadians = interpolate(t);
          const angleDegrees = 360 * angleRadians / (2 * Math.PI);
          return `
            translate(158 176)
            rotate(${angleDegrees + 180} 3.5 7)
            translate(0 132)
          `;
        };
    });

function pathTween(path) {
    const length = path.node().getTotalLength(); // Get the length of the path
    const r = d3.interpolate(0, length); // Set up interpolation from 0 to the path length
    return function (t) {
        const point = path.node().getPointAtLength(r(t)); // Get the next point along the path
        d3
            .select(this) // Select the circle
            .attr("transform", `translate(${point.x}, ${point.y})`);
    };
}
.main-wrapper{
  max-width: 80%;
  margin: 20px auto;
}

.element{
  display: flex;
  flex-flow: column nowrap;
  margin-bottom: 20px;
    border: 1px solid rgba(0,0,0,.4);
    padding: 20px;
    border-radius: 6px;
}

.title{
  margin-bottom: 4px;
  font-weight: 500;
}
.description{
  margin-bottom: 10px;
  color: rgba(0,0,0,.4);
}

#speedometer {
    width: 300px;
    height: 300px;
}

canvas{
    width: 100%;
    height: 100%;
}

        Speedometr

        <svg id="speedometer" viewbox="0 0 300 300"></svg>

Comment: Thank @Ruben, it helped but, I want to avoid a hard code, so how should I calculate values for animations translation ? return `
            translate(158 176) ???
            rotate(${angleDegrees + 180} 3.5 7) // 3.5 ? 7?
            translate(0 132)
          `;
Comment: 158 and 176 are approximately equal to the translate on foreground, 3.5 and 7 are half of the size of the triangle marker (which is 7.5*14px) to put the rotation point in the centre, and 132 is outerRadius + some padding. All other values in your example are hardcoded, so in the future, I recommend using variables for them in your question too
Comment: Don't use the same question to ask a massive follow-up like this. You completely altered the nature of the question, rendering it useless to anyone who has the same question you originally did. StackOverflow is not meant to help only you. It's based on the idea that if you have a question, other people will too, and we build a system of questions and answers that will help other people too. If you can't figure it out, ask a new question.
Comment: If you post a new question in the next hour, I'd be happy to answer it
Comment: done, you can check it here. I will very much appreciate it. https://stackoverflow.com/questions/64959415/d3-animate-group-by-path

d3 animate path by arc


How to draw $S^1\times I$

Question: I always thought $P=S^1\times I$, where $S^1$ is the circle and $I=(0,1)$ with the standard topology is the surface of the cylinder, but I was reading a book which says me another thing:

Even, if the book is right, I didn't understand why $P$ is the open annulus, because the radius inside the annulus is not the same as $S^1$.
So, why $P$ is not the surface of the cylinder? why $P$ is the open annulus? what the author said doesn't convince me.
Thanks
Comment: The closed cylinder and closed annulus are homeomorphic.
Comment: Topologically, you cannot "see" the radius. So to go from one to the other, just "push" the middle out to make a cylinder.
Comment: When you say you think it's the surface of a cylinder, do you think it includes the discs at each end, or just the tube?
Comment: So what happens if you shrink the top end of the tube a little, then expand the bottom part a little (so it's kind of a cut-off cone), then smash the whole thing flat into the floor?
Comment: @MartianInvader We get the open annulus?
Comment: @MartianInvader So both are $P$?
Answer: Let $C$ be the cylinder consisting of the set of points in 3-space with cylindrical coordinates $(r,\theta,z)$ such that $r=1$ and $0 \lt z \lt 1$.
Let $A$ be a particular example of an annulus $-$ say, consisting of the set of points in the plane with polar coordinates $(r,\theta)$ such that $1 \lt r \lt 2$.
The cylinder $C$ is probably what you have in mind when you think of $S^1 \times (0,1)$. But the function which maps $(1,\theta,z) \in C$ to $(z+1,\theta) \in A$ is a homeomorphism. So the topological spaces $C$ and $A$ are both the same as the space $S^1 \times (0,1)$ (where "the same as" means "homeomorphic to").
Comment: Why $(z+1,\theta)$?
Comment: @user42912 The goal was to show that $C$ and $A$ are homeomorphic; the direct way to do this is to given an example of a continuous function $f:C \rightarrow A$ whose inverse is also a continuous function. The function $f(1,\theta,z)=(z+1,\theta)$ (using cylindrical and polar coordinates, respectively), is just an example; I chose "$z+1$" since $C$ has $0 \lt z \lt 1$ while $A$ has $1 \lt r \lt 2$.

How to draw $S^1\times I$


decision tree training: gini vs entropy vs precision vs recall

Question: When training decision trees, the standard algorithms (e.g. ID3, C4.5, C5.0) use either the gini index or entropy to determine which node to add next. Only once the tree is built, and the ROC curve is being evaluated in comparison to other classification models, are the decision tree's precision and recall evaluated.
Are there any decision tree building algorithms that use the precision and recall, instead of the gini index or entropy, to decide which node to add next?
Answer: There are two terms here:
1- The objective function: this is the function that the algorithm tries to optimize. In the case of DT it is Gini/Entropy, in the case of Linear Regression, it is Gradient Descent, etc.
2- Then it is the metric that you use to evaluate the overall performance of the model after the model is done. Here you use precision, recall, AUC ROC, etc. These are not objective function you can be optimized.
However, you can use recall/precision for model selection. You can modify your hyperparameters and see which one results in a better recall/precision (closer to what you need). Moreover, if you are really concern about one error type, you can change the weight of different errors, or upsample/downsample your data so that the "metrics" you need is achieved.


Example of Matrix in Reduced Row Echelon Form

Question: I'm struggling with this question and can't seem to come up with an example:
Give an example of a linear system (augmented matrix form) that has:

reduced row echelon form
consistent
3 equations
1 pivot variable
1 free variable

The constraints that I'm struggling with is: If the system has 3 equations, that means the matrix must have at least 3 non-zero rows. And given everything else, how can I have only 1 pivot?
Answer: Hint: It's gotta have only three columns, one for each of the variables (1 pivot, 1 free) and one column for the constants in the equations.
Comment: It counts as the equation $0x + 0y + ... = 0$. I know it sounds silly, but that's going to be what it means. On that note, I actually made a mistake (which I will now fix), as I didn't see that they were asking for an *augmented* matrix, in which case you need to throw in one more column.
Comment: if I only have 2 columns then I still don't see how I can have 3 pivots and satisfy the reduced row echelon form. The book that we're using states that a) if a row does not consist entirely of zeroes, then the first nonzero number in the row is a 1. If I have all 1s there it also can't be in the reduced echelon form because b) column with leading 1 must have 0 everywhere else .. $$
  \left[\begin{array}{rrr|r}
    1 & * \\
    1 & * \\
    1 & *
  \end{array}\right]
$$ Also, wouldn't this be just 1 variable in total?
Comment: Notice that the condition is "**if** a row does not consist entirely of zeroes". In your case, some of your rows will have to consist of only zeroes. In particular, how many rows must be all zero? (Use the fact that there's only one pivot)
Comment: Hmm.. looks like I missed this. I was under the assumption that a row that contains all zeroes does not count as 1 equation.


PHP array comparison to get total sum

Question: I have 2 set of array. The first array output the category and quantity, the second one comes with category and price.
array:2 [
  0 => array:1 [
    "Adult " => " 2"
  ]
  1 => array:1 [
    " Senior " => " 1"
  ]
]

array:3 [
  0 => array:6 [
    "id" => 1
    "variant_id" => 1
    "variant_dtl_name" => "Adult"
    "variant_dtl_price" => 25.0

  ]
  1 => array:6 [
    "id" => 2
    "variant_id" => 1
    "variant_dtl_name" => "Senior"
    "variant_dtl_price" => 15.0

  ]
  2 => array:6 [
    "id" => 3
    "variant_id" => 1
    "variant_dtl_name" => "Children"
    "variant_dtl_price" => 8.0

  ]
]

How can I cross match these two array to get total price? Eg: Adult x 2 will output the price 50 and Senior x 1 will output 15 and total would sum up to 65. Thanks!
Comment: Show us what you have tried
Comment: just loop em all up, `foreach` should suffice
Answer: Try this out. Should work.
I think you understand what the $secondArray and $thirdArray are.
LEt me know the output.
<?php

foreach($secondArray as $catKey => $cat){

    foreach($cat as $key=>$val){
        $categoryName = $key;
        $quantity = $val;
    }

    foreach($thirdArray as $catDetails){
        if($catDetails['variant_dtl_name'] == $categoryName){
            $secondArray[$catKey]['price'] = $catDetails['variant_dtl_price'] * $quantity;
            $price[] = $catDetails['variant_dtl_price'] * $quantity;
        }
    }
}

print_r($secondArray);

//Since You needed the total, you can do this.
    echo array_sum($price);
    ?>

Comment: it returns back the array 2.
Answer: To make it less costly, first make $price_scale containing category prices.
And then multiplying that in the first array to calculate the category price.
Assuming the first array's name as $array1 ans second's $array2.
$price_scale = [];

foreach ($array2 as $arr)
{
    $price_scale[trim($arr['variant_dtl_name'])] = $arr['variant_dtl_price'];
}

$count = [];

foreach ($array1 as $arr)
{
    $key = key($arr); $name = trim($key);
    $count[$name] = $price_scale[$name] * $arr[$key];
}

print_r($count);

To get the total sum, just one more line
$sum = array_sum($count);

This foreach will iterate
(t1+t2) times
t1 = number of arrays in $array1
t2 = number of arrays in $array2
Comment: OK, how to sum back for each category?

PHP array comparison to get total sum