red borders are not coming outside of input types while error in angular

Question: app.module.ts
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { InputFormatDirective } from './input-format.directive';
    import { ContactFormComponent } from './contact-form/contact-form.component';

    @NgModule({
      declarations: [
        AppComponent,
        InputFormatDirective,
        ContactFormComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        FormsModule,
        ReactiveFormsModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

contact-form.component.ts
    import { Component } from '@angular/core';
    import { FormGroup, FormControl, Validators } from '@angular/forms'

    @Component({
      selector: 'contact-form',
      templateUrl: './contact-form.component.html',
      styleUrls: ['./contact-form.component.css']
    })
    export class ContactFormComponent {
      form = new FormGroup({
        username: new FormControl('', [
          Validators.required,
          Validators.minLength(3)

        ]),
        password: new FormControl('',[
          Validators.required
        ])
      });

      get username(){
        return this.form.get('username');
      }
      get password(){
        return this.form.get('password');
      }
    }

contact-form.component.html
    <form [formGroup]="form">

        Username
        <input
            formControlName="username"
            id="username"
            type="text"
            class="form-control"
        />

                Username required

                    Username should be min {{ username.errors.minlength.requiredLength }} char

        Passowrd
        <input
            formControlName="password"
            id="password"
            type="text"
            class="form-control"
        />

                Password Required

    <button class="btn btn-info" type="submit">Sign Up</button>
    </form>

Here i am adding angular custom validations.
It is working for error messages but my borders of input types not becomes red.
I found the same this from one tutorial but the red borders outside is not coming.
Please have a look into my code.
I want red borders outside input types.
Comment: try this in your styles `.ng-invalid { border: 1px solid red; }`
Comment: Not working bro.
Answer: Add this on your style.css;
.ng-invalid.ng-touched:not(form) , .ng-invalid.ng-dirty:not(form){
    border: 3px solid red;
}

Other way
In your style.css;
.invalid-input{
border-color:red !important;
}

and on your inputs:
<input [class.invalid-input]="password.touched && password.invalid" formControlName="password" id="password" type="text" class="form-control"/>

Comment: I did not understand what you said. By default, you want the border color to be red? Or are you talking about something different? @soubhagya
Comment: No. I think in custom validation automatically border should become red or we need to make it customly
Comment: Okey, i understand you. I found this, maybe it'il work; .ng-invalid.ng-touched , .ng-invalid.ng-dirty{
    border-bottom: 3px solid red;
}
Comment: And here is a my working sample: https://stackblitz.com/edit/angular-zh9y8i @soubhagya
Comment: PLease check above url
Comment: I added this on your  style.css, and it's working: .ng-invalid.ng-touched:not(form) , .ng-invalid.ng-dirty:not(form){
    border: 3px solid red;
} https://stackblitz.com/edit/angular-9de3ym what is wrong?


Is the set of regular points in a scheme open in general?

Question: In the situation when smooth/k coincides with regularity (for a finite-type k scheme edit: k also perfect, thanks Remy), I think this should be true (?). But I am not sure about the situation for a general scheme.
Maybe there is a scheme consisting only of singular (non-regular) points? Oh, there is, I think: $k[x]/x^2$. But this doesn't answer my question about openness.
By regularity I mean that local ring is a regular local ring, i.e. the dimension of the Zariski tangent space is the same as the dimension of the local ring.
Comment: The regular locus is open for schemes of finite type over any field. In fact, quite a lot is known even in the case where the base is not Spec(k). See [here](http://stacks.math.columbia.edu/tag/07R2)
Comment: Two remarks: (1) For $X$ a variety over a field $k$, it is not true that the smooth points and the regular points coincide. This is only the case if $k$ is perfect. (2) Any localisation of a regular local ring is again regular. Thus, the regular locus is closed under generisation. Unfortunately, this does not yet prove that it's open, but it would follow if we know for example that the regular locus is constructible.
Comment: And yes, for varieties over a perfect field $k$ you can use the Jacobian criterion to prove that the set of smooth points is open (although it could be empty, as you noted).
Answer: No. According to this mathoverflow post, there is an example of an affine Noetherian integral scheme of dimension 1 whose regular locus is not open, see Exposé XIX of the volume "Travaux de Gabber" in Astérisque 363-364.
See comments by Remy and Rieux for nice sufficient conditions for the regular locus to be open.


Integrating the inverse-Wishart density

Question: It is alleged in this question and in the Wikipedia article and elsewhere that the density function for the inverse-Wishart distribution with $n$ degrees of freedom on $p\times p$ positive-definite symmetric matrices is
$$
f(X) = c\times (\det X)^{-(n+p+1)/2} \exp\left( -\frac{1}{2} \operatorname{tr} \left(\Sigma X^{-1}\right) \right)$$
where $\Sigma$ is the scale matrix and $c$ the normalizing constant.
With respect to what measure is this the density? One could guess that it means
$$
\Pr( X\in A) = \int_A f(X) \prod_{i,j} dx_{ij}
$$
where $x_{ij}$ is the $ij$ entry of the matrix $x,$ i.e. it's with respect to Lebesgue measure on a $p^2$-dimensional space. But then it's really a $p(p-1)/2$-dimensional space, since $x$ is symmetric, and that complicates the question. And that's something of a wild guess. The bounds of integration would be messy since the support of the density is the space of symmetric positive-definite matrices.
Answer: In complete analogy to the (non-singular) Wishart distribution with $n$ degrees of freedom, for $n \in \mathbb N_{\geq p},$ the function $f$ can be interpreted as a joint probability density of the $p(p+1)/2$ distinct entries of $X$, e.g. of $\mathrm{vech}(X)$, w.r.t. the corresponding Lebesgue measure defined by
$$
\mathrm d\hspace{0.05em} X = \prod_{1\leq j \leq i \leq p} \mathrm d\hspace{0.05em} x_{ij}.
$$

Integrating the inverse-Wishart density


Consecutive visits

Question: My stat for consecutive visits is missing a day and was reset on Saturday, 12 October. I did visit that day on my mobile phone a number of times and yet it wasn't registered for some reason...
I had over 200 consecutive days prior to this issue.
Comment: Get a life, you two! *(/me checks consecutive stats...)*
Comment: You should ask for you money back.
Comment: I ran into this with mine just 8 days shy of hitting 100. I was so peeved...would have gotten that pretty little gold badge!!
Answer: I see you hit the site from your smart phone several times on Sat, 12 October, but you didn't actually use the site. Looking at the home page does not count.
Unfortunately, after years of following up on reports of bugs for "missed days", I have never (not once) come across a case of miscalculating hits for the Enthusiast or Fanatic Badge.
More often than not, the problem is that Stack Exchange uses the UTC timezone… so if you visited the site on one day, and then much later on the next day, it is possible to miss the 24-hour windows in Stack Exchange time. We see a lot of "missed days" over the weekend because their routine of when they visit changes over the weekend. That's not what happened in this case, but it is quite common.
Another common problem is when users visit the site using their smartphone and don't realize they are not logged in. You were fine there, too, but that happens a lot.
I know this all seems a bit wonky, but no matter what timezone we choose, users are going to live in a different timezone. Unfortunately, we haven't been able to make it any easier for well-meaning folks to earn the badge without inviting large-scale cheating from others.
Sorry about the inconvenience. I hope it works out better the next time.
Comment: Thank you for *actually* looking into it -- you're absolutely right, hitting the home page was probably what I did those days. I didn't realize that didn't count - will be mindful for the future.
Comment: In addition, I already have the Fanatic badge - tmk it can't be awarded more than once - it was more a question of knowing exactly how addicted I am! thanks again.

Consecutive visits


A 3rd grade math problem: fill in blanks with numbers to obtain a valid equation

Question: Even though this is a 3rd-grade math problem, people found it extremely hard. Any people have a solution, or algorithm is welcome. I'll try make a program base on the algorithm and see if it's correct. And, people are welcome to provide the best solution (least loop, recursion)
Enough said, here's the original: Fill in the blank the number from 1-9 to complete the equation. (probably distinct numbers each blank)

PS: Help me with tags. I'm not sure which tags should I use.
EDIT 1: After a few shortened, here's what I've got:
a + d - f + 12*e + 13*b/c + g*h/j = 87.

So, as you see, the priority does matter.
EDIT 2: Maybe my description is not clear enough, but I think it require to use every number
Like this: an array from [1:9], each fill in the blank remove one component.
As Martigan point out, it's like: fill in the blanks using once and only once each number from 1 to 9. Simple math here: There are 9*8*7*6*5*4*3*2 = 362880 possibilitities. (You may correct this simple math if I'm wrong).
And b mod c should = 0 (as only integers appear.)
EDIT 3: I just asked my mom (who's an elementary teacher). She's confirmed that 3rd grade has studied about mathematic priority, so sorry Hagen von Eitzen. Your answer is half right, she'd give you an 7/10.
PS2: People, please share your wisdom and provide the math algorithm.
Sorry for my bad English.
Comment: It's divide. X = multiple, : = divide. + = Plus. - = Minus.
Comment: What does the colon : mean in those two boxes?
Comment: Why not just put a zero in every box except that last (empty) one and make that one $76$?
Comment: Even if you did that, it's doesn't equal to the end. I'll edit the question.
Comment: You have many many possible solutions. I don't see the point of the problem? Do you want a specific solution? What is the criterai to put forward as a measure of success?
Comment: There are nine unknowns, $x_1,\dots,x_{9}$.  Here's a possible solution: $x_1=76$,  $x_2=x_4=x_5=x_6=x_7=x_8=0$, $x_3=1$, $x_{9}=1$.
Comment: $76$ $0$ $1$ $0$ $0$ $0$ $0$ $1$ $1$ is a solution. Grilled by @Gregory Rant
Comment: 1 -> 9 means 9 unknowns. Only 362880 try (because distinct numbers). But only of them true.
Comment: As a general comment, you can reduce the problem by stating all products to 0, and keep only one positive and one negative term ($a$,$f$)... You can do what you want then.
Comment: I would like to have an algorithm to this problem, with have the least loop as possible.
Comment: @Eddie Thanks I fixed it
Comment: Do you want to use once and only once each number from 1 to 9? This would be a different and trickier problem.
Comment: Probably that is. It's not that easy to solve as you point earlier. That's why i'm having a headache here. It's 3rd-grade math problem :( dafaq my country is thinking?
Comment: @Eddie just wondering, how are you so sure it is a third grade problem?
Comment: It's in one of their math exercise book.
Answer: I assume that (as usual in this type of problem) the operations are executed left toright (not by arithemtic priority). Here are the solutions:

[9, 4, 8, 6, 7, 3, 1, 2, 5]: $9+13=22$, $22\times 4=88$, $88:8=11$, $11+6=17$, $17+12=29$, $29\times 7=203$, $203-3=200$, $200-11=189$, $189+1=190$, $190\times 2=380$, $380:5=76$, $76-10=66$.
[9, 7, 2, 8, 4, 3, 6, 1, 5]
[9, 6, 3, 8, 5, 7, 2, 1, 4]
[9, 1, 4, 8, 2, 7, 5, 6, 3]
[9, 5, 3, 8, 1, 2, 7, 6, 4]
[9, 2, 4, 7, 8, 6, 5, 1, 3]
[9, 3, 2, 4, 8, 7, 6, 1, 5]
[9, 3, 2, 7, 6, 5, 8, 1, 4]
[9, 5, 3, 7, 1, 2, 8, 6, 4]
[9, 4, 3, 5, 2, 1, 8, 6, 7]
[9, 3, 2, 6, 1, 7, 5, 8, 4]
[9, 3, 2, 5, 1, 7, 6, 8, 4]
[8, 9, 7, 1, 4, 2, 5, 3, 6]
[7, 9, 8, 5, 6, 2, 4, 1, 3]
[7, 9, 4, 8, 6, 2, 3, 1, 5]
[7, 9, 5, 8, 3, 6, 1, 2, 4]
[2, 9, 4, 3, 8, 6, 7, 1, 5]
[7, 9, 5, 6, 1, 8, 3, 4, 2]
[7, 9, 5, 3, 1, 8, 6, 4, 2]
[1, 9, 7, 5, 2, 8, 6, 4, 3]
[1, 9, 7, 3, 5, 8, 6, 2, 4]
[3, 9, 6, 5, 4, 8, 7, 1, 2]
[6, 9, 3, 1, 4, 8, 5, 2, 7]
[1, 9, 3, 7, 2, 5, 8, 4, 6]
[1, 9, 6, 2, 3, 7, 8, 4, 5]
[4, 9, 3, 2, 6, 7, 8, 1, 5]
[3, 9, 4, 6, 5, 1, 8, 2, 7]
[2, 9, 5, 7, 1, 3, 6, 8, 4]
[2, 9, 5, 6, 1, 3, 7, 8, 4]
[7, 9, 5, 6, 3, 1, 2, 4, 8]
[1, 9, 7, 2, 5, 3, 6, 4, 8]
[8, 6, 9, 7, 5, 3, 1, 2, 4]
[8, 3, 9, 5, 7, 6, 1, 2, 4]
[8, 6, 9, 5, 2, 1, 7, 4, 3]
[8, 5, 9, 3, 6, 4, 7, 1, 2]
[8, 1, 9, 3, 4, 2, 7, 6, 5]
[8, 6, 9, 3, 5, 2, 1, 4, 7]
[8, 5, 9, 1, 4, 2, 3, 6, 7]
[5, 4, 9, 1, 8, 7, 2, 3, 6]
[5, 4, 9, 1, 6, 8, 7, 2, 3]
[5, 4, 9, 3, 7, 6, 8, 1, 2]
[5, 1, 9, 3, 7, 2, 8, 4, 6]
[5, 6, 9, 7, 1, 4, 3, 8, 2]
[5, 4, 9, 7, 1, 3, 6, 8, 2]
[5, 6, 9, 3, 1, 4, 7, 8, 2]
[5, 4, 9, 6, 1, 3, 7, 8, 2]
[5, 1, 9, 2, 3, 6, 7, 8, 4]
[5, 4, 9, 1, 3, 2, 7, 8, 6]
[5, 1, 9, 2, 4, 3, 7, 8, 6]
[7, 3, 9, 4, 5, 2, 1, 6, 8]
[5, 7, 9, 1, 6, 2, 3, 4, 8]
[2, 6, 9, 1, 7, 3, 5, 4, 8]
[8, 1, 7, 9, 2, 4, 5, 6, 3]
[8, 4, 3, 9, 5, 7, 1, 2, 6]
[8, 1, 3, 9, 5, 2, 6, 4, 7]
[2, 8, 4, 9, 1, 7, 5, 6, 3]
[5, 8, 6, 9, 1, 3, 7, 4, 2]
[7, 6, 8, 9, 2, 5, 1, 4, 3]
[5, 2, 4, 9, 8, 7, 6, 1, 3]
[3, 1, 4, 9, 8, 6, 7, 2, 5]
[7, 1, 3, 9, 6, 8, 5, 2, 4]
[7, 1, 4, 9, 2, 8, 5, 6, 3]
[5, 7, 6, 9, 4, 8, 3, 1, 2]
[1, 7, 6, 9, 3, 8, 2, 4, 5]
[5, 1, 6, 9, 7, 8, 3, 2, 4]
[5, 4, 1, 9, 3, 8, 6, 2, 7]
[4, 6, 3, 9, 7, 2, 8, 1, 5]
[5, 1, 3, 9, 6, 7, 8, 2, 4]
[5, 4, 3, 9, 6, 1, 8, 2, 7]
[7, 3, 6, 9, 1, 5, 4, 8, 2]
[7, 3, 4, 9, 2, 5, 1, 8, 6]
[2, 7, 6, 9, 1, 4, 5, 8, 3]
[2, 6, 3, 9, 1, 7, 5, 8, 4]
[5, 3, 2, 9, 1, 6, 7, 8, 4]
[7, 1, 3, 9, 6, 5, 2, 4, 8]
[7, 3, 1, 9, 2, 5, 6, 4, 8]
[8, 1, 7, 3, 9, 5, 6, 2, 4]
[8, 4, 7, 3, 9, 5, 1, 2, 6]
[8, 4, 6, 5, 9, 3, 1, 2, 7]
[7, 4, 8, 5, 9, 6, 2, 1, 3]
[7, 2, 8, 1, 9, 4, 5, 3, 6]
[3, 4, 8, 7, 9, 5, 1, 2, 6]
[7, 2, 6, 8, 9, 5, 4, 1, 3]
[7, 1, 3, 8, 9, 5, 4, 2, 6]
[3, 6, 4, 8, 9, 7, 2, 1, 5]
[3, 1, 6, 8, 9, 7, 4, 2, 5]
[7, 6, 4, 2, 9, 8, 3, 1, 5]
[3, 7, 6, 5, 9, 8, 2, 1, 4]
[1, 5, 7, 4, 9, 3, 8, 2, 6]
[5, 1, 6, 3, 9, 7, 8, 2, 4]
[3, 2, 6, 1, 9, 7, 5, 4, 8]
[2, 1, 5, 3, 9, 6, 7, 4, 8]
[1, 8, 6, 7, 3, 9, 2, 4, 5]
[6, 8, 4, 5, 3, 9, 7, 1, 2]
[7, 5, 8, 4, 2, 9, 1, 6, 3]
[7, 2, 5, 1, 8, 9, 4, 3, 6]
[1, 2, 7, 5, 8, 9, 4, 3, 6]
[3, 5, 2, 7, 8, 9, 4, 1, 6]
[1, 4, 7, 5, 2, 9, 8, 6, 3]
[1, 4, 3, 7, 2, 9, 8, 6, 5]
[2, 1, 5, 3, 7, 9, 8, 4, 6]
[2, 7, 3, 6, 1, 9, 5, 8, 4]
[2, 7, 3, 5, 1, 9, 6, 8, 4]
[3, 7, 2, 5, 1, 9, 4, 8, 6]
[3, 7, 2, 4, 1, 9, 5, 8, 6]
[1, 4, 7, 5, 3, 9, 2, 8, 6]
[6, 3, 4, 7, 2, 9, 1, 8, 5]
[4, 1, 6, 7, 3, 9, 2, 8, 5]
[5, 1, 6, 2, 3, 9, 7, 8, 4]
[2, 5, 6, 4, 3, 9, 1, 8, 7]
[6, 2, 1, 5, 3, 9, 7, 4, 8]
[8, 1, 7, 5, 6, 4, 9, 2, 3]
[5, 8, 6, 7, 1, 3, 9, 4, 2]
[2, 8, 4, 5, 1, 7, 9, 6, 3]
[1, 7, 8, 6, 4, 5, 9, 2, 3]
[3, 6, 8, 7, 5, 1, 9, 2, 4]
[1, 6, 7, 8, 2, 5, 9, 4, 3]
[2, 1, 5, 8, 6, 3, 9, 4, 7]
[2, 1, 6, 3, 8, 5, 9, 4, 7]
[2, 6, 5, 4, 7, 8, 9, 1, 3]
[7, 3, 6, 4, 1, 5, 9, 8, 2]
[7, 2, 5, 1, 3, 4, 9, 8, 6]
[2, 7, 6, 5, 1, 4, 9, 8, 3]
[1, 3, 7, 5, 2, 6, 9, 8, 4]
[1, 2, 7, 5, 3, 4, 9, 8, 6]
[5, 3, 2, 7, 1, 6, 9, 8, 4]
[2, 6, 3, 5, 1, 7, 9, 8, 4]
[5, 2, 4, 1, 3, 7, 9, 8, 6]
[3, 5, 4, 1, 2, 7, 9, 8, 6]
[4, 5, 1, 7, 3, 6, 9, 2, 8]
[7, 4, 6, 8, 1, 2, 5, 9, 3]
[7, 4, 6, 5, 1, 2, 8, 9, 3]
[8, 7, 3, 1, 2, 4, 5, 6, 9]
[8, 2, 1, 7, 3, 6, 5, 4, 9]
[8, 2, 1, 6, 3, 5, 7, 4, 9]
[1, 8, 7, 2, 6, 3, 5, 4, 9]
[1, 8, 4, 7, 5, 2, 6, 3, 9]
[5, 8, 3, 1, 2, 4, 7, 6, 9]
[3, 7, 8, 5, 4, 1, 2, 6, 9]
[7, 1, 2, 8, 6, 3, 5, 4, 9]
[7, 2, 1, 8, 4, 6, 5, 3, 9]
[1, 4, 2, 8, 5, 7, 6, 3, 9]
[3, 1, 4, 8, 5, 2, 7, 6, 9]
[5, 7, 4, 1, 8, 6, 3, 2, 9]
[2, 1, 3, 6, 8, 7, 5, 4, 9]
[7, 1, 2, 4, 5, 8, 3, 6, 9]
[4, 6, 1, 7, 2, 8, 5, 3, 9]
[1, 2, 4, 7, 5, 8, 3, 6, 9]
[2, 3, 5, 6, 7, 8, 1, 4, 9]
[4, 6, 1, 5, 2, 7, 8, 3, 9]
[2, 7, 6, 4, 3, 5, 1, 8, 9]
[2, 1, 6, 4, 5, 3, 7, 8, 9]
Comment: @HagenvonEitzen: A commenter on this [Huffingtonpost article](http://www.huffingtonpost.com/2015/05/20/vietnamese-math-puzzle_n_7346332.html?ncid=txtlnkusaolp00000592) also arrived at the total of 152 solutions. Apparently, the puzzle was created by Tan Phuong of Vietnam.
Comment: I've just read your answer more closely. Probably you're right, it's not using arithmetic priority. But what if they does? Because grouping using priority reduce the solutions.
Comment: @TitoPiezasIII Look at my answer. There are only 20 solutions. probably the other commenter was wrong, or didn't use mathematic priority. Or my algorithm is not correct? Can you check it at stackOverflow?
Comment: @Eddie: More accurately, if you use one assumption, you get 152 solutions. If you use another, you have just 20 solutions. It depends on how the problem was originally stated.
Answer: There is 1 equation and 9 unknowns, the problem is we have an underdetermined system: http://en.wikipedia.org/wiki/Underdetermined_system.
The only relationship we know (in the typical phrasing of the question) is that they all belong to the set [1...9] and are mutually exclusive. While all solutions can be found using brute force (with a program), I don't believe there is a mathematical way to prove or derive the existence of any solutions since the placement of any number impacts the choices for the remaining numbers and the information is too limited. We know without brute forcing that the system has at most a limited number of solutions. We know from running programs (only after the fact) that the puzzle is consistent and has solutions.
a + d - f + 12*e + 13*b/c + g*h/j = 87
The values of a and d are interchangeable, as are g and h. It does not help us with the problem, but it does show that if at least 1 solution exists, then more than 1 solution must exist; specifically, if you find 1 it has 4 variants since some of the math is commutative.
Comment: So, to summarize, you're saying that there are no mathematical solution to this problem? Brute force is the only way?
Answer: I ask StackOverflow for a programmatic solution, turn out having 20 answer:
2015-05-20 01:44:23.568 Math[29526:3757225] a=3 b=2 c=1 d=5 e=4 f=7 g=8 h=9 i=6
2015-05-20 01:44:23.569 Math[29526:3757225] a=3 b=2 c=1 d=5 e=4 f=7 g=9 h=8 i=6
2015-05-20 01:44:24.074 Math[29526:3757225] a=5 b=2 c=1 d=3 e=4 f=7 g=8 h=9 i=6
2015-05-20 01:44:24.075 Math[29526:3757225] a=5 b=2 c=1 d=3 e=4 f=7 g=9 h=8 i=6
2015-05-20 01:44:24.127 Math[29526:3757225] a=5 b=3 c=1 d=7 e=2 f=6 g=8 h=9 i=4
2015-05-20 01:44:24.127 Math[29526:3757225] a=5 b=3 c=1 d=7 e=2 f=6 g=9 h=8 i=4
2015-05-20 01:44:24.162 Math[29526:3757225] a=5 b=4 c=1 d=9 e=2 f=7 g=3 h=8 i=6
2015-05-20 01:44:24.163 Math[29526:3757225] a=5 b=4 c=1 d=9 e=2 f=7 g=8 h=3 i=6
2015-05-20 01:44:24.290 Math[29526:3757225] a=5 b=9 c=3 d=6 e=2 f=1 g=7 h=8 i=4
2015-05-20 01:44:24.290 Math[29526:3757225] a=5 b=9 c=3 d=6 e=2 f=1 g=8 h=7 i=4
2015-05-20 01:44:24.381 Math[29526:3757225] a=6 b=3 c=1 d=9 e=2 f=5 g=7 h=8 i=4
2015-05-20 01:44:24.381 Math[29526:3757225] a=6 b=3 c=1 d=9 e=2 f=5 g=8 h=7 i=4
2015-05-20 01:44:24.548 Math[29526:3757225] a=6 b=9 c=3 d=5 e=2 f=1 g=7 h=8 i=4
2015-05-20 01:44:24.548 Math[29526:3757225] a=6 b=9 c=3 d=5 e=2 f=1 g=8 h=7 i=4
2015-05-20 01:44:24.630 Math[29526:3757225] a=7 b=3 c=1 d=5 e=2 f=6 g=8 h=9 i=4
2015-05-20 01:44:24.630 Math[29526:3757225] a=7 b=3 c=1 d=5 e=2 f=6 g=9 h=8 i=4
2015-05-20 01:44:25.115 Math[29526:3757225] a=9 b=3 c=1 d=6 e=2 f=5 g=7 h=8 i=4
2015-05-20 01:44:25.115 Math[29526:3757225] a=9 b=3 c=1 d=6 e=2 f=5 g=8 h=7 i=4
2015-05-20 01:44:25.143 Math[29526:3757225] a=9 b=4 c=1 d=5 e=2 f=7 g=3 h=8 i=6
2015-05-20 01:44:25.143 Math[29526:3757225] a=9 b=4 c=1 d=5 e=2 f=7 g=8 h=3 i=6
2015-05-20 01:44:25.294 Math[29526:3757225] Result: 20 correct / 362880 total

Not sure how it will look like as a mathematic problem.
Comment: that's incorrect, there are 136 solutions ... someone clearly didn't pay attention to floating operations ... here is a python script - https://repl.it/oxA/7
Answer: There are 136 solutions for this:
126478359   1   2   6   4   7   8   3   5   9   66
126478539   1   2   6   4   7   8   5   3   9   66
132458796   1   3   2   4   5   8   7   9   6   66
132458976   1   3   2   4   5   8   9   7   6   66
132956478   1   3   2   9   5   6   4   7   8   66
132956748   1   3   2   9   5   6   7   4   8   66
134765298   1   3   4   7   6   5   2   9   8   66
134765928   1   3   4   7   6   5   9   2   8   66
136279458   1   3   6   2   7   9   4   5   8   66
136279548   1   3   6   2   7   9   5   4   8   66
139478256   1   3   9   4   7   8   2   5   6   66
139478526   1   3   9   4   7   8   5   2   6   66
148279356   1   4   8   2   7   9   3   5   6   66
148279536   1   4   8   2   7   9   5   3   6   66
152348796   1   5   2   3   4   8   7   9   6   66
152348976   1   5   2   3   4   8   9   7   6   66
152847396   1   5   2   8   4   7   3   9   6   66
152847936   1   5   2   8   4   7   9   3   6   66
153942786   1   5   3   9   4   2   7   8   6   66
153942876   1   5   3   9   4   2   8   7   6   66
183745269   1   8   3   7   4   5   2   6   9   66
183745629   1   8   3   7   4   5   6   2   9   66
196458372   1   9   6   4   5   8   3   7   2   66
196458732   1   9   6   4   5   8   7   3   2   66
196752348   1   9   6   7   5   2   3   4   8   66
196752438   1   9   6   7   5   2   4   3   8   66
214379568   2   1   4   3   7   9   5   6   8   66
214379658   2   1   4   3   7   9   6   5   8   66
236179458   2   3   6   1   7   9   4   5   8   66
236179548   2   3   6   1   7   9   5   4   8   66
248179356   2   4   8   1   7   9   3   5   6   66
248179536   2   4   8   1   7   9   5   3   6   66
269851473   2   6   9   8   5   1   4   7   3   66
269851743   2   6   9   8   5   1   7   4   3   66
286941573   2   8   6   9   4   1   5   7   3   66
286941753   2   8   6   9   4   1   7   5   3   66
296351478   2   9   6   3   5   1   4   7   8   66
296351748   2   9   6   3   5   1   7   4   8   66
314279568   3   1   4   2   7   9   5   6   8   66
314279658   3   1   4   2   7   9   6   5   8   66
321547896   3   2   1   5   4   7   8   9   6   66
321547986   3   2   1   5   4   7   9   8   6   66
324851796   3   2   4   8   5   1   7   9   6   66
324851976   3   2   4   8   5   1   9   7   6   66
328651794   3   2   8   6   5   1   7   9   4   66
328651974   3   2   8   6   5   1   9   7   4   66
352148796   3   5   2   1   4   8   7   9   6   66
352148976   3   5   2   1   4   8   9   7   6   66
364958172   3   6   4   9   5   8   1   7   2   66
364958712   3   6   4   9   5   8   7   1   2   66
392815674   3   9   2   8   1   5   6   7   4   66
392815764   3   9   2   8   1   5   7   6   4   66
396251478   3   9   6   2   5   1   4   7   8   66
396251748   3   9   6   2   5   1   7   4   8   66
426178359   4   2   6   1   7   8   3   5   9   66
426178539   4   2   6   1   7   8   5   3   9   66
432158796   4   3   2   1   5   8   7   9   6   66
432158976   4   3   2   1   5   8   9   7   6   66
439178256   4   3   9   1   7   8   2   5   6   66
439178526   4   3   9   1   7   8   5   2   6   66
496158372   4   9   6   1   5   8   3   7   2   66
496158732   4   9   6   1   5   8   7   3   2   66
512967348   5   1   2   9   6   7   3   4   8   66
512967438   5   1   2   9   6   7   4   3   8   66
521347896   5   2   1   3   4   7   8   9   6   66
521347986   5   2   1   3   4   7   9   8   6   66
531726894   5   3   1   7   2   6   8   9   4   66
531726984   5   3   1   7   2   6   9   8   4   66
541927386   5   4   1   9   2   7   3   8   6   66
541927836   5   4   1   9   2   7   8   3   6   66
548967132   5   4   8   9   6   7   1   3   2   66
548967312   5   4   8   9   6   7   3   1   2   66
572839164   5   7   2   8   3   9   1   6   4   66
572839614   5   7   2   8   3   9   6   1   4   66
593621784   5   9   3   6   2   1   7   8   4   66
593621874   5   9   3   6   2   1   8   7   4   66
628351794   6   2   8   3   5   1   7   9   4   66
628351974   6   2   8   3   5   1   9   7   4   66
631925784   6   3   1   9   2   5   7   8   4   66
631925874   6   3   1   9   2   5   8   7   4   66
693521784   6   9   3   5   2   1   7   8   4   66
693521874   6   9   3   5   2   1   8   7   4   66
714965238   7   1   4   9   6   5   2   3   8   66
714965328   7   1   4   9   6   5   3   2   8   66
728965134   7   2   8   9   6   5   1   3   4   66
728965314   7   2   8   9   6   5   3   1   4   66
731526894   7   3   1   5   2   6   8   9   4   66
731526984   7   3   1   5   2   6   9   8   4   66
732859164   7   3   2   8   5   9   1   6   4   66
732859614   7   3   2   8   5   9   6   1   4   66
734165298   7   3   4   1   6   5   2   9   8   66
734165928   7   3   4   1   6   5   9   2   8   66
752849136   7   5   2   8   4   9   1   3   6   66
752849316   7   5   2   8   4   9   3   1   6   66
764859132   7   6   4   8   5   9   1   3   2   66
764859312   7   6   4   8   5   9   3   1   2   66
783145269   7   8   3   1   4   5   2   6   9   66
783145629   7   8   3   1   4   5   6   2   9   66
796152348   7   9   6   1   5   2   3   4   8   66
796152438   7   9   6   1   5   2   4   3   8   66
824351796   8   2   4   3   5   1   7   9   6   66
824351976   8   2   4   3   5   1   9   7   6   66
832759164   8   3   2   7   5   9   1   6   4   66
832759614   8   3   2   7   5   9   6   1   4   66
852147396   8   5   2   1   4   7   3   9   6   66
852147936   8   5   2   1   4   7   9   3   6   66
852749136   8   5   2   7   4   9   1   3   6   66
852749316   8   5   2   7   4   9   3   1   6   66
864759132   8   6   4   7   5   9   1   3   2   66
864759312   8   6   4   7   5   9   3   1   2   66
869251473   8   6   9   2   5   1   4   7   3   66
869251743   8   6   9   2   5   1   7   4   3   66
872539164   8   7   2   5   3   9   1   6   4   66
872539614   8   7   2   5   3   9   6   1   4   66
892315674   8   9   2   3   1   5   6   7   4   66
892315764   8   9   2   3   1   5   7   6   4   66
912567348   9   1   2   5   6   7   3   4   8   66
912567438   9   1   2   5   6   7   4   3   8   66
914765238   9   1   4   7   6   5   2   3   8   66
914765328   9   1   4   7   6   5   3   2   8   66
928765134   9   2   8   7   6   5   1   3   4   66
928765314   9   2   8   7   6   5   3   1   4   66
931625784   9   3   1   6   2   5   7   8   4   66
931625874   9   3   1   6   2   5   8   7   4   66
932156478   9   3   2   1   5   6   4   7   8   66
932156748   9   3   2   1   5   6   7   4   8   66
941527386   9   4   1   5   2   7   3   8   6   66
941527836   9   4   1   5   2   7   8   3   6   66
948567132   9   4   8   5   6   7   1   3   2   66
948567312   9   4   8   5   6   7   3   1   2   66
953142786   9   5   3   1   4   2   7   8   6   66
953142876   9   5   3   1   4   2   8   7   6   66
964358172   9   6   4   3   5   8   1   7   2   66
964358712   9   6   4   3   5   8   7   1   2   66
986241573   9   8   6   2   4   1   5   7   3   66
986241753   9   8   6   2   4   1   7   5   3   66
I used c++ and Excel to solve it.
Check the solution here:
https://github.com/jpruiz114/cpp-tests/tree/master/DevCppTest02
Comment: I love how you store it on github :)
Comment: MAAAANNNN, where do you from? How did you extract all the information and write a complete documentation of this math problem? You're my idol!
Comment: Hey Eddie, from the US, based in South America. There's a document for this, is here: http://issuu.com/jpruiz114/docs/brute_force_solution_for_vietnamese

Feel free to touch base with me via email.


Form input-field is too small using Materialize-CSS

Question: I have a Login form for a basic Admin Portal, however the input-field itself to click on is extremely small. The bar itself seems to be the entire size of the clickable input-field, so you can't click the label whatsoever to enter.
Code as follows:

      <form onSubmit={handleSubmit} className="white">

Cars4U Administration

          <input type="text" name="username" className="validate" required onChange={handleChange} />
          Username

          <input type="password" name="password" className="validate" required onChange={handleChange} />
          Password

          <button className='btn z-depth-0' type='submit'>Login</button>

      </form>

If my cursor is in the following position, I am unable to click the input-field. I am only able to click it directly on the line:

CSS:
form {
  background-color: white;
  margin-top: 80px;
  margin-left: 350px;
  margin-right: 350px;
  border-radius: 3px;
}

form label {
  padding-left: 40px;
  padding-right: 40px;
  padding-top: 20px;
  font-weight: 700;
}

form .input-field {
  padding-left: 40px;
  padding-right: 40px;
  padding-top: 20px;
}

Comment: Can you please post your code here so we can help debug. What I'm guessing is the input field is too small or has too much padding on it, obscuring the clickable area.
Comment: I added everything that remotely pertained to the field, but also if I remove all of that the field is still working properly
Answer: According to Anthony's suggestion, you're supposed to have both name and id as identifiers.

Add id to your input -
<input name="username"/> to <input  name="username"id="username"/>

class App extends React.Component {
  render() {
    return (

        <form className="white">

Cars4U Administration

              <input type="text" id="username" className="validate" required />
              Username

              <input
                type="password"
                id="password"
                className="validate"
                required
              />
              Password

            <button className="btn z-depth-0" type="submit">
              Login
            </button>

        </form>

    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet"/>

Comment: Thank you! Also the the active label will not remain color coded for validation. As is as soon as I click on another field the label will go back from red to grey. Any ideas?
Comment: You need to have both, as the `name` is the identifier used when passing the form data from the browser to the server.
Comment: It's because you have it as required, you can validate it in a function `onClick`, and highlight fields that you need to highlight for errors.


Which file system best handle multiple, concurrent write sessions

Question: Which file system best handle multiple, concurrent write sessions
Which file system can handle more concurrent write sessions; let's say 32 write sessions?
The file system has to handle 32 concurrent sessions with each session writing 100Mb uncompressed data file in 5 minutes. Please suggest
Comment: @JijoJohn: your re-written question is now a product recommendation which also off-topic. Your IO requirements are very simple 32 x 100 MB in 300 seconds equals storing 10 MB/s in a more-or-less sequential writes, something even a slow 5400 rpm laptop drive can accommodate easily. With simple IO patterns the disks become a limiting factor long before the choice of file-system makes any difference. Using compression like ewwhite proposes reduces the amount of data that needs to be stored making things quicker and my tempfs also cheats and stores all data in memory rather than on (slow) disk.
Comment: This doesn't make sense.
Comment: I believe I corrected the question which was confusing earlier.
Answer: ZFS with lz4 compression is pretty quick, depending on the compressibility of the data.
But the rest of the items you're comparing aren't actually comparable. You've listed cluster filesystems, network filesystems, caching layers, and traditional filesystems.
Answer: No contest, tmpfs !

tmpfs is designed as a performance enhancement ...


Dynamically assigning json response content-type in WCF Azure Service Bus

Question: I am writing a POC application which uses Microsoft.ServiceBus.dll 126.96.36.199 (the .NET 3.5 version).
My WCF contract  and service look like the following:

[ServiceContract(Name="MyServiceContract", Namespace = "http://mydomain.com/")]
internal interface IServiceContract
{
    [WebInvoke(Method = "POST", UriTemplate = "/DoOperation")]
    [OperationContract]
    Stream RelayRequest(Stream requestBody);
}

[ServiceBehavior(Name = "Service1", Namespace = "http://mydomain.com/Service1/", InstanceContextMode = InstanceContextMode.Single)]
internal class Service1 : IServiceContract
{
    Stream RelayRequest(Stream requestBody)
    {
        var contents = GetJsonResponse();
        var responseStream = new MemoryStream();
        var streamWriter = new StreamWriter(responseStream);
        streamWriter.AutoFlush = true;
        var writer = new JsonTextWriter(streamWriter);
        var serializer = new JsonSerializer();
        serializer.Serialize(responseStream, contents);

        responseStream.Position = 0 // reset the position of the stream so that it's contents will be read from the beginning.

        //Problem Line:
        WebOperationContext.OutgoingResponse.ContentType = "application/json";
        return responseStream;
    }
}

The listening end point is configured to use WebHttpRelayBinding:

SecurityMode: Transport
TransferMode: Streamed

When I attempt to assign the ContentType of the outgoing response to "application/json" an error doesn't occur but the calling request returns with status code 504 (Gateway Timeout).
If I change the ContentType to "text/javascript" the calling request returns with 200 (OK).
Some things to note:

The content-type is not known until run time so it must be dynamically assigned.
The contents of the stream is pure - 100% valid - json.
The intention for accepting and returning a stream is so we can accept streamed requests and stream data down to the client.

Each request / response could contain a small json payload or a 200MB document.

If you want to repro - this code uses the Newtonsoft Json library for serialization.

Why is this happening and how can I fix this?
EDIT: The 504 status code could be a red herring inferred by fiddler with which I am testing.
Sending the same request from System.Net.Http.HttpClient indicates the connection is closed before a response is received.
EDIT: setting the content-type to pretty much anything else (including non-sensical values) works fine. The only content type that I can get to break it is application/json
Comment: Can you add the info from your config file / how you set up the service? What type of binding are you using?
Comment: As pointed out above we use WebHttpRelayBinding. This binding / end point is not created by config, it is created programatically at runtime.
Comment: Ah, guess I had a series of mental lapses reading your description...
Comment: Any progress on solving this problem?
Comment: Unfortunately not, no. We ended up working around this with custom headers.
Comment: [sound of a crow] me.  this is absurd.  i think i might see what Godot suggests I do.
Answer: This is how I made it work but it's a simple WCF service hosted locally in IIS. I don't use Microsoft.ServiceBus or Azure.
First Fiddler's response. If this is what you are looking for then proceed to code :)
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 121
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 04 Apr 2013 17:17:05 GMT

[{"BoolValue":true,"StringValue":"blah"},{"BoolValue":false,"StringValue":"boo"},{"BoolValue":true,"StringValue":"floo"}]

Service definition:
namespace yourNS
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(UriTemplate = "/CT", ResponseFormat = WebMessageFormat.Json)]
        List<CompositeType> GetData();
    }

    [DataContract]
    public class CompositeType
    {
        [DataMember]
        public bool BoolValue { get; set; }

        [DataMember]
        public string StringValue { get; set; }
    }

    public class Service1 : IService1
    {
        public List<CompositeType> GetData()
        {
            return new List<CompositeType>
            {
                new CompositeType { BoolValue = true, StringValue = "blah" },
                new CompositeType { BoolValue = false, StringValue = "boo" },
                new CompositeType { BoolValue = true, StringValue = "floo" },
            };
        }
    }
}

And web.config
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="yourNS.Service1">
        <endpoint
          address=""
          binding="webHttpBinding"
          behaviorConfiguration="MyBehave"
          contract="yourNS.IService1" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="MyBehave">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>

          <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

Comment: Your solution only works because you've removed all of the complexity from the original question that was causing the problem in the first place. As stated in the original question I need to dynamically assign the response content type, I also need to use Azure Service Bus to achieve this.


Ratio of $\frac{\sin x_1 }{\sin x_2}$ where $f(x_1)=f(x_2)$ for a trigonometric sum $f(x)$

Question: If $f(x) = \cos(x+a_1)+\frac12\cos(x+a_2)+\frac14\cos(x+a_3)+\cdots+\frac1{2^{n-1}}\cos(x+a_n)$, where $a_1, a_2, ... a_n$ are some constants and $f(x_1)-f(x_2)=0$, where $x_2 \neq m\pi$, find
$$\frac{\sin x_1}{\sin x_2}+\frac{\left|\sin x_1\right|}{\sin x_2}+\frac{\sin x_1}{\left|\sin x_2\right|}+\left|\frac{\sin x_1}{\sin x_2}\right|$$
A friend gave me this one and I tried using
$$0=f(x_1)-f(x_2) = 2\sin\left(\frac{x_2-x_1}2 \right)\left[\sin\left(\frac{x_1+x_2}2+a_1 \right)+\frac12\sin\left(\frac{x_1+x_2}2+a_2 \right) +\dots\right]$$
which gives one possibility $x_2=x_1+2k\pi$ so the desired value can be $0$ or $4$.  However I also see a possibility of $a_i=-\frac{x_1+x_2}2+2k_i\pi$ which leads to a lot of possibilities for the value.  Am I doing this incorrectly or is there something missing in the question (my friend swears no)?
Answer: Unless you are considering complex numbers, you are probably trying too hard (a mistake I also made on this problem). Instead of fixing $\cos(a+b)-\cos(a-b)\not=2\sin(a)\cos(b)$ you might fix your attention on the final result, perhaps expanding $|\sin x_1|\in\pm\sin x_1$ and $|\sin x_2|\in\pm\sin x_2$
Comment: Fixing the sum formula error, but the problem persists - when both sines are positive, the ratio becomes important to determine the value. And there are more solutions possible that the ones written above.
Answer: Use the addition formula for cosine
$\cos(A+B) = \cos A \cos B - \sin A \sin B$
to write
$f(x) = \cos{x} \displaystyle\sum\limits_{i=1}^{n}{\dfrac{2}{2^{n-k}}\cos a_k} - \sin{x} \displaystyle\sum\limits_{i=1}^{n}{\dfrac{2}{2^{n-k}}\sin a_k}$
Regard the summations as fixed since you are given $a_1,a_2,\dots,a_n$
Let $\sigma_c = \displaystyle\sum\limits_{i=1}^{n}{\dfrac{2}{2^{n-k}}\cos a_k} \tag{1}$ and $\sigma_s = \displaystyle\sum\limits_{i=1}^{n}{\dfrac{2}{2^{n-k}}\sin a_k} \tag{2}$
Then you have:
$f(x) = \sigma_c \cos{x} - \sigma_s \sin{x} \tag{3}$
Since $f(x_1)-f(x_2)=0$, you must have
$\sigma_c \cos{x_1} - \sigma_s \sin{x_1} = \sigma_c \cos{x_2} - \sigma_s \sin{x_2} \tag{4}$
and so finding a $\theta$ such that $\tan\theta = \dfrac{\sigma_s}{\sigma_c} \tag{5}$, you can divide (4) through by $\sqrt{{\sigma_c}^2 + {\sigma_c}^2}$ and set $\sigma_s = \sin\theta, \sigma_c = \cos\theta$ to get
$\cos\theta \cos x_1 - \sin\theta \sin x_1 = \cos\theta \cos x_2 - \sin\theta \sin x_2$
which is really
$\cos(\theta + x_1) = \cos(\theta + x_2) \tag{6}$
and which has two sets of solutions.
The first is (as you had it)
$\boxed{x_2 = x_1 + 2\pi n, n\in\mathbb{Z}} \tag{a}$
Now from (5) without loss of generality, set
$\theta = \arctan\Big(\dfrac{\sigma_s}{\sigma_c}\Big) \tag{6}$
The other set of solutions is given by setting $\theta + x_2 = -(\theta + x_1)$ [from the identity $\cos(-\alpha) = \cos \alpha$] and then allowing for multiples of $2\pi$:
$x_2 = -x_1 - 2\theta + 2\pi n, n\in\mathbb{Z}$
so finally by (6):
$\boxed{x_2 = -x_1 - 2\arctan\Big(\dfrac{\sigma_s}{\sigma_c}\Big) + 2\pi n, n\in\mathbb{Z}} \tag{b}$
with ${\sigma_c},{\sigma_s}$ given by (1) and (2)


DMA write to SD card (SSP) doesn't write bytes

Question: I'm currently working on replacing a blocking busy-wait implementation of an SD card driver over SSP with a non-blocking DMA implementation. However, there are no bytes actually written, even though everything seems to go according to plan (no error conditions are ever found).
First some code (C++):
(Disclaimer: I'm still a beginner in embedded programming so code is probably subpar)
namespace SD {
    bool initialize() {
        //Setup SSP and detect SD card
        //... (removed since not relevant for question)

        //Setup DMA
        LPC_SC->PCONP |= (1UL << 29);
        LPC_GPDMA->Config = 0x01;
        //Enable DMA interrupts
        NVIC_EnableIRQ(DMA_IRQn);
        NVIC_SetPriority(DMA_IRQn, 4);
        //enable SSP interrupts
        NVIC_EnableIRQ(SSP2_IRQn);
        NVIC_SetPriority(SSP2_IRQn, 4);
    }

    bool write (size_t block, uint8_t const * data, size_t blocks) {
        //TODO: support more than one block
        ASSERT(blocks == 1);

        printf("Request sd semaphore (write)\n");
        sd_semaphore.take();
        printf("Writing to block " ANSI_BLUE "%d" ANSI_RESET "\n", block);

        memcpy(SD::write_buffer, data, BLOCKSIZE);

        //Start the write
        uint8_t argument[4];
        reset_argument(argument);
        pack_argument(argument, block);
        if (!send_command(CMD::WRITE_BLOCK, CMD_RESPONSE_SIZE::WRITE_BLOCK, response, argument)){
            return fail();
        }

        assert_cs();
        //needs 8 clock cycles
        delay8(1);

        //reset pending interrupts
        LPC_GPDMA->IntTCClear = 0x01 << SD_DMACH_NR;
        LPC_GPDMA->IntErrClr = 0x01 << SD_DMACH_NR;

        LPC_GPDMA->SoftSReq = SD_DMA_REQUEST_LINES;

        //Prepare channel
        SD_DMACH->CSrcAddr = (uint32_t)SD::write_buffer;
        SD_DMACH->CDestAddr = (uint32_t)&SD_SSP->DR;
        SD_DMACH->CLLI = 0;
        SD_DMACH->CControl = (uint32_t)BLOCKSIZE
                                             | 0x01 << 26 //source increment
                                             | 0x01 << 31; //Terminal count interrupt

        SD_SSP->DMACR = 0x02; //Enable ssp write dma

        SD_DMACH->CConfig = 0x1  //enable
                                            | SD_DMA_DEST_PERIPHERAL << 6
                                            | 0x1 << 11 //mem to peripheral
                                            | 0x1 << 14 //enable error interrupt
                                            | 0x1 << 15; //enable terminal count interrupt
        return true;
    }
}
extern "C" __attribute__ ((interrupt)) void DMA_IRQHandler(void) {
    printf("dma irq\n");
    uint8_t channelBit = 1 << SD_DMACH_NR;
    if (LPC_GPDMA->IntStat & channelBit) {
        if (LPC_GPDMA->IntTCStat & channelBit) {
            printf(ANSI_GREEN "terminal count interrupt\n" ANSI_RESET);
            LPC_GPDMA->IntTCClear = channelBit;
        }
        if (LPC_GPDMA->IntErrStat & channelBit) {
            printf(ANSI_RED "error interrupt\n" ANSI_RESET);
            LPC_GPDMA->IntErrClr = channelBit;
        }
        SD_DMACH->CConfig = 0;

        SD_SSP->IMSC = (1 << 3);

    }
}

extern "C" __attribute__ ((interrupt)) void SSP2_IRQHandler(void) {
    if (SD_SSP->MIS & (1 << 3)) {
        SD_SSP->IMSC &= ~(1 << 3);
        printf("waiting until idle\n");
        while(SD_SSP->SR & (1UL << 4));

        //Stop transfer token
        //I'm not sure if the part below up until deassert_cs is necessary.
        //Adding or removing it made no difference.
        SPI::send(0xFD);

        {
            uint8_t response;
            unsigned int timeout = 4096;
            do {
                response = SPI::receive();
            } while(response != 0x00 && --timeout);
            if (timeout == 0){
                deassert_cs();
                printf("fail");
                return;
            }
        }

        //Now wait until the device isn't busy anymore
        {
            uint8_t response;
            unsigned int timeout = 4096;
            do {
                response = SPI::receive();
            } while(response != 0xFF && --timeout);
            if (timeout == 0){
                deassert_cs();
                printf("fail");
                return;
            }
        }
        deassert_cs();
        printf("idle\n");
        SD::sd_semaphore.give_from_isr();
    }
}

A few remarks about the code and setup:

Written for the lpc4088 with FreeRTOS
All SD_xxx defines are conditional defines to select the right pins (I need to use SSP2 in my dev setup, SSP0 for the final product)
All external function that are not defined in this snippet (e.g. pack_argument, send_command, semaphore.take() etc.) are known to be working correctly (most of these come from the working busy-wait SD implementation. I can't of course guarantee 100% that they are bugless, but they seem to be working right.).
Since I'm in the process of debugging this there are a lot of printfs and hardcoded SSP2 variables. These are of course temporarily.
I mostly used this as example code.

Now I have already tried the following things:

Write without DMA using busy-wait over SSP. As mentioned before I started with a working implementation of this, so I know the problem has to be in the DMA implementation and not somewhere else.
Write from mem->mem instead of mem->sd to eliminate the SSP peripheral. mem->mem worked fine, so the problem must be in the SSP part of the DMA setup.
Checked if the ISRs are called. They are: first the DMA IRS is called for the terminal count interrupt, and then the SSP2 IRS is called. So the IRSs are (probably) setup correctly.
Made a binary dump of the entire sd content to see if it the content might have been written to the wrong location. Result: the content send over DMA was not present anywhere on the SD card (I did this with any change I made to the code. None of it got the data on the SD card).
Added a long (~1-2 seconds) timeout in the SSP IRS by repeatedly requesting bytes from the SD card to make sure that there wasn't a timeout issue (e.g. that I tried to read the bytes before the SD card had the chance to process everything). This didn't change the outcome at all.

Unfortunately due to lack of hardware tools I haven't been able yet to verify if the bytes are actually send over the data lines.
What is wrong with my code, or where can I look to find the cause of this problem? After spending way more hours on this then I'd like to admit I really have no idea how to get this working and any help is appreciated!
UPDATE: I did a lot more testing, and thus I got some more results. The results below I got by writing 4 blocks of 512 bytes. Each block contains constantly increasing numbers module 256. Thus each block contains 2 sequences going from 0 to 255. Results:

Data is actually written to the SD card. However, it seems that the first block written is lost. I suppose there is some setup done in the write function that needs to be done earlier.
The bytes are put in a very weird (and wrong) order: I basically get alternating all even numbers followed by all odd numbers. Thus I first get even numbers 0x00 - 0xFE and then all odd numbers 0x01 - 0xFF (total number of written bytes seems to be correct, with the exception of the missing first block). However, there's even one exception in this sequence: each block contains 2 of these sequences (sequence is 256 bytes, block is 512), but the first sequence in each block has 0xfe and 0xff "swapped". That is, 0xFF is the end of the even numbers and 0xFE is the end of the odd series. I have no idea what kind of black magic is going on here. Just in case I've done something dumb here's the snippet that writes the bytes:
uint8_t block[512];
for (int i = 0; i < 512; i++) {
    block[i] = (uint8_t)(i % 256);
}
if (!SD::write(10240, block, 1)) { //this one isn't actually written
    WARN("noWrite", proc);
}
if (!SD::write(10241, block, 1)) {
    WARN("noWrite", proc);
}
if (!SD::write(10242, block, 1)) {
    WARN("noWrite", proc);
}
if (!SD::write(10243, block, 1)) {
    WARN("noWrite", proc);
}

And here is the raw binary dump. Note that this exact pattern is fully reproducible: so far each time I tried this I got this exact same pattern.
Update2: Not sure if it's relevant, but I use sdram for memory.
Comment: Added `embedded` tag to reach a wider audience
Answer: When I finally got my hands on a logic analyzer I got a lot more information and was able to solve these problems.
There were a few small bugs in my code, but the bug that caused this behaviour was that I didn't send the "start block" token (0xFE) before the block and I didn't send the 16 bit (dummy) crc after the block. When I added these to the transfer buffer everything was written successfully!
So this fix was as followed:
bool write (size_t block, uint8_t const * data, size_t blocks) {
    //TODO: support more than one block
    ASSERT(blocks == 1);

    printf("Request sd semaphore (write)\n");
    sd_semaphore.take();
    printf("Writing to block " ANSI_BLUE "%d" ANSI_RESET "\n", block);

    SD::write_buffer[0] = 0xFE; //start block

    memcpy(&SD::write_buffer[1], data, BLOCKSIZE);

    SD::write_buffer[BLOCKSIZE + 1] = 0; //dummy crc
    SD::write_buffer[BLOCKSIZE + 2] = 0;

    //...
}

As a side note, the reason why the first block wasn't written was simply because I didn't wait until the device was ready before sending the first block. Doing so fixed the problem.


How to Estimate Population Variance from Multiple Samples

Question: Suppose I have $N$ samples each of size $n$, drawn from the same population, where each sample has its own sample variance $s_i^2$.
I understand that for any given sample, a first estimate of the population variance $\sigma^2$ is:
$$\hat{\sigma}^2 = s_i^2 \displaystyle\frac{n}{n-1}$$
But what if you have multiple samples? What is the best estimate of $\sigma^2$ given multiple $s^2$?
Comment: @whuber I made a mistake, the factor should have been $n/(n-1)$. The factor makes it an unbiased estimator of the population variance, according to http://mathworld.wolfram.com/SampleVariance.html
Comment: Some meta-analysis techniques might be of interest.
Comment: Could you explain why you multiply the sample variance by $(n-1)/n$?  There's nothing illegitimate about it, but your reason for including that factor will shed light on what you might mean by "best" estimate of $\sigma^2$.
Comment: In that case the answer you have accepted is completely wrong, understanding you want an unbiased estimate of the variance of the population.  The expected value of the accepted answer is $N$ times larger than it should be.  It is also inadmissible in the sense that other unbiased estimates can be constructed that have smaller standard errors.
Comment: @whuber Thank you for pointing that out. Do you have a proposed solution? Also it would probably be best to comment on the answer as well/instead
Comment: I commented on that answer immediately after it was posted.  One (but not the only) solution is to use a weighted average of the variance estimates, but I haven't time now to post it.
Answer: A comment clarified that the best estimator of the variance is intended to be unbiased.  A standard way to find such an estimator is to restrict one's attention to linear combinations of the estimators (because almost anything else would be difficult to analyze).
Let there be $k$ independent samples indexed by $i=1,2,\ldots, k$, each with its own unbiased variance estimator $\hat\sigma_i^2$.  Let the unknown weights of the linear combination be $w_i$, so that the combined estimator will be
$$\hat\sigma^2 = \sum_{i=1}^k w_i \hat \sigma_i^2.$$
Because this is supposed to be unbiased for any population, by definition the population variance will equal its expected value:
$$\sigma^2 = \mathbb{E}(\hat\sigma^2) = \sum_{i=1}^k w_i \mathbb{E}(\hat\sigma_i^2) = \sum_{i=1}^k w_i \sigma^2 = \left(\sum_{i=1}^k w_i\right)\sigma^2.$$
Since $\sigma^2 \ne 0$ is possible, division of both sides by $\sigma^2$ implies the weights sum to unity:
$$1 = \sum_{i=1}^k w_i.$$
Let the sample size for estimator $\hat\sigma_i$ be $n_i$.  (In the question all the $n_i$ are equal to $n$.)  Because each estimator $\hat\sigma_i^2$ has $n_i-1$ degrees of freedom, its variance will be approximately proportional to $1/(n-1)$ times some value that is an (unknown) property $f$ of the population.  (This unknown property depends on the first four moments of the population.)  In fact, for a Normal population this is not an approximation at all: the variances of the estimators are exactly proportional to $1/(n_i-1)$.  Therefore we may approximate the variance of the combined estimator as
$$\operatorname{Var}(\hat\sigma^2) = \operatorname{Var}\left(\sum_{i=1}^k w_i \hat\sigma_i^2\right) = \sum_{i=1}^k w_i^2 \operatorname{Var}(\hat\sigma_i^2) \approx \sum_{i=1}^k w_i^2 \frac{f}{n_i-1}.$$  The second equality is due to the independence of the $k$ samples.
Subject to the sum-to-unity constraint, this variance is minimized when the $w_i$ are proportional to $n_i-1$.  Therefore an (approximate) minimum variance unbiased linear estimator of the population variance is
$$\hat\sigma^2 = \frac{1}{n_1+\cdots n_k - k}\sum_{i=1}^k (n_i-1)\hat\sigma_i^2.$$
When all the $n_i$ are equal to a common value $n$, this reduces to the arithmetic mean of the individual variance estimators.  It should be intuitively obvious that some kind of equally-weighted average of all $k$ estimators would be the best one in this case.
Comment: @Anomaly I wouldn't go quite so far as to say "not valid," but you're certainly right to call into question what such a statistic might mean and to wonder what it could be estimating.  Such calculations come into their own in situations where it's possible the subsamples do come from a common population and your objective is to test that hypothesis.  My estimator is not the same as the sample variance of the pooled observations, though, as you can see by considering a situation with two subgroups of two observations each and each subgroup has a tiny variance but their means differ greatly.
Comment: +1 Very clear explanation. How does this estimate compare to pooling observations from all the samples and using the sample variance? That is, to consider all the observations as one large sample and calculate the sample variance. Is it equivalent?
Comment: Of course, if each sample is drawn from a population with a different mean (but same variance), then the sample variance of the pooled observations would not be valid. But if the means are identical, then I think your estimator should be equivalent to the sample variance of the pooled observations?
Answer: How about putting a hat on your estimates of the variance for each of the N samples
$\hat{\sigma}_{i}^{2}\simeq s_{i}^{2}\frac{n-1}{n}$
and appealing to the Law of Propagation of Uncertainty, add them in quadrature to get the estimate of the overall variance
$\tilde{\sigma}^{2}=\sum_{i=1}^{N}\hat{\sigma}_{i}^{2}$
Comment: It looks like your formula should not have any square root and, regardless, it will grossly overestimate the variance.  Try it out on some simple data to see what's going wrong.
Comment: I made an initial mistake which has been copied here, the factor should be $n/(n-1)$ and not the inverse. @whuber Have the issues you brought up been fixed?
Answer: I presume this is the issue where you have k samples size n of a population that are all random with a given mean m and sample unbiassed variance s^2. As you do not have the real population mean, NOR the population variance that is used in all the textbooks, you have to find a means to not only calculate this population mean (rather easy), but also have a good estimator of the population variance. I did not find a description how to do this in the HANDBOOK OF PARAMETRIC AND NONPARAMETRIC STATISTICAL PROCEDURES (2000 pages, really quite complete) and that leaves us two ways. Theory (approach each sample of the same parameter as RANDOM and thus state the population is a sum of the INDEPENDENT samples with a weight 1/k of each, giving you a resulting population variance if you pull another sample size n. Then multiply that population variance with n to obtain the population variance when pulling single size samples). Another way is to pragmatically create a program that simulates your population (does not have to be exact) to calculate variances of many sample sizes using your guessed formula and then see what method is actually (after 1000 repetitions, computers are patient) most robust. I propose you use the theoretical approach.


Why aren't nodes indexed when they are saved?

Question: Why aren't nodes indexed when they are saved?
As we all know, node_update_index is invoked by search_cron, which means that the search index is only updated as frequently as cron runs.
I am curious why _node_index_node isn't part of the normal node_save process, eg
if ($node->status == NODE_PUBLISHED) {
  _node_index_node($node);
}

Is there a good reason for this?  Since this function is defined by the node module itself, I don't see how it is a separation of responsibilities thing, nor can I think of a good reason for not doing this.
The related question would be, is is safe to wire up an action to fire when a node is created or updated?
Comment: Think in VBO demoting from front page a thousand of nodes, one little click for a user, but a big process for the system.
Answer: I believe it is in the interest of scalability. Imagine you had a large, popular site with user-generated content. Imagine you had users saving a node (say, posted a question or answer) every 20 seconds. Imagine a node being indexed as well as submitted every 20 seconds. The site would become unusable very quickly. So it's much better to allow the indexing to happen independently of node submission.
Comment: Indexing text for search is often as expensive as the rest of the node save process, and would add even more time to the save operation (causing the site to feel slower, since the next page wouldn't load until indexing is complete). Using a separate search system (like Solr) will make things better all around :)
Comment: I would counter by saying that you are only indexing a single node and not the whole site when you save.  Saving a node is already an expensive process.


Table cell on click add row just under

Question: I have a table this way:

                        STORE
                        SECTION
                        ELEMENT
                        ACTION

                    2227
                    BATHROOM
                    CABIN GLAS
                    NEED REPARATION

I want when I click on the first cell of each row I create a new row just under the clicked one. Here is my JS Code:
                    function is_done(row)
                        {
                        var currentdate = new Date();
                        var tm = currentdate.getDate() + "/"
                                    + (currentdate.getMonth()+1)  + "/"
                                    + currentdate.getFullYear() + " "
                                    + currentdate.getHours() + ":"
                                    + currentdate.getMinutes();
                        row.closest('td').html('Maintenance');  //This works
                        row.closest('tr').append('
checked on'+tm+'
');  //Here is the problem.. no row is added under the clicked
                        }

Answer: You have to switch 2 lines of code:
From:
row.closest('td').html('Maintenance');
row.closest('tr').after('
checked on' + tm + '
');

To:
row.closest('tr').after('
checked on' + tm + '
');
row.closest('td').html('Maintenance');

When you run row.closest('td').html('Maintenance'); you change the html and the object of row
Please Note: You have an unclosed  at the end

, Also user .after() and not .append()
Demo

function is_done(row) {
  var currentdate = new Date();
  var tm = currentdate.getDate() + "/" +
    (currentdate.getMonth() + 1) + "/" +
    currentdate.getFullYear() + " " +
    currentdate.getHours() + ":" +
    currentdate.getMinutes();
  row.closest('tr').after('
checked on' + tm + '
');
  row.closest('td').html('Maintenance');
}

      STORE
      SECTION
      ELEMENT
      ACTION

        click

      2227
      BATHROOM
      CABIN GLAS
      NEED REPARATION

Comment: Thank you so much for your help!!
Comment: @karmel No problem, happy to help

Table cell on click add row just under


Homotopy coherence

Question: $\require{AMScd}$
I am trying to get an understanding of the meaning of homotopy coherence - in order to understand homotopy limits and colimits - in the category $\mathbf{Top}$. Often when I see this discussed, the explanation there amounts to "homotopies commuting up to homotopy, and so on". Whilst I find this conceptually OK, I am struggling to get my hands on what this means explicitly.
My goal is to understand why the homotopy pullback of a diagram of topological spaces can be represented by the so-called homotopy fibre product, and in particular why the homotopy fibre of an arbitrary map $f:X \rightarrow Y$ can be represented by the mapping fibre: $$M_f:=\{(x,\gamma) \in X \times Y^I \; | \; f(x)=\gamma(1), \gamma(0)=*_Y\}.$$
Alternatively/additionally, I would like a concrete explanation for why it is appropriate that the homotopy fibre of a map $f:X \rightarrow Y$ be defined to be the homotopy pullback of $f$ with the inclusion of the basepoint. What is the universal property which we want the homotopy fibre to satisfy, and how does it come from being this particular homotopy pullback?

Question: Is my understanding of homotopy coherence in the following context correct?

At this Nlab page on the homotopy pullback, the following is written:
The homotopy pullback of $X \xrightarrow{f} Z \xleftarrow{g} Y$ consists of a square
\begin{CD}
P @>{p_2}>> Y;\\
@V{p_1}VV @V{g}VV \\
X @>{f}>> Z;
\end{CD}
which commutes up to homotopy, such that for any other square
\begin{CD}
T @>{t_2}>> Y;\\
@V{t_1}VV @V{g}VV \\
X @>{f}>> Z;
\end{CD}
that commutes up to homotopy (say via a homotopy $H:T \times I \rightarrow Z$), there exists a unique morphism $T \rightarrow P$ making the two triangles commute up to homotopy, and similarly for homotopies and higher homotopies.
Now, I think (from previous efforts to understand this stuff) that that last italicized part is crucial, and otherwise the definition doesn't make sense. What I want to know is whether I'm interpretting it correctly in the following:
There is a unique map $\phi:T \rightarrow P$ such that $p_1 \circ \phi \simeq t_1$ via $H_1:T \times I \rightarrow X$ and $p_2 \circ \phi \simeq t_2$ via $H_2:T \times I \rightarrow Y$, AND such that the resulting homotopies  $H_1 \circ f: T \times I \rightarrow Z$, $H_2 \circ g: T \times I \rightarrow Z$ and $H: T \times I \rightarrow Z$ are homotopic, say via $\Lambda: T \times I \times I \rightarrow Z$
Is that correct? And if these conditions are satisfied, then the map $T \rightarrow P$ is unique up to homotopy?
Would it be true that, in the case that we had multiple homotopies from $f \circ t_1$ to $g \circ t_2$, we would need these to be homotopic, say via $\bar{\Lambda}:T \times I \times I \rightarrow Z$, and we would then need $\Lambda$ and $\bar{\Lambda}$ to be homotopic?
Comment: @Carot Thank you for the references. I thought about adding this to my question. I have over the last year or so been around and about various standard sources - Dwyer and Spalinski included. Reading that did indeed help me lots, but not with this particular issue. Unfortunately I cannot read french (even though I really should learn to), so your first reference is no good for me - but may be of help for others who come here :)
Comment: I'm afraid not. The problem is that the diagrams being considered here really aren't complex enough to have any actual coherence issues: there aren't really any higher homotopies. If you want to understand issues related specifically to homotopy coherence then I think you might want to ask a more specific question. If you want to know about homotopy pullbacks in the topological category I can give you the definition that I like to use, which is pretty similar to what you have written down.
Comment: I think there is something wrong with the display of the diagrams
Comment: Edited. Is it now fixed?
Comment: Yes, looks good now.
Comment: You should try to read a course or a book about Model Categories.  You can find a really good  one in Gregory Ginot's home page if you understand french: https://www.math.univ-paris13.fr/~ginot/Homotopie/. Otherwise, I guess Dwyer and Spalinski is fine http://www.math.jhu.edu/~eriehl/616/DwyerSpalinski.pdf
Comment: I think the most natural expression of this uniqueness principle is "the space of solutions to this condition is a weakly contractible space". This may or may not be satisfying, since it passes the question along to exactly what space should count as the space of solutions to the condition.
Comment: I don't understand what you mean by that remark - when you say the space of solutions to the condition, are you referring to the space of all homotopy pullbacks? In what sense is this weakly contractible?
Comment: I think a right way to express the condition here is that you want to define the space $B$ whose points are homotopy coherent diagrams containing objects $X,Y,Z,P,T$ and arrows $f,g,t_i,p_i$ (and the relevant homotopy coherences), and your given diagrams are a point $x$ of this space. Then you construct the space $E$ which is the same thing except that it includes $\phi$ as well. And then the space we want to be weakly contractible is the homotopy fiber at $x$ of the forgetful map $E \to B$.
Comment: Also, I think I may have misunderstood the point of the question since I think I was focusing on the wrong parts.
Comment: I'm not really sure what this has to do with homotopy coherence? Is this just a question about homotopy pullbacks in the topological category, or rather is there something you haven't spelled out explicitly?
Comment: The relation to homotopy coherence is perhaps a little indirect. I have seen a definition (universal property) of the homotopy limit which says that "the homotopy limit represents homotopy coherent cones up to homotopy". My question involves a particular example. The italicized *and similarly for homotopies higher homotopies* in the question seems to me to be other words for *homotopy coherence*. I am then asking whether my interpretation of homotopy coherence in this specific small example is correct. Does that make sense?
Comment: In your question here https://math.stackexchange.com/questions/3263796/homotopy-colimit/3263917, Kevin Carlson explains the idea in his comment, and includes the phrase 'For more complicated diagram shapes...' which sums up what I'm trying to say, really.
Comment: Consider a cubical diagram, in which each face is just assumed to homotopy commute. You can choose homotopies for the top and front faces and glue these together, and you can choose homotopies $F,G,H$ for the top front and bottom faces and homotopies $K,L,M$ for the left, back and right faces. Then $H+G+F$ and $M+L+K$ are homotopies which each begin and end at the same maps, but pass through different compositions. The cube (with chosen homotopies and the 2-homotopy $\theta$ about to be defined) is *homotopy coherent* if $H+G+F$ is homotopic to $M+L+K$ by a homotopy of homotopy $\theta$.
Comment: I think I see what you're saying. In my question I write three homotopies which I ask to be homotopic via a homotopy $\Lambda$ - so I think there are ``higher homotopies", but just one level up, and only one of them. Is that correct or am I mistaken? I would indeed be very grateful to hear the definition of homotopy pullback which you use.
Comment: The link between homotopy pullback and homotopy fiber is the same as that between pullbacks and fibers : perhaps you should try to understand that one first
Comment: Thank you for the tip. I do indeed understand the link between fibres and pullbacks, and I understand that the homotopy fibre is the homotopy pullback of the same diagram which the fibre is the pullback of for a fibration. My gap in understanding lies in the technical details in the definition of the homotopy limit/pullback.
Answer: The following definition comes more or less from Mather's paper Pullbacks in Homotopy Theory. Different authors make slightly different definitions, and there seems to be fair amount of abuse in the terminology some adopt. I'll try to say some words about this later on.
A homotopy pullback is a pair $(\mathcal{S},F)$ consisting of a homotopy commutative square $\mathcal{S}$ of topological spaces and continuous maps
\begin{CD}
P @>q>> Y\\
@VpVV @V{g}VV \\
X @>{f}>> Z
\end{CD}
together with a chosen homotopy $W:fp\Rightarrow gq$ which, together, must satisfy the following properties
$\bullet$ Given a space $A$, maps $\alpha:A\rightarrow X$, $\beta:A\rightarrow Y$, and a homotopy $F:f\alpha\Rightarrow g\beta$ there exists a map $\theta=\theta(\alpha,F,\beta):A\rightarrow P$ and a pair of homotopies $K:\alpha\Rightarrow p\theta$, $L:\beta\Rightarrow  q\theta$ such that there is a 2-homotopy
$$-gL+W\theta+fK\Rrightarrow F :A\rightarrow D$$
$\bullet$ If $\theta':A\rightarrow P$ is another map, and $K':\alpha\Rightarrow p\theta'$, $L':\beta\Rightarrow q\theta'$ another pair of homotopies for which there exists a 2-homotopy $-gL'+W\theta'+fK'\Rrightarrow F$, then there exists a homotopy $M:\theta\Rightarrow \theta'$ and 2-homotopies
$$K+pM\Rightarrow K',\qquad -L'+qM\Rrightarrow L.$$
I've tried to write this definition in the spirit of your question: a 2-homotopy is a homotopy of homotopies. So if $F,G:f\Rightarrow g$ are homotopies, then a 2-homotopy $\Psi:F\Rrightarrow G:X\rightarrow Y$ is a map $\Psi:X\times I\times I\rightarrow Y$ with
$$\Psi(x,s,0)=F(x,s),\quad \Psi(x,s,1)=G(x,s),\quad \Psi(x,0,t)=f(x),\quad \Psi(x,1,t)=g(x)$$
for all $x\in X$ and $s,t\in I$. The point is that this becomes a really convoluted way of expressing things in the case of this simple square diagram. It's much easier to ask that, for instance, $[-gL+W\theta+fK]=[F]$ as track classes of homotopies, since we never need to go to 3-homotopies or above for the square diagram.
What is important to note is that the word "unique" never appears in the above. When the chance for such a statement occurs we ask instead only that there exist a homotopy, or a 2-homotopy, or a 3-homotopy, or a... This is very much in the spirit of homotopy coherence. The point I was trying to make in the comments is that we never really see this idea take off with the square diagram. If you want to understand homotopy coherence you really need to consider slightly more interesting digrams. You might like to think about Stasheff's theory of $A_n$-spaces, for instance, or some homotopical group actions, before going on to study the (mainly simplicial) techniques developed by Cordier-Porter and discussed by Riehl and Shulman.
Now, I'll try to justify what I said in the opening. Really a homotopy pullback is a (right) derived functor of the limit functor, applied to diagrams indexed on the cospan category
$$\mathcal{P}=\left(\bullet\rightarrow\ast\leftarrow\square\right).$$
Now these gadgets can be discussed in any reasonable model category, and come in two main flavours. Name what are called total derived functors, and what are called point-set derived functors (this is Shulman's terminology). Total derived functors are defined on the homotopy category of diagram, and take values in the homotopy category of spaces. They satisfy a certain universal property which is very weak, and come equipped with only the bare minimum of structure. Since they are defined on homotopy category, there are not maps - only homotopy classes of maps - and no homotopies involved in their definition. In particular, with reference to the square above, the maps $p,q$ are not even part of their stucture.
On the other hand, a point-set derived functor is defined on diagrams and takes values in spaces (rather than homotopy categories). The universal property it satisfies is the same as the total derived functor, after projecting to the homotopy category. Of course, to arrange for this to be true it comes supplied with actual maps, and homotopies of such to ensure this universal property will hold. The definition I have given above is closer to this sort of derived functor.
Of course, the homotopy pullback square I've defined above is really its own thing. Different authors required different amounts of the available structure for their work, and are willing to spend different amounts of time setting up the theory. Hence you will find slightly different definitions across the literature. Personally I'd be very wary of anything written on nlab, and would rather follow up their well-collected references to understand the theory.
As motivation for the definition I've given let me end with this. Often when doing homotopy theory it is not enough to work with only homotopy classes of maps. Supplying specific homotopies can be really useful for defining secondary operations and compositions such as Massey products or Toda brackets. Including the homotopy $F$ together with the homotopy-commuting square $\mathcal{S}$ as part of the structure can be really useful when you sit down to actually make computations.
Comment: Those 'implicit maps' are included as, say, the time $1/2$ maps of the homotopies $W:P\times I\rightarrow A$ and $F:A\times I\rightarrow Z$. The ability to vary the 2-homotopy classes of these homotopies gives flexibility on the homotopy classes of these maps. Note how this works in your example: there is a 1-1 correspondence between maps $f:X\rightarrow \Omega Y$ and sef-homotopies $F:\ast\Rightarrow\ast$ of the constant map $X\rightarrow Y$.
Comment: The situation you suggest doesn't pan out, since the homotopy $F:\Omega S^1\times I\rightarrow S^1$, $F_s(\omega)=\omega(s)$ doesn't factor through the trivial homotopy.
Comment: Is it also necessary to include that there are implicit maps $P \rightarrow Z$ and $A \rightarrow Z$ which the maps $gq$ and $fp$ and $g \beta$ and $f \alpha$ must be homotopic to, respectively? I am imagining hiccup with a diagram like $* \rightarrow S^1 \leftarrow *$, where we could claim that a candidate space $A$ could be $S^1$ with homotopy $F:S^1 \times I \rightarrow S^1$ given by the projection $(s,t) \mapsto s$. I think this would still satisfy the above, and we don't want it to, is that correct?

Homotopy coherence


Are you allowed to fake a field goal or punt?

Question: Whenever an offense reaches the 4th down in American Football, i.e. they didn't achieve to get a new 1st down in their past 3 attempts, they're faced with basically 2 fundamentally different options. They can either play that down as a "normal" offensive play in order to reach a new 1st down, or they can either punt the ball or attempt a field goal, depending how far they are from the end zone.
The usual strategy is to settle for a punt or field goal, unless the situation is rather urgent (i.e. you can't risk giving your opponent the offense) and/or you're confident you can make a new 1st down. What I haven't ever seen in the NFL (although, I'm only following it rather actively for about 2 seasons) is a faked field goal attempt or punt and I wonder if this is even possible. What I mean is making the play look like a field goal/punt, i.e. putting the special team and kicker on the field, and then having the kicker actually run (or pass?) the ball instead, trying to make a normal 4th down attempt.
So do the rules actually allow you to fake a field goal attempt or punt which you then transform into a normal play or does making a genuine field goal attempt require you to go through with this and not doing so would just result in a failed field goal? Is there a difference between punt and field goal in this regard? Or is there a difference between various rule sets, i.e. College and NFL? If you are technically allowed to do that to some degree in the NFL, then why isn't it done more often as a trick play?
Comment: The Colts faked a punt on Thanksgiving. https://www.youtube.com/watch?v=6ZR4mH_vT3o
Comment: You don't have to go through with a punt/field goal attempt if lined up as such prior to the snap (many examples can be found via your preferred search engine). I'm not sure if the rules address a fake punt/field goal specifically, but descriptions of a [fake punt](https://en.wikipedia.org/wiki/Trick_play#Fake_punt) and  [fake field goal](https://en.wikipedia.org/wiki/Trick_play#Fake_field_goal) are found at Wikipedia.
Comment: Wouldn't worry about it, it was an honest question, sometimes we overlook things!  You aren't the only one who's wondered, I'm sure.  Another one to note, as was loosely alluded to in Coach-D's answer, was the opposite reality, of a https://en.wikipedia.org/wiki/Quick_kick.  Field goals out of situation are very rare (I've never seen one in hundreds of games, though I see Coach-D links to one)... but punts from other formations do happen a bit more often.  Though both are less common than fake field goals or fake punts, which probably happen every 5-10 games or so.
Comment: If you have been following the NFL for two seasons, I'm surprised you are not aware of the Seahawks' [fake field goal in the NFC Championship game](http://www.nfl.com/videos/green-bay-packers/0ap3000000460213/Seahawks-fake-field-goal), less than two years ago.
Comment: @JeopardyTempest - maybe just a trend in my area but punters line up in a shotgun formation more than a traditional punt formation.   Also "bad" punters are taught to roll out to their kicking foot if they see there is no rush.  This allows gunners more time to get downfield.  My son's high school team had a very average (being nice) with a 40 yard average because half his kicks bounced within 20 yards but returner couldn't do anything because gunners were past the ball... so it rolls another 10-30 yards (turf) and all of a sudden, good punt.
Comment: good thing Lucy Van Pelt doesn't have a grave to roll over in.
Comment: Yeah, apparently I'm a moron anyway, I even watched that Thanksgiving game. Sorry, that question is starting to get embarrassing. :'(
Comment: Teams can certainly deceive the defense, and here are around thirty video examples of such fake-punt formations used to great effect: https://youtu.be/Sq1z1P9AK78.
Answer: A punt has no special bearing and follows the rules of football.  Meaning you must have 7 men on the line of scrimmage, the end players are eligible, the backs are eligible, you are allowed a forward pass and so on.  You can punt on 1st down if you want.
For punting anyone can do it behind the line of scrimmage.   There are several rules around what happens during a punt but more or less any player can punt, they can punt on any down, and the opposing team can return the ball or take it where it is downed.
For field goals it is the same thing.  You can do it on any down and the play follows the rules of football.  Really the only difference on field goals is the place holder is allowed to stand up and become an active player in the play even though they are kneeling on the ground when they catch the ball.  This is the one allowance offered for fake field goals.
Notes:

punt or field goal can happen in any formation.  Even the traditional shotgun has led to a field goal try (last one I remember was a drop kick by Flutie)
punt/field goal does offer the kicker protection more so than any other player on any other play.  But they aren't the kicker unless they are kicking.  Also refs are much less likely to offer this protection if the play is very non-standard.  Meaning on a punt if the punter looks like he is taking off running, then pulls up and kicks it at the last second, the defender would be allowed to hit him if he was already in the act of tackling before kick.
drop kicks are things too.  But that is a different question and categorized under field goal tries.
I have seen punts used as a weapon - rarely and not lately.  But if you get a player who is extremely good kicker on the run, he can perform a squib pseudo-rugby kick.  If this kick hits a defender beyond the line of scrimmage, the offensive player can pick up the ball and play it.  It is an extremely dangerous play but with the right skill set could make defending the punt rather hard.
Answer: Yes you can fake both.  They are very difficult to pull off but have succeeded in the past.  They are so difficult for many reasons, the first two I can think of:

The line-up (positions and personnel) is specific to make a kick successful and not another type of play.  For example look at how far
back the ball is sent to a kicker / placeholder compared to a
quarterback in shotgun formation.
Also, other teams are always prepared to defend against this.


Checking if model is null fails

Question:     @model Seriebeheer.Domain.Serie

    @{
        ViewBag.Title = "Verijwder serie";
        Layout = "~/Views/Shared/_AdminLayout.cshtml";
    }

    @if (Model != null)
    {

Verwijder @Model.Name

    Weet u zeker dat u deze serie wilt verwijderen? Dit zal ook alle afleveringen van deze serie verwijderen!

    using (Html.BeginForm("Delete", "SerieAdmin", FormMethod.Post, new {enctype = "multipart/form-data"}))
    {
        @Html.AntiForgeryToken()
        @Html.Hidden("id", @Model.ID)
        <input type="submit" value="Verwijder" />
    }

} else
{ Deze serie bestaat niet }

The above code fails on the "weet u zeker..." line (expected ;). What's wrong with this null check?
Thanks
EDIT:
The exact error message:
 Foutbericht van compiler: CS1002: ; wordt verwacht
Translateed: error message from compiler: CS1002: expected ;
Comment: what's the exact error?
Comment: **Please translate the error into English**  Please provide the code where you define and declare `Model`
Answer: Razor engine treats everything in curly brackets { } as code if it is not between html tags. For this one to work you have to add  before Weet and  after verwijderen! to this to work. (OF course you can use any html tag you like/want :)
Answer: Better change this
  Weet u zeker dat u deze serie wilt verwijderen? Dit zal ook
   alle afleveringen van deze serie verwijderen!

to
<text>  Weet u zeker dat u deze serie wilt verwijderen? Dit zal ook
       alle afleveringen van deze serie verwijderen!
</text>

wrapping with text  node would be a better choice, which will not hurt your CSS or html
Also the Razor view engine will not assume that its a server side code as it start with HTML tag. In your case you are writing
Html inside razor with out @{}

Checking if model is null fails


Adding strings and values to a hash table in C

Question: I'm trying to add a persons and number to a hash table, but when I'm adding these values I get the incompatible pointer types passing 'char *[20]' to parameter of type 'char *' error.
I'm also getting an EXC_BAD_ACCESS (code=1, address=0x140) when assigning the customer_number to the index.
<code>
typedef struct
{
    char *first_name[20];
    int customer_number;
} Customer;

Customer *list[10];
int hash_table[10];

void insert(char *first_name, int customer_number)
{
    int index = calculate_hash(customer_number);

    list[index]->customer_number = customer_number;
    strcpy(list[index]->first_name, first_name);
    hash_table[index]=customer_number;
}

int main(void)
{
    insert("Chris", 9999);
    return 0;
}
</code>
When the insert is passed a first name and phone_number, I want these to be added to the hash.
Comment: For the other problem, you have an array of pointers that don't point to anything.
Comment: Thank you! Very helpful. I'm just getting used to C :D
Answer: There are a number of issues here. You need to look again at pointers and buffer overflows...
<code>#define CUSTOMER_NAME_MAX_LEN 20

typedef struct
{
    char first_name[CUSTOMER_NAME_MAX_LEN + 1];
    int customer_number;
} Customer;

Customer list[10];
int hash_table[10];

int calculate_hash(int customer_number) {
  return 3;
}

void insert(char *first_name, int customer_number)
{
    int index = calculate_hash(customer_number);

    list[index].customer_number = customer_number;
    list[index].first_name[CUSTOMER_NAME_MAX_LEN] = 0;     // Avoid buffer overflow.
    strncpy(list[index].first_name, first_name, CUSTOMER_NAME_MAX_LEN);
    hash_table[index]=customer_number;
}

int main(void)
{
    insert("Chris", 9999);
    printf("%s %i\n", list[3].first_name, list[3].customer_number);
    return 0;
}

// Outputs Chris 9999
</code>
Comment: If you're going to use `strncpy()`, you have to make sure the result gets 0-terminated. It won't in this if the name is 20 characters or more...
Comment: Thank you for your help, I'm starting to see where I'm going wrong.
Comment: @Shawn It does get null terminated because on the previous line I set the last element to zero.


Joint density function of $\vert X\vert$ and $\vert Y\vert$.

Question: I am given such a question:
Let $(X,Y)$ be a point randomly chosen on region $R = \{(x,y):  |x| +  |y| \leq 1 \}$. Find the marginal densities of X and Y.
The graph looks like a diagonal square with vertices at $x=1,x=-1,y=1,y=-1$. In order to find the marginal density of $x$, I need to find the following integral:
$$f_x(x)=\int^{x+1}_{-x-1}f_{x,y}(x,y)dy$$
I had no idea how to proceed given the absolute values, until I referred to the solution which gave the next step as
$$f_x(x)=\int^{x+1}_{-x-1}f_{x,y}(x,y)dy=\int^{x+1}_{-x-1}\frac{1}{2}dy$$
Can anyone point out to me where did the $\frac{1}{2}$ come from?
Thank you!
Comment: The area of the diagonal square is $2$ so the joint density is $1/2$
Answer: Since we are dealing with absolute values, we are going to split this problem into two cases: $x > 0$ and $x < 0$.
If $x \geq 0$, then $|y| \leq 1-x$ and thus $x-1 \leq y \leq 1-x$.
If $x < 0$, then $|y| \leq 1 + x$ and thus $-x-1 \leq y \leq 1+x$.
Now, since we assume every point within $R$ has the same chance of occurring, the joint density function of $(X,Y)$ is
$$f_{X,Y}(x,y) = \frac{1}{\text{area of diagonal square}} = \frac{1}{2}.$$
To obtain the marginal density of $X$ we have to integrate over all the values that $y$ can take on, and thus
\begin{align}
f_X(x) &= \int_{-x-1}^{1+x} \frac{1}{2}\ dy \ \mathbb{1}_{[-1,0)}(x) \ + \int_{x-1}^{1-x} \frac{1}{2}\ dy \ \mathbb{1}_{[0,1]}(x) \\[0.5em]
&= (x+1)\ \mathbb{1}_{[-1,0)}(x) \ + \ (1-x)\mathbb{1}_{[0,1]}(x).
\end{align}
So, we can write the marginal density as follows:
$$f_X(x) = \begin{cases}x+1, & -1 \leq x < 0 \\
1-x, & \ \ \ 0 \leq x \leq 1 \\
0,& \ \ \ \text{otherwise}. \tag{1}\end{cases}$$
If you graph $(1)$ you will see that the marginal density of $X$ is has the form of a triangle with vertices on  $(-1,0),(0,1)$ and $(1,0)$.


CakePHP - página com uso de mais de uma table

Question: Eu tenho uma dúvida, sobre salvar dados no banco de dados usando CakePHP, quando precisa manipular com mais de uma tabela.
Eu estou criando um sistema de cadastro de clientes e nele tem um um sistema para cadastrar login's e senhas do cliente, como painel de controle, banco de dados, etc.
A estrutura do banco de dados
Clientes
Tem os campos com os dados do cliente, como telefone, email, etc
opcoes

id
opcao (nome da opção, como painel de controle, banco de dados, etc)
usuario_ativ (campo para indicar se tal opção vai ter preenchimento de usuário)
host_ativ (campo para indicar se tem o host/ip, como banco de dados... painel de controle não teria esta opção

rel_op_cliente

id_cliente
id_opcao
senha
host
usuario

Eu consegui resolver a questão de no formulário aparecer os dados, no controller de cliente eu coloquei public $uses = array('Cliente','Opcao', 'RelInfoCliente'); e com isso ele consegue capturar os dados das 3 tabelas... mas no caso de salvar os dados do form, qual seria a melhor forma que ao salvar o cliente salve os dados das opções, se eu alterar o nome de usuário alterar na tabela rel_op_cliente
Comment: Eu não entendi direito. Mas me parece que você não estabeleceu uma relação (hasMany, hasOne, etc...) entre elas, estabeleceu?
Se não, você deve repensar suas tabelas e models e fazer o link entre elas corretamente. http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
Comment: Eu acho que você tem uma relção de `hasMany`ou `hasMany trought` da uma olhada e estabeleça essa relação usando a conveção correta do cakephp. Vai ficar muito mais facil de trabalhar
Comment: qual a relação entre essas tabelas?
Comment: clientes seria tipo a tabela pai, o rel_op_cliente relaciona com o clientes. Tabela clientes tem o campo id e rel_op_clientes tem o id_cliente, as duas ligam dessa forma. A tabela opcoes liga com o rel_op_cliente por meio do id_opcao. Não sei se expliquei claro, mas resumindo, rel_op_clientes é onde fica armazenado os dados e opcoes seria o nome desses dados, como painel de controle, banco de dados e teria também o campo de ativar ou desativar alguns campos (na exibição), como painel de controle que não é necessário aparecer o ip, é só usuário e senha
Comment: Entendi, vou dar uma pesquisada nessa questão.
O esquema seria simples, rel_op_cliente liga com cliente, opcoes liga com o rel_op_cliente... mas vou analisar melhor, que parece ser a melhor solução para o problema de linkar, e iria ser do modo correto do que eu fiz
Comment: Valeu cara, já tinha feito com hasMany e ficou bem melhor que a solução que fiz de array( 'joins'... etc.... No caso, teria um pai, filho e neto, a associação, vou dar uma olhada nesta questão de relação hasMany trought.... Para exibição parece perfeito, depois vou ver se para salvar segue a mesma ideia
Comment: Bem, eu ainda estou quebrando um pouco a cabeça, do cliente ligando com a tabela rel_op_cliente está perfeito, agora esse rel_op_cliente teria que ser ligado com o opcoes... usei o hasmany em cliente e em rel_op_cliente coloquei, mas quando dou um vardump não aparece as informações da tabela opcoes, como se não estivesse fazendo a ligação, o opcoes seria como uma classe neto. Cliente liga com o rel_op_cliente que liga com o opcoes. Essa parte que não estou conseguindo resolver
Comment: Para que o cakephp funcione corretamente você tem que usar as suas conveções. Sua tabela `rel_op_cliente` não segue a conveção de nome de tabela do cakephp. Explique um pouco mais sobre o que pretende fazer e qual a função dessas tabelas na sua pergunta que te ajudo a relaciona-las.
Comment: Bem, colocando a estrutura |

**Clientes**

id = 3

nome = Braulio

**rel_op_clientes**

id_cliente = 3

id_opcao = 2

senha = 123

usuario = braulio_holtz

host = 192.168.0.1

**opcoes**

id = 2

opcao = Banco de dados mysql

usuario_ativ = 1

host_ativ = 1

| Seria mais ou menos esse esquema que estaria, acho que dá para compreender um pouco, em clientes fica os clientes, em rel_op_clientes fica a relação clientes e opções, em opções fica os nomes dos campos que entra o usuário e senha, tipo, painel de controle, banco de dados, etc
Comment: Cara, então é isso mesmo. Você tem uma relação onde `Usuarios HABTM Opcoes`. Você deve olhar a opção `HABTM`no link que te passei e nomear a tabela de acordo com o que está lá!!
Comment: Mas e o caso da tabela rel_op_clientes? o Opcoes seria tipo mostrar o nome do campo, por exemplo, lá teria o id e o nome, onde o nome seria por exemplo, Painel de controle, banco de dados, etc, basicamente esta tabela seria apenas mostrar qual é o campo escolhido, evitando ter que a cada cadastro de clientes colocar as mesmas coisas (como painel de controle que todas as hospedagens tem)... Não é uma tabela de usuários para logar no sistema, é uma tabela com registros de dados dos clientes de login's e senhas para múltiplos serviços (Paineis de controle, banco de dados, etc)
Comment: Exatamente. A tabela de usuarios podem ter as informaçoes que você quiser e voce deve criar uma terceira tabela `opcoes_usuarios` onde irá conter `user_id` e `option_id` assim você pode relacionar varios usuarios com varias opcoes. Leia sobre o `HABTM`
Answer: Resolvido a questão
public  $hasAndBelongsToMany  =  array (
    'opcoes_clientes'  =>  array (
        'className'  =>  'opcoes' ,
        'joinTable' => 'rel_infos_clientes',
        'foreignKey'  =>  'id_cliente' ,
        'associationForeignKey'  => 'id_opcao',
        'dependent'  =>  true
    )
);

No caso só estou mudando o nome da tabela para ficar dentro da convenção, mas agora entendi. joinTable seria a tabela intermediária e em classname seria a classe com a tabela "neto"...
Comment: que bom que conseguiu, cara! =)
Comment: Valeu pela ajuda, mudei para a convenção, ficou melhor ainda, dai não precisei colocar joinTable, ForeignKey, AssociationForeignKey


How to remove a value from URL parameter?

Question: I'm using entity reference prepopulate and views. On the start of my node add form I'm using views to display some products and I have created a PHP button to pass the nid of those products to the URL. Here is the code:
<?php
$url = token_replace('[current-page:url]');
$l = l( t('SELECT THIS VENUE'), $url,  array('query' => array('field_product_venue' =>$row->nid )  ));
echo $l;
?>

And on the last part of my node add form the user can see the summary of all the products he or she has chosen but he or she must also have the ability to remove those items, since the form gets its selected products from the url I want to create a button that deletes that specific product (nid) from the URL.
Any help would be greatly appreciated.
Answer: You need to get the value of the parameter, then check if the parameter contains the nid, then replace/remove the nid on your parameter from your url.
Use this code on your Views: PHP
<?php
$url = token_replace('[current-page:url]');
$venue =$_GET['field_product_venue'];
if (strpos($venue, $row->nid) !== false) {
$change= str_replace($row->nid .',', '', $venue);
$l = l( t('DELETE'), $url,  array('query' => array('field_product_venue'=>$change)  ));
echo $l;
}
?>

Comment: Looks promising will try later. :D


How to document functions that are assigned, rather than defined?

Question: When using functional programming in Python, I'm finding myself declaring functions with assignment, e.g.
where = compose(pluck(0), filter(get(1)), enumerate)

rather than using def, e.g.
def where(seq):
    """Return the indices of truthy values in a sequence."""
    return pluck(0, filter(get(1), enumerate(seq))

The first method is elegant and terse, but there's no docstring, which is unacceptable. The second method allows for a docstring but is less elegant, and less in the functional style.
What's the best practice for documenting functions created by assignment in Python?
Answer: There is a means by which you can document such functions in Python; however, it's not considered good practice to do so. Despite how def fun doesn't seem in the functional style unfortunately for now at least, it seems to be the best practice. The workaround can be seen below:
where = compose(pluck(0), filter(get(1)), enumerate)
where.__doc__ = """some docstrings here"""

Comment: I considered that but also determined it was inadequate, as you say. I'll stick with `def` for now. Thanks!


How to present KM estimate for mean and median survival times for those with small no. of events?

Question: I wanted to obtain the mean and median survival times using survfit and Surv but due to the small event size, I can't obtain them. How should I proceed with analysing this survival data?
sfit <- survfit(Surv(time_to_event, event) ~ 1, data = df)
sfit
Call: survfit(formula = Surv(time_to_event, event) ~ 1, data = df)

      n  events  median 0.95LCL 0.95UCL
     62      15      NA      NA      NA

Answer: With only 15 events out of 62 cases, it seems likely that your Kaplan-Meier curve hasn't even reached the median survival yet. See this page for a similar situation.
Unless the very last time is an event (which can't be the case if you haven't yet reached the median survival), the mean survival will be a truncated value calculated out only to some particular time. The survfit() function does allow for such mean survivals, but you have to specify what type of upper time limit you want (your call to the software might have specified "none" for that mean calculation) and they aren't always very informative in any event.
The best way to present the data is to show the Kaplan-Meier curve with confidence limits. You could consider showing values and CI for a survival time you have reached, perhaps 80% survival.