How can I insert an additional SystemStartBrace into a PianoStaff in Lilypond?

Question: A piece of sheet music uses two separated bars as coda. These bars also have a SystemStartBrace and a normal bar line.
When recreating this with Lilypond I have not figured out yet, how to put these elements into the sheet music. For this example, I followed the snippet from the Lilypond documentation Positioning segno and coda (with line break) with some minor adjustments and without line break.
If I understand it, the staves are interrupted for the "D.S. con rep." text and then continue for the coda. So it is the same PianoStaff.
Is there a way to draw a system start brace and a bar line at the beginning of the coda?
Original:

Lilypond:

Edit 1:
Adding a snippet showing non-compiling code using @jeanas solution.
\version "2.24.1"
\include "replicate-delims.ly"

\new PianoStaff <<
  \new Staff \relative c' {
    r2 c8 d e4 ~
    e r8 b8 b c d d ~
    4 c r4 a8 b
    c4 a8 c f e d e ~
    4 r4 <c e>8 <d f> <e g>4 ~
    4 r8 8 8 <c e> <d f>8 8 ~  %% comment this line
    4 <c e> ~ 4 r4          %% and this, too, then it compiles
    \stopStaff
    s1*2
    \replicateDelims
    \startStaff
    \clef violin
    <>^\markup { \musicglyph "scripts.coda" }
    c'1  \bar "|."
  }
  \new Staff {
    \clef bass
    R1*7        %% may reduce to 5 after commenting above lines
    \stopStaff
    s1*2
    \startStaff
    \clef bass % <-- not showing
    c'1
  }
>>

Comment: This is quite tricky to do. Perhaps look into https://firstname.lastname@example.com/msg139604.html for ideas.
Comment: I will have a closer look at it. Looks really complicated though.
Another idea is to use a second score for the coda. This will have the brace, but the system starts on a new line. I have not yet figured out, how to suppress the line break.
Comment: Believe me, there's really no way to suppress the line break at the end of a \score. It's deeply hardwired in LilyPond's brain.
Comment: In reply to the bounty request: what do you mean by a "pure LilyPond" solution? A solution not involving Scheme? There are solutions that are much shorter than the very general solution I linked to, but with my LilyPond developer hat on, I don't believe there is a solution without Scheme code.
Comment: With 'pure' I mean everything that the Lilypond compiler can process. So, Scheme is fine, too. Non-pure would be using LaTeX to stitch stuff together, e.g. inserting a second PDF containing the coda.
Answer: This is the simplest way I can think of:
\version "2.24.1"

%% probably put this in an \include file

#(define replicate-stil
   (grob-transformer
    'stencil
    (lambda (grob original)
      (let* ((replicate (ly:grob-array->list (ly:grob-object grob 'replicate-on-cols)))
             (left (ly:spanner-bound grob LEFT))
             (own (interval-start (ly:paper-column::break-align-width left 'clef)))
             (sts (map (lambda (col)
                         (let ((tr (interval-start (ly:paper-column::break-align-width col 'clef))))
                           (ly:stencil-outline
                            (ly:stencil-translate-axis original (- tr own) X)
                            empty-stencil)))
                       replicate)))
        (apply ly:stencil-add (cons original sts))))))

\layout {
  \context {
    \Score
    \consists
      #(lambda (context)
         (let ((delims '())
               (cols '()))
           (make-engraver
            (acknowledgers
             ((system-start-delimiter-interface engraver grob source-engraver)
              (set! delims (cons grob delims))))
            ((stop-translation-timestep engraver)
             (let ((col (ly:context-property context 'currentCommandColumn)))
               (when (assoc-get 'replicate-delims (ly:grob-property col 'details))
                 (set! cols (cons col cols)))))
            ((finalize engraver)
             (for-each (lambda (delim)
                         (ly:grob-set-object! delim 'replicate-on-cols (ly:grob-list->grob-array cols)))
                       delims)))))
    \override SystemStartBar.stencil = #replicate-stil
    \override SystemStartBracket.stencil = #replicate-stil
    \override SystemStartBrace.stencil = #replicate-stil
    \override SystemStartSquare.stencil = #replicate-stil
  }
}

replicateDelims = {
  \once \override Score.NonMusicalPaperColumn.details.replicate-delims = ##t
  \once \set Staff.forceClef = ##t
  \once \override Staff.Clef.full-size-change = ##t
  \once \set Score.measureBarType = ##f
  \once \override Score.BreakAlignment.X-extent =
    #(lambda (grob)
       (match-let (((a . b) (ly:axis-group-interface::width grob)))
         (cons (- a 0.8) b)))
}

%% main file

\new PianoStaff <<
  \new Staff \relative c' {
    r2 c8 d e4 ~
    e r8 b8 b c d d ~
    4 c r4 a8 b
    c4 a8 c f e d e ~
    4 r4 <c e>8 <d f> <e g>4 ~
    4 r8 8 8 <c e> <d f>8 8 ~
    4 <c e> ~ 4 r4
    \stopStaff
    s1*2
    \replicateDelims
    \startStaff
    \clef violin
    <>^\markup { \musicglyph "scripts.coda" }
    c'1  \bar "|."
  }
  \new Staff {
    \clef bass
    R1*7
    \stopStaff
    s1*2
    \startStaff
    \replicateDelims
    \clef bass
    c'1
  }
>>

Comment: I tried this approach with my score, but the compiler aborts with error at `init.ly:65:2: Guile signaled an error for the expression beginning here: #
 (let ((book-handler (if (defined? 'default-toplevel-book-handler)
In procedure ly:grob-extent: Wrong type argument in position 1 (expecting Grob): #`
After commenting the `\replicateDelims` command, the file compiles fine. Commenting all music following a specific position does the same with the `\replicateDelims` command active, but I don't see anything wrong with the music itself.
Comment: I have added a snippet to my question labelled as "Edit 1".
Comment: As an additional note: when adding clefs in the above minimal example they will be smaller and an additional bar line is added after them and before the coda music. This can be fixed by overriding Staff.Clef attributes and omitting BarLines as shown in @Lazy answer. However, I need to use `\clef bass` at the beginning of the left hand staff and then the bass clef is no longer shown at the start of the coda.
Comment: Can you share your code, or a snippet reproducing the problem?
Comment: Pff, I made a stupid mistake. I'll correct it when I'm back home.
Comment: @AndreasN I have updated the answer.
Comment: I selected this answer as preferred solution because I just have to use a single command to make a system brace, whereas in Lazys solution an additional  inline is required. Overall, both solutions work perfectly fine. It's a photo finish.
Answer: This is not something Lilypond supports natively, so we have to somehow get this done ourselves. This code here tries to replicate the default delimiters behaviour. Currently this has Brace, Bracket and Bar implemented. This could then be expanded to allow for in Staff Instrument names and such.
#(define (inside-staff-linkage-gen)
   (let ((tree '()) (cc #f) (cc2 #f))
     (define (merge-branch-to-tree branch tree)
       (if (eq? (assoc-get 'context (car branch)) (assoc-get 'context (car tree)))
           (let* ((sub (map (lambda (x) (merge-branch-to-tree (cadr branch) x)) (cdr tree)))
                  (anysub (reduce (lambda (x y) (or x y)) #t (map car sub))))
             (if (not anysub)
                 (cons #t (cons (car tree) (append (cdr branch) (cdr tree))))
                 (cons #t (cons (car tree) (map cdr sub)))))
           (cons #f tree)))
     (define (add-to-tree el)
       (if (null? tree)
           (set! tree el)
           (set! tree (cdr (merge-branch-to-tree el tree)))))
     (define (tree-get-refpoints tree)
       (if (null? tree)
           '()
           (cons (assoc-get 'ref (car tree)) (apply append (map tree-get-refpoints (cdr tree))))))
     (define (tree-make-delimiter tree support)
       (let* ((engraver (assoc-get 'engraver (car tree)))
              (type (assoc-get 'type (car tree)))
              (refp (tree-get-refpoints tree))
              (grob #f))
         (cond ((eq? type 'SystemStartBrace)
                (set! grob (ly:engraver-make-spanner engraver 'InlineStaffBrace '())))
               ((eq? type 'SystemStartBracket)
                (set! grob (ly:engraver-make-spanner engraver 'InlineStaffBracket '())))
               ((eq? type 'SystemStartBar)
                (set! grob (ly:engraver-make-spanner engraver 'InlineStaffBar '()))))
         (if grob
             (begin
              (ly:grob-set-property! grob 'details `((ref . ,refp)))
              (ly:spanner-set-bound! grob LEFT cc)
              (ly:spanner-set-bound! grob RIGHT cc2)
              (ly:grob-set-object! grob 'side-support-elements (ly:grob-list->grob-array (cons cc2 support)))
              (cons grob support))
             support)))
     (define (tree-make-all-delimiters tree support)
       (if (pair? tree)
           (let ((sup2 (tree-make-delimiter tree support)))
             (map (lambda (t) (tree-make-all-delimiters t sup2)) (cdr tree)))))
     (lambda (action . args)
       (cond ((equal? action 'add-to-tree) (set! cc (cadr args)) (add-to-tree (car args)))
             ((equal? action 'make-delimiters) (set! cc2 (car args)) (tree-make-all-delimiters tree '()))
             ((equal? action 'clear-tree) (set! tree '()))))))

#(define inside-staff-linkage (inside-staff-linkage-gen))

#(define-event-class 'inline-staff-event 'music-event)

#(define (define-event! type properties)
   (set-object-property! type
                         'music-description
                         (cdr (assq 'description properties)))
   (set! properties (assoc-set! properties 'name type))
   (set! properties (assq-remove! properties 'description))
   (hashq-set! music-name-to-property-table type properties)
   (set! music-descriptions
         (sort (cons (cons type properties)
                     music-descriptions)
               alist<?)))

#(define-event!
  'InlineStaffEvent
  '((types . (inline-staff-event event))
    (description . "")))

#(set-object-property! 'InlineRef 'is-grob? #t)
#(set-object-property! 'InlineRef 'translation-type? ly:grob-properties?)
#(set-object-property! 'InlineStaffBrace 'is-grob? #t)
#(set-object-property! 'InlineStaffBrace 'translation-type? ly:grob-properties?)
#(set-object-property! 'InlineStaffBracket 'is-grob? #t)
#(set-object-property! 'InlineStaffBracket 'translation-type? ly:grob-properties?)
#(set-object-property! 'InlineStaffBar 'is-grob? #t)
#(set-object-property! 'InlineStaffBar 'translation-type? ly:grob-properties?)

#(define (inline-staff-brace::print grob)
   (define (font-get-brace font name)
     (ly:font-get-glyph font (format #f "brace~a" name)))
   (define (font-brace-exists font name)
     (not (ly:stencil-empty? (font-get-brace font name))))
   (define (internal-font-get-upper-limit font u)
     (if (font-brace-exists font u)
         (internal-font-get-upper-limit font (* 2 u))
         u))
   (define (font-get-upper-limit font) (internal-font-get-upper-limit font 1))
   (define (internal-font-get-count font l u)
     (if (< (1+ l) u)
         (let ((m (quotient (+ l u) 2)))
           (if (font-brace-exists font m)
               (internal-font-get-count font m u)
               (internal-font-get-count font l m)))
         l))
   (define (font-get-count font) (internal-font-get-count font 0 (font-get-upper-limit font)))
   (define (internal-font-fit-brace font l stc1 u stc2 height)
     (if (< (1+ l) u)
         (let* ((m (quotient (+ l u) 2)) (stcm (font-get-brace font m)))
           (if (> (interval-length (ly:stencil-extent stcm Y)) height)
               (internal-font-fit-brace font l stc1 m stcm height)
               (internal-font-fit-brace font m stcm u stc2 height)))
         stc1))
   (define (font-fit-brace font height)
     (let ((l 0) (u (font-get-count font)))
       (internal-font-fit-brace font l (font-get-brace font l) u (font-get-brace font u) height)))
   (define (grob-is-parent? grob axis par)
     (if (null? grob)
         #f
         (if (eq? grob par)
             #t
             (grob-is-parent? (ly:grob-parent grob axis) axis par))))
   (let* ((det (ly:grob-property grob 'details))
          (refs (assoc-get 'ref det))
          (refs (filter (lambda (x) x) refs))
          (stsym (map (lambda (r) (ly:grob-object r 'staff-symbol)) refs))
          (refp (ly:grob-common-refpoint-of-array grob (ly:grob-list->grob-array stsym) Y))
          ; If check is false this means that at least one staff symbol is on a different system
          ; This does most likely mean that the system is broken, in which case we do not want to print
          ; the delimiter
          (check (not (any (lambda (ss) (not (grob-is-parent? ss Y refp))) stsym)))
          (exts (if check (map (lambda (ss) (ly:grob-extent ss refp Y)) stsym) '()))
          (ext (reduce interval-union '(0 . 0) exts))
          (height (interval-length ext)))
     (if (or (not check) (< height (ly:grob-property grob 'collapse-height 5.0)))
         (ly:grob-suicide! grob)
         (let* ((font (ly:paper-get-font (ly:grob-layout grob) '(((font-encoding . fetaBraces)))))
                (bracstc (font-fit-brace font (interval-length ext))))
           (ly:stencil-translate-axis bracstc (interval-center ext) Y)))))

#(define (inline-staff-bracket::print grob)
   (define (grob-is-parent? grob axis par)
     (if (null? grob)
         #f
         (if (eq? grob par)
             #t
             (grob-is-parent? (ly:grob-parent grob axis) axis par))))
   (let* ((det (ly:grob-property grob 'details))
          (refs (assoc-get 'ref det))
          (refs (filter (lambda (x) x) refs))
          (stsym (map (lambda (r) (ly:grob-object r 'staff-symbol)) refs))
          (refp (ly:grob-common-refpoint-of-array grob (ly:grob-list->grob-array stsym) Y))
          ; If check is false this means that at least one staff symbol is on a different system
          ; This does most likely mean that the system is broken, in which case we do not want to print
          ; the delimiter
          (check (not (any (lambda (ss) (not (grob-is-parent? ss Y refp))) stsym)))
          (exts (if check (map (lambda (ss) (ly:grob-extent ss refp Y)) stsym) '()))
          (ext (reduce interval-union '(0 . 0) exts))
          (height (interval-length ext)))
     (if (or (not check) (< height (ly:grob-property grob 'collapse-height 5.0)))
         (ly:grob-suicide! grob)
         (let* ((font (ly:paper-get-font (ly:grob-layout grob) '(((font-encoding . fetaMusic)))))
                (tipsd (ly:font-get-glyph font "brackettips.down"))
                (tipsu (ly:font-get-glyph font "brackettips.up"))
                (thick (ly:grob-property grob 'thickness 0.25))
                (overlap (* 0.1 thick))
                (height2 (+ (/ height 2) overlap))
                (bracket-line (make-filled-box-stencil (cons 0 thick) (cons (- height2) height2)))
                (stc (stack-stencils Y DOWN 0 (list tipsu bracket-line tipsd)))
                (stc (ly:stencil-aligned-to stc Y CENTER))
                (stc (ly:make-stencil (ly:stencil-expr stc)
                                      (ly:stencil-extent bracket-line X)
                                      (ly:stencil-extent stc Y))))
           (ly:stencil-translate-axis stc (interval-center ext) Y)))))

#(define (inline-staff-bar::print grob)
   (define (grob-is-parent? grob axis par)
     (if (null? grob)
         #f
         (if (eq? grob par)
             #t
             (grob-is-parent? (ly:grob-parent grob axis) axis par))))
   (let* ((det (ly:grob-property grob 'details))
          (refs (assoc-get 'ref det))
          (refs (filter (lambda (x) x) refs))
          (stsym (map (lambda (r) (ly:grob-object r 'staff-symbol)) refs))
          (refp (ly:grob-common-refpoint-of-array grob (ly:grob-list->grob-array stsym) Y))
          ; If check is false this means that at least one staff symbol is on a different system
          ; This does most likely mean that the system is broken, in which case we do not want to print
          ; the delimiter
          (check (not (any (lambda (ss) (not (grob-is-parent? ss Y refp))) stsym)))
          (exts (if check (map (lambda (ss) (ly:grob-extent ss refp Y)) stsym) '()))
          (ext (reduce interval-union '(0 . 0) exts))
          (height (interval-length ext)))
     (if (or (not check) (< height (ly:grob-property grob 'collapse-height 5.0)))
         (ly:grob-suicide! grob)
         (let* ((lt (ly:output-def-lookup (ly:grob-layout grob) 'line-thickness))
                (thick (ly:grob-property grob 'thickness 1))
                (w (* lt thick))
                (height2 (/ height 2))
                (stc (ly:round-filled-box (cons 0 w) (cons (- height2) height2) lt)))
           (ly:stencil-translate-axis stc (interval-center ext) Y)))))

#(define (inline-spanner::minimum-length grob)
   (ly:output-def-lookup (ly:grob-layout grob) 'indent))

\layout {
  \context {
    \Global
    \grobdescriptions #`((InlineRef
                          . (
                              (meta
                                (name . InlineRef)
                                (classes Item)
                                (interfaces grob-interface)
                              )
                            )
                          )
                         (InlineStaffBrace
                          . (
                              (stencil . ,inline-staff-brace::print)
                              (direction . -1)
                              (X-offset . ,ly:side-position-interface::x-aligned-side)
                              (padding . 0.3)
                              (springs-and-rods . ,ly:spanner::set-spacing-rods)
                              (minimum-length . ,inline-spanner::minimum-length)
                              (meta
                                (name . InlineStaffBrace)
                                (classes Item Spanner)
                                (interfaces spanner-interface
                                            font-interface
                                            side-position-interface)
                              )
                            )
                         )
                         (InlineStaffBracket
                          . (
                              (stencil . ,inline-staff-bracket::print)
                              (direction . -1)
                              (extra-spacing-width . (-10 . 10))
                              (X-offset . ,ly:side-position-interface::x-aligned-side)
                              (padding . 0.8)
                              (thickness . 0.45)
                              (springs-and-rods . ,ly:spanner::set-spacing-rods)
                              (minimum-length . ,inline-spanner::minimum-length)
                              (meta
                                (name . InlineStaffBrace)
                                (classes Item Spanner)
                                (interfaces spanner-interface
                                            font-interface
                                            side-position-interface)
                              )
                            )
                         )
                         (InlineStaffBar
                          . (
                              (stencil . ,inline-staff-bar::print)
                              (direction . -1)
                              (X-offset . ,ly:side-position-interface::x-aligned-side)
                              (padding . -0.1)
                              (thickness . 1.6)
                              (springs-and-rods . ,ly:spanner::set-spacing-rods)
                              (minimum-length . ,inline-spanner::minimum-length)
                              (meta
                                (name . InlineStaffBrace)
                                (classes Item Spanner)
                                (interfaces spanner-interface
                                            font-interface
                                            side-position-interface)
                              )
                            )
                          )
                         )
  }
}

inline = #(make-music 'InlineStaffEvent)

#(define (inline-staff-engraver context)
   (define (make-branch context engraver childr ref)
     (let* ((par (ly:context-parent context))
            (type (ly:context-property context 'systemStartDelimiter))
            (typecontext (ly:context-property-where-defined context 'systemStartDelimiter))
            (type (if (eq? context typecontext) type '()))
            (leaf `((context . ,context) (type . ,type) (engraver . ,engraver) (ref . ,ref))))
       (if par
           (make-branch par engraver (cons leaf (list childr)) #f)
           (cons leaf (list childr)))))
   (define (get-column context allow-musical?)
     (if (and (ly:moment<? (ly:make-moment 0 0) (ly:context-property context 'measurePosition))
              allow-musical?)
         (ly:context-property context 'currentMusicalColumn)
         (ly:context-property context 'currentCommandColumn)))
   (make-engraver
    (listeners
     ((inline-staff-event engraver event)
      (let* ((ref (ly:engraver-make-grob engraver 'InlineRef '()))
             (branch (make-branch context engraver '() ref)))
        (inside-staff-linkage 'add-to-tree branch (get-column context #t)))))
    ((process-music engraver)
     (inside-staff-linkage 'make-delimiters
                           (get-column context #t))
     (inside-staff-linkage 'clear-tree))))

\layout {
  \context {
    \Staff
    \consists #inline-staff-engraver
  }
}

\new PianoStaff \new PianoStaff <<
  \new Staff { c'4 4 4 4 \inline 4 4  }
  \new Staff { c'4 4 4 4 \inline 4 4 }
>>

\new PianoStaff \new PianoStaff <<
  \new Staff { c'4 4 4 4 \break \inline 4 4  }
  \new Staff { c'4 4 4 4 \inline 4 4 }
>>

\new StaffGroup \new StaffGroup <<
  \new Staff { c'4 4 4 4 \inline 4 4  }
  \new Staff { c'4 4 4 4 \inline 4 4 }
>>

\new PianoStaff <<
  \new Staff {
    c'4 4 4 4
    \cadenzaOn
    \stopStaff s1
    \cadenzaOff
    \startStaff
    \once\override Staff.Clef.full-size-change = ##t
    \once\override Staff.Clef.extra-spacing-width = #'(0 . 2)
    \once\override Staff.Clef.extra-offset = #'(0.5 . 0)
    \once \omit Staff.BarLine
    \once \omit PianoStaff.SpanBar
    \set Staff.forceClef = ##t
    \inline 4 4
  }
  \new Staff {
    c'4 4 4 4
    \cadenzaOn
    \stopStaff s1
    \cadenzaOff
    \startStaff
    \once\override Staff.Clef.full-size-change = ##t
    \once\override Staff.Clef.extra-spacing-width = #'(0 . 2)
    \once\override Staff.Clef.extra-offset = #'(0.5 . 0)
    \once \omit Staff.BarLine
    \set Staff.forceClef = ##t
    \inline 4 4
  }
>>

Comment: @AndreasN Interesting, it seems like at some point a change was implemented that repeated `\clef something` calls are omitted. Instead use `\set Staff.forceClef = ##t` to force a repeat of the current clef.
Comment: Seems like we raced… That works, although TBH it seems needlessly complicated to me. FWIW, I think we should eventually turn system start delimiters into items so that having separate grobs will not be needed.
Comment: @ABOUSAMRAJean Hello Jean, I suppose so, but arguing like in the old russian joke I got second place while you only got second last ... What my version goes for is to allow having the System preamble print anywhere within the System. If I can get this to print after the BarLine, with potential Instrument names and automatic hiding of the Staff symbol this could implement the whole "inside Staff start" thing while at the same time being break friendly.
Comment: @ABOUSAMRAJean I think potentially the whole System start preamble could be placed in this manner in the first place with a Clef like behaviour so that be can force a system start placed by a context option.
Comment: This works quite well, but as mentioned in the other answer from @jeanas the bass clef is not shown in the coda, if it was already used before in the staff. The violin clef works as I don't have to declare it before the coda.


Aplicar máscara em campos dinâmicos gerados após o onload da página

Question: Estou utilizando uma diretiva para mask em campo monetário, o trabalho é realizado na tela

o problema é quando insiro um novo item o ng-repeat insere novos campos sem a mask, faço a referencia para a classe e uso a directiva criada format="priceformat".
Ao clicar em + os novos itens não iniciam com a mascara utilizada.

var myApp = angular.module('myApp', []);

myApp.controller('PushController', function ($scope, $http, $timeout) {

    $scope.discriminations = [];

    $scope.discrimination = {
        id: '',
        name: '',
        value: 'R$ 0,00',
        value_addition: 'R$ 0,00',
        value_discount: 'R$ 0,00'
    };

       $scope.addDiscrimination = function() {
    var _length = $scope.discriminations.push({
                                                id: '',
                                                value: 'R$ 0,00',
                                                value_decimal: 0,
                                                value_addition: 'R$ 0,00',
                                                value_addition_decimal: 0,
                                                value_discount: 'R$ 0,00',
                                                value_discount_decimal: 0,
                                                observations: ''
    });

   };

    $scope.$watch('discrimination.id', function (value) {

        if (value != '') {

            alert(value);
            //     $scope.id_restaurant_menu = value;

        }
    });
});

// Angular
myApp.filter('priceformat', function () {
    var is_number = /[0-9]/;
    var prefix = 'R$ ';
    var suffix = '';
    var centsSeparator = ',';
    var thousandsSeparator = '.';
    var limit = false;
    var centsLimit = 2;
    var clearPrefix = false;
    var clearSufix = false;
    var allowNegative = false;
    var insertPlusSign = false;

    if (insertPlusSign) allowNegative = true;

    function to_numbers(str) {
        var formatted = '';
        for (var i = 0; i < (str.length); i++) {
            char_ = str.charAt(i);
            if (formatted.length == 0 && char_ == 0) char_ = false;
            if (char_ && char_.match(is_number)) {
                if (limit) {
                    if (formatted.length < limit) formatted = formatted + char_
                } else {
                    formatted = formatted + char_
                }
            }
        }
        return formatted
    }

    function fill_with_zeroes(str) {
        while (str.length < (centsLimit + 1)) str = '0' + str;
        return str
    }

    return function (str) {
        var formatted = fill_with_zeroes(to_numbers(str));
        var thousandsFormatted = '';
        var thousandsCount = 0;
        if (centsLimit == 0) {
            centsSeparator = "";
            centsVal = ""
        }
        var centsVal = formatted.substr(formatted.length - centsLimit, centsLimit);
        var integerVal = formatted.substr(0, formatted.length - centsLimit);
        formatted = (centsLimit == 0) ? integerVal : integerVal + centsSeparator + centsVal;
        if (thousandsSeparator || $.trim(thousandsSeparator) != "") {
            for (var j = integerVal.length; j > 0; j--) {
                char_ = integerVal.substr(j - 1, 1);
                thousandsCount++;
                if (thousandsCount % 3 == 0) char_ = thousandsSeparator + char_;
                thousandsFormatted = char_ + thousandsFormatted
            }
            if (thousandsFormatted.substr(0, 1) == thousandsSeparator) thousandsFormatted = thousandsFormatted.substring(1, thousandsFormatted.length);
            formatted = (centsLimit == 0) ? thousandsFormatted : thousandsFormatted + centsSeparator + centsVal
        }
        if (allowNegative && (integerVal != 0 || centsVal != 0)) {
            if (str.indexOf('-') != -1 && str.indexOf('+') < str.indexOf('-')) {
                formatted = '-' + formatted
            } else {
                if (!insertPlusSign) formatted = '' + formatted;
                else formatted = '+' + formatted
            }
        }
        if (prefix) formatted = prefix + formatted;
        if (suffix) formatted = formatted + suffix;
        return formatted
    }
});

myApp.directive('format', ['$filter',

function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            $(elem).priceFormat({
                    prefix: 'R$ ',
                    centsSeparator: ',',
                    thousandsSeparator: '.',
                    centsLimit: 2,
                    limit: 14,
                });

            ctrl.$formatters.unshift(function (a) {
                return $filter('priceformat')(ctrl.$modelValue)
            });
            ctrl.$parsers.unshift(function (viewValue) {
                return $filter('priceformat')(viewValue)
            });
        }
    };
}]);

Valor

        <input type="text" style="width: 100%; text-align: right;" ng-model="discrimination.value" format="priceformat" placeholder="R$ 0,00" class="money" />

Adicional

        <input type="text" style="width: 100%; text-align: right;" ng-model="discrimination.value_addition" format="priceformat" placeholder="R$ 0,00" class="money" />

Desconto

        <input type="text" style="width: 100%; text-align: right;" ng-model="discrimination.value_discount" format="priceformat" placeholder="R$ 0,00" class="money" />

            +

        <input type="text" style="width: 100%; text-align: right;" ng-model="obj.value" format="priceformat" placeholder="R$ 0,00" class="money" />

                    VALOR
                    ADICIONAL
                    DESCONTO
                    TOTAL

                    {{ discrimination.value }}
                    {{ discrimination.value_addition }}
                    {{ discrimination.value_discount }}
                    R$ 0,00

JSFiddle
Comment: Resolvido aplicando um plugin para mask de campo monetário https://github.com/assisrafael/angular-input-masks
Comment: Você pode postar o código com a resolução para ajudar outras pessoas com o mesmo problema?
Comment: Complementando o que disse o @GiovaniRaciPaganini, seria legal dizer por que você escolheu essa solução. Transformei sua resposta em comentário, mas se quiser pode editar a resposta original e desfazer a exclusão. Obrigado.
Answer: Você está aplicando o plugin assim:
$('.money').priceFormat({
    prefix: 'R$ ',
    centsSeparator: ',',
    thousandsSeparator: '.',
    centsLimit: 2,
    limit: 14,
});

Este trecho só será executado uma vez e irá aplicar o plugin somente aos elementos que já estão no DOM.
Uma alternativa é você chamar $.priceFormat em cada elemento diretamente função link da sua diretiva:
myApp.directive('format', ['$filter',

function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            $(elem).priceFormat({
                    prefix: 'R$ ',
                    centsSeparator: ',',
                    thousandsSeparator: '.',
                    centsLimit: 2,
                    limit: 14,
                });

            ctrl.$formatters.unshift(function (a) {
                return $filter('priceformat')(ctrl.$modelValue)
            });
            ctrl.$parsers.unshift(function (viewValue) {
                return $filter('priceformat')(viewValue)
            });
        }
    };
}]);

Desta forma cada vez que o angular processar um novo item que contenha a diretiva o plugin já será aplicado diretamente.
Veja funcionando:

var myApp = angular.module('myApp', []);

myApp.controller('PushController', function ($scope, $http, $timeout) {

    $scope.discriminations = [];

    $scope.discrimination = {
        id: '',
        name: '',
        value: 'R$ 0,00',
        value_addition: 'R$ 0,00',
        value_discount: 'R$ 0,00'
    };

       $scope.addDiscrimination = function() {
    var _length = $scope.discriminations.push({
                                                id: '',
                                                value: 'R$ 0,00',
                                                value_decimal: 0,
                                                value_addition: 'R$ 0,00',
                                                value_addition_decimal: 0,
                                                value_discount: 'R$ 0,00',
                                                value_discount_decimal: 0,
                                                observations: ''
    });

   };

    $scope.$watch('discrimination.id', function (value) {

        if (value != '') {

            alert(value);
            //     $scope.id_restaurant_menu = value;

        }
    });
});

// Angular
myApp.filter('priceformat', function () {
    var is_number = /[0-9]/;
    var prefix = 'R$ ';
    var suffix = '';
    var centsSeparator = ',';
    var thousandsSeparator = '.';
    var limit = false;
    var centsLimit = 2;
    var clearPrefix = false;
    var clearSufix = false;
    var allowNegative = false;
    var insertPlusSign = false;

    if (insertPlusSign) allowNegative = true;

    function to_numbers(str) {
        var formatted = '';
        for (var i = 0; i < (str.length); i++) {
            char_ = str.charAt(i);
            if (formatted.length == 0 && char_ == 0) char_ = false;
            if (char_ && char_.match(is_number)) {
                if (limit) {
                    if (formatted.length < limit) formatted = formatted + char_
                } else {
                    formatted = formatted + char_
                }
            }
        }
        return formatted
    }

    function fill_with_zeroes(str) {
        while (str.length < (centsLimit + 1)) str = '0' + str;
        return str
    }

    return function (str) {
        var formatted = fill_with_zeroes(to_numbers(str));
        var thousandsFormatted = '';
        var thousandsCount = 0;
        if (centsLimit == 0) {
            centsSeparator = "";
            centsVal = ""
        }
        var centsVal = formatted.substr(formatted.length - centsLimit, centsLimit);
        var integerVal = formatted.substr(0, formatted.length - centsLimit);
        formatted = (centsLimit == 0) ? integerVal : integerVal + centsSeparator + centsVal;
        if (thousandsSeparator || $.trim(thousandsSeparator) != "") {
            for (var j = integerVal.length; j > 0; j--) {
                char_ = integerVal.substr(j - 1, 1);
                thousandsCount++;
                if (thousandsCount % 3 == 0) char_ = thousandsSeparator + char_;
                thousandsFormatted = char_ + thousandsFormatted
            }
            if (thousandsFormatted.substr(0, 1) == thousandsSeparator) thousandsFormatted = thousandsFormatted.substring(1, thousandsFormatted.length);
            formatted = (centsLimit == 0) ? thousandsFormatted : thousandsFormatted + centsSeparator + centsVal
        }
        if (allowNegative && (integerVal != 0 || centsVal != 0)) {
            if (str.indexOf('-') != -1 && str.indexOf('+') < str.indexOf('-')) {
                formatted = '-' + formatted
            } else {
                if (!insertPlusSign) formatted = '' + formatted;
                else formatted = '+' + formatted
            }
        }
        if (prefix) formatted = prefix + formatted;
        if (suffix) formatted = formatted + suffix;
        return formatted
    }
});

myApp.directive('format', ['$filter',

function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            $(elem).priceFormat({
                    prefix: 'R$ ',
                    centsSeparator: ',',
                    thousandsSeparator: '.',
                    centsLimit: 2,
                    limit: 14,
                });

            ctrl.$formatters.unshift(function (a) {
                return $filter('priceformat')(ctrl.$modelValue)
            });
            ctrl.$parsers.unshift(function (viewValue) {
                return $filter('priceformat')(viewValue)
            });
        }
    };
}]);

Valor

        <input type="text" style="width: 100%; text-align: right;" ng-model="discrimination.value" format="priceformat" placeholder="R$ 0,00" class="money" />

Adicional

        <input type="text" style="width: 100%; text-align: right;" ng-model="discrimination.value_addition" format="priceformat" placeholder="R$ 0,00" class="money" />

Desconto

        <input type="text" style="width: 100%; text-align: right;" ng-model="discrimination.value_discount" format="priceformat" placeholder="R$ 0,00" class="money" />

            +

        <input type="text" style="width: 100%; text-align: right;" ng-model="obj.value" format="priceformat" placeholder="R$ 0,00" class="money" />

                    VALOR
                    ADICIONAL
                    DESCONTO
                    TOTAL

                    {{ discrimination.value }}
                    {{ discrimination.value_addition }}
                    {{ discrimination.value_discount }}
                    R$ 0,00


$\frac{1}{t}e^{F(t)} \to \infty \Rightarrow t F'(t) \to \infty$?

Question: Let $F:[0,\infty)\to[0,\infty)$ be a non-decreasing continuously differentiable function satisfying $F(t)\to\infty$ as $t\to\infty$. Consider the following statements:

$t F'(t) \to \infty$, as $t\to\infty$.
$\frac{F(t)}{\log t} \to \infty$, as $t\to\infty$.
For each $\epsilon>0$, $\frac{1}{t}e^{\epsilon F(t)} \to \infty$, as $t\to\infty$.
For each $\epsilon>0$, $F'(t)e^{\epsilon F(t)} \to \infty$, as $t\to\infty$.

I can derive that
1 $\Rightarrow$ 2 $\Rightarrow$ 3 and 1 $\Rightarrow$ 4 $\Rightarrow$ 3, as follows.
1 $\Rightarrow$ 2: Straightforward application of L'Hôpital's rule.
2 $\Rightarrow$ 3: $\frac{1}{t}e^{\epsilon F(t)} = \exp( \epsilon F(t) - \log t ) = \exp\left[ \left(\epsilon \frac{F(t)}{\log t} - 1 \right) \log t \right]$.
1 $\Rightarrow$ 4: Using 1 and 3, $F'(t)e^{\epsilon F(t)} = t F'(t) \cdot \frac{1}{t}e^{\epsilon F(t)}$.
4 $\Rightarrow$ 3: Straightforward application of L'Hôpital's rule.

So here are my questions:

Are the above derivations correct?
Can we prove that 3 $\Rightarrow$ 1? If so, then we get two closed loops 1 $\Rightarrow$ 2 $\Rightarrow$ 3 $\Rightarrow$ 1 and 1 $\Rightarrow$ 4 $\Rightarrow$ 3 $\Rightarrow$ 1, so that all the four statements are equivalent. If not, any counterexamples?

TIA...
Answer: Here is a counterexample of 2 $\Rightarrow$ 1:
Let $F(t) = t + \sin(t)$, then $F(t)$ is non-decreasing since $F'(t) = 1 + \cos(t) \ge 0$.
In addition, $\lim_\limits{t\to +\infty}\dfrac{F(t)}{\log t} = +\infty$, but $\lim\limits_{t\to +\infty}tF'(t)$ does not exist since $F'((2n+1)\pi) = 0$.
I believe this is also a counterexample of 3 $\Rightarrow$ 1.


Como criar array dinamicamente?

Question: Gostaria de criar um array dinamicamente, tentei desta forma:
$zt = array();
    $zt = ($p_p[0] => $_p_p[1]);
    print_r($zt);

$p_p é um array, onde o índice 0 é o nome, e o índice 1 é o valor, 2 nome, 3 valor..
$p_p está configurado assim, mas infelizmente dá erro na linha $zt:

Parse error: syntax error, unexpected '=>'

Se eu fizer assim:
$zt = ($p_p[0]);

não dá erro, mas o índice é "0", eu precisava que fosse de fato o nome, já que vou passar este array $zt por POST como se fossem campos de um formulário.
Comment: Olha, achei a solução, mas não achei lógico isso. Eu declarei como array $zt, assim: `$zt = array();`, então eu esperava que o que $zt recebe-se se comporta-se como array, mas eu precisei alterar para isso: `array($p_p[0] => $_p_p[1]);`, ou seja, informei que era array(novamente) o que coloquei ali dentro.
Comment: Você precisou declarar novamente que o `$zt` é um array porque você estã **sobrescrevendo** a variável `$zt`.
Comment: perfeito! valeu
Answer: Pelo que entendi você quer que $p_p[0] seja a key e $p_p[1] o value, então:
$zt = array();
$zt[$p_p[0]] = $p_p[1];
print_r($zt);

Comment: Luiz, agradeço pela resposta, não sabia que um índice podia receber um valor dessa forma!
Answer: Se quiseres criar uma array simples (não associativa):
$zt = array();
$zt[] = $p_p[0] => $_p_p[1];

Se quiseres criar uma array associativa
$zt = array();
$zt[$p_p[0]] = $p_p[0] => $_p_p[1];

A diferença é que uma atribui o index automaticamente (numérico) e a segunda variante pode ter um index atribuído (string).

Como criar array dinamicamente?


Module over a ring satisfying ACC

Question:
Let $R$ be a ring that satisfies ACC on the set of its left ideals and
  $M$ be a finite generated $R$-module. Prove that every submodule of
  $M$ is finitely generated.

I know that if $M$ satisfies ACC condition then every submodules of it are finite generated. I only want to show that $M$ satisfies ACC condition.
Help me some hints.
Thanks a lot.
Comment: *Hint:* Rings meeting the ACC condition are called *Noetherian* rings. Prove that a ring is Noetherian iff all of its ideals are finitely generated. Then prove that a module meets the ACC condition iff all its submodules are finitely generated.
Comment: I've done the first part of you hint. For the second, can you explain more precise?
Comment: A module that meets the ACC conditon is called Noetherian module. Is it right?
Answer: First try to show following fact: For any exact sequence $A\rightarrow M\rightarrow B$, $M$ satisfies ACC iff $A$ and $B$ satisfy ACC. Use it to prove that finitely generated free modules satisfy ACC.

There is an exact sequence $R^{n-1}\rightarrow R^n\rightarrow R$. $R$ satisfy ACC. Assume that $R^{n-1}$ satisfy ACC too then by induction so does $R^n$.

Now notice that module $M$ is finitely generated iff there is a finitely generated free module $F$ and a surjection $f:F\rightarrow M$.

If $M$ has generators $\{m_1,...,m_n\}$ then there is a surjection $f:R^n\rightarrow M$ defined on base $f:x_i\mapsto m_i$

Use fact again to prove that $M$ satisfy ACC.

There is an exact sequence $\ker(f)\rightarrow R^n\rightarrow M$.

Suppose that there is submodule $N\subset M$ which is not finitely generated. Enumerate its elements then we have sequence of submodules $(m_1)\subset (m_1,m_2)...$ It is easy to see that this sequence will not stabilise.
Comment: The first fact you told is Lemma $4.1.5$ of http://modular.math.washington.edu/129/ant/html/node11.html
Comment: Can you explain more precise?
Comment: What is unclear exactly is unclear for you?
Comment: All except the first fact ("For any exact sequence $A\rightarrow M\rightarrow B$, $M$ satisfies ACC iff $A$ and $B$ satisfy ACC") and the final ("Suppose that ... stabilise")
Comment: This post improve your hint http://math.stackexchange.com/questions/306546/specific-proof-that-any-finitely-generated-r-module-over-a-noetherian-ring-is?rq=1

Module over a ring satisfying ACC


Show that a set is not open

Question: Suppose  $U_1$ and $U_2$ are both nonempty subsets of $\mathbb R$ such that $U_1 \cap U_2 =\emptyset $ and $U_1\cup U_2 = \mathbb R.$
Consider points $p \in U_1\ \text{and}\ q \in U_2.$ Without loss of generality, we may assume that $p < q.$
Now, let $A$ be the set of all points $x \in U_1$ with $x< q.$ We know that $A$ is nonempty (since $p \in A$) and that it has an upper bound (since $q$ is an upper bound for $A$). Thus $A$ must have a least upper bound, call it $m.$
Suppose that $m \in U_1$. Show that $U_1$ not open.
[Is it possible to prove with the definition of an Open Set in Metric Space?
Definition: Let X be a metric space, and let U be a subset of X. We say that U is open if, for every point p ∈ U, there is some real number ε > 0 such that Bε(p) ⊂ U.
Note: Bε(p) is the set of all points x in X such that d(x, p) < ε.]
Comment: Can you clarify your question: are you trying to show that $U_1$ is open or is not open?
Comment: Sorry about the confusion. The question is to show U1 is not open.
Comment: Find a sequence in $(m,m+\epsilon)$ in $U_2$ that converges to $m\in U_1$.
Comment: For each $n\in\mathbb N$ there must be an element of $U_2$ in $(m,m+1/n)$.
Comment: Because if not then $q>m+1/n$ for some $n$ and $[m,m+1/n]$ must be in $U_1$ contradicting the definition of $m$.
Comment: How to show such sequence exist?
Answer: If possible let us assume that $U_1$ is open and since $m\in U_1$ so there exists an $\epsilon>0$ such that $(m-\epsilon,m+\epsilon) \subset U_1$. Now there are two possibilities, either $q \in (m-\epsilon,m+\epsilon)$ or $q\notin (m-\epsilon,m+\epsilon)$.
But you can clearly see that the only possibility is actually $q \notin (m-\epsilon,m+\epsilon)$ because $U_1\cap U_2 =\emptyset$. But if $q \notin (m-\epsilon,m+\epsilon)$ then this  is a contradiction to fact that $m$ was supremum.

Show that a set is not open


Find the norm of the operator $T:\ell^2 \to \ell^2$ defined by $Tx := (x_1, x_1+x_2, x_3, x_3+x_4, x_5, x_5+x_6, \ldots)$

Question: Let $T : \ell^2 \to \ell^2$ (involving complex numbers) be defined by
$$
Tx := (x_1, x_1+x_2, x_3, x_3+x_4, x_5, x_5+x_6, \ldots).
$$
What is $\|T\|$?
Essentially I've tried :

To find $M \geq 0$ s.t. $\|Tx\| \leq M \|x\|$ and $\|T\| \geq M$. Cauchy-Schwarz led me nowhere. The triangle inequality gives $\|Tx\| \leq 2 \|x\|$, but I've not been able to show that $\|T\| \geq 2$ (in fact I don't think $2$ is small enough).
To maximise
$$
\frac{\|Tx\|}{\|x\|}
$$
for $x \neq 0$, or equivalently
$$
\|Tx\|
$$
for $\|x\|=1$. I didn't succeed.
I've tried to write $|x_k| = x_k e^{- i\theta_k}$ and see if I could simplify some things or recognize known expressions. I failed with this idea.

Apparently there is a way to use matrices, but I don't see how.
Comment: Okay, write $\ell^2 = E \oplus F$, where the direct sum is orthogonal, and $E$ is the subspace where all components with even index are $0$, $F$ the subspace where the components with odd index are $0$. Then $T$ becomes $(e,f) \mapsto (e,e+f)$ if we identify each of $E$ and $F$ with $\ell^2$. Obviously(?) for $\lVert e\rVert$ and $\lVert f\rVert$ fixed, the norm of $T(e,f)$ is maximised when $\lVert e+f\rVert = \lVert e\rVert + \lVert f\rVert$. _Now_ it is not too hard to get $\lVert T\rVert$.
Answer: You probably know that the norm of a diagonal matrix is the supremum of absolute values of its diagonal entries. Here's a generalization of this:
Claim
Suppose $T:\ell^2\to\ell^2$ has invariant subspaces $\{V_k:k=1,2\dots\}$ which are mutually orthogonal and satisfy $\ell^2=\bigoplus_k V_k$. Let $T_k:V_k\to V_k$ be the induced operator on $V_k$, essentially the restriction of $T$ to this subspace. Then
$$\|T\|=\sup_k \|T_k\|$$
Proof
It's easy to see that $\|T\|\ge   \|T_k\|$ for all $k$. Conversely, given any vector $x\in \ell_2$ we can write it as $x=\sum_k x_k$ with $x_k\in V_k$. Then
$$
\|Tx\|^2 = \sum_k \|T_k x_k\|^2 \le \sup_k \|T_k\|^2 \sum_k \| x_k\|^2 = \sup_k \|T_k\|^2 \|x\|^2
$$
which proves $\|T\|\le \sup_k \|T_k\|$. $\quad\Box$
Armed with the above (which is useful not only on this occasion), you can find $\|T\|$ just by examining the operator norm of $2\times 2$ matrix $$\begin{pmatrix} 1 & 1 \\ 0 & 1\end{pmatrix}$$
Comment: [WolframAlpha agrees](http://www.wolframalpha.com/input/?i=norm+%5B%5B1%2C1%5D%2C%5B0%2C1%5D%5D)
Comment: Nice. So I think $\|T\| = \left( \frac{3+\sqrt{5}}{2} \right)^{\frac{1}{2}}$.


geometric algebra: dot products of vectors with vectors vs bivectors

Question: The book "Matrix Gateway to Geometric Algebra" by Garret Sobczyk gives the following identity:
$a\cdot(b \wedge c)=(a\cdot b)c - (a\cdot c)b$
Using the identities
$a\cdot b= (ab+ba)/2$
$a\wedge b=(ab-ba)/2$
to expand the proposed identity, including the step, e.g.,
$$a\cdot (b\wedge c)=(a(b\wedge c) + (b\wedge c) a)/2$$
I get $$abc + bca - acb - cba = abc + cba - acb - bca$$
which does not appear to check.
Is there a step I am missing?
On the same page 31 the author writes (equation 2.14)
$$a\cdot(b\wedge c) = (a(b\wedge c) - (b\wedge c)a)/2$$
which is the opposite sign to the basic "identity" I relied upon. Why is there sign minus in this instance? Is not $x=(b\wedge c)$, where x is an element, subject to the identity $a\cdot x = (ax+xa)/2$? There is a similar reversal of sign in equation 2.15.
Thanks,
Gary
Comment: What does the text call the binary operations you notate as a heavy dot and a wedge? Are your two identities simply definitions? [I assume the multiplication on the right side of these is not done over a commutative field; what is the set on which the right sides are computed?]
Comment: Your computation is not correct. For $a\bullet (b\wedge c)$ the factor would be $\frac{1}{4}$, but for $(a\bullet b)c$ only $\frac{1}{2}$.
Answer: The identities
$$a\cdot b= (ab+ba)/2$$
$$a\wedge b=(ab-ba)/2$$
are correct, but they are only for vectors $ a, b $.  Eq 2.14 from the text:
$$a\cdot(b\wedge c) = (a(b\wedge c) - (b\wedge c)a)/2$$
(with the negative sign), is also correct.  In general, if $ M $ is a k-vector, and $ a $ is a vector, then one has
$$a \cdot M=\frac{1}{{2}} \left( { a M + (-1)^{k-1} M a } \right).$$
I don't know how the Matrix Gateway book derives eq 2.14.  Here's one way to show it, rewriting the dot product as a grade 1 selection (i.e. take just the vector parts of any multivector products)
$$\begin{aligned}a \cdot \left( { b \wedge c } \right)&={\left\langle{{ a \left( { b \wedge c } \right) }}\right\rangle}_{1} \\    &={\left\langle{{ a \left( { b c - b \cdot c } \right) }}\right\rangle}_{1} \\ &={\left\langle{{ a b c }}\right\rangle}_{1} - a \left( { b \cdot c } \right),\end{aligned}$$
however, using $ b a = 2 a \cdot b - b a $, we have
$$\begin{aligned}{\left\langle{{ a b c }}\right\rangle}_{1}&={\left\langle{{ \left( { 2 a \cdot b - b a } \right) c }}\right\rangle}_{1} \\ &=2 \left( { a \cdot b } \right) c - {\left\langle{{ b a c }}\right\rangle}_{1} \\ &=2 \left( { a \cdot b } \right) c - {\left\langle{{ b \left( { 2 a \cdot c - c a } \right) }}\right\rangle}_{1} \\ &=2 \left( { a \cdot b } \right) c - 2 \left( { a \cdot c } \right) b + {\left\langle{{ b c a }}\right\rangle}_{1} \\ &=2 \left( { a \cdot b } \right) c - 2 \left( { a \cdot c } \right) b + \left( { b \wedge c } \right) \cdot a + \left( { b \cdot c } \right) a.\end{aligned}$$
Putting the pieces together, we have
$$a \cdot \left( { b \wedge c } \right)=2 \left( { a \cdot b } \right) c - 2 \left( { a \cdot c } \right) b + \left( { b \wedge c } \right) \cdot a.$$
Finally, note that the reverse of vector is a vector ($\tilde{a} = a$), so if we apply the reversion operator to the last term:
$$\begin{aligned}\left( { b \wedge c } \right) \cdot a&=a \cdot \left( { c \wedge b } \right) \\ &=-a \cdot \left( { b \wedge c } \right),\end{aligned}$$
and then substitute this back in, we are most of the way towards a derivation of eq 2.14 from the text:
$$a \cdot \left( { b \wedge c } \right)=2 \left( { a \cdot b } \right) c - 2 \left( { a \cdot c } \right) b - a \left( { b \wedge c } \right),$$
so after some trivial rearrangement, we have:
$$a \cdot \left( { b \wedge c } \right)=\left( { a \cdot b } \right) c - \left( { a \cdot c } \right) b.$$
You could also derive this from 2.14, using the reversion argument above, since the trivector terms in that antisymmetric sum cancel.
Answer: Assuming that we are given a multiplication that is associative
and bilinear, but not commutative, then define
$$a\cdot b := \frac12(ab+ba),\qquad
a\wedge b := \frac12(ab-ba),$$
which apply, at least for $1$-vectors, with perhaps some sign
changes for general $k$-vectors. No equation such as
$$a\cdot(b \wedge c)=(a\cdot b)c -
  (a\cdot c)b$$
can be an identity because, as you computed,
the left side is equal to
$\,\frac14(abc + cba - acb - bca)\,$ while
$\, (a\cdot b)c = \frac12(abc+bac)\,$ and
$\, a(b\cdot c) = \frac12(abc+acb).\,$
There is no way to get $\,\frac12(abc+cba)\,$
no matter what scalar factors are introduced.
The proof is by linear algebra using as the basis $$(abc,acb,bac,bca,cab,cba).$$
Comment: The problem stemmed from my erroneous assumption that the expansion of products of vectors extends in the same form to the product of vectors and bivectors. I resolved this with the help of Peeter Joot's book entitled "Geometric Algebra for Electrical Engineers", which is very nice. Sobzcyk's book seems to have glossed over a key point, perhaps for pedagogical reasons. Certainly resulted in my learning the hard way! Many thanks and cheers!
Comment: @GaryLomp Please help to enlighten us about the key point glossed over by adding it to your question at the end. This would help others benefit from your hard won learning!


Why does MS's Exchange Server need a SAN/UC Cert?

Question: Out of curiosity: what's the reason behind this?
To be clear: I've checked a couple of root CA's websites while searching for an appropriate SSL Cert (that's another story). Every single one of them illustrates the usefullness of Multidomain Certs with MS Exchange Server's need.
Comment: In future you might want to wait a while before accepting an answer to your question, maybe a day or two.
Answer: Usually because various application and naming conventions use different external names. Outlook RPC over HTTPS looks for autodiscover.domain.com, webmail usually points to webmail.domain.com, SMTP name might be presented like mail.domain.com
Comment: Wildcard certificates are not supported by some versions of Windows Mobile. While that may not be a concern now, at the time Exchange 2007 was released, it was, hence the official line was that a wildcard was not the way to do it.
Comment: Thanks, that sheds some light in the dark. But then again, this sounds like a perfect application for Wildcard Certs ... just wondering.
Comment: Well, not exactly. It very much depends what roles will do the Exchange server you're planning installing a certificate on. For example getting a wild card cert for a single-server scenario might require adding an external DNS zone along with the internal one.
Comment: The good thing about wild card is that you can export it and install on any external server of the domain. Some customers found it valuable.
Answer: Wildcard certificates are useful if you have many subdomains that you want to serve out.
Or you can have a SAN/UCC SSL Certificate from a third party for:
- mail.yourdomain.com
- autodiscover.yourdomain.com
- exchange.yourdomain.local
- remote.yourdomain.local   <-- VPN/RDP access.
With the new announcement that the coming IIS8 will support SNI (http://blogs.iis.net/wonyoo/archive/2012/03/01/iis-8-0-platform-features-for-web-hosters-and-service-providers.aspx), this will probably change the way we apply certificates for exchange and everything else. In the future we could switch from using a Wildcard or UCC to using a single SSL cert for each SSL application we have, and a UCC one for Exchange.
More on SNI in IIS8:
IIS 8.0 support Server Name Indication (SNI), which has extended TLS to include the virtual domain name to be passed from the client at the time of "SSL Hello". This effectively allows IIS 8.0 to enable "hostname binding" for SSL sites, which eliminates the need for having a dedicated IPv4 address per SSL site.


Understanding how unitary operators act on Hilbert space

Question: Let $\mathcal{H} \cong \mathbb{C}^2$ denote some Hilbert space. For example, this could be Hilbert space of a single spin-1/2 particle. Let $SU(2)$ be the special unitary Lie group as per usual. Let $su(2)$ be its associated algebra. I know that there exists the exponential map $exp: su(2) \rightarrow SU(2)$. So that if $g \in su(2)$, then $exp(g) \in SU(2)$.
I would like to know how one makes contact between elements of $SU(2)$ and $su(2)$ with Hilbert space $\mathcal{H}$.
I assume that you define some sort of a representation of $su(2)$ to make contact with $\mathcal{H}$, i.e.
$$\pi: su(2) \times \mathcal{H} \rightarrow \mathcal{H},$$
which gives us a way to represent elements of the Lie algebra as linear transformations over the Hilbert space. I assume that you can do something similar for the Lie group itself:
$$\phi: SU(2) \times \mathcal{H}\rightarrow \mathcal{H}.$$
But, another one of my confusions now comes up. Then, what is the role of the exponential map here and what does it mean to take the taylor expansion of the exponential map? In books like Sakurai and Townsend, some argument is made that unitary transformations by a finite amount of a parameter $j$ take on the form $e^{-ij\hat{O} / \hbar}$. This exponential is then taylor expanded, becoming a series of powers of $\hat{O}$, and its action on a state $\psi \in \mathcal{H}$ can then be deduced.
It then seems like

we are implicitly using a representation of the Lie algebra containing $\hat{O}$ over $\mathcal{H}$.
We seem to be using the exponential map to go from $su(2)$ to $SU(2)$ and then taylor expanding the exponential map to go back to $su(2)$ and then representing $su(2)$ once more as elements acting over $\mathcal{H}$.

Point 2. seems absurd. Unless the taylor expansion of the exponential together with the representation of the associated Lie algebra defines the representation of the Lie group itself. I would like some clarification about what is really mathematically going on here.
Comment: This is really a math question…
Comment: I wouldn't have to ask it at all if it was included in physics books :) @ZeroTheHero
Comment: right but neither Sakurai nor Townsend present their material is such a language.  For this level of "formality" (which has nothing to do with QM), you will likely get more satisfying answers from MSE.
Comment: hm I see what you're saying. I almost think that I'd get too formal an answer from mathstack. But I do see what you're saying @ZeroTheHero
Answer: What you write is mostly correct, I only note that the representations would usually be written as $\pi: \mathfrak{su}(2) \to \mathfrak{gl}(\mathcal H)$ and $\phi: \mathrm{SU}(2) \to \mathrm{GL}(\mathcal H)$. Maybe some of your confusion stems from the fact that in the setup you are describing, there is a canonical representation $\pi = \mathrm{id}$, $\phi = \mathrm{id}$. Physics texts will therefore usually not distinguish the group / algebra and its representation.
I will very briefly (and without claiming to be 100% rigorous) recap the general theory. Beyond that, I would recommend reading an actual math book on Lie theory.

A Lie group is a differentiable group, and a Lie algebra is a vector space equipped with a Lie bracket $[.,.]$. Given a Lie group $G$, the corresponding Lie algebra $\mathfrak g$ is the tangent space on $G$ (seen as a differentiable manifold) at the identity, $\mathfrak g \equiv T_e\, G$. The group structure on $G$ induces the Lie bracket on $\mathfrak g$, but I will not go into detail how that works. The main point is that for curves $\gamma$ in $G$ with $\gamma(0) = e$, the derivatives $\gamma'(0)$ are Lie algebra elements, $\gamma'(0) \in \mathfrak g$.

Given a Lie algebra $\mathfrak g$, there is a unique simply connected Lie group $G$ such that $\mathfrak g$ is the algebra corresponding to $G$. That is Lie's third theorem.

For a vector $X \in \mathfrak g$ there is a unique 1-parameter subgroup $\gamma: \mathbb R \to G$ (that is, a curve with $\gamma(0) = e$ and $\gamma(t+s) = \gamma(t) \gamma(s)$) such that $\gamma'(0) = X$. We define the exponential map as
$$ \exp(X) \equiv \gamma(1) . $$

Given a representation $\phi$ of $G$ we can construct a representation $\pi$ of $\mathfrak g$, and vice versa, in such a way that the diagram commutes:
$$ \begin{array}{}
\mathfrak g & \stackrel{\pi}{\longrightarrow} & \mathfrak{gl}(\mathcal H) \\
\downarrow{\exp} & & \downarrow{\exp} \\
G & \stackrel{\phi}{\longrightarrow} & \mathrm{GL}(\mathcal H)
\end{array} \tag 1 $$
where $\exp$ on the right is the usual matrix exponential.

In the argument you are describing, the authors seem to start from the fact that a 1-parameter subgroup of $\mathrm{SU}(2)$ can be written as $\gamma: j \mapsto \exp(-\mathrm i j O / \hbar)$. Through the Taylor expansion, we are taking the derivative at the identity and find that the operators $O$ here are elements of the Lie algebra. (The extra factor $\mathrm i/\hbar$ is a physicist's convention but does not change the point.) Thanks to the magic in (1), the representation of $O$ is "what you would expect".
Comment: @SillyGoose It is the right idea that differentiation takes us from the group to the algebra, but you can not "differentiate an element", only curves.
Comment: I am sorry is $\gamma(1)$ meant to be $\gamma(e)$?
Comment: @SillyGoose No, $\gamma$'s domain is $\mathbb R$. The idea is that $\exp(tX) = \gamma(t)$.
Comment: ohh I see thank you
Comment: So can I describe the differentiation of an element $g \in G$ as a map from the Lie group to the Lie algebra?
Comment: Very nice answer!


Polimorfismo com ArrayList

Question: Tenho a Iinterface abaixo e gostaria de saber como faço para sobrepor o método passando outro objeto para List pois possuo 4 classes na minha entidade, por exemplo as classes da entidade são cliente, colaborador, produto e serviço e as classes que implementam a interface são ClienteDAO, ColaboradorDAO, ServicoDAO, ProdutoDAO segue abaixo também um exemplo dessas:
public interface ISalaoDAO {

    int save(Object object);
    int update(Object object);
    int remove(Long id);
     List<Cliente> findAll();

}

public class ClienteDAO implements ISalaoDAO{
private static final String SQL_FIND_ALL =
            "select * from CLIENTE";
public List<Cliente> findAll() {
        Connection conn = DBConnection.getConnection();
        PreparedStatement pstm = null;
        List<Cliente> clientes = new ArrayList<Cliente>();
        ResultSet rs = null;
        try {
            pstm = conn.prepareStatement(SQL_FIND_ALL);
            rs = pstm.executeQuery();
            while(rs.next()){
                Cliente cliente = new Cliente();
                cliente.setId(rs.getLong("ID_CLIENTE"));
                cliente.setCliente(rs.getString("NOME_CLIENTE"));
                cliente.setEnderecoCliente(rs.getString("ENDERECO_CLIENTE"));
                cliente.setTelefoneCliente(rs.getString("TELEFONE_CLIENTE"));
                clientes.add(cliente);
            }
        } catch (SQLException e) {
            try{
                if(conn != null){
                    conn.setAutoCommit(false);
                    conn.rollback();
                }
            }catch(SQLException e1){
                e1.printStackTrace();

            }finally{
                DBConnection.close(conn, pstm, rs);
            }
        }
        return clientes;
    }

Answer: Nunca tentei fazer e não sei se viola o princípio de substituição de Liskov ou algo assim, mas sugiro o seguinte:
public interface ISalaoDAO<T> {
    int save(T object);
    int update(T object);
    int remove(Long id);
    List<T> findAll();
}

Aí você especifica o tipo de T na classe implementadora:
public class ClienteDAO implements ISalaoDAO<Cliente> {
    ...
    public List<Cliente> findAll() {
        ...
    }
}

Polimorfismo com ArrayList


Assign DHCP IPs for specific MAC prefixes

Question: I'm running a ISC DHCPd server for my network serving a number of subnets. One of the things I would like to do is assign a specific range of IPs to hosts with a common MAC prefix (ex. 00:01:02). Also, the assignments have to be able to be over-ridden by assignments with fixed-address. I've googled for it, but haven't found anything definitive.
Bonus if I can put the statement within a subnet stanza of my dhcpd.conf (it would fit better with my management software).
Answer: Something like this:
class "specialK" {
    match if substring (hardware, 1, 3) = 00:01:02;
}
subnet 10.0.0.0 netmask 255.255.255.0 {
    pool {
        range 10.0.0.16 10.0.0.32;
        allow members of "specialK";
    }
}

hmm, is it supposed to be (hardware, 0, 2) or (.. 1, 3), test it out. :)
Comment: +1 - this works better than the binary-to-ascii stuff. Also - offset 1,3 is correct, not 1,8.
Comment: Wonderful minimal example.  The `allow` implicitly denies other clients that don't match the class.  However, if you have a second pool with no rules, clients matching that MAC prefix could still be placed there unless it has `deny members of "specialK";`.
Comment: Syntax is substring(string, offset, length), so it should be (1, 8) I think... man 5 dhcp-eval isn't clear on this.
Comment: Note that with this solution, the mac address is a list of hex values and not a string, so it should not be quoted.
Answer: On my system (debian lenny), I need to need binary-to-ascii in order to match mac-addresses. In this (working) example from my dhcpd.conf, server247 is in class "local", however, I give it a fixed address that it not in the pool. I would recommend that the fixed addresses be in a separate range from the dynamically assigned addresses (they can still be in the same subnet).
class "kvm" {
   match if binary-to-ascii(16,8,":",substring(hardware, 1, 2)) = "56:11";
}

class "local" {
   match if binary-to-ascii(16,8,":",substring(hardware, 1, 2)) = "52:54";
}

host meme {
 fixed-address 10.1.0.254;
}

host server247 {
  hardware ethernet 52:54:00:2f:ea:07;
  fixed-address 10.1.0.247;
}

subnet 10.1.0.224 netmask 255.255.255.224 {
  option routers 10.1.0.225;
  pool {
     allow members of "kvm";
     range 10.1.0.226 10.1.0.235;
  }
  pool {
     allow members of "local";
     range 10.1.0.236 10.1.0.240;
  }
  pool {
     # Don't use this pool. It is really just a range to reserve
     # for fixed addresses defined per host, above.
     allow known-clients;
     range 10.1.0.241 10.1.0.253;
  }
}

For your example, you would do:
match if binary-to-ascii(16,8,":",substring(hardware, 1, 3)) = "00:01:02";

Comment: The problem with this approach is that `binary-to-ascii()` does not know anything about MAC addresses and will truncate leading zeroes from every byte.


Como fixar um conteúdo ou um fundo em uma div

Question: Gostaria de fazer com essa div rolasse junto com a página mas o seu conteúdo ou o conteúdo de um before que seria no caso a imagem(se fosse o caso), ficasse fixado de forma que desse a aparência de o conteúdo (ou fundo) sumisse ao rolar a página.
De fato, como eu fiz o fundo ficou fixo mas ele não foi sumindo de  acordo com que eu rolasse a página. A ideia é fazer tipo um overflow: hidden.

#teste {
  width: 100%;
  height: 100%;
  position: relative;
}

#teste:before {
  content: '';
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-image: url("https://upload.wikimedia.org/wikipedia/commons/8/8f/%24700%2C000_Home.jpg");
  background-size: cover;
  position: fixed;
  overflow: hidden;
}

eu

eu

eu

eu

eu

eu

eu

eu

eu

eu

eu

eu

Comment: Não sei se entendi, mas é isso que quer? https://repl.it/@Costamilam/HurtfulHilariousKeygens
Comment: Não! O que eu quero fazer é o que acontece no banner que está no topo desse site: https://www.banesecard.com.br/Home/
Comment: Mas teria como você alterar esse teu exemplo para ficar apenas a div.imagem e um bloco de eu  como na pergunta para fazer om que o efeito que ocorre na div.imagem continue ocorrendo? Porém, ao invés de content do before ter 'Imegem', gostaria que existisse mesmo uma imagem, pode ser do google, que tivesse as dimensoes da div.
Comment: Não entendi bem o que quer, parece que tu já tem o que deseja, só arrumar o `z-index` como o hugocsl respondeu. Você pode inspecionar elemento e ver como foi feito no site para tirar alguma dúvida
Comment: Carlos Editei completamente a resposta, acho que agora está mais de acordo com o efeito que vc queria
Answer: Essa técnica na verdade não é com um elemento com position:fixed, mas sim um elemento com background-attachment: fixed. Dessa forma o elemento rola com a tela, mas o background dele não, ai da esse efeito meio que de parallax.

Segue o código da imagem acima:

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    font-size: 70px;
    color: red;
}

.fixo {
    width: 100%;
    height: 100px;
 background-image: url("https://upload.wikimedia.org/wikipedia/commons/8/8f/%24700%2C000_Home.jpg");
    background-size: cover;
    background-attachment: fixed;
        background-position: center center;

}
.con {
/* essa altura é só para vc ver melhor o exemplo, mas vc não precisa definir uma altura aqui*/
    height: 100%;
}

    conteúdo qq

    resto do content

OBS: A única ressalva que fica é sobre o background-attachment: fixed nos iOS dos iPhones mais antigos como vc pode ver aqui Problema de background com Iphone 6, 7 e 8
Comment: Oi Hugo, ainda não é isso! O que eu quero fazer é o que acontece no banner que está no topo desse site: https://www.banesecard.com.br/Home/
Comment: @CarlosRocha agora entendi melhor, fiz uma edição por completo da resposta, inclusive a técnica é outra, diferente do que a gente pensou inicialmente... ;)
Comment: Hum, entendi. Mas a imagem precisa ser obrigatoriamente do tamanho da div Como faz?
Comment: @CarlosRocha não jovem, aqui `.fixo { ...  height: 100px;` vc pode coloca a altura que achar melhor, inclusive em pixels, na outra div eu coloquei uma altura só para ter scroll na página e vc poder ver e testar o efeito. https://imgur.com/IALMY03 com 100px de altura em .fixo ficara assim
Comment: hum. Mas esse height: 100px é o tamanho da div. O que eu preciso é que a imagem tenha o tamanho da div. Eu coloquei background-size: cover; e nãp funcionou. Será que não precisa usar um :before?
Comment: Carlos pra que ::before se a imagem é o background da div principal? Vc está complicando as coisas sem motivo...
Comment: devo estar sim. Mas aqui para mim, a imagem de fundo está  muito maior que a div. E o objetivo é que a imagem permaneça da altura do div.
Comment: @CarlosRocha eu **editei** a resposta e coloquei um `background-position: center center;` para centralizar a imagem no tamanho da div, vc pode alterar para tipo `top left` se quiser para ver se fica mais do seu agrado... Tb mudei a altura para vc ver que a imagem respeita sim o tamanho da div, pois ela é o background da própria div e não tem como ser maior que ela....
Comment: Agora só mais essa dúvda: Sabendo que a altura da imagem será sempre 32% da largura e sabendo que a largura da imagem será será sempre a largura de uma div container.
Como eu calculo a altura dessa div containner para que ela nunca empurre as divs de baixo?
Eu tentei height: calc (100vw * 0.3251622); mas não funcionou –
Comment: @CarlosRocha na boa jovem, ai já é outra pergunta... se tu tiver duvida com outra coisa abre outra Pergunta, coloca o seu problema, imagem de como esta ai e como vc precisa que fique etc, ai eu ou outro alguém pode te ajudar com esse problema. Sobre o efeito que vc queria acho que vc já resolveu
Comment: de acordo. Obrigado. Vou postar outra!


Can't replace the footer text in a word application through Delphi

Question: I am trying to replace text in a footer, I am using the following code through which i can replace the normal content (body) but not the content in the footer/header
myWinWordApp := CreateOLEObject('Word.Application');
myWinWordApp.visible := true;
myWinWordApp.documents.open('c:\ole.doc');
myWinWordApp.Selection.Find.Text :=  'oo';
myWinWordApp.selection.Find.Replacement.Text := 'aa';
myWinWordApp.Selection.Find.Execute(Replace := 2);

any help is highly appreciated. Thanks in advance
Comment: @Andreas That is Delphi code. It's a late bound named parameter.
Comment: That's not Delphi code... At any rate, I would try to set the view to the header/footer mode, maybe by doing something like `ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader` as shown [here](http://www.your-save-time-and-improve-quality-technologies-online-resource.com/vba-word-footer-and-header.html)
Comment: @David: Yes, you are right. I must read up on variants... (Slightly embarrassed!)
Comment: @Andreas: Thanks for your comment it helped me, i added the following line and it works    myWinWordApp.ActiveWindow.ActivePane.View.SeekView := 10; // footer
Answer: Made comment into answer:
I would try to set the view to the header/footer mode, maybe by doing something like ActiveWindow.ActivePane.View.SeekView := wdSeekCurrentPageHeader as shown here.


Lazy loading implementation

Question: I am trying to implement lazy loading in angular 5.
app.module.ts
  import { BrowserModule } from '@angular/platform-browser';
  import { NgModule } from '@angular/core';
  import { FormsModule } from '@angular/forms';
  import {RouterModule , Routes} from '@angular/router';
  import { HttpClientModule } from '@angular/common/http';
  import { AppComponent } from './app.component';
  import { HomeComponent } from './home/home.component';
  import {LocationStrategy, HashLocationStrategy} from
  '@angular/common';
  import { DataService } from './data.service';
  import { AboutComponent } from './about/about.component';
  import { ContactComponent } from "./contact/contact.component";
  import { NavComponent } from './nav/nav.component';
  @NgModule({
     declarations: [
     AppComponent,
     HomeComponent,
     AboutComponent,
     ContactComponent,
     NavComponent
  ],
imports: [
  BrowserModule,
  HttpClientModule,
  FormsModule,
  RouterModule.forRoot([
    {path: 'home', component: HomeComponent},
    {path: '', redirectTo: 'home', pathMatch: 'full'},
    {path: 'about', component: AboutComponent},
    {path: 'contact', component: ContactComponent},
  ])
],
providers: [DataService,{provide: LocationStrategy, useClass:
HashLocationStrategy}],
bootstrap: [AppComponent]
 })

export class AppModule { }

I want contact and about component to get lazy loaded. How to do that?? Does i need to create some new modules and components for that ??
Comment: I think you need to read this first: https://angular.io/guide/lazy-loading-ngmodules. Here you have nice working demo: https://github.com/UltimateAngular/angular-lazy-load-demo
Answer: To achieve lazy loading, you use child routes which refer to the lazy loaded Modules RoutingModule where the child Routes will be resolved further:
loadChildren: './pages/myPath/myPath.module#MyPathModule'
MaiModule->MainRoutingModule -> childRoute=LazyLoadModule -> LazyLoadRoutingModule
const appRoutes: Routes = [
 {
   path: 'myPath',
   loadChildren: './pages/myPath/myPath.module#LazyLoadedModule'
 },
]

Comment: Bro i am not getting. Can you explain me how to code it
Comment: Your Lazy Loaded Module is a Module that has its own Routing Module. Just like the top level AppModule has its AppRoutingModule. You then just refer in the AppRoutingModule to a childroute that points to the LazyLoadedModule.
Answer: You can add your AboutComponent and ContactComponent into separate module which is named as 'LandingModule'. Then you can create a separate routing page for your landing module.
const routes: Routes = [
 {path: 'about', component: AboutComponent},
 {path: 'contact', component: ContactComponent },
];

After that you need to go to create AppRoutingModule which include app level routing for create lazy loading routes.
const routes: Routes = [
{
  path: 'customers',
  loadChildren: './landing/landing.module#LandingModule'
},
{
  path: '', redirectTo: '', pathMatch: 'full'
}
];

If you want to read more you can visit given links.

https://angular.io/guide/lazy-loading-ngmodules
https://blog.khophi.co/angular-module-lazy-loading-like-pro/

Adding separate file for routing is a good practice other than keeping all your routes inside your appModule.
Answer: Create 2 new modules:
ng generate module about --roputing
ng generate module contact --routing

Create components for each of these modules:
ng generate component about/components/about
ng generate component contact/components/contact

Because we used the --routing options each of these modules will have an about-routing.module.ts and contact-routing.module.ts created. Here you need to specify the routes for the modules. Add this to the about module:
const routes: Routes = [
  { path: '', component: AboutComponent, pathMatch: 'full' }
];

And for the contact module:
const routes: Routes = [
  { path: '', component: ContactComponent, pathMatch: 'full' }
];

Change the app.module.ts to:
 RouterModule.forRoot([
    {path: 'home', component: HomeComponent},
    {path: '', redirectTo: 'home', pathMatch: 'full'},
     path: 'about', loadChildren: './about/about.module#AboutModule' },
     path: 'contact', loadChildren: './contact/contact.module#ContactModule' },
  ])

Comment: I got it. already one module was there named as about. Thanks bro
Comment: ng generate module about --routing. Its showing
error! src/app/about/about.module.ts already exists.
Comment: @Ronit, you created alreadhy the about module? After the question was posted?
Comment: NO. i have two componenets named about and contacts. I have no module named about
Comment: But i am unable to see the content of about and contact page when i run my app
Answer: You have to create new Module that will your about and related component loading using the child concept link to main app-routing file.
Comment: Please provide better explanations and code samples.

Lazy loading implementation


MSMQ Firewall Ports

Question: I'd like to know what ports need to be opened on a firewall in order to allow public read access to an MSMQ private queue.
I'm aware that Microsoft publishes a list of ports here:  http://support.microsoft.com/default.aspx?scid=kb;EN-US;178517
But I only want to open the ports that are specificially required in order to connect to the MSMQ instance and read messages from a private queue (no Active Directory involved).
Comment: okay, you can do it, but are you sure you want to be doing this. Your opening up this port to attack from anonymous users from the whole internet.  Now, with Microsoft's track record of zero days, patch tuesday etc etc, do really want to do this.
Answer: I eventually found this article: How To Configure a Firewall for MSMQ Access
. And this article: Clear the way - MSMQ coming through
To recap, you need ports 135, 2103 and 2105 open in order to read a message from a public queue.
Answer: From that article, it looks like all those ports are required, with the exception of port 389, which it indicates is for Active Directory.
Comment: Thanks Adam, but I'm specifically looking for the specific ports that are required to read from a MSMQ queue on a public facing website. I don't want to open any unnecessary ports.
Comment: I guess you could test it by just enabling/disabling firewall rules and see how it goes. I suspect though that all those ports are needed regardless of the implementation scenario.
Answer: MSMQ requires TCP ports

135
2103
2105

(my personal experience)
Answer: To only send (push) messages from server to server you need TCP 1801.
To remote receive (pull) messages from a server you need TCP 135, 2103, and 2105.
Usually you should not do remote received with MSMQ. If you have MSMQ configured in workgroup mode then only TCP 1801 is required.

MSMQ Firewall Ports


What exactly does it mean to write an API for an OO language?

Question: I have been asked to write an API for a high-level OO language of my choosing (I'll be using Java). The API needs to perform specific functions, of course, but they are very basic things that I know I can accomplish.
I'm familiar with the concept of an API for a web application and that's straightforward enough, but what exactly does it mean to write an API for an OO language? In Java's case, does this mean writing a package that can be imported and provides the desired functionality via classes/functions, so I would write a) the package and b) a separate module to test it? (For clarification, I have been provided no information other than "write an API" and "it needs to do X, Y, and Z". Further clarification: I mentioned the web application API concept just to show that I know what an API is. This is not any sort of web API whatsoever.)
Comment: Since you mentioned API for web application, I guess it could be SOAP on which you can make function calls like you do with an instance of a class.
Comment: @DinoTw I just edited the post to clarify that the web application example is just to show that I know what an API is. The API that I write won't have anything to do with the internet. Thank you though, I greatly appreciate it!
Answer: There are different definitions depending on the context and who you ask.
Some people call all public types that are exposed by a module an API. By this very broad definition almost every library or package has an API. I think this is a quite common definition but not everyone agrees with it.
At a more abstract level, an API is a kind of contract or specification that defines some functionality. An API is more like a well defined interface of a module or service that is used to separate the public available functionality from it's internal implementation. A good example of this kind of API are the Java EE APIs.
Practically, in Java an API usually consist mostly of Interface types. The functionality is defined by the methods of the interface and by the documentation. The API itself does not need to have any functionality on its own (it can have some basic default classes or helper classes though).
It's up to another class to implement the interface and provide implementations of the defined functionality. Those implementations shouldn't violate the contract which is defined in the documentation.
If a some application wants to use the API, it only accesses the interface and never the implementing classes. This is the principle "Program to an interface, not an implementation". In my opinion this is the most important aspect of APIs and is what separates the API from regular interfaces. It makes the API reusable and enables the internal implementation to change without breaking the API.
Of course to actually use an API, there has to be some kind of mechanism to get an instance of a class that implements the API. Usually it's some kind of factory method or dependency injection.
The packaging usually depends on the API's usage. API as defined by the first definition usually are included in the jar of their library, because it wouldn't make sense to import them alone. If there are multiple implementations of an API then the API should be be packaged separately from the implementations.
Answer: Yes, you just need to write the classes need to implement the desired functionality.  Make sure whatever functionality is requested can be accessed by some other programmer using your code.  (Methods they need to use should be public for example).
Comment: I would say the `interface` is key for defining a public API, write a set of `interface`s not `class`es.
Answer: I'd say your assumption is correct - yes, you are asked to write "a package that can be imported and provides the desired functionality via classes/functions."
Then again, I've never written an API. I was trying to imagine an "offline" one, but the examples that come to mind are mostly referred to as SDKs.
Anyway, this is what Wikipedia has to say on the subject:

API in object-oriented languages
In its simplest form, an object API is a description of how objects work in a given object-oriented language – usually it is expressed as a set of classes with an associated list of class methods.
For example, in the Java language, if the class Scanner is to be used (a class that reads input from the user in text-based programs), it is required to import the java.util.Scanner library, so objects of type Scanner can be used by invoking some of the class' methods

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        System.out.println("Enter your name:");
        Scanner inputScanner = new Scanner(System.in);
        String name = inputScanner.nextLine();
        System.out.println("Your name is " + name + ".");
        inputScanner.close();
    }
}

In the example above, methods nextLine() and close() are part of the API for the Scanner class, and hence are described in the documentation for that API.

So what I read here is, in OO languages, you can think of any class as being kind of an API for something. Swift is an API for building UIs, and the entire JDK itself is an API for building software for anything that can run the Java runtime environment.

In such [object-oriented] languages, the API is still distributed as a library. For example, the Java language libraries include a set of APIs that are provided in the form of the JDK used by the developers to build new Java programs. The JDK includes the documentation of the API in JavaDoc notation.

Also note that...

An API is usually related to a software library: the API describes and prescribes the expected behavior while the library is an actual implementation of this set of rules. A single API can have multiple implementations (or none, being abstract) in the form of different libraries that share the same programming interface.

So basically, whoever told you "it needs to do X and Y" described an API for you (using natural language), and you're supposed to write its implementation - a library, in an object-oriented one. (And years later, some other developer may be writing a new library implementing your API, described by the JavaDoc documentation your produce.)
So yeah, your deliverable is a package that can be imported and used in someone else's Java code.


Remove null value from json and return it as json not json string in c#?

Question: I tried to remove null values from json. I used [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] and serialized the json to remove null values. It is working. But I need the output as JSON object, not JSON string.
Here I am serializing the chatbotclass for removing null values.
When I Serialize the object it is returning the result as string.
Is there any other ways available to remove null values without serializing.
    List<elements> elementList = new List<elements>();

                    for (int i = 0; i < articleList.Count; i++)
                    {
                        List<buttons> buttonList = new List<buttons>();
                        btnclass = new buttons();
                        btnclass.type = "web_url";
                        btnclass.url = Convert.ToString(Utility.GetAppsettingValue("MMUrl")) + articleList[i].Url;
                        btnclass.title = "Read this story";
                        buttonList.Add(btnclass);
                        eleclass = new elements();
                        eleclass.buttons = buttonList;
                        eleclass.title = articleList[i].HeadLine;
                        eleclass.image_url = articleList[i].ImageLink + "_SECVPF.gif";
                        eleclass.subtitle = articleList[i].Abstract;
                        elementList.Add(eleclass);
                    }
                    payldclass.elements = elementList;
                    payldclass.template_type = "generic";
                    atchmntclass.payload = payldclass;
                    atchmntclass.type = "template";
                    msgclass.attachement = atchmntclass;
                    List<messages> messageList = new List<messages>();
                    messageList.Add(msgclass);
                    chatbotclass.messages = messageList;
                    jsonstring = Newtonsoft.Json.JsonConvert.SerializeObject(chatbotclass, Formatting.None);
                    return Json(jsonstring);

And also I tried Deserializing object. When Deserialize the string using ChatbotMdl it adds a null value to the missing fields.
var settings = new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        MissingMemberHandling = MissingMemberHandling.Ignore
                    };
var jsonModel = JsonConvert.DeserializeObject<ChatbotMdl>(jsonstring, settings);

Output I am getting:
"{\"messages\":[{\"attachement\":{\"type\":\"template\",\"payload\":{\"template_type\":\"generic\",\"elements\":[{\"title\":\"உத்தரபிரதேசத்தில் பள்ளத்தில் டிராக்டர் கவிழ்ந்து 4 பேர் பலி\",\"image_url\":\"https://img.maalaimalar.com/Articles/2018/Feb/201802050158532561_Four-Dies-As-Tractortrolly-Falls-From-Bridge_SECVPF.gif\",\"subtitle\":\"உத்தரபிரதேசத்தில் பள்ளத்தில் டிராக்டர் கவிழ்ந்த விபத்தில் டிராக்டரில் பயணம் செய்த 4 பேர் சம்பவ இடத்திலேயே உடல் நசுங்கி பரிதாபமாக உயிர் இழந்தனர்.\",\"buttons\":[{\"type\":\"web_url\",\"title\":\"Read this story\",\"url\":\"https://www.maalaimalar.com/News/TopNews/2018/02/05015853/1144022/Four-Dies-As-Tractortrolly-Falls-From-Bridge.vpf\"}]}]}}}]}"

Output I need:
{
  "messages": [
    {
      "attachement": {
        "type": "template",
        "payload": {
          "template_type": "generic",
          "elements": [
            {
              "title": "உத்தரபிரதேசத்தில் பள்ளத்தில் டிராக்டர் கவிழ்ந்து 4 பேர் பலி",
              "image_url": "https://img.maalaimalar.com/Articles/2018/Feb/201802050158532561_Four-Dies-As-Tractortrolly-Falls-From-Bridge_SECVPF.gif",
              "subtitle": "உத்தரபிரதேசத்தில் பள்ளத்தில் டிராக்டர் கவிழ்ந்த விபத்தில் டிராக்டரில் பயணம் செய்த 4 பேர் சம்பவ இடத்திலேயே உடல் நசுங்கி பரிதாபமாக உயிர் இழந்தனர்.",
              "buttons": [
                {
                  "type": "web_url",
                  "title": "Read this story",
                  "url": "https://www.maalaimalar.com/News/TopNews/2018/02/05015853/1144022/Four-Dies-As-Tractortrolly-Falls-From-Bridge.vpf"
                }
              ]
            }
          ]
        }
      }
    }
  ]
}

Answer: JObject.Parse(jsonString); parses string to a JObject, so if you return it from your controller, it will be an object, not a string.
You can change this
var jsonModel = JsonConvert.DeserializeObject<ChatbotMdl>(jsonstring, settings); to this dynamic jsonModel = JsonConvert.DeserializeObject(jsonstring);. Because deserializing to ChatbotMdl gives you all the properties, obviously, even if they are null.
But if you have globally set NullValueHandling to Ignore, you should return Json(chatbotclass); and it should be ok. The framework will take care of it, you don't need to serialize it yourself.
Comment: When I return JObject.Parse(jsonString) I am getting "Cannot access child value on Newtonsoft.Json.Linq.JValue. "exception
Comment: Return Json(JObject.Parse(jsonString))
Comment: Yes, this is what I returned. And one more thing when I change "JsonConvert.DeserializeObject(jsonstring, settings);"  to "dynamic jsonModel = JsonConvert.DeserializeObject(jsonstring, settings);" ,I cant able to pass settings.
Comment: Don't pass settings then.
What project is this? Web Api2?
Comment: I am getting an error "cannot convert from Newtonsoft.Json.JsonserializerSettings to 'System.Type'"
Comment: What's the exact environment? .Net Core or Framework? And what version
Answer: I found a solution to my question by changing the return type of the method to HttpResponseMessage.
 public HttpResponseMessage getNewsList(string topic, string district, string type,string count)
 {
    jsonstring = Newtonsoft.Json.JsonConvert.SerializeObject(chatbotclass, Formatting.None);
    if (!string.IsNullOrEmpty(jsonstring))
    {
       var response = this.Request.CreateResponse(HttpStatusCode.OK);
       response.Content = new StringContent(jsonstring, Encoding.UTF8, "application/json");
       return response;
    }
       throw new HttpResponseException(HttpStatusCode.NotFound);
}


Normal distribution probability

Question: just a quick question dealing with probability.  The annual returns on stocks and treasury bonds over the next 12 months are uncertain. Suppose that these returns can be described by normal distributions with stocks having a mean of 15% and a standard deviation of 20%, and bonds having a mean of 6% and a standard deviation of 9%. Which asset is more likely to have a negative return?  Thanks for any help!
Comment: The question is formally well-defined, and Shai Covo has given an answer, but note that many distributions (these in particular) are not normal-the tails are much larger than Gauss would predict.  Also, to know which is more likely to be negative, all you really need to know is how many standard deviations down from the mean zero is.  You can compare the two numbers without calculating either one.
Comment: @Ross Great points.  Under the assumption that the two distributions have the same shape (i.e., are the same up to rescaling and translation), non-normality doesn't matter: it will affect the probability calculation but does not change the answer.
Comment: This question was cross-posted at http://stats.stackexchange.com/q/5504/919 .
Answer: I don't know if that's what you are looking for, but if $X$ is normally distributed with mean $\mu$ and standard deviation $\sigma > 0$, then
$$
{\rm P}(X<0) = {\rm P}\bigg(\frac{{X - \mu }}{\sigma } < \frac{{0 - \mu }}{\sigma }\bigg) = {\rm P}\bigg(Z < \frac{{ - \mu }}{\sigma }\bigg),
$$
where $Z$ is a standard normal random variable, i.e. having mean zero and unit variance (or standard deviation). The probability ${\rm P}(Z<z)$ can be found using a Normal Distribution Calculator, and many are available online (check, e.g., this one).
Comment: Because the probability is a monotonic function of -mu/sigma, you don't have to compute it: you only need to compare the two values of -mu/sigma.
Comment: Indeed, but it is useful to know how to compute it.

Normal distribution probability


How to solve this limit involving cube root and infinity? $\lim_{x\to\infty} \left((x^3+x^2)^{1/3} - (x^3-x^2)^{1/3})\right)$

Question: How can I solve this limit? I know the answer is $2/3$.
I tried factorisation, but solving the complicated denominator using L'Hopital's Rule returns a wrong answer, $0$.
$$ \lim_{x\to\infty} \left((x^3+x^2)^{1/3} - (x^3-x^2)^{1/3})\right)  $$
Thanks.
Answer: You can use the identity $$a^3−b^3=(a−b)(a^2+ab+b^2)$$ with $a=(x^3+x^2)^{1/3}$ and $b=(x^3-x^2)^{1/3}$. So, you want to multiply (numerator and denominator) with $a^2+ab+b^2$. This will give you \begin{align}a-b&=\frac{(a-b)(a^2+ab+b^2)}{a^2+ab+b^2}=\frac{a^3-b^3}{a^2+ab+b^2}\\[0.2cm]&=\frac{x^3+x^2-(x^3-x^2)}{(x^3+x^2)^{2/3}+(x^3+x^2)^{1/3}(x^3-x^2)^{1/3}+(x^3-x^2)^{2/3}}\\[0.2cm]&=\frac{2x^2}{(x^{3})^{2/3}(1+\frac1x)+(x^3)^{1/3}(1+\frac1x)(x^3)^{1/3}(1-\frac1x)+(x^3)^{2/3}(1-\frac1x)}\\[0.2cm]&=\frac{2x^2}{x^2(1+\frac1x)+x(1+\frac1x)x(1-\frac1x)+x^2(1-\frac1x)}\\[0.2cm]&=\frac{2}{1+\frac1x+(1+\frac1x)(1-\frac1x)+1-\frac1x}\\[0.2cm]&=\frac{2}{3-\frac1{x^2}}\end{align} Now let $x\to +\infty$ to conclude that $$\lim_{x\to +\infty}\frac{2}{3-\frac1{x^2}}=\frac2{3-0}=\frac23$$
Answer: $$
\lim_{x\to\infty} (x(1+1/x)^{1/3} - x(1-1/x)^{1/3}))
$$
and then expand $(1\pm\epsilon)^{1/3}\approx 1\pm\epsilon/3...$ for $\epsilon\to 0\ .$
Answer: With $t:=\frac1x$, The limit is the same as
$$\lim_{t\to0^+}\frac{(1+t)^{1/3}-(1-t)^{1/3}}{t}.$$
By L'Hospital,
$$\lim_{t\to0^+}\frac{(1+t)^{1/3}-(1-t)^{1/3}}{t}=\frac13\lim_{t\to0^+}\left((1+t)^{-2/3}+(1-t)^{-2/3}\right).$$

Alternatively, with the generalized binomial theorem,
$$\lim_{t\to0^+}\frac{\left(1+\frac13t-\frac{1\cdot2}{3\cdot3}\frac{t^2}2+\frac{1\cdot2\cdot5}{3\cdot3\cdot3}\frac{t^3}{3!}\cdots\right)-
\left(1-\frac13t-\frac{1\cdot2}{3\cdot3}\frac{t^2}2-\frac{1\cdot2\cdot5}{3\cdot3\cdot3}\frac{t^3}{3!}\cdots\right)}t.$$


Dice simulation in java

Question: I'm trying to simulate rolling a die 100 times, and printing the results of how many 1/2/3/4/5/6 i landed. Here's my code thus far: I'm trying to use a while loop for my assignment, and i need to use (Math.random( )*6 + 1) to generate numbers.
public class RollingDice {

    public static void main(String args[]) {

        int count = 0; // number of times die was rolled
        int count1s = 0; // number of times 1 was rolled
        int count2s = 0; // number of times 2 was rolled
        int count3s = 0;
        int count4s = 0;
        int count5s = 0;
        int count6s = 0;

        while (count < 100) {
            count1s = (int) (Math.random( )*6 + 1);
            count2s = (int) (Math.random( )*6 + 1);
            count3s = (int) (Math.random( )*6 + 1);
            count4s = (int) (Math.random( )*6 + 1);
            count5s = (int) (Math.random( )*6 + 1);
            count6s = (int) (Math.random( )*6 + 1);

            count++;

    }
        System.out.println("Number of times the die was rolled: "+ count);
        System.out.println("Number of times 1 was rolled: " + count1s);
        System.out.println("Number of times 2 was rolled: " + count2s);
        System.out.println("Number of times 3 was rolled: " + count3s);
        System.out.println("Number of times 4 was rolled: " + count4s);
        System.out.println("Number of times 5 was rolled: " + count5s);
        System.out.println("Number of times 6 was rolled: " + count6s);

    }
}

My code currently prints:
Number of times the die was rolled: 100
Number of times 1 was rolled: 3
Number of times 2 was rolled: 1
Number of times 3 was rolled: 5
Number of times 4 was rolled: 2
Number of times 5 was rolled: 4
Number of times 6 was rolled: 4

As you can see, its rolling 100 times, but its only saving the results of 1 roll, not 100, How do I fix this?
Answer: On each iteration of your while loop, you are reassigning the value of count1s, count2s, and the others. Instead what you should do is you should "roll the dice" and then see what value it is, and increment the proper variable.
while (count < 100) {
    int diceRoll = (int) (Math.random() * 6 + 1);
    if (diceRoll == 1)
        count1s++;
    else if (diceRoll == 2)
        count2s++;
    // ... you get the idea

    count++;
}

And as a fun sidenote, using Java 8 there is a significantly easier, and more cool way to do this.
        Stream.generate(() -> (int) (Math.random() * 6 + 1))
             .limit(100L)
             .collect(Collectors.groupingBy(num -> num,
                 Collectors.counting()))
             .forEach((num, count) -> System.out.println("number of times " + num + " was rolled: " + count));

Comment: THANK YOU SO MUCH!! Was driving me insane. Man that was simple
Comment: Nice solution on Java 8. Thanks.
Answer: Each iteration you are replacing the previous roll's data.You can rewrite the logic as
// initialization
while(count < 100){
   int currentRoll = (int) (Math.random() * 6 + 1);
   if(currentRoll == 1)
      count1s++;
  // Same logic for all occurances
}

Answer: Because your logic is incorrect.
Inside while loop, you assigned appearance time of each roll with value of dice.
=> Counter of each always < 7.
Also, each time your call Math.random() will give you new value => Should call it once each roll.
In this case, use switch - case statement will be correct.
  while (count < 100) {
        int num = (int) (Math.random( )*6 + 1);
        switch(num)  {
            case 1:
                count1s++;
                break;
            case 2:
                count2s++;
                break;
            case 3:
                count3s++;
                break;
            case 4:
                count4s++;
                break;
            case 5:
                count5s++;
                break;
            case 6:
                count6s++;
                break;
        }
        count++;
   }

Comment: Thanks, forgot all about switch statements

Dice simulation in java