ngFor depends on another ngFor to finish rendering - getting ExpressionChangedAfterItHasBeenCheckedError [Angular 2]

Question: I have two lists of components that use data provided by two different services:

the first list contains some components with random heights (I don't know their heights until they are rendered)
the components in the second list must have their heights calculated based on the heights of the ones in the first list.

Both lists are generated by the same component using two *ngFor loops, and the services data is changed from another child component.
The problem is that when the model data changes, both ngFor loops try to update the template, but the second one fails because it is dependent upon the first ngFor which is not yet ready.
I did try to use ChangeDetectorRef.detectChanges() or to listen for the changes emitted by the QueryList containing the first list's components, but I'm still getting ExpressionChangedAfterItHasBeenCheckedError.
The real scenario is a bit more complicated, but here's a simplified version of what the code looks like:
https://embed.plnkr.co/sr9k0wLQtyWSATiZuqaK/
Thanks in advance, this is my first question on stackoverflow :)
Comment: you might find this article useful [Everything you need to know about the `ExpressionChangedAfterItHasBeenCheckedError` error](https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4)
Answer: I would avoid using methods that calculate height within template. Instead i would prepare data for view:
<second-cmp
  *ngFor="let cmp of generatedData"
 [model]="cmp"
 [height]="cmp.height"> <------------ already calculated value

Then i would subscribe to QueryList.changes to track changes of generated elements and calculate height there:
constructor(
  ...,
  private cdRef: ChangeDetectorRef) {}

ngAfterViewInit() {
    this.components.changes.subscribe(components => {
      const renderedCmps =  components.toArray();
      this.generatedData.forEach((x, index) => {
        switch (index) {
          case 0: // first
            x.height = renderedCmps[0].height / 2;
            break;
          case this.modelData.length: // last
            x.height = (renderedCmps[renderedCmps.length - 1].height / 2);
            break;
          default: // in-between
            x.height = (renderedCmps[index - 1].height + renderedCmps[index].height) / 2
        }
      });
      this.cdRef.detectChanges();
    });
}

+  'px' is redundant because we can specify it within style binding:
[style.height.px]="height"

Plunker Example
Answer: Excellent response @yurzui, works like a charm!
Setting the height property on the model data also removes the necessity of binding it separately since I'm already passing the reference of the entire model to the component in the *ngFor.
<second-cmp
  *ngFor="let cmp of generatedData"
 [model]="cmp">

@Component({
selector: 'second-cmp',
template: `

Calculated height

`
)}
export class Second {
  @Input('model') model;
  // @Input('height') height; <-- removed
}

Final solution
Comment: Good improvement )


Manipulate a field before it is rendered

Question: I want to add two text fields and programmatically alter their content before the fields are rendered. The fields should use a WYSIWYG editor.
How would I go around this?
Should I create my own custom field or use hooks?
Can you provide a not too complex example?
Answer: Since version 5, Drupal provides filters, a mechanism to manipulate the value of a text filter before rendering. In Drupal 8, filters are implemented as plugins.
So, in order to have two (text) fields which can can manipulate the value before display, you would need to

Create a custom filter (in a custom module)
Define a text format specific for your two fields, configured to use your custom filter (and any other filter you still want to apply)
On your content type, configure the two fields to use that text format
?
Profit

You filter code would look like
<code>namespace Drupal\celebrate\Plugin\Filter;

use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * @Filter(
 *   id = "filter_ninjafart",
 *   title = @Translation("NinjaFart Filter"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
 * )
 */
class NinjaFartFilter extends FilterBase {
  public function process($text, $langcode) {
    $text = doSomethingWith($text);
    return new FilterProcessResult($text);
  }
}
</code>


Invalid Firebase path: Firebase paths must not contain '.', '#', '$', '[', or ']'

Question: I am creating an app on appinventor with firebase and I have an error returned when I introduce an email to the firebase, how to resolve it?
Invalid Firebase path:  Firebase paths must not contain '.', '#', '$', '[', or ']'
Comment: You can't have any of the above characters in your key. So your email, which contains `.` cannot be used as the key. You have to use username or uid as your key in your data structure.
Comment: Don't use the email value as a key or mutate it to remove the `.` from it
Answer: Using email address as a key in Firebase Realtime Database is not a very good idea.  Email addresses are problematic because they are not case sensitive, users may change them over time, and as you've see, they contain invalid characters.
Instead, you should use some other identifier, such as an automated push id, or some other unique id.  You can store the email address as a child value within the space you create for each user, and you can query users to look for a specific email address later, if you like.
If you really must use an email address as a child key, you'll need to encode the string some way in order to remove the invalid characters, and always remember to encode email address strings the same way when searching for the user by that email.
Answer: This an example for storing to firebase if a value contains . # $ [ ]
Answer: Simple, before using the email address replace all the '.' with '1'.
Therefore this email "firstname.lastname@example.com" will look like "example@email1com".
This can also be done to replace any other characters that are illegal.
Comment: This does not answer the question.
Answer: this seems to work
Utils.EncodeString(user.email)

cheers
Answer: You receive this exception because email contain invalid characters such as '.' and '@' which are invalid to the firebase database. Instead, use user id.
Simply use FirebaseAuth.getInstance().getCurrentUser().getUid().
Hopefully, the problem should go away.
Answer: I received this error while trying to use orderBy, as i copy-pasted from the UI something like:
.collection("my_collection").orderBy("", "asc")

forgot to fill out the "" inside it ...
Answer: I also got the same error. I resolved it in a simple step, it seems that you might be using email address as the key (which I did in my case) is not a very good practice it would be better to use any other variables as key which doesnot contain the special characters.
Hope its helpful


Compare the goodness of fit between two GLMs that are NOT nested

Question: as far as I understand, AIC or BIC can be used to judge the goodness of fit between two GLMs, but they two has to be one nested inside the other. If I have two models that are not nested and based on different data, is there a way to compare the goodness of fit? TIA
Comment: If they are based on different datasets then how will you distinguish between differences due to different models and differences due to different data?
Comment: I agree with @mdewey
It's hard to imagine a meaningful scenario where you would want to compare GOF of two models fit to different data.
Comment: Maybe a duplicate:   http://stats.stackexchange.com/questions/116935/comparing-non-nested-models-with-aic
Answer: One thing you can do is to get the residuals from each model and compare them.  You could use a t-test but it's probably more useful to simply compare absolute values and then ask yourself if the improvement in fit is worth it.  This is not a formal test but it's still useful.
Various plots of the outputs can be useful; I've found it helpful to look at Tukey mean difference plots, QQ plots of the different residuals; box plots of residuals and so on.


Como verificar se todos os valores de um array são Number

Question: gostaria de colocar uma condicional, para verificar se um determinado array, é composto apenas por Number.
O meu array esta dessa forma:
let arrayTeste = [1, 3, 4, 6, 80, 33, 23, 90]; //apenas com Number

Mas se eu declarasse um array de String:
let arrayTeste = ["1", "3", "4", "6", "80", "33", "23", "90"];

Como poderia colocar na minha função, uma condição para verificar se o array é diferente de Number?
Tentei colocar uma condição na minha função dessa forma:
if (array != Number) return "Insira um array valido!";

mas não funcionou, mesmo eu declarando o array apenas com Number, quando chamo a função, ela cai nesse IF, entendendo que o meu array é diferente de Number, mesmo ele estando da forma correta:
let arrayTeste = [1, 3, 4, 6, 80, 33, 23, 90];

Alguém teria alguma ideia de como posso estar arrumando essa condição pra ela validar corretamente?
Comment: Se você quer checar o tipo de uma variável, use `typeof variavel === "number"`, `Number` é um objeto e não serve para checagem de tipo. Adicionalmente, você pode usar `Number(variavel)` para converter uma string em número e usar `Number.isNaN(variavel)` para checar se o número resultante é válido
Answer: Como que você quer checar se algum elemento da lista é diferente do tipo Number, é necessário utilizar o typeof.
Código
Segue o código, onde tenho um array que contém valores do tipo String, e percorro ela utilizando o every e verificando se contém algum valor diferente do tipo Number, caso não contenha elemento do tipo  Number no array, me retorna true.
// array com valores Strings
let  array  = ["a", "b", "c"]

// Verificando se contém algum elemento diferente do tipo Number
console.log(array.every(function(elem) {return  typeof  elem  !==  'number';}));


Bad XML block, Error: No resource found that matches the given name (at 'icon' with value '@android:drawable

Question: Background: I am using Eclipse to develop an Android app. I have an xml file that contains a menu that contains three items. Each of the items contains an android:icon declaration. Only the first android:icon declaration is referenced in my program. NOTE: The second two android:icon declarations are NOT referenced ANYWHERE in my program or in any of the project files.
The Problem: I tried in vain to add a fourth menu item and discovered something very baffling to me. Not only cannot I not add an item to my menu, I cannot alter the existing last two android:icon declarations or I get the errors described in the title. For example I cannot change the following android:icon declaration from:
android:icon="@android:drawable/ic_menu_preferences"

To:
android:icon="@android:drawable/ic_menu_preference"

I find this very baffling because the android:icon is declared but not referenced anywhere in my program or in any of the project files. And none of the "solutions" I found on the internet fix my problem. And as I write this Stackoverflow is telling me my question has been asked and answered, but it hasn't!
Any ideas anyone?
Answer:
NOTE: The second two android:icon declarations are NOT referenced ANYWHERE in my program or in any of the project files

They are in your menu. Otherwise, the android:icon attributes would not exist. Hence, the icons are referenced by the menu itself.

For example I cannot change the following android:icon declaration

That is because there is no icon in the OS with that name.
Also, unless every icon you use in your menu will come from the OS, you are better served by copying them from your SDK into your project. Some OEMs replace the standard icons with their own versions. If you will be mixing OS icons with your own icons, even if you design your icons to match those on, say, the emulator, they will not match on other devices. By copying the icons from the SDK into your project, you ensure consistency within your menu -- if the icons look right on the emulator, they will look the same on other devices.

I find this very baffling because the android:icon is declared but not referenced anywhere in my program or in any of the project files.

The icon is part of the menu. Otherwise, the android:icon attribute would not exist. Hence, the non-existent icon is referenced by the menu itself.
Comment: Thanks @CommonsWare. The more I read your answer the more get out of it. Thanks! I'm also trying to "vote up" your answer but it won't let me.
Comment: this is a great answer. I am glad it is still here to review. Also I think it will help others.
Answer: The line @android:drawable/ic_menu_preferences is actually a reference itself. It is referencing a standard Android image that is displayed on your menu item. Here is some documentation to help you with drawables.
Comment: Thanks @Gary. I also saw this which helped a lot [link](http://www.darshancomputing.com/android/1.5-drawables.html)
Answer: i think  , you have added a png file which is corrupted
follow this link , probably it will help you
Comment: No @Houcine I did not add any png files.


Should I teach Bayesian or frequentist statistics first?

Question: I am helping my boys, currently in high school, understanding statistics, and I am considering beginning with some simple examples without disregarding some glimpses to theory.
My goal would be to give them the most intuitive yet instrumentally constructive approach to learn statistics from scratch, in order to stimulate their interest in further pursuing statistics and quantitative learning.
Before beginning, though, I have a particular question with very general implications:
Should we begin teaching statistics using a Bayesian or frequentist framework?
Researching around I have seen that a common approach is beginning with a brief introduction on frequentist statistics followed by an in depth discussion of Bayesian statistics (e.g. Stangl).
Comment: Your question is difficult to answer without more context. What is it you'd like to achieve?
Comment: Nate Silver's book "The Signal and the Noise" makes a case for teaching young people Bayesian statistics.
Comment: It's bad parenting to teach kids Bayesian stats, akin to pouring them vodka or lighting up cigars. Note that both vodka and cigars are fine for adults as long they discover them on their own
Comment: @Aksakal I was actually planning to teach them Bayes theorem while sipping vodka and puffing havanas... ;-)
Comment: That's a good way to keep kid away from bayesian stats for a few years. You tell them that is just the Bayes theorem applications. The theorem works fine in frequentist stats
Comment: @Glen_b I have edited the question to make more explicit my goals.
Answer: Both Bayesian statistics and frequentist statistics are based on probability theory, but I'd say that the former relies more heavily on the theory from the start. On the other hand, surely the concept of a credible interval is more intuitive than that of a confidence interval, once the student has a good  understanding of the concept of probability. So, whatever you choose, I advocate first of all strengthening their grasp of probability concepts, with all those examples based on dice, cards, roulette, Monty Hall paradox, etc..
I would choose one approach or the other based on a purely utilitarian approach: are they more likely to study frequentist or Bayesian statistics at school? In my country, they would definitely learn the frequentist framework first (and last: never heard of high school students being taught Bayesian stats, the only chance is either at university or afterwards, by self-study). Maybe in yours it's different. Keep in mind that if they need to deal with NHST (Null Hypothesis Significance Testing), that more naturally arises in the context of frequentist statistics, IMO. Of course you can test hypotheses also in the Bayesian framework, but there are many leading Bayesian statisticians who advocate not using NHST at all, either under the frequentist or the Bayesian framework (for example, Andrew Gelman from Columbia University).
Finally, I don't know about the level of high school students in your country, but in mine it would be really difficult for a student to successfully assimilate (the basics of) probability theory and integral calculus at the same time. So, if you decide to go with Bayesian statistics, I'd really avoid the continuous random variable case, and stick to discrete random variables.
Comment: "In my country, they would definitely learn the frequentist framework first" — This (or omitting discussion of Bayesianism entirely) is the traditional approach worldwide.
Comment: I was under impression (from reading his blog) that Andrew Gelman would advocate against frequentist NSHT as much as against Bayesian.
Comment: @psarka [yes, sure](http://andrewgelman.com/2011/04/02/so-called_bayes/) - I never said the contrary.
Comment: @Kodiologist I suspected as much. At least, there may be some educational systems where, after the frequentist framework, also the Bayesian one is introduced in high school. But that's not the case around here.
Answer: Bayesian and frequentist ask different questions. Bayesian asks what parameter values are credible, given the observed data. Frequentist asks about the probability of imaginary simulated data if some hypothetical parameter values were true. Frequentist decisions are motivated by controlling errors, Bayesian decisions are motivated by uncertainty in model descriptions.
So which should you teach first? Well, if one or the other of those questions is what you want to ask first, that's your answer. But in terms of approachability and pedagogy, I think that Bayesian is much easier to understand and is far more intuitive. The basic idea of Bayesian analysis is re-allocation of credibility across possibilities, just like Sherlock Holmes famously said, and which millions of readers have intuitively understood. But the basic idea of frequentist analysis is very challenging: The space of all possible sets of data that might have happened if a particular hypothesis were true, and the proportion of those imaginary data sets that have a summary statistic as or more extreme than the summary statistic that was actually observed.
A free introductory chapter about Bayesian ideas is here. An article that sets frequentist and Bayesian concepts side by side is here. The article explains frequentist and Bayesian approaches to hypothesis testing and to estimation (and a lot of other stuff). The framework of the article might be especially useful to beginners trying to get a view of the landscape.
Comment: Including titles of the chapter and the article could be helpful in case the links go dead in the future.
Answer: This question risks being opinion-based, so I'll try to be really brief with my opinion, then give you a book suggestion. Sometimes it's worth taking a particular approach because it's the approach that a particularly good book takes.
I would agree that Bayesian statistics are more intuitive. The Confidence Interval versus Credible Interval distinction pretty much sums it up: people naturally think in terms of "what is the chance that..." rather than the Confidence Interval approach. The Confidence Interval approach sounds a lot like it's saying the same thing as the Credible Interval except on general principle you can't take the last step from "95% of the time" to "95% chance", which seems very frequentist but you can't do it. It's not inconsistent, just not intuitive.
Balancing that out is the fact that most college courses they will take will use the less-intuitive frequentist approach.
That said I really like the book Statistical Rethinking: A Bayesian Course with Examples in R and Stan by Richard McElreath. It's not cheap, so please read about it and poke around in it on Amazon before you buy. I find it a particularly intuitive approach that takes advantage of the Bayesian approach, and is very hands-on. (And since R and Stan are excellent tools for Bayesian statistics and they're free, it's practical learning.)
EDIT: A couple of comments have mentioned that the book is probably beyond a High Schooler, even with an experienced tutor. So I'll have to place an even bigger caveat: it has a simple approach at the beginning, but ramps up quickly. It's an amazing book, but you really, really would have to poke through it on Amazon to get a feel for its initial assumptions and how quickly it ramps up. Beautiful analogies, great hands-on work in R, incredible flow and organization, but maybe not useful to you.
It assumes a basic knowledge of programming and R (free statistical package), and some exposure to the basics of probability and statistics. It's not random-access and each chapter builds on prior chapters. It starts out very simple, though the difficulty does ramp up in the middle -- it ends on multi-level regression. So you might want to preview some of it at Amazon, and decide if you can easily cover the basics or if it jumps in a bit too far down the road.
EDIT 2: The bottom line of my contribution here and attempt to turn it from pure opinion is that a good textbook may decide which approach you take. I'd prefer a Bayesian approach, and this book does that well, but perhaps at too fast a pace.
Comment: McElreath's book is excellent, but I would be really surprised if high school students would be able to follow that level of treatment, even with a talented tutor.
Comment: @DeltaIV: Good feedback, I'll edit my answer. I've been fooled several times by how readable and analogical it is at the beginning. It does enter a _steep_ learning curve around halfway through, and probably a lot earlier than that.
Comment: Another note: I think there's a bigger gap between fundamentals (i.e., probability theory) and application in Frequentist methods over Bayesian methods. That is, I have trouble imagining someone really understanding MLE theory, proof of the CLT etc., without a graduate level education, which is required for even the most basic of Frequentist procedures. Once you know conditional probability, you basically understand how Bayesian inference works. MCMC theory is a bit tricky, but honestly much simpler than truly understanding MLE theory...
Comment: ... and since it is easier to bridge the gap between probability and application of statistics in the Bayesian framework, at the very least, I think that makes things more mentally satisfying quicker. I hated TA-ing the courses where we had to say "and trust us, MLE theory works with large samples", as I felt that had to somewhat kill someone's scientific curiosity, or require a much larger mental commitment.
Comment: ... But the **intuition** behind mle is natural enough ... https://stats.stackexchange.com/questions/112451/maximum-likelihood-estimation-mle-in-layman-terms/112480#112480
Answer: I have been taught the frequentist approach first, then the Bayesian one.
I am not a professional statistician.
I have to admit I didn't find my prior knowledge of the frequentist approach to be decisively useful in understanding the Bayesian approach.
I would dare to say it depends on what concrete applications you will be showing your pupils next, and how much time and effort you will be spending on them.
Having said this, I would start with Bayes.
Answer: The Bayesian framework is tightly coupled to general critical thinking skills. It's what you need in the following situations:

You think about applying for a competitive job. What are your chances of getting in? What payoff do you expect from applying?
A headline tells you mobile phones cause cancer in humans in the long term. How much evidence do they have for this?
Which charity should you donate money to if you want it to have the greatest effect?
Someone offers to flip a coin with a bet of \$0.90 from you and \$1.10 from them. Would you give them the money? Why, why not?
You've lost your keys (or an atom bomb). Where do you start looking?

Also, this is much more interesting than memorising the formula for a two sample t-test :p. Which increases the chance that students will stay interested long enough to bother with increasingly technical material.
Answer: I would stay away from Bayesian, follow the giants.
Soviets had an excellent book series for secondary school students, roughly translated into English as "'Quant' little library." Kolmogorov contributed a book with co-authors titled "Introduction to a probability theory." I'm not sure it has ever been translated into English, but here's the link to its Russian original.
They approach explaining the probabilities through combinatorics, which I think is the great way to start. The book is very accessible for a high school student with decent maths. Note, that Soviets taught math rather extensively, so the average Western high school students may not be as well prepared, but with enough interest and will power can still handle the content, in my opinion.
The content is very interesting for students, it has random walks, limiting distributions, survival processes, law of large numbers etc. If you combine this approach with computer simulations, it becomes even more fun.
Answer: No one has mentioned likelihood, which is foundational to Bayesian statistics. An argument in favor of teaching Bayes first is that the flow from probability, to likelihood, to Bayes, is pretty seamless. Bayes can be motivated from likelihood by noting that (i) the likelihood function looks (and acts) like a probability distribution function, but is not because the area under the curve is not 1.0, and (ii) the crude, commonly-used Wald intervals assume a likelihood function that is proportional to a normal distribution, but Bayesian methods easily overcome this limitation.
Another argument favoring Bayes first is that the P(A|B) versus P(B|A) concern about p-values can be more easily explained, as mentioned by others.
Yet another argument favoring "Bayes first" is that it forces students to think more carefully about conditional probability models, which is useful elsewhere, e.g., in regression analysis.
Sorry for the self-promotion, but since it is entirely on-topic, I do not mind stating that this is precisely the approach that Keven Henning and I took in our book "Understanding Advanced Statistical Methods," (https://peterwestfall.wixsite.com/book-1) whose intended audience is non-statisticians.
Answer: Are you teaching for fun and insight or for practical use? If it's about teaching and understanding, I'd go Bayes. If for practical purposes, I'd definitely go Frequentist.
In many fields -and I suppose most fields- of natural sciences, people are used to publish their papers with a p-value. Your "boys" will have to read other people's papers before they come to writing their own. To read other people's papers, at least in my field, they need to understand null hypotheses an p-values, no matter how stupid they may appear after Bayesian studies. And even when they are ready to publish their first paper, they will probably have some senior scientist leading the team and chances are, they prefer Frequentism.
That being said, I would like to concur with @Wayne , in that Statistical rethinking shows a very clear way towards Bayesian statistics as a first approach and not based on existing knowledge about Frequentism. It is great how this book does not try to convince you in a fight of the better or worse statistics. The stated argument of the author for Bayes is (IIRC) that he has been teaching both kinds and Bayes was easier to teach.


Using Panels - Node Template.. How do i pass additional arguments for my blocks?

Question: I have content types: Project, News, and Country.
I have a node template that displays details of a Project. This node template displays a view, which displays all the News. I want to filter all the news by the project's Country.
Project has a cck field: country_id. How do i pass it's value to my News view?

tl;dr: using a panel node-template, how do i use the node's cck field as argument?
Comment: So I think the critical piece of information here is number one in my answer in the linked to question. You must have a "content pane", not a "block".
Comment: Welcome to d.se :) I'm wondering how this is different from http://drupal.stackexchange.com/questions/20486/panels-node-template-with-additional-arguments/ where you also posted? I have posted step by step instructions, and they should be relevant for your question as well.
Comment: hi thanks! i just finished updating my question after trying your solution. im still lost.
Comment: I used content pane when I tried it. I added an argument, then went to pane settings and changed argument input to From Context.. but i cant seem to find a way to choose my country_id there..
Comment: Let's take a step back. Excluding Panels from the equation all together, can you make the View create the list that you want? It sounds like the problem here is really in the contextual filters in the View?
Comment: well, the content pane displays all the countries. but when i try to enter a country id on the preview, nothing is displayed
Comment: I think you should start with a Views related question then. :) The _only_ things Panels will do in this context is put the number in the equivalent of the preview. The remaining 99% of the work is done by Views. You need to ensure the View can do what you want first. :)
Comment: lol i just realized i was trying to preview a country_id that does not have any news on it. so, yeah the view works the way i want it
Comment: Projects have a field country_id. how do i pass it to my view that displays all the news? i know i can just code it through a module hook. but i just would like to know if it is possible and how.
Comment: I'm not sure I understand the question. You should probably open a new question and start there. :)
Comment: @Letharion Maybe you can help me understanding something: Basing on the last comment from the OP, does the question still need to be answered?
Comment: I believe the answer is no. I think the OP needs create a View that will fulfill his requirements, and then this will be a dup to the linked to question, and my answer there should make sense. :)
Comment: thanks letharion, i edited my question (im not sure if you have seen it yet)
Answer: You need to use content pane for the view to make it accept arguments.
Then when you insert the content pane, you should be able to use the node and all fields on the node using a token system to pass any variable to the view pane. How you setup the content pane determines which types of variables it will accept.


Lista crescente em c

Question: <code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    int total = 10;
    char letra = '*';

    char *retorno;
    retorno = (char *) malloc(total + 1);

    for (int i=0; i<total; i++) {
      retorno[i] = letra;
      retorno[i+1] = '\0';

      printf("%s\n", retorno);
    }

    return 0;
}
</code>
Comment: Você tem o trecho do código que você fez? Tente explicar melhor a sua dúvida
Comment: @AndreLacomski não precisa de dois laços para fazer isso
Comment: é necessário fazer dois laço de repetição. Caso não for respondida a pergunta, quando eu chegar em casa eu mando a resposta
Answer: É possível sim resolver esta questão com apenas um laço, apesar de requerer mais variáveis.
Segue uma possível solução:
<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    int total = 10;
    char letra = '*';

    char *retorno;
    retorno = (char *) malloc(total + 1);

    for (int i=0; i<total; i++) {
      retorno[i] = letra;
      retorno[i+1] = '\0';

      printf("%s\n", retorno);
    }

    return 0;
}
</code>

Já com dois laços, talvez seja mais fácil de entender:
<code>#include <stdio.h>

int main()
{
    int total = 10;
    char letra = '*';

    for (int i=0; i<total; i++) {
      for (int j=0; j<=i; j++){
        printf("%c", letra);
      }
      printf("\n");
    }

    return 0;
}
</code>

peço desculpas se estraguei a pergunta (já que eu mesmo votei para fechá-la por não ser muito clara), mas os comentários não me
  permitiram deixar passar..
Comment: Boa! Realmente dá para fazer só com 1 laço. Nem me tinha ocorrido essa solução criativa, de ir concatenando apenas um char na mesma string.

Lista crescente em c


Can you compare regression models using RMSE when samples have different proportions of zeros?

Question: I am using the ranger package (which implements random forests) in R to build regression models of tree species' basal area, a continuous measure of abundance and size.  Predictors are climate variables.  From a very large dataset I am selecting a sample of $400,000$ points for training for each species.  I then test prediction with $100,000$ other points  For most species, zeros (indicating absence) are much more common than positive values and the data are left-skewed.
I want to test how the proportion of zeros included in the sample affects predictive performance of the model. I'm using a range of proportions of zero from $0$ to $0.5$.
I have read in many answers that RMSE can't be used to compare models if the scale of the dependent variable is different. In this case, the scale is the same, but I'm concerned that the differing proportion of $0$s may affect RMSE independently of model performance.  Should that be a concern?  I could always use $R^2$ instead.
Comment: I suspect you have [zero-inflated data](https://stats.stackexchange.com/questions/tagged/zero-inflation?tab=Votes), i.e., your data could be represented by two coupled models: first you model presence/absence, then you model abundance for presence.
Comment: That's an interesting idea @Roland. I guess I would train a classification pres/abs model with a 50% presence sample, then train the regression model with only with the half of samples actually present.  In predicting, I would first predict pres/abs, then predict basal area with the regression model on the subset predicted to be present.  Sound right?
Comment: Only problem is, regression predictions with no 0s are the worst, and improve the more 0s you add.
Answer: First off, if you have a dataset which includes exclusively positive values (e.g. proportions like yours), then you will likely need to fit your model in a way that only includes positive values. Much has been said about how regressions like Poisson, negative binomial, etc. achieve this. After fitting the model, you may still believe there are just too many zeroes, and may want to check, as noted by your question below:

I want to test how the proportion of zeros included in the sample affects predictive performance of the model. I'm using a range of proportions of zero from 0 to 0.5.

The most common test that I've seen for this is to fit your model and then compare the predicted zero values against the observed zero values. If the observed zero values are much higher, then your model is underfitting and is consequently zero-inflated. This often happens when there is some data generating process that in some part explains differences in zero counts and positive counts, which you hint at below:

For most species, zeros (indicating absence) are much more common than positive values and the data are left-skewed.

I think you mean right-skewed by the way...its impossible for proportional data to be left-skewed unless you've done something weird like inverse coding. In any case, as Roland suggested, you can use something like a zero-inflated regression to overcome this issue. The theoretical justification for using this method is that you treat your dependent variable as a mixture distribution composed of two zero-generating processes: one which is the "zero" model and the other which is the Poisson "count" model (where some of the counts are still zero). Regarding model metrics:

I have read in many answers that RMSE can't be used to compare models if the scale of the dependent variable is different. In this case, the scale is the same, but I'm concerned that the differing proportion of 0s may affect RMSE independently of model performance. Should that be a concern? I could always use $R^2$ instead.

You ought to use both as a guiding metric for how your model is behaving, as they say different things. For learning more about zero-inflated regression (and because you are using R), this link shows how to run this. Hilbe's book on negative binomial models has a lot more information on these models.


How to migrate Link Fields ('title' and 'url') involving local variables?

Question: I have performed the following query:
$query = db_select('sage.USER', 'USER')
  ->fields('USER', array('USER_ID', 'OFFICE_ID', 'USER_PASSWORD'))
  ->range(0, 1);
$result = $query->execute();
...
$url = '/sage/office-' . $result->office_id;
$arguments = MigrateLinkFieldHandler::arguments(array('source_field' => 'office_id'));
$this->addFieldMapping('field_office_id', $url);
  ->arguments($arguments);

However, the above is not working. I would like to manipulate the 'office_id' field to be used as the 'title' and the variable $url to be used as the URL that was linked. I have followed what's on this post
Could someone please point out my mistakes?
EDIT: Updated question to reflect jdu's answer.
Comment: could anyone provide any insight into the correctness of my syntax?
Answer: The link.migrate.inc file is not included in the Migrate Extras module, it's part of the Link module.
The file doesn't exist in the stable version of Link, but it does exist in the dev release. I think you're going to have to install the dev version of Link if you want this to work.
If you install the dev version and still get the error it's most likely because the file is not being automatically included. If that's the case try adding this to the top of your code:
module_load_include('inc', 'link', 'link.migrate');

EDIT
As I mentioned in your other question there's a slight error in your code, you should change this line:
$result = $query->execute();

to:
$result = $query->execute()->fetchObject();

That will return an object representing the first result that was returned by the query.
Comment: Questions are merged if the questions are exact duplicates; in this case, the other question is more generic than this one, and they cannot be merged. Also, the answer for this question ("The `link.migrate.inc` file is not included in the Migrate Extras module") is not the answer for the other question.
Comment: Hi Clive thank you very much. I've found the file and put it in link.migrate.inc and it no longer complains about the file. I am now just getting partial, incomplete migrations of the link 'title' and 'url' fields.
Comment: I just answered your newer question, that might help a bit :)
Comment: Yes it does a lot! I don't know if it's proper, but should I give you the bounty for it? Even though you answered the one without it lol...
Comment: I really don't know to be honest, seems like these questions should be merged but I don't think that can be done when there's a bounty open on one of them. It might be worth asking a question on how best to proceed on the [meta site](http://meta.drupal.stackexchange.com/), I'm sure one of the mods will weigh in :)
Answer: This is how I imported nodes:

Download link.migrate.inc from link 7.x dev version and add this file to your module
Add file entry in your .info module (files[] = link.migrate.inc)
Apply this patch link-migrate_subfields.patch
Then you can use the following code:
$this->addFieldMapping('field_portrait_affiliation_link', 'field_portrait_affiliation_link');
$this->addFieldMapping('field_portrait_affiliation_link:title', 'field_portrait_affiliation_link:title');
$this->addFieldMapping('field_portrait_affiliation_link:attributes', 'field_portrait_affiliation_link:attributes');
$this->addFieldMapping('field_portrait_affiliation_link:language', 'language');

Answer: Fill a new variable with the results of executing your query:
$result = $query->execute();

$url = 'office-' . $result->office_id;

Comment: jdu, still crashing, it says Class MigrateLinkFieldHandler could not be found. I thought this was included in Migrate Extras?
Comment: http://drupal.org/project/migrate_extras

yep, says it's built in.  is there a file called "link.migrate.inc" ?

perhaps installation of the module failed somehow.  I'd upload the module to the directory again, check permissions and dependencies.

there's always the web servers "error_log" file too, just in case something is being generated in there that could be more helpful.
Comment: hmm thanks it really isn't in there...i'll keep digging..
Answer: Have you checked: /admin/content/migrate/configure
There check the Field handlers for the link field:
[x] link  MigrateLinkFieldHandler   link_field
Install the dev version of the Link module. Then this should work:
....
$arguments = array('title' => array('source_field' => 'office_id'));
$this->addFieldMapping('field_office_id', 'field_office_id_path')->arguments($arguments);
...

function prepareRow($row) {
    $row->field_office_id_path = '/sage/office-' . $row->office_id;
}

Comment: $arguments = array('title' => array('source_field' => 'office_id'));

should be

$arguments = array(array('source_field' => 'office_id'));


Windows: View other network shares without sharing anything myself

Question: Using windows, I would like to be able to browse computers and their shares on the network, without publishing any shares, administrative shares, and not even having my computer listed in the "Network" folder on other computers.
When using windows, if I go to the "Network" folder, I get this yellow bar:

If I click and select "Turn on network discovery and file sharing", then my computer appears on other people's view of the network, and they can browse my files.

Basically, if I want to see your files, I must show you mine.
Let's take an example: At work, I visit a client, and need to access some data on a windows share on his network. How can I do that without displaying the confidential information stored on my laptop?
I know how to disable sharing of my home folder, but there are other shares that can't be disabled, they are apparently called "administrative shares", and may be vulnerable to attacks by humans or viruses on the netwok.

Also, access to these administrative shares and to my home folder are protected by my password on that computer, but that can be brute-forced I guess. Also, some people don't have a secure password — or even don't have a password at all.
When using linux to access shares on the windows network, the linux box doesn't publish anything on the network unless you explicitely ask for it (by installing a samba server etc).
How can I get the same functionnality in Windows?
Comment: This question appears to be off-topic because it is a rant masquerading as a question.
Comment: @joeqwerty No, it is an actual question (with a bit of a rant in the way it is presented). I really **do** want to know how I can view shares on the network I'm connected to without risking exposing my data, if that's possible. I currently have disabled file sharing altogether, but it's not a satisfactory solution.
Comment: @joeqwerty I removed the sarcastic line and picture, to make the question look more objective.
Comment: The guy's doing work for clients. I see this a professional question, regardless of him still having a few things to learn about Windows. Voting to re-open.
Answer: Why don't you just browse to <code>\\server\sharename</code> ? You don't have to enable "Network discovery"  on your own workstation for that.
Or, you could enable it, and configure the Windows Firewall properly - it even has different location profiles.
Regardless, you should be using strong passwords and NTFS permissions on your own account(s) and data. Regarding brute-forcing, that's why there are best practices like account lockout, and changing the default administrator name.
It sounds like you might be more of an expert on Linux than Windows? There's a lot to learn about Windows, as you will find. It looks like you're reading more into something than is actually the case.
Comment: I do have a strong password on *my* account, but that measure isn't effective for other people's laptop -- we all know that when you ask them to put a strong password, they end up putting their dog's name :), and I think they shouldn't have to use a strong password to prevent access to a service that shouldn't be offered in the first place. Setting up the firewall is a great idea, though, that way their computers can be configured once and for all. Also, I do know more about linux than windows, but I am aware that there is plenty to know about the latter, so please don't be dismissive :) .
Comment: What does other people's laptops have to do with your question about being a consultant, needing access to your customers' file shares?
Comment: There are other consultants in my company (and I occasionally do some sysadmin tasks, although that's not my primary job), sorry if that wasn't clear.
Comment: So are you asking on behalf of them? Educate them. Don't send out consultants that don't know the technology.
Comment: Windows 10 Pro - that doesn't work.
Comment: @user626528 - what doesn't work?
Comment: browsing to `\\server\sharename` doesn't work with network discovery turned off. There must be something else.
Comment: @user626528 :  Works fine for me on my Windows 10 box at home, tested right now. I turned off network discovery and I can't browse my network, but I can hit UNC paths on other devices on my LAN.
Comment: No idea what makes it different on my PC, but it simply doesn't work. I can ping the target computer, but can't open the UNC path on it.
Comment: And that's fine, but your experience (without an explainer) isn't adding a lot to the conversation.


Como sobrescrever uma imagem sem absolute? HTML+CSS

Question: Meu objetivo é inserir uma imagem de fundo que possa ser escrita por cima com
,
 e etc por cima dela, mas sem o uso do position: absolute pois isso interfere os sub-menus da página aparecendo textos e etc por cima deles quando exibidos !!
Comment: Cara coloca o que vc já tem de código ai, HTML e CSS, da forma como vc peguntou sem o código não da para te dar uma resposta precisa... Talvez o problema nem seja o position, mas a forma como vc mentou o menu. Então quando puder edite sua pergunta e inclua os códigos
Answer: Aqui segue um exemplo, utilizando background-size: cover, ele redefine o tamanho para ser suportado dentro do container que você deseja, no caso toda essa
, mesmo tendo que esticar a imagem ou cortar um pouco dela:

.main-section{
  background-image: url(https://i.imgur.com/ODmMf1p.jpg);
  background-size: cover;
  height: 400px;
  color: #FFFFFF;
  text-align: center;
}
.main-section h2{
  font-size: 30px;
}
.main-section p{
  font-size: 20px;
}

Título Aqui

Texto Aqui

Answer: Não sei se entendi bem, mas poderia tentar da seguinte forma.
Aplica o conteúdo dentro de  e via css aplica.
header {
  background-image:url('add caminho imagem');
  width: 100%;
}


Securing the network: IP conflicts and its solutions

Question: Today I found out that I don't know how to fix IP conflicts.
Say you have a server with IP1
another machine connects and assigns itself IP1.
How do people usually prevent this? How they(you) resolve?
I heard that usually it is secured by ROUTER. Is that correct?
And it is the only way?
UPDATE:
My question was about the situations when some user just assigns server IP to itself and that would cause problems.
But I found out that system administrators just should control all the hosts and machines and never allow users to assign any IP but given by Admin (read as given by DHCP server)
Answer: One way to do it is to assign each server its own vlan.  Any IP ranges that the server should have access to are assigned to that vlan.  They are not permitted to use any IP that falls outside those ranges (the router simply won't route it to them).
The other option is to statically route all traffic for a certain IP to a certain MAC address.  This isn't great, as there's a brief period where if the server gets rebooted another client can claim the MAC address.
Comment: MAC addresses are (typically) not randomly picked on boot.
Comment: I never said they were.  However, if you've got a malicious device on the network, it can easily change it's mac address to be the server's.  Then, they just have to wait for ARP to time out (which usually happens on reboot), and they start getting all the traffic destined for the server.
Comment: that's what port security is for.
Answer: If you had a DHCP server on your network, it would manage a range of IP adresses and assign new clients one of them, making sure no two clients use the same IP at the same time.
Some hardware routers already include a DHCP server (particularly those for home-use) and several Linux distributions include a DHCP server role. Of course clients would have to be configured to use the DHCP server instead of having fixed IP addresses or assinging themselves one (as Windows does when it can't get one via DHCP).
Comment: it is said "manually assigns IP to itself" so it's not about DHCP
Comment: DHCP is indeed the way to do this. with static reservations if needed for the servers, usually outside the dhcp-pool.
Comment: Accepted this because: read UPDATE section
Comment: more importantly, the users should not (nearly always) have the permissions needed to set their own IP addresses in the first place.
Answer: If you are manually assigning IP addresses for devices that are on the same network, it is up to you to ensure they do not conflict.
The usual route is as @PersonalNexus says - DHCP - which can auto-assign them in such a way that you do not get conflicts. This is the simplest for a large network, in fact for very large networks it is the only practical solution.
An alternative, which is very messy (and one I would not recommend), is to have each device on a separate network (and actually run networks to each patch point) - this, however, requires you to set up the router/switch to cope with multiple LANs or VLANs using the same network space so requiring every one to be NAT'ed.
If you are haven't had experience managing network conflicts I would suggest configuring a switch to do this may be exceptionally difficult.
Answer: There is no real way to block users from assigning themselfs IPs by random ( = risk a colliding IP) but to restrict them from assigning the IPs themself - aka by the admin's own hand or by DHCP.
If the network is a little larger it might be a good idea to seperate into client and server vlans with some routing (L3-Switch) in between - so at least the precious servers are safe from these coliding IPs. - but no need for a vlan for each server - just one vlan where only the admin can change things and no user has physical access and just plug in their laptops...
tsg
Answer: With certain switches you can restrict exactly what ip addresses are allowed on each port. For example, on a Cisco you could do:
<code>ip access-list standard fa001
permit 192.0.2.1
int Fa0/1
ip access-list fa001 in
</code>
What this means is that the only ip address allowed to be on the device on Fa0/1 is 192.0.2.1. If the user tries adding other ip address, they'll get no where.
Of course this will only work where each host has a static ip. It might work as well with DHCP!
This is on Cisco, but I'm sure other switches have similar features.
Answer: You have some DHCP server running on your network that gave it this address. Could be a DHCP router/ switch (probably) or just some box with dhcpd running on it. Which makes it kind of a network-server. It is very normal that you get conflicts and other problems when you use both techniques on 1 network.


Access Java local variable via Groovy script

Question: Through Groovy script (meta programming), I can access and modify the variables which are declared in globally in a java class. Even I can invoke or override a java method using the script. But I can not find any way to access the variables which are inside a particular method of class.
Consider a class MethodInjection.java
public class MethodInjection {

static String text = "";

public static void main(String[] args) throws Exception
{
    Execute();
}

public static void Execute() throws IOException
{
    System.out.println("Before Value : "+text);
    String script = loadScript("Path_to_script");
    Script scripting = new GroovyShell().parse(script);
    scripting.run();
}

public static void print()
{
    System.out.println("After Value : "+text);
}

public static void access()
{
    String local ="";
}

static String loadScript(String fileName) throws IOException
{
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try
    {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null)
        {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    }
    finally
    {
        br.close();
    }
}}

And the same Script is :
import methodinjection.MethodInjection

def access = new MethodInjection()
access.text = "Modified"
access.metaClass.access.local = "change"
access.print()
println access.metaClass.access.local

and I got output as
Before Value :
After Value : Modified
groovy.lang.ExpandoMetaClass$ExpandoMetaProperty@75f9ecc

But I need to modify local variable and print it through Groovy script.
Tried many ways but could not found any
Comment: You can use a Java bytecode manipulation library. In any case all this doesn't look like a good idea, why are you doing all this?
Comment: what makes you think this is/should be possible?
Answer: Short answer: Groovy cannot do that.
Longer answer: In the end Groovy depends on what the JVM and Reflection do offer. It was actually on purpose to not include features, which require the transformation of the bytecode for "normal" Groovy logic like meta programming. Local variables exists only as "slots" that may have a name in the methods bytecode. Thus you would need a bytecode manipulation library as was mentioned here already.


How to adapt guitar playing style to a new genre

Question: I have been playing guitar for about 7 years now. I've started with classical guitar, grew up with punk music and I have a decent playing style.
I've freshly started in a band who plays metalcore (I've been listening to that genre for about a year, but I've never played it). We are two guitar players and while the other guitarist is a die-hard metal guitarist, my techniques are way too "punky" and not precise enough for being an essential part of the band. He advised me to learn this song to get started with metal/metalcore basics.
I really struggle with precision and the typical "djent" or "chuck" guitar technique (fast strumming on the lowest string, same rhythm as the double bass) and I need help to learn that technique. I am extremely motivated to learn a whole new genre and to get more technical!
Do you guys have any good advice on how to approach a whole new genre without getting frustrated and on how to be a precise guitarist?
Comment: The videos linked in [this question](http://music.stackexchange.com/questions/20652/scalpel-technique-in-guitar) go into several techniques of speed picking.
Comment: Asking Alexandria wouldn't have been my first choice but alternate picking is a key technique to materialize in Metalcore its mostly 4/4 timing signature and above 150bpm so teaching your brain the alternate picking manoeuvre would be very beneficial look at the likes of early Bullet for My Valentine, All That Remains and Trivium. you will be surprised to know that metal has punk influences in some of its riffs and structures.
Comment: @muffin haha no problem the list goes on I would run out of characters on the comments section if I named them all :P. Heres a few more to get the creative Juices flowing stemming from Metal core to thrash to Groove Metal. Lamb of God, Disturbed, Hatebreed, As I Lay Dying, Killswitch Engage, Atreyu, Avenged Sevenfold, Chimera.
Answer: Like almost everything it's about practice, practice, practice. That aside, there are some other things to consider. What string gauge are you using, and what tuning? Usually quite thin strings are used since less force is needed, which makes it easier to play with precision.
Pay attention to your picking hand. Make sure there are no wasted movements. The movement should be in the wrist and not the whole arm. That is quite hard when you're trying to play stuff that's faster than you can handle at the moment.
There's some quite fast picking in the song in the video. I think you would need to start with something slower and easier. Back in the day Seek and destroy by Metallica was the ubiquitous stating point for the aspiring thrasher. Maybe your band mate can give you suggestions for other songs?
Answer: A great first band for learning metal is Lamb of God. Their songs are very "note-y" but not too fast/crazy or discouraging. The first song I learned by them (and really the first metal song I learned period) was "Laid to Rest." Super fun to play at that point in time.
Answer: Pick a metal band you like and learn the album from beginning to end,  don't be afraid to slow the tempo down as guitar playing is about muscle memory. Practice practice practice and slowly speed it up once you feel comfortable. There is no shame in slowing it back down after speeding it up if you struggle a bit and be patient.


Vetor de grande tamanho em C

Question: Estou estudando os tipos de dados da linguagem C. E hoje eu resolvi criar um vetor de tamanho muito grande, no caso, 10^8. Então, fiz um pequeno código em que declaro esse grande vetor (Sendo que o valor 10^8 cabe no tipo Int), preencho suas posições e tento acessar um determinado elemento dele. Porém, o programa não está sendo executado corretamente, nada acontece, embora nenhum erro de compilação esteja sendo exibido. Poderiam me indicar qual a forma correta de se criar um vetor de tamanho tão grande? Desde já obrigado!
<code>#include <stdio.h>

int main() {
  int vet[100000000], i;

  for (i = 0; i < 100000000; i++)
    vet[i] = i;

  printf("%d", vet[200]);

  return 0;
}
</code>
Comment: Aqui https://ideone.com/8qyNex rodou corretamente. Mas vai depender de seu ambiente e da memória disponível.
Comment: Complementando: dê uma estudada em stack e heap para entender a alocação de memória e porque quando se utiliza alocação dinâmica pode fugir do stack overflow.
Answer: Existe um limite para alocação de memória para um processo/programa, isso é válido para qualquer linguagem de programação e ambiente. Se você ultrapassa determinado limite, processos no computador começarão a travar por falta de memória disponível (isso inclui processos do próprio Sistema Operacional). Provavelmente você atingiu esse limite.
Você pode, em vez de alocar estaticamente a memória para um vetor de 100000000 elementos (4 bytes x 100000000 = ~400 MB), utilizar o mecanismo de alocação dinâmica de memória da linguagem C.
Como funciona: Você aloca a memória necessária para armazenar uma unidade de informação no vetor por vez. No seu caso, a unidade de informação é um int (4 bytes) (desprezando informações de endereçamento e ponteiros).
Você pode ver mais detalhes sobre este processo neste link.
Mas reforçando, isso não vai resolver o seu problema de alocar um vetor deste tamanho ou maior. Para isso você vai precisar de mais memória disponível.

Vetor de grande tamanho em C


Setting up custom email addresses for domain bought from Digital Ocean

Question: I have a domain name hosted on digital ocean, 'www.mydomain.com' and hosting an application made in django. I need to create an email address 'email@example.com'. I have searched on a way to do this from start to finish but cant get a definite answer. Need some guidance.
Comment: This question is not related to Django, but a general problem how to setup email infrastructure for your domain and not strictly a programming question. ServerFault would be a better forum.
Comment: digital ocean sells domains?
Answer: Digital Ocean does not provide an e-mail component. You can either install and setup your own e-mail server from scratch, which you don't want to do. Or use an e-mail hosting service provider, zoho.com is a free one. There are others. Rackspace, and Google offer e-mail host solutions, but they are both fee-based.
Once you sign up for an e-mail hosting account, zoho.com or whichever e-mail service provider you choose will provide you with an MX record setup. You will then add an MX record to your DNS records on your Digital Ocean domain.
This will connect your domain name to the e-mail hosting service.
After this, you need to setup your e-mail on the e-mail hosting service. THis is a non-trival task and you'll have to do reading on SMTP, POP, IMAP etc. There is plenty of help on the zoho site.
Make sure to test sending and receiving e-mails to make sure the setup is working.
Once you have working e-mail on your domain, then you can move on to using it in your Django app.


How to Update SQL Query's Result in a separate column

Question: I have used following PostgreSQL query to find the time difference between end time and next start time with different source IDs.
SELECT obu_id, trip_id, start_time, end_time, dwell_time
     , end_time - LEAD(start_time) OVER(PARTITION BY obu_id ORDER BY start_time) AS diff
 FROM clean_trips_byobu;

What I am trying to do is update the column dwell_time with the results being shown in diff(temporary result, Its not being stored anywhere) and to insert a value "-1"  as instead of empty space. Please refer to the following screenshot.

Desired result:
obu_id trip_id  start_time            end_time              dwell_time  diff
2      135736   2004-10-29 15:22:14   2004-10-29 16:13:37   -02:01:42   -02:01:42
2      135738   2004-10-29 18:15:19   2004-10-29 18:28:37   -1
3      137826   2005-03-17 17:56:41   2005-03-17 18:02:31   -00:05:30   -00:05:30
3      137826   2005-03-17 18:08:01   2005-03-17 18:12:10   -00:07:51   -00:07:51
3      137826   2005-03-17 18:20:01   2005-03-17 18:27:51   -14:51:24   -14:51:24

Answer: My educated guess what you might be after:
UPDATE clean_trips_byobu c
SET    dwell_time = COALESCE(u.diff, interval '-1 hour')
FROM  (
   SELECT id, ref, start_time, end_time
        , end_time - lead(start_time) OVER (PARTITION BY id ORDER BY start_time) AS diff
   FROM   clean_trips_byobu
   ) u
WHERE (c.id, c.ref, c.start_time, c.end_time)
    = (u.id, u.ref, u.start_time, u.end_time)
AND c.dwell_time IS DISTINCT FROM COALESCE(u.diff, interval '-1 hour');

Use COALESCE() to replace NULL with a default interval.
Use the query as subquery in your UPDATE. Join on a unique set of columns.
If you already have values in diff, add the last line to prevent empty updates.

You should have a simpler way to identify rows than the combination of 4 columns. I suggest a surrogate primary key. Can be done with this single line of code:
ALTER TABLE clean_trips_byobu ADD COLUMN ctb_id serial PRIMARY KEY;

See:

Do I need a primary key for my table, which has a UNIQUE (composite 4-columns), one of which can be NULL?


A graph defined by a set of positive integers

Question: I'm struggling to find a proof for this proposition from chromatic graph theory by bundy.
Let be $S$ a set of positive integers, with maximum element $n$. There exists a graph $G$ on $n+1$ vertices such that:

For each vertex $u\in V(G)$, we have that $d(u)\in S$
For all $k\in S$ there exists a vertex  $v\in V(G)$ such that $d(v)=k$

What I try is using induction in the cardinality of $S = n$, for $n =1$ we have the complete graph, and when $n=2$, we if we have $m_1$, $m_2$ if $m_1$ is less than $m_2$, we can make the complete in $m_1$ vertex and then combine with $m_2- m_1 + 1$ vertex using the product between graphs, but when I try to make the inductive step I get stuck, I try removing $n$, and decrease all elements 1 degree if I have 1 in $S$ it's easy just add the vertex who are going to need since we don't know if the second bigger element is $n - 1$. But if 1 is not in $S$  I don't know how to proceed.
Is this the right approach?
I would prefer a hint, or a suggestion on another approach
Comment: What is $d(u)$?
Comment: The degree of a vertex, thanks
Comment: The set of positive integers is universally called the natural numbers, $\Bbb{N}=\{1,2,3,4,\cdots\}$.
Comment: Only if is inductive
Answer: As far as I can tell, it's possible to modify your attempts to work in each case.  As requested...
Hints:

There's two ways of applying induction: deleting $n$ from $S$, and subtracting $1$ from everything in $S$.  They work in different cases.
When $n-1 \not\in S$, try replacing $S$ with $S \cup \{n-1\}$.

But for those who don't want hints...  we induct on $n=|S|$.  Base cases: it's true when $n=1$, realized by $K_2$, and when $n=2$ realized by $K_3$ and $K_3$ minus an edge.  Now assume $n \geq 3$.
Case I:  $1 \in S$ and $n-1 \in S$.

 We apply induction to $S':=\{d-1:d \in S \setminus \{n,1\}\}$.  Since $\mathrm{max}(S')=n-2$, we get an $(n-1)$-vertex graph with degree set equal to $S'$, then we (a) add an isolated vertex, and (b) add a vertex and connect it to every other vertex.  This gives an $(n+1)$-vertex graph with degree set equal to $S$.

Case II: $1 \in S$ and $n-1 \not\in S$.

 We apply induction to $S':=(S \setminus \{n\}) \cup \{n-1\}$.  Since $\mathrm{max}(S')=n-1$, we get an $n$-vertex graph with degree set equal to $S'$, and add a pendant edge to the degree-$(n-1)$ vertex (noting that there can only be one, otherwise we contradict $1 \in S'$).

Case III: $1 \not\in S$.

 We apply induction to $S':=\{d-1:d \in S\}$.  Since $\mathrm{max}(S')=n-1$, we get an $n$-vertex graph with degree set equal to $S'$, then we add a vertex and connect it to every other vertex.  This gives an $(n+1)$-vertex graph with degree set equal to $S$ (we end up with $2$ degree-$n$ vertices).

And I note that in all three cases the modified $S$ is non-empty, so has a maximum element.
Comment: Okay, I can phrase it that way.
Comment: I'm not sure I follow case II: surely if we add an edge to the only degree 1 vertex (i.e. the pedant vertex), then our graph no longer has any vertex with degree 1. However, case II requires that $1\in S$
Comment: We add a new vertex, and add an edge from it to the vertex of degree n-1.  This both creates a degree-1 vertex, and changes the unwanted degree-(n-1) vertex to a degree-n vertex.
Answer: I can do point 2. Still working on 1.
Let's try to draw $G$ given $S$. The maximum element of element is $n$. It is clear that we can have a vertex in a graph with $n+1$ vertices whose degree is $n$.
The other possible elements in $S$ are $1,2,...,n-1$ since $n$ is the largest element ($S$ may have only some of these).
It is no problem to draw a graph $G$ on $n+1$ vertices whose degrees have a degree among $1,2,3,...,n-2,n-1$ and each of the numbers $1,2,3,...,n-2,n-1$ is the degree of at least one vertex as follows. Label the vertices of $G$ by $v_1,v_2,...,v_n,v_{n+1}$. Give vertex $v_1$ degree $n$ (by making it adjacent to all of $v_2,v_3,...,v_n,v_{n+1}$). Then give vertex $v_2$ degree $n-1$ (by making it adjacent to enough of $v_3,...,v_n,n_{n+1}$, starting from the leftmost vertex in the list, to give $v_2$ degree $n-1$). And so on. Yuu will end up with two vertices of the same degree.
Now, suppose that one of the numbers $1,2,3,...,n-2,n-1$ is not contained in $S$. The graph described above still satisfies the requirement, since all the possible numbers that could be in $S$ (i.e. $1,2,3,...,n-2,n-1$) are the degree of at least one vertex of $G$. So we are done.
Comment: I misunderstood the question, I thought that was an iff
Comment: Ah ha, so point 1. is not required?
Comment: If that's true, please update your question :)
Comment: I believe the problem is to show that, given any nonempty finite set $S$ of positive integers, there is a graph of order $n+1$ whose degree set is exactly equal to $S.$
Comment: The first comment by Edgar M suggests otherwise.


FreeIPA AD Trust based Integration using SunLDAP to store Policies

Question: If we want to use the FreeIPA Active Directory Trust Integration Option, can we use an existing implementation of SunLDAP to store the Policies (e.g. sudo, hbac etc.)
Essentially we don't to create another LDAP Directory just for storing the Policies.
Comment: The purpose of the IPA/AD trust is to store user accounts in AD, and policy in IPA. If you don't want policy in IPA, what do you want IPA to do?
Comment: Hi Andy, we do want IPA to maintain the policies, but just want to use SunLDAP instead of 389 Directory Server for storing the policies. AD would be System of Records for the User Accounts.
Answer: This is not possible as Alexander explained on freeipa-users: http://www.redhat.com/archives/freeipa-users/2016-June/msg00294.html
Comment: I guess my question is why it can't be done. Both 389DS and SunLDAP are LDAP complaint. So it should be possible. Right?
Comment: FreeIPA has a ton of plugins that only work with 389DS and IPA depends on them.


How do I theme a webform?

Question: I am in need to theme webform in D7.
How can I do that ?
In the search I've come to know that by using web-form-nid.tpl.php we are able to theme a drupal individual form.
Could any one guide me in this case to theme a webform.
Comment: There is a THEMING.TXT included with the module: http://drupalcode.org/project/webform.git/blob/HEAD:/THEMING.txt, which is listed on the module's documentation page under THEMING: http://drupal.org/documentation/modules/webform
Answer: You can theme a individual webform using webform-form-nid.tpl.php.
For example if our webform node id is 7 , create a template file namely webform-form-7.tpl.php and place it in your theme folder. Clear site cache.
Do a print_r($form); to see all the elements. Then render each elements in file within your html elements.

    <?php print drupal_render($form['submitted']['name']); ?>

As  @Patrick Kenny said read the theming.txt, it explain all aspects of theming a webform
Comment: Or, alternatively, to render submit, you can just do: . It will render everything else that you haven't specifically rendered, which for my form I'm working on now is just the submit button.
Comment: I can't figure out how to render the submit button, please can you help
Comment: Can you specify what have been you tried so far and where you struck at?   The submit button can render by something like this   Do a print_r($form); for better understanding.
Answer: If you know the .tpl.php filename, here is what you do:

Create empty file with that name in your theme. Element it was supposed to template disappeared? Good.
Put simple html tag and see if it is displayed in place of your element. It is? Great, you have correct template file.
See all variables you can use: place
<?php print_r(get_defined_vars()); ?>
 in your template.
Now when you have a file and data structure, just do it!

How do I theme a webform?


How many data points for my new product do I need to tell if my new product performs differently to the old?

Question: We've been using the old formula to produce a product for years. We take a sample every quarter or so and run it through 8 different quality tests (every quarter because it takes that long for the tests to complete). Currently 53 samples of the old formulation have been put through these tests.
One of the components of the old formula became unavailable so we're using a new formula that replaces the unavailable component with what we believe is a suitable substitute. Again, every quarter or so, we're going to take a sample and run it through the same tests as we did for the old formula.
How many samples of the new formula are we going to have to test to be confident we can tell whether the new formula is "significantly different" or "not significantly different" to the old formula?
(Whether it is significantly different or not is beside the point, I just want to know when we can be 95% confident that we are reaching the right conclusion - different or not different - rather than having to wait for 53 samples and 13 years to find out).
If the answer to this question is "it depends", could someone please explain what it depends on? Much gratitude.
Comment: You should search around for "minimum detectable effects." A paper that I usually recommend is "Minimum Detectable Effects: A Simple Way to Report the Statistical Power of Experimental Designs" by Howard Bloom in *Evaluation Review* 19(5) (October 2005). My library proxy isn't working right now or I'd try to find a link for it. It's a pretty gentle introduction to the subject and offers formulas for calculating the necessary sample sizes.
Answer: This is more of an extended comment than an answer, sorry.  The concept you are after is "power", and the text below might help you get started.
It's useful in these situations to be very careful with terminology.  I advocate saving the word "significant" to describe statistically significant evidence; and using "material" to mean significant in the way you use it.  Otherwise one quickly becomes tangled up on "statistically significant".  Statistically significant actually is usually shorthand for "there is evidence of a non-zero difference between the two".  If you get a big enpough sample almost inevitably you will reach this point.
One of the things "it depends" on then is how material a difference has to be before it matters to you.  Ie is a 5%, 1%, 0.1% deviation in quality the maximum permissable.
Another thing is whether you are interested only in detecting the bad case (new formula is materially worse) or in either direction of change (materially different).
A third thing that makes a big difference is the variance in measurements of the quality.  Is each of your 53 observations so far identical (probably not), and if not, how much do they vary (ie what is their standard deviation)?  A possible complication is in if the quality has been changing systematically over time eg improving as techniques got better; so you would need to carefully look at that too.
The final thing it depends on is how much different the formulae in reality are - which obviously you don't know.  Typically we can get around this by calculating the power of a statistical test as a function of the unobserved population difference ie we can say "if the real difference is Y, the probability of us incorrectly concluding from our observations so far that the difference is zero is X", and calculating this for all plausible Ys (you will see from this why it is important to think through what difference would be material for you).
Comment: While that didn't answer the question, the commentary was helpful, and I think pointed me in the rigt direction. You're right. a 0.01% difference is not material and we won't care - or even notice given the already present batch-to-batch variation, but 50% improvement or reduction in performance - thats big news.


PHP page to remember visitor's selection to forward them automatically on their next visit

Question: After extensive research, I can't find the solution anyway for this, and it's frustrating and after days of smashing the keyboard, shouting at the sky and taking long meandering walks to calm down - we've all been there! But what's worse, I'm pretty sure my hairline has receded a fair bit from all this...
What I have found, either sniff out the IP to automatically redirect you or uses a form to set the cookie, non of which help, unfortunately.

I have a PHP country landing page
within a WordPress template.
It has 2 images, one is UK and
points to [domain]/UK, the other is
IE and points to [domain]/IE.
When a user initially clicks their
country/image, I'd like a cookie to
be set.
So the next time they visit that
page, they're directed to their
initial selection automatically.
Reference site here: http://goo.gl/9hEI8

I've tried and tried to get something working but I just can't get my head around this one.
Help me Obi Wan Kenobi your my only hope, thank you!
Comment: It would be nice to see your corresponding code
Answer: First of all you need to identify the user. The easiest way is to store an HTTP cookie in the visitors' browser.
You can set this with PHP, JavaScript, it does not matter because the stored cookie will be the same regardless of the method you select. But you need to aware of that the maximal age of the HTTP cookie needs to be set to a month or so.
On the second visit you check the stored cookie on the server side and redirects the user to the selected page (but keep in mind that an option should be there to change this first decision).
So, the steps:

check whether a cookie exists ($_COOKIE array in PHP)
if does not exist show the selection page
if the user selected store his/her decision with setcookie for example
if it does exist, redirect to the previous selection with header("Location ...") redirect