text:
import {NgForOfContext} from '@angular/common';
import {ElementRef, TemplateRef} from '@angular/core';

import {AttributeMarker, defineComponent, templateRefExtractor} from '../../src/render3/index';
import {bind, template, elementEnd, elementProperty, elementStart, getCurrentView, interpolation1, interpolation2, interpolation3, interpolationV, listener, load, nextContext, restoreView, text, textBinding, elementContainerStart, elementContainerEnd, reference} from '../../src/render3/instructions';
import {RenderFlags} from '../../src/render3/interfaces/definition';

import {NgForOf, NgIf, NgTemplateOutlet} from './common_with_def';
import {ComponentFixture} from './render_util';

describe('@angular/common integration', () => {

  describe('NgForOf', () => {
    it('should update a loop', () => {
      function liTemplate(rf: RenderFlags, ctx: NgForOfContext<string>) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'li');
          { text(1); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const item = ctx.$implicit;
          textBinding(1, bind(item));
        }
      }

      class MyApp {
        items: string[] = ['first', 'second'];

        static ngComponentDef = defineComponent({
          type: MyApp,
          factory: () => new MyApp(),
          selectors: [['my-app']],
          consts: 2,
          vars: 1,
          //

          //
{{item}}

          //

          template: (rf: RenderFlags, ctx: MyApp) => {
            if (rf & RenderFlags.Create) {
              elementStart(0, 'ul');
              { template(1, liTemplate, 2, 1, undefined, ['ngForOf', '']); }
              elementEnd();
            }
            if (rf & RenderFlags.Update) {
              elementProperty(1, 'ngForOf', bind(ctx.items));
            }
          },
          directives: () => [NgForOf]
        });
      }

      const fixture = new ComponentFixture(MyApp);
      expect(fixture.html).toEqual('

first

second

');

      // change detection cycle, no model changes
      fixture.update();
      expect(fixture.html).toEqual('

first

second

');

      // remove the last item
      fixture.component.items.length = 1;
      fixture.update();
      expect(fixture.html).toEqual('

first

');

      // change an item
      fixture.component.items[0] = 'one';
      fixture.update();
      expect(fixture.html).toEqual('

one

');

      // add an item
      fixture.component.items.push('two');
      fixture.update();
      expect(fixture.html).toEqual('

one

two

');
    });

    it('should support ngForOf context variables', () => {
      function liTemplate(rf: RenderFlags, ctx: NgForOfContext<string>) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'li');
          { text(1); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const item = ctx.$implicit;
          textBinding(1, interpolation3('', ctx.index, ' of ', ctx.count, ': ', item, ''));
        }
      }

      class MyApp {
        items: string[] = ['first', 'second'];

        static ngComponentDef = defineComponent({
          type: MyApp,
          factory: () => new MyApp(),
          selectors: [['my-app']],
          consts: 2,
          vars: 1,
          //

          //
{{index}} of
          //   {{count}}: {{item}}

          //

          template: (rf: RenderFlags, ctx: MyApp) => {
            if (rf & RenderFlags.Create) {
              elementStart(0, 'ul');
              { template(1, liTemplate, 2, 3, undefined, ['ngForOf', '']); }
              elementEnd();
            }
            if (rf & RenderFlags.Update) {
              elementProperty(1, 'ngForOf', bind(ctx.items));
            }

          },
          directives: () => [NgForOf]
        });
      }

      const fixture = new ComponentFixture(MyApp);
      expect(fixture.html).toEqual('

0 of 2: first

1 of 2: second

');

      fixture.component.items.splice(1, 0, 'middle');
      fixture.update();
      expect(fixture.html)
          .toEqual('

0 of 3: first

1 of 3: middle

2 of 3: second

');
    });

    it('should retain parent view listeners when the NgFor destroy views', () => {

      function liTemplate(rf: RenderFlags, ctx: NgForOfContext<string>) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'li');
          { text(1); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const item = ctx.$implicit;
          textBinding(1, interpolation1('', item, ''));
        }
      }

      class MyApp {
        private _data: number[] = [1, 2, 3];
        items: number[] = [];

        toggle() {
          if (this.items.length) {
            this.items = [];
          } else {
            this.items = this._data;
          }
        }

        static ngComponentDef = defineComponent({
          type: MyApp,
          factory: () => new MyApp(),
          selectors: [['my-app']],
          consts: 4,
          vars: 1,
          // <button (click)="toggle()">Toggle List</button>
          //

          //
{{index}}

          //

          template: (rf: RenderFlags, ctx: MyApp) => {
            if (rf & RenderFlags.Create) {
              elementStart(0, 'button');
              {
                listener('click', function() { return ctx.toggle(); });
                text(1, 'Toggle List');
              }
              elementEnd();
              elementStart(2, 'ul');
              { template(3, liTemplate, 2, 1, undefined, ['ngForOf', '']); }
              elementEnd();
            }
            if (rf & RenderFlags.Update) {
              elementProperty(3, 'ngForOf', bind(ctx.items));
            }

          },
          directives: () => [NgForOf]
        });
      }

      const fixture = new ComponentFixture(MyApp);
      const button = fixture.hostElement.querySelector('button') !;

      expect(fixture.html).toEqual('<button>Toggle List</button>

');

      // this will fill the list
      fixture.component.toggle();
      fixture.update();
      expect(fixture.html)
          .toEqual('<button>Toggle List</button>

1

2

3

');

      button.click();
      fixture.update();

      expect(fixture.html).toEqual('<button>Toggle List</button>

');

      button.click();
      fixture.update();
      expect(fixture.html)
          .toEqual('<button>Toggle List</button>

1

2

3

');
    });

    it('should support multiple levels of embedded templates', () => {
      /**
       *

       *

       *      {{cell}} - {{ row.value }} - {{ items.length }}
       *
       *

       *

       */
      class MyApp {
        items: any[] = [{data: ['1', '2'], value: 'first'}, {data: ['3', '4'], value: 'second'}];

        static ngComponentDef = defineComponent({
          type: MyApp,
          factory: () => new MyApp(),
          selectors: [['my-app']],
          consts: 2,
          vars: 1,
          template: (rf: RenderFlags, ctx: MyApp) => {
            if (rf & RenderFlags.Create) {
              elementStart(0, 'ul');
              { template(1, liTemplate, 2, 1, null, ['ngForOf', '']); }
              elementEnd();
            }
            if (rf & RenderFlags.Update) {
              elementProperty(1, 'ngForOf', bind(ctx.items));
            }

          },
          directives: () => [NgForOf]
        });
      }

      function liTemplate(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'li');
          { template(1, spanTemplate, 2, 3, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const row = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(row.data));
        }
      }

      function spanTemplate(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'span');
          { text(1); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const cell = ctx.$implicit;
          const row = nextContext().$implicit as any;
          const app = nextContext() as any;
          textBinding(1, interpolation3('', cell, ' - ', row.value, ' - ', app.items.length, ''));
        }
      }

      const fixture = new ComponentFixture(MyApp);

      // Change detection cycle, no model changes
      fixture.update();
      expect(fixture.html)
          .toEqual(
              '

1 - first - 22 - first - 2

3 - second - 24 - second - 2

');

      // Remove the last item
      fixture.component.items.length = 1;
      fixture.update();
      expect(fixture.html)
          .toEqual('

1 - first - 12 - first - 1

');

      // Change an item
      fixture.component.items[0].data[0] = 'one';
      fixture.update();
      expect(fixture.html)
          .toEqual('

one - first - 12 - first - 1

');

      // Add an item
      fixture.component.items[1] = {data: ['three', '4'], value: 'third'};
      fixture.update();
      expect(fixture.html)
          .toEqual(
              '

one - first - 22 - first - 2

three - third - 24 - third - 2

');
    });

    it('should support multiple levels of embedded templates with listeners', () => {
      /**
       *

       *

       *
       *        {{ row.value }} - {{ name }}
       *

       *

       */
      class MyApp {
        items: any[] = [{data: ['1'], value: 'first'}];
        name = 'app';
        events: string[] = [];

        onClick(value: string, name: string) { this.events.push(value, name); }

        static ngComponentDef = defineComponent({
          type: MyApp,
          factory: () => new MyApp(),
          selectors: [['my-app']],
          consts: 1,
          vars: 1,
          template: (rf: RenderFlags, ctx: MyApp) => {
            if (rf & RenderFlags.Create) {
              template(0, divTemplate, 2, 1, null, ['ngForOf', '']);
            }
            if (rf & RenderFlags.Update) {
              elementProperty(0, 'ngForOf', bind(ctx.items));
            }

          },
          directives: () => [NgForOf]
        });
      }

      function divTemplate(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div');
          { template(1, pTemplate, 3, 2, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const row = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(row.data));
        }
      }

      function pTemplate(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          const state = getCurrentView();
          elementStart(0, 'p');
          {
            elementStart(1, 'span');
            {
              listener('click', () => {
                restoreView(state);
                const row = nextContext().$implicit as any;
                const app = nextContext();
                app.onClick(row.value, app.name);
              });
            }
            elementEnd();
            text(2);
          }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const row = nextContext().$implicit as any;
          const app = nextContext() as any;
          textBinding(2, interpolation2('', row.value, ' - ', app.name, ''));
        }
      }

      const fixture = new ComponentFixture(MyApp);

      fixture.update();
      expect(fixture.html).toEqual('

first - app

');

      const span = fixture.hostElement.querySelector('span') as any;
      span.click();
      expect(fixture.component.events).toEqual(['first', 'app']);

      fixture.component.name = 'new name';
      fixture.update();
      expect(fixture.html).toEqual('

first - new name

');

      span.click();
      expect(fixture.component.events).toEqual(['first', 'app', 'first', 'new name']);
    });

    it('should support skipping contexts', () => {
      /**
       *

       *

       *
       *           {{ cell.value }} - {{ name }}
       *
       *

       *

       */
      class MyApp {
        name = 'app';
        items: any[] = [
          [
            // row
            {value: 'one', data: ['1', '2']}  // cell
          ],
          [{value: 'two', data: ['3', '4']}]
        ];

        static ngComponentDef = defineComponent({
          type: MyApp,
          factory: () => new MyApp(),
          selectors: [['my-app']],
          consts: 1,
          vars: 1,
          template: (rf: RenderFlags, ctx: MyApp) => {
            if (rf & RenderFlags.Create) {
              template(0, divTemplate, 2, 1, null, ['ngForOf', '']);
            }
            if (rf & RenderFlags.Update) {
              elementProperty(0, 'ngForOf', bind(ctx.items));
            }

          },
          directives: () => [NgForOf]
        });
      }

      function divTemplate(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div');
          { template(1, innerDivTemplate, 2, 1, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const row = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(row));
        }
      }

      function innerDivTemplate(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div');
          { template(1, spanTemplate, 2, 2, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const cell = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(cell.data));
        }
      }

      function spanTemplate(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'span');
          { text(1); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const cell = nextContext().$implicit as any;
          const app = nextContext(2) as any;
          textBinding(1, interpolation2('', cell.value, ' - ', app.name, ''));
        }
      }

      const fixture = new ComponentFixture(MyApp);

      fixture.update();
      expect(fixture.html)
          .toEqual(
              `<div><div><span>one - app</span><span>one - app</span></div></div><div><div><span>two - app</span><span>two - app</span></div></div>`);

      fixture.component.name = 'other';
      fixture.update();
      expect(fixture.html)
          .toEqual(
              `<div><div><span>one - other</span><span>one - other</span></div></div><div><div><span>two - other</span><span>two - other</span></div></div>`);
    });

    it('should support context for 9+ levels of embedded templates', () => {
      /**
       *
       *
       *
       *
       *
       *
       *
       *
       *
       *
       *                                    {{ item8 }} - {{ item7.value }} - {{ item6.value }}...
       *
       *
       *
       *
       *
       *
       *
       *
       *
       */
      class MyApp {
        value = 'App';
        items: any[] = [
          {
            // item0
            data: [{
              // item1
              data: [{
                // item2
                data: [{
                  // item3
                  data: [{
                    // item4
                    data: [{
                      // item5
                      data: [{
                        // item6
                        data: [{
                          // item7
                          data: [
                            '1', '2'  // item8
                          ],
                          value: 'h'
                        }],
                        value: 'g'
                      }],
                      value: 'f'
                    }],
                    value: 'e'
                  }],
                  value: 'd'
                }],
                value: 'c'
              }],
              value: 'b'
            }],
            value: 'a'
          },
          {
            // item0
            data: [{
              // item1
              data: [{
                // item2
                data: [{
                  // item3
                  data: [{
                    // item4
                    data: [{
                      // item5
                      data: [{
                        // item6
                        data: [{
                          // item7
                          data: [
                            '3', '4'  // item8
                          ],
                          value: 'H'
                        }],
                        value: 'G'
                      }],
                      value: 'F'
                    }],
                    value: 'E'
                  }],
                  value: 'D'
                }],
                value: 'C'
              }],
              value: 'B'
            }],
            value: 'A'
          }
        ];

        static ngComponentDef = defineComponent({
          type: MyApp,
          factory: () => new MyApp(),
          selectors: [['my-app']],
          consts: 1,
          vars: 1,
          template: (rf: RenderFlags, ctx: MyApp) => {
            if (rf & RenderFlags.Create) {
              template(0, itemTemplate0, 2, 1, null, ['ngForOf', '']);
            }
            if (rf & RenderFlags.Update) {
              elementProperty(0, 'ngForOf', bind(ctx.items));
            }

          },
          directives: () => [NgForOf]
        });
      }

      function itemTemplate0(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'span');
          { template(1, itemTemplate1, 2, 1, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const item0 = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(item0.data));
        }
      }

      function itemTemplate1(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'span');
          { template(1, itemTemplate2, 2, 1, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const item1 = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(item1.data));
        }
      }

      function itemTemplate2(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'span');
          { template(1, itemTemplate3, 2, 1, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const item2 = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(item2.data));
        }
      }

      function itemTemplate3(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'span');
          { template(1, itemTemplate4, 2, 1, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const item3 = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(item3.data));
        }
      }

      function itemTemplate4(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'span');
          { template(1, itemTemplate5, 2, 1, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const item4 = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(item4.data));
        }
      }

      function itemTemplate5(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'span');
          { template(1, itemTemplate6, 2, 1, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const item5 = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(item5.data));
        }
      }

      function itemTemplate6(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'span');
          { template(1, itemTemplate7, 2, 1, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const item6 = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(item6.data));
        }
      }

      function itemTemplate7(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'span');
          { template(1, itemTemplate8, 2, 10, null, ['ngForOf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const item7 = ctx.$implicit as any;
          elementProperty(1, 'ngForOf', bind(item7.data));
        }
      }

      function itemTemplate8(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'span');
          { text(1); }
          elementEnd();
        }

        if (rf & RenderFlags.Update) {
          const value = ctx.$implicit;
          const item7 = nextContext().$implicit;
          const item6 = nextContext().$implicit;
          const item5 = nextContext().$implicit;
          const item4 = nextContext().$implicit;
          const item3 = nextContext().$implicit;
          const item2 = nextContext().$implicit;
          const item1 = nextContext().$implicit;
          const item0 = nextContext().$implicit;
          const myApp = nextContext();
          textBinding(1, interpolationV([
                        '',  value,       '.', item7.value, '.', item6.value, '.', item5.value,
                        '.', item4.value, '.', item3.value, '.', item2.value, '.', item1.value,
                        '.', item0.value, '.', myApp.value, ''
                      ]));
        }
      }

      const fixture = new ComponentFixture(MyApp);

      expect(fixture.html)
          .toEqual(
              '' +
              '1.h.g.f.e.d.c.b.a.App' +
              '2.h.g.f.e.d.c.b.a.App' +
              '' +
              '' +
              '3.H.G.F.E.D.C.B.A.App' +
              '4.H.G.F.E.D.C.B.A.App' +
              '');
    });

  });

  describe('ngIf', () => {
    it('should support sibling ngIfs', () => {
      class MyApp {
        showing = true;
        valueOne = 'one';
        valueTwo = 'two';

        static ngComponentDef = defineComponent({
          type: MyApp,
          factory: () => new MyApp(),
          selectors: [['my-app']],
          consts: 2,
          vars: 2,
          /**
           *
{{ valueOne }}

           *
{{ valueTwo }}

           */
          template: (rf: RenderFlags, ctx: MyApp) => {
            if (rf & RenderFlags.Create) {
              template(0, templateOne, 2, 1, undefined, ['ngIf', '']);
              template(1, templateTwo, 2, 1, undefined, ['ngIf', '']);
            }
            if (rf & RenderFlags.Update) {
              elementProperty(0, 'ngIf', bind(ctx.showing));
              elementProperty(1, 'ngIf', bind(ctx.showing));
            }

          },
          directives: () => [NgIf]
        });
      }

      function templateOne(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div');
          { text(1); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const myApp = nextContext();
          textBinding(1, bind(myApp.valueOne));
        }
      }

      function templateTwo(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div');
          { text(1); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const myApp = nextContext();
          textBinding(1, bind(myApp.valueTwo));
        }
      }

      const fixture = new ComponentFixture(MyApp);
      expect(fixture.html).toEqual('
one

two
');

      fixture.component.valueOne = '$$one$$';
      fixture.component.valueTwo = '$$two$$';
      fixture.update();
      expect(fixture.html).toEqual('
$$one$$

$$two$$
');
    });

    it('should handle nested ngIfs with no intermediate context vars', () => {
      /**
       *

       *

       *

       *           {{ name }}
       *

       *

       *

       */
      class AppComponent {
        showing = true;
        outerShowing = true;
        innerShowing = true;
        name = 'App name';

        static ngComponentDef = defineComponent({
          type: AppComponent,
          factory: () => new AppComponent(),
          selectors: [['my-app']],
          consts: 1,
          vars: 1,
          template: (rf: RenderFlags, ctx: AppComponent) => {
            if (rf & RenderFlags.Create) {
              template(0, divTemplate, 2, 1, undefined, ['ngIf', '']);
            }
            if (rf & RenderFlags.Update) {
              elementProperty(0, 'ngIf', bind(ctx.showing));
            }

          },
          directives: () => [NgIf]
        });
      }

      function divTemplate(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div');
          { template(1, outerDivTemplate, 2, 1, undefined, ['ngIf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const app = nextContext();
          elementProperty(1, 'ngIf', bind(app.outerShowing));
        }
      }

      function outerDivTemplate(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div');
          { template(1, innerDivTemplate, 2, 1, undefined, ['ngIf', '']); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const app = nextContext(2);
          elementProperty(1, 'ngIf', bind(app.innerShowing));
        }
      }

      function innerDivTemplate(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div');
          { text(1); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const app = nextContext(3);
          textBinding(1, bind(app.name));
        }
      }

      const fixture = new ComponentFixture(AppComponent);
      expect(fixture.html).toEqual(`<div><div><div>App name</div></div></div>`);

      fixture.component.name = 'Other name';
      fixture.update();
      expect(fixture.html).toEqual(`<div><div><div>Other name</div></div></div>`);
    });

  });

  describe('NgTemplateOutlet', () => {

    it('should create and remove embedded views', () => {

      class MyApp {
        showing = false;
        static ngComponentDef = defineComponent({
          type: MyApp,
          factory: () => new MyApp(),
          selectors: [['my-app']],
          consts: 3,
          vars: 1,
          /**
           * <ng-template #tpl>from tpl</ng-template>
           * <ng-template [ngTemplateOutlet]="showing ? tpl : null"></ng-template>
           */
          template: (rf: RenderFlags, myApp: MyApp) => {
            if (rf & RenderFlags.Create) {
              template(0, (rf1: RenderFlags) => {
                if (rf1 & RenderFlags.Create) {
                  text(0, 'from tpl');
                }
              }, 1, 0, undefined, undefined, ['tpl', ''], templateRefExtractor);
              template(2, null, 0, 0, null, [AttributeMarker.SelectOnly, 'ngTemplateOutlet']);
            }
            if (rf & RenderFlags.Update) {
              const tplRef = load(1);
              elementProperty(2, 'ngTemplateOutlet', bind(myApp.showing ? tplRef : null));
            }
          },
          directives: () => [NgTemplateOutlet]
        });
      }

      const fixture = new ComponentFixture(MyApp);
      expect(fixture.html).toEqual('');

      fixture.component.showing = true;
      fixture.update();
      expect(fixture.html).toEqual('from tpl');

      fixture.component.showing = false;
      fixture.update();
      expect(fixture.html).toEqual('');
    });

    it('should allow usage on ng-container', () => {
      class MyApp {
        showing = false;
        static ngComponentDef = defineComponent({
          type: MyApp,
          factory: () => new MyApp(),
          selectors: [['my-app']],
          consts: 3,
          vars: 1,
          /**
           * <ng-template #tpl>from tpl</ng-template>
           * <ng-container [ngTemplateOutlet]="showing ? tpl : null"></ng-container>
           */
          template: (rf: RenderFlags, myApp: MyApp) => {
            if (rf & RenderFlags.Create) {
              template(0, (rf1: RenderFlags) => {
                if (rf1 & RenderFlags.Create) {
                  text(0, 'from tpl');
                }
              }, 1, 0, undefined, undefined, ['tpl', ''], templateRefExtractor);
              elementContainerStart(2, [AttributeMarker.SelectOnly, 'ngTemplateOutlet']);
              elementContainerEnd();
            }
            if (rf & RenderFlags.Update) {
              const tplRef = reference(1);
              elementProperty(2, 'ngTemplateOutlet', bind(myApp.showing ? tplRef : null));
            }
          },
          directives: () => [NgTemplateOutlet]
        });
      }

      const fixture = new ComponentFixture(MyApp);
      expect(fixture.html).toEqual('');

      fixture.component.showing = true;
      fixture.update();
      expect(fixture.html).toEqual('from tpl');

      fixture.component.showing = false;
      fixture.update();
      expect(fixture.html).toEqual('');

    });

  });
});


text:
#import "AutoScalingCreateAutoScalingGroupRequest.h"

@implementation AutoScalingCreateAutoScalingGroupRequest

@synthesize autoScalingGroupName;
@synthesize launchConfigurationName;
@synthesize minSize;
@synthesize maxSize;
@synthesize desiredCapacity;
@synthesize defaultCooldown;
@synthesize availabilityZones;
@synthesize loadBalancerNames;
@synthesize healthCheckType;
@synthesize healthCheckGracePeriod;
@synthesize placementGroup;
@synthesize vPCZoneIdentifier;
@synthesize tags;

-(id)init
{
    if (self = [super init]) {
        autoScalingGroupName    = nil;
        launchConfigurationName = nil;
        minSize                 = nil;
        maxSize                 = nil;
        desiredCapacity         = nil;
        defaultCooldown         = nil;
        availabilityZones       = [[NSMutableArray alloc] initWithCapacity:1];
        loadBalancerNames       = [[NSMutableArray alloc] initWithCapacity:1];
        healthCheckType         = nil;
        healthCheckGracePeriod  = nil;
        placementGroup          = nil;
        vPCZoneIdentifier       = nil;
        tags                    = [[NSMutableArray alloc] initWithCapacity:1];
    }

    return self;
}

-(void)addAvailabilityZone:(NSString *)availabilityZoneObject
{
    if (availabilityZones == nil) {
        availabilityZones = [[NSMutableArray alloc] initWithCapacity:1];
    }

    [availabilityZones addObject:availabilityZoneObject];
}

-(void)addLoadBalancerName:(NSString *)loadBalancerNameObject
{
    if (loadBalancerNames == nil) {
        loadBalancerNames = [[NSMutableArray alloc] initWithCapacity:1];
    }

    [loadBalancerNames addObject:loadBalancerNameObject];
}

-(void)addTag:(AutoScalingTag *)tagObject
{
    if (tags == nil) {
        tags = [[NSMutableArray alloc] initWithCapacity:1];
    }

    [tags addObject:tagObject];
}

-(NSString *)description
{
    NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256];

    [buffer appendString:@"{"];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"AutoScalingGroupName: %@,", autoScalingGroupName] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"LaunchConfigurationName: %@,", launchConfigurationName] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"MinSize: %@,", minSize] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"MaxSize: %@,", maxSize] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"DesiredCapacity: %@,", desiredCapacity] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"DefaultCooldown: %@,", defaultCooldown] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"AvailabilityZones: %@,", availabilityZones] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"LoadBalancerNames: %@,", loadBalancerNames] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"HealthCheckType: %@,", healthCheckType] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"HealthCheckGracePeriod: %@,", healthCheckGracePeriod] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"PlacementGroup: %@,", placementGroup] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"VPCZoneIdentifier: %@,", vPCZoneIdentifier] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"Tags: %@,", tags] autorelease]];
    [buffer appendString:[super description]];
    [buffer appendString:@"}"];

    return [buffer autorelease];
}

-(void)dealloc
{
    [autoScalingGroupName release];
    [launchConfigurationName release];
    [minSize release];
    [maxSize release];
    [desiredCapacity release];
    [defaultCooldown release];
    [availabilityZones release];
    [loadBalancerNames release];
    [healthCheckType release];
    [healthCheckGracePeriod release];
    [placementGroup release];
    [vPCZoneIdentifier release];
    [tags release];

    [super dealloc];
}

@end

redpajama_set_name: RedPajamaGithub


text:
fiddle-0042-FunctionReturnPointer
======

### Title

Function Return Pointer

### Creation Date

03-20-17

### Location

Chicago, IL

### Issue

[Issue 149](https://github.com/bradyhouse/house/issues/149)

### Description

Create a fiddle based on Program 11.10 from Stephen Kochan's book [Programming in C (Developer's Library) 4th Edition](#).
This program demonstrates how to return a pointer from a function.

### Use Case

Navigate to the scripts directory and execute the following command:

    ./fiddle.sh "start" "c" "0042"

This should produce the following output:

     {{ ʕ・ɭ・ʔ }}
     FIDDLE.SH
     FIDDLE-START.SH
     ├────STARTSERVER
     ├────GCCSTART
     ├────INVOKING EXECUTABLE

     functionreturnpointer started

     Enter value to locate:

Enter the value `300` and press `[enter]`

    Found 300.

    functionreturnpointer ended

### Tags

gcc, c, stdio.h, pointer, struct, scanf, printf


text:
using System.Collections.Generic;
using BEPUutilities;
using BEPUphysics.BroadPhaseEntries;

namespace BEPUphysics.BroadPhaseSystems
{
    ///
    /// Defines a system that accelerates bounding volume and ray cast queries.
    ///
    public interface IQueryAccelerator
    {
        ///
        /// Gets the broad phase associated with this query accelerator, if any.
        ///
        BroadPhase BroadPhase { get; }
        ///
        /// Gets the broad phase entries overlapping the ray.
        ///
        ///<param name="ray">Ray to test.</param>
        ///<param name="outputIntersections">Overlapped entries.</param>
        ///<returns>Whether or not the ray hit anything.</returns>
        bool RayCast(Ray ray, IList<BroadPhaseEntry> outputIntersections);
        ///
        /// Gets the broad phase entries overlapping the ray.
        ///
        ///<param name="ray">Ray to test.</param>
        /// <param name="maximumLength">Maximum length of the ray in units of the ray's direction's length.</param>
        ///<param name="outputIntersections">Overlapped entries.</param>
        ///<returns>Whether or not the ray hit anything.</returns>
        bool RayCast(Ray ray, float maximumLength, IList<BroadPhaseEntry> outputIntersections);

        //There's no single-hit version because the TOI on queries isn't really meaningful.
        //TODO: IQueryAccelerator + BroadPhase.  Both have add methods.  A user might expect to be able to add separately, but that doesn't really work.
        //Consider pulling the query accelerator into the broadphase so people consider it to be a part of the broadphase- it accelerates queries against the broadphase.
        //If someone wanted to raycast against something other than the broadphase, they can create an IQueryAccelerator of some kind in isolation.

        ///
        /// Gets the entries with bounding boxes which overlap the bounding shape.
        ///
        /// <param name="boundingShape">Bounding shape to test.</param>
        /// <param name="overlaps">Overlapped entries.</param>
        void GetEntries(BoundingBox boundingShape, IList<BroadPhaseEntry> overlaps);
        ///
        /// Gets the entries with bounding boxes which overlap the bounding shape.
        ///
        /// <param name="boundingShape">Bounding shape to test.</param>
        /// <param name="overlaps">Overlapped entries.</param>
        void GetEntries(BoundingSphere boundingShape, IList<BroadPhaseEntry> overlaps);
        /////
        ///// Gets the entries with bounding boxes which overlap the bounding shape.
        /////
        ///// <param name="boundingShape">Bounding shape to test.</param>
        ///// <param name="overlaps">Overlapped entries.</param>
        //void GetEntries(BoundingFrustum boundingShape, IList<BroadPhaseEntry> overlaps);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Allen Herrera | Developer</title>
    <link rel="stylesheet" href="/public/system/package/demo/css/normalize.css">
    <link href='http://fonts.googleapis.com/css?family=Changa+One|Open+Sans:400italic,700italic,400,700,800' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="/public/system/package/demo/css/main.css">
    <link rel="stylesheet" href="/public/system/package/demo/css/responsive.css">

Allen Herrera

LAMP Stack Developer

Portfolio

About

Contact

Experimentation with color and texture.

Playing with blending modes in Photoshop.

Trying to create an 80's style of glows.

Drips created using Photoshop brushes.

Creating shapes using repetition.

© 2014 Nick Pettit.


text:
require 'spec_helper'

module MemFs
  module Fake
    describe Directory do
      subject(:directory) { described_class.new('test') }

      describe '.new' do
        it 'sets . in the entries list' do
          expect(directory.entries).to include('.' => directory)
        end

        it 'sets .. in the entries list' do
          expect(directory.entries).to have_key('..')
        end
      end

      describe '#add_entry' do
        let(:entry) { described_class.new('new_entry') }

        it 'adds the entry to the entries list' do
          directory.add_entry entry
          expect(directory.entries).to include('new_entry' => entry)
        end

        it 'sets the parent of the added entry' do
          directory.add_entry entry
          expect(entry.parent).to be(directory)
        end
      end

      describe 'empty?' do
        it 'returns true if the directory is empty' do
          expect(directory).to be_empty
        end

        it 'returns false if the directory is not empty' do
          directory.add_entry described_class.new('test')
          expect(directory).not_to be_empty
        end
      end

      describe '#entry_names' do
        it 'returns the list of the names of the entries in the directory' do
          3.times do |n|
            directory.add_entry described_class.new("dir#{n}")
          end

          expect(directory.entry_names).to eq(%w[. .. dir0 dir1 dir2])
        end
      end

      describe '#find' do
        let(:sub_directory) { described_class.new('sub_dir') }
        let(:file) { File.new('file') }

        before :each do
          sub_directory.add_entry file
          directory.add_entry sub_directory
        end

        it 'returns the named entry if it is one of the entries' do
          expect(directory.find('sub_dir')).to be(sub_directory)
        end

        it 'calls find on the next directory in the search chain' do
          expect(directory.find('sub_dir/file')).to be(file)
        end

        it 'should remove any leading / in the path' do
          expect(directory.find('/sub_dir/file')).to be(file)
        end
      end

      describe '#parent=' do
        let(:parent) { described_class.new('parent') }

        it 'sets the .. entry in entries list' do
          directory.parent = parent
          expect(directory.entries).to include('..' => parent)
        end

        it 'sets the parent directory' do
          directory.parent = parent
          expect(directory.parent).to be(parent)
        end
      end

      describe '#path' do
        let(:root) { described_class.new('/') }

        it 'returns the directory path' do
          directory.parent = root
          expect(directory.path).to eq('/test')
        end

        context 'when the directory is /' do
          it 'returns /' do
            expect(root.path).to eq('/')
          end
        end
      end

      describe '#paths' do
        before do
          subdir = described_class.new('subdir')
          directory.add_entry(subdir)
          subdir.add_entry File.new('file1')
          subdir.add_entry File.new('file2')
        end

        it 'returns the path of the directory and its entries recursively' do
          expect(directory.paths).to eq \
            %w[test test/subdir test/subdir/file1 test/subdir/file2]
        end
      end

      describe '#remove_entry' do
        let(:file) { File.new('file') }

        it 'removes an entry from the entries list' do
          directory.add_entry file
          directory.remove_entry file
          expect(directory.entries).not_to have_value(file)
        end
      end

      describe '#type' do
        it "returns 'directory'" do
          expect(directory.type).to eq('directory')
        end
      end
    end
  end
end


text:
@implementation BMETopNavigationController

#pragma mark -
#pragma mark Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.interactivePopGestureRecognizer.delegate = nil; // Enable swipe to dismiss http://stackoverflow.com/questions/24710258/no-swipe-back-when-hiding-navigation-bar-in-uinavigationcontroller
}

- (BOOL)shouldAutorotate {
    return [[self activeViewController] shouldAutorotate];
}

- (NSUInteger)supportedInterfaceOrientations {
    return [[self activeViewController] supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return [[self activeViewController] preferredInterfaceOrientationForPresentation];;
}

#pragma mark -
#pragma mark Private Methods

- (UIViewController *)activeViewController {
    UIViewController *topViewController = self.presentedViewController;
    while (topViewController.presentedViewController) {
        topViewController = topViewController.presentedViewController;
    }
    return self.topViewController;
}

@end


text:
Want to contribute to php-halo-api? That's great! Here are a couple of guidelines that will help you contribute. Before we get started: Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md) to ensure that this project is a welcoming place for **everyone** to contribute to. By participating in this project you agree to abide by its terms.

#### Overview

* [Contribution workflow](#contribution-workflow)
* [Reporting a bug](#reporting-a-bug)
* [Contributing to an existing issue](#contributing-to-an-existing-issue)
* [Additional info](#additional-info)

## Contribution workflow

 * Fork the project.
 * Make your feature addition or bug fix.
 * Add tests for it. This is important so we don't break it in a future version unintentionally.
 * Send a pull request. Bonus points for topic branches.

## Reporting a bug

So you've found a bug, and want to help us fix it? Before filing a bug report, please double-check the bug hasn't already been reported. You can do so [on our issue tracker](https://github.com/halo-api/php-halo-api/issues). If something hasn't been raised, you can go ahead and create a new issue with the following information:

* How can the error be reproduced?
* If possible, please also provide an error message or a screenshot to illustrate the problem.

If you want to be really thorough, there is a great overview on Stack Overflow of [what you should consider when reporting a bug](http://stackoverflow.com/questions/240323/how-to-report-bugs-the-smart-way).

It goes without saying that you're welcome to help investigate further and/or find a fix for the bug. If you want to do so, just mention it in your bug report and offer your help!

## Contributing to an existing issue

### Finding an issue to work on

We've got a few open issues and are always glad to get help on that front. You can view the list of issues [here](https://github.com/halo-api/php-halo-api/issues). Most of the issues will be labelled, so you can use the labels to get an idea of which issue could be a good fit for you. (Here's [a good article](https://medium.freecodecamp.com/finding-your-first-open-source-project-or-bug-to-work-on-1712f651e5ba) on how to find your first bug to fix).

Before getting to work, take a look at the issue and at the conversation around it. Has someone already offered to work on the issue? Has someone been assigned to the issue? If so, you might want to check with them to see whether they're still actively working on it.

If the issue is a few months old, it might be a good idea to write a short comment to double-check that the issue or feature is still a valid one to jump on.

Feel free to ask for more detail on what is expected: are there any more details or specifications you need to know?
And if at any point you get stuck: don't hesitate to ask for help.

### Making your contribution

We've outlined the contribution workflow [here](#contribution-workflow). If you're a first-timer, don't worry! GitHub has a ton of guides to help you through your first pull request: You can find out more about pull requests [here](https://help.github.com/articles/about-pull-requests/) and about creating a pull request [here](https://help.github.com/articles/creating-a-pull-request/).

## Additional info

Especially if you're a newcomer to Open Source and you've found some little bumps along the way while contributing, we recommend you write about them. [Here](https://medium.freecodecamp.com/new-contributors-to-open-source-please-blog-more-920af14cffd)'s a great article about why writing about your experience is important; this will encourage other beginners to try their luck at Open Source, too!


text:
#import "UIViewController.h"

#import "PLEffectSelectionViewControllerDelegate-Protocol.h"
#import "PLImageAdjustmentViewDelegate-Protocol.h"
#import "UIActionSheetDelegate-Protocol.h"
#import "UIAlertViewDelegate-Protocol.h"
#import "UIPopoverControllerDelegate-Protocol.h"
#import "UIScrollViewDelegate-Protocol.h"

@class CIContext, CIFilter, EAGLContext, NSArray, NSDictionary, NSMutableArray, NSMutableDictionary, NSObject<OS_dispatch_queue>, NSTimer, NSUndoManager, PLEffectSelectionViewController, PLImageAdjustmentView, PLManagedAsset, PLProgressHUD, UIActionSheet, UIAlertView, UIImage, UILabel, UINavigationBar, UIPopoverController, UIScrollView, UIToolbar, UIView;

@interface PLEditPhotoController : UIViewController <PLImageAdjustmentViewDelegate, UIScrollViewDelegate, UIActionSheetDelegate, UIAlertViewDelegate, UIPopoverControllerDelegate, PLEffectSelectionViewControllerDelegate>
{
    UIScrollView *_scrollView;
    UIView *_zoomView;
    PLImageAdjustmentView *_editView;
    UILabel *_messageView;
    UINavigationBar *_navigationBar;
    UIToolbar *_toolbar;
    PLEffectSelectionViewController *_effectSelectionViewController;
    PLProgressHUD *_savingHUD;
    UIActionSheet *_actionSheet;
    UIAlertView *_alertView;
    UIPopoverController *_popover;
    int _initialOrientation;
    NSDictionary *_initialAdjustmentState;
    NSUndoManager *_undoManager;
    NSDictionary *_previousAdjustmentState;
    NSUndoManager *_previousUndoManager;
    NSTimer *_messageTimer;
    NSMutableArray *_navBarItems;
    NSArray *_originalItems;
    PLManagedAsset *_editedPhoto;
    PLManagedAsset *_pendingPhoto;
    UIImage *_adjustedImage;
    NSArray *_autoAdjustmentFilters;
    struct CGRect _enhanceCalcRect;
    NSArray *_autoRedEyeCorrections;
    CIFilter *_autoRedEyeFilter;
    CIFilter *_redEyeFilter;
    NSArray *_effectFilters;
    struct CGRect _normalizedCropRect;
    double _straightenAngle;
    double _rotationAngle;
    NSDictionary *_cachedMetadata;
    UIImage *_scaledCachedImage;
    UIImage *_smallThumbnailImage;
    UIImage *_largeThumbnailImage;
    NSObject<OS_dispatch_queue> *_cachedImageQueue;
    id _didEndZoomingBlock;
    id _editCompletionBlock;
    id _actionCompletionBlock;
    unsigned int _redEyeCycleCount;
    unsigned int _didInitializeNavigationItem:1;
    unsigned int _toolbarWasHidden:1;
    unsigned int _isUserAction:1;
    unsigned int _isCroppingImage:1;
    unsigned int _didTapForRedEyeCorrection:1;
    unsigned int _didEverTapForRedEyeCorrection:1;
    unsigned int _isCanceling:1;
    unsigned int _isOrderedOut:1;
    unsigned int _autoAdjustmentEnabled:1;
    unsigned int _preloadingEnhancementFilters:1;
    unsigned int _applyingAutoEnhance:1;
    unsigned int _modal:1;
    unsigned int _isUsingProxyImage:1;
    unsigned int _shouldPublishToPhotoStreams:1;
    unsigned int _needsFilteredFullSizeImage:1;
    unsigned int _preloadedEffectFilters:1;
    unsigned int _stopPreloadEffectFilters:1;
    _Bool _supportsEffects;
    unsigned long long _nextPreloadEffectFilterIndex;
    NSMutableDictionary *_thumbnailCache;
    NSDictionary *_thumbnailCacheAdjustmentState;
    CIContext *_ciContextThumbnails;
    CIContext *_ciContextFullSize;
    CIContext *_ciContextMainThread;
    EAGLContext *_glesContextThumbnails;
    EAGLContext *_glesContextFullSize;
    NSObject<OS_dispatch_queue> *_effectQueueThumbnails;
    NSObject<OS_dispatch_queue> *_effectQueueFullSize;
    int _currentMode;
    _Bool _savesAdjustmentsToCameraRoll;
    _Bool __toolbarHidden;
}

+ (void)initialize;
@property(nonatomic, setter=_setToolbarHidden:) _Bool _toolbarHidden; // @synthesize _toolbarHidden=__toolbarHidden;
@property(copy, nonatomic) id actionCompletionBlock; // @synthesize actionCompletionBlock=_actionCompletionBlock;
@property(nonatomic) double rotationAngle; // @synthesize rotationAngle=_rotationAngle;
- (_Bool)isEditing;
- (void)setMinimumZoom:(double)arg1 maximumZoom:(double)arg2;
- (_Bool)savesAdjustmentsToCameraRoll;
- (struct CGSize)editedImageSize;
- (void)_setUndoManager:(id)arg1;
- (void)effectSelectionViewController:(id)arg1 requestsThumbnailWithEffect:(id)arg2 completionBlock:(id)arg3;
- (void)_computeFullSizeFilteredImageWithAdjustmentState:(id)arg1;
- (void)_computeFullSizeFilteredImage;
- (void)effectSelectionViewController:(id)arg1 didSelectEffect:(id)arg2;
- (void)_thumbnailImageWithEffectFilters:(id)arg1 inputImage:(id)arg2 applyOrientation:(_Bool)arg3 forceSquareCrop:(_Bool)arg4 completionBlock:(id)arg5;
- (void)_fetchSmallThumbnailForEffectFilter:(id)arg1 completionBlock:(id)arg2;
- (void)_preloadNextEffectFilter;
- (void)_preloadEffectFilters;
- (void)_dismissEffectSelection;
- (void)_presentEffectSelection;
- (struct CGSize)_editedImageFullSize;
- (void)updatePendingPhoto;
@property(readonly, nonatomic) PLManagedAsset *pendingPhoto;
@property(retain, nonatomic) PLManagedAsset *editedPhoto;
- (void)_setEditedPhoto:(id)arg1 resetFilters:(_Bool)arg2;
@property(readonly, nonatomic) UIScrollView *scrollView;
@property(retain, nonatomic) UIToolbar *toolbar;
- (void)_layoutToolbar;
@property(retain, nonatomic) UINavigationBar *navigationBar;
- (void)_updateAggregateInfoForCurrentAdjustmentState;
- (_Bool)_adjustmentState:(id)arg1 isEqualTo:(id)arg2;
- (_Bool)_currentStateIsEqualToAdjustmentState:(id)arg1;
- (id)_originalState;
- (id)_adjustmentState;
- (void)_setAdjustmentState:(id)arg1;
- (void)_cleanupFilters;
- (void)_loadFiltersFromDatabase;
- (void)_saveFiltersToAsset:(id)arg1;
- (void)_displayRedEyeCorrections:(id)arg1;
- (void)_displayAllRedEyeCorrections;
- (_Bool)hasRedEyeCorrections;
- (id)redEyePoints;
- (_Bool)_setRedEyeCorrections:(id)arg1 changedCorrections:(id *)arg2;
- (void)_removeRedEyeCorrections:(id)arg1;
- (_Bool)removeRedEyePoint:(struct CGPoint)arg1;
- (void)_addRedEyeCorrections:(id)arg1 fromFilter:(id)arg2 isUserAction:(_Bool)arg3;
- (void)addRedEyePoint:(struct CGPoint)arg1;
- (id)_newCIImageFromUIImage:(id)arg1;
- (void)_setAspectRatio:(struct CGSize)arg1;
- (void)_rotatePhotoByAngle:(double)arg1;
- (void)_autoAdjustImage;
- (void)_preloadEnhancementFilters;
@property(nonatomic) _Bool autoAdjustmentEnabled;
- (void)_setAutoAdjustmentFilters:(id)arg1;
- (id)_autoAdjustmentFilters;
- (void)_setAutoRedEyeFilterFromArray:(id)arg1;
- (id)_calculateAutoFiltersWithFeatures:(int)arg1 includeGeometry:(_Bool)arg2;
- (void)setStraightenAngle:(double)arg1 normalizedCropRect:(struct CGRect)arg2;
@property(readonly, nonatomic) struct CGRect normalizedCropRect;
@property(readonly, nonatomic) double straightenAngle;
- (id)_masterImagePath;
- (void)saveAdjustments;
- (void)_saveAdjustmentsToOriginal;
- (void)_saveXMPPropertiesToPhoto:(id)arg1;
- (void)_saveAdjustmentsToCopy;
- (id)newAdjustedImageWithoutGeometryUsingContext:(id)arg1;
- (id)_croppedStraightenedImage;
- (id)_cropAndStraightenFiltersForImageSize:(struct CGSize)arg1 forceSquareCrop:(_Bool)arg2 forceUseGeometry:(_Bool)arg3;
- (id)_newImageFromImage:(id)arg1 filters:(id)arg2 orientation:(int)arg3 ciContext:(id)arg4;
- (id)_largeThumbnailImage;
- (id)_smallThumbnailImage;
- (id)_scaledCachedImage;
- (id)_currentNonGeometryFiltersWithEffectFilters:(id)arg1;
- (void)assetContainerDidChange:(id)arg1;
- (void)didRedoNotification:(id)arg1;
- (void)didUndoNotification:(id)arg1;
- (void)popoverControllerDidDismissPopover:(id)arg1;
- (void)alertView:(id)arg1 willDismissWithButtonIndex:(long long)arg2;
- (void)willPresentAlertView:(id)arg1;
- (_Bool)_dismissPopoverViews;
- (void)actionSheet:(id)arg1 didDismissWithButtonIndex:(long long)arg2;
- (void)actionSheet:(id)arg1 clickedButtonAtIndex:(long long)arg2;
- (void)willPresentActionSheet:(id)arg1;
- (void)scrollViewDidEndZooming:(id)arg1 withView:(id)arg2 atScale:(double)arg3;
- (id)viewForZoomingInScrollView:(id)arg1;
- (void)_undoTransformImage:(struct CGRect)arg1 angle:(double)arg2;
- (void)editViewDidTouchImage:(id)arg1 location:(struct CGPoint)arg2;
- (void)editViewDidCropImage:(id)arg1;
- (void)editViewWillCropImage:(id)arg1;
- (void)setToolbarItems:(id)arg1 animated:(_Bool)arg2;
- (void)_updateToolbarSetHiddenState:(_Bool)arg1;
- (void)_updateToolbar;
- (void)_updateModeButtons;
- (void)_updateEditedImage:(_Bool)arg1;
- (void)_setEditedImage:(id)arg1 isProxyImage:(_Bool)arg2 updateCropAndStraighten:(_Bool)arg3 forceAnimate:(_Bool)arg4;
- (void)_setEditedImage:(id)arg1 isProxyImage:(_Bool)arg2 updateCropAndStraighten:(_Bool)arg3;
- (void)_updateEnhanceButton;
- (void)_updateButtons;
- (void)_updateControls;
- (void)_dismissSavingHUD;
- (void)_presentSavingHUD;
- (void)_setControlsEnabled:(_Bool)arg1 animated:(_Bool)arg2;
- (void)orderOut:(_Bool)arg1;
- (void)cancel:(id)arg1;
- (void)save:(id)arg1;
- (void)applySubmode:(id)arg1;
- (void)showConstraints:(id)arg1;
- (void)selectEditMode:(id)arg1;
- (void)rotatePhoto:(id)arg1;
- (void)enhancePhoto:(id)arg1;
- (void)undo:(id)arg1;
- (void)revertToSaved:(id)arg1;
- (void)revertToOriginal:(id)arg1;
- (void)_pushNewUndoManager;
- (void)_popModalState;
- (void)_pushModalState;
- (void)_setEditMode:(int)arg1;
- (void)_dismissProgressAlertIfNeeded;
- (void)_verifyProgress:(id)arg1 completion:(id)arg2;
- (void)_updateMessageOverlayFrame;
- (void)hideMessage:(id)arg1;
- (void)showMessage:(id)arg1 duration:(double)arg2;
- (void)_displayAutoAdjustmentMessage;
- (id)_constrainActionSheet;
- (id)_buttonWithTag:(long long)arg1;
- (id)_rightButtonForMode:(int)arg1 enableDone:(_Bool)arg2 enableSave:(_Bool)arg3;
- (id)_newButtonItemWithIcon:(id)arg1 title:(id)arg2 target:(id)arg3 action:(SEL)arg4 tag:(long long)arg5;
- (id)_cropAndStraightenToolbarItems;
- (id)_redEyeLabel;
- (id)_startToolbarItems;
- (id)_currentToolbarItems;
- (id)navigationItem;
- (void)motionEnded:(long long)arg1 withEvent:(id)arg2;
- (_Bool)canBecomeFirstResponder;
- (void)_updateCropInsetsForOrientation:(long long)arg1;
- (void)didReceiveMemoryWarning;
- (_Bool)hidesBottomBarWhenPushed;
- (void)willAnimateRotationToInterfaceOrientation:(long long)arg1 duration:(double)arg2;
- (void)willRotateToInterfaceOrientation:(long long)arg1 duration:(double)arg2;
- (_Bool)shouldAutorotateToInterfaceOrientation:(long long)arg1;
- (void)viewDidAppear:(_Bool)arg1;
- (void)viewWillAppear:(_Bool)arg1;
- (void)viewDidLoad;
- (void)loadView;
- (_Bool)_isZoomedToScale:(double)arg1;
- (void)zoomToScale:(double)arg1 completionBlock:(id)arg2;
- (double)rotatedZoomToFitScale;
- (double)zoomToFitScale;
- (void)sizeToFit:(_Bool)arg1;
- (id)contentScrollView;
- (void)_startEditingWithAsset:(id)arg1;
- (void)startEditingAsset:(id)arg1 proxyImage:(id)arg2 completion:(id)arg3;
- (void)dealloc;
- (id)initWithNibName:(id)arg1 bundle:(id)arg2;

@end


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Maps.SpatialToolbox;

namespace Microsoft.Maps.SpatialToolbox.Imaging
{
    public class SpatialDataRenderEngine
    {
        #region Private Properties

        private DrawingStyle _defaultStyle;

        private Bitmap _bitmap;

        private bool _isHighSpeed = true;

        private StyleColor? _backgroundColor;

        #endregion

        #region Constructor

        public SpatialDataRenderEngine()
        {

        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="isHighSpeed">Indicates if high speed rendering should be used. If true then quality of rendering may be degraded.</param>
        public SpatialDataRenderEngine(bool isHighSpeed)
        {
            _isHighSpeed = isHighSpeed;
        }

        public SpatialDataRenderEngine(ShapeStyle defaultStyle)
        {
            _defaultStyle = new DrawingStyle(defaultStyle);
        }

        public SpatialDataRenderEngine(ShapeStyle defaultStyle, bool isHighSpeed)
        {
            _defaultStyle = new DrawingStyle(defaultStyle);
            _isHighSpeed = isHighSpeed;
        }

        public SpatialDataRenderEngine(DrawingStyle defaultStyle)
        {
            _defaultStyle = defaultStyle;
        }

        public SpatialDataRenderEngine(DrawingStyle defaultStyle, bool isHighSpeed)
        {
            _defaultStyle = defaultStyle;
            _isHighSpeed = isHighSpeed;
        }

        #endregion

        #region Public Methods

        public Task RenderDataAsync(SpatialDataSet data, ViewInfo viewInfo)
        {
            return RenderDataAsync(data.Geometries, data.Styles, viewInfo);
        }

        public Task RenderDataAsync(List<Geometry> data, ViewInfo viewInfo)
        {
            return RenderDataAsync(data, new Dictionary<string, DrawingStyle>(), viewInfo, null);
        }

        public Task RenderDataAsync(SpatialDataSet data, ViewInfo viewInfo, StyleColor? backgroundColor)
        {
            return RenderDataAsync(data.Geometries, ConvertStyles(data.Styles), viewInfo, backgroundColor);
        }

        public Task RenderDataAsync(List<Geometry> data, ViewInfo viewInfo, StyleColor? backgroundColor)
        {
            return RenderDataAsync(data, new Dictionary<string, DrawingStyle>(), viewInfo, backgroundColor);
        }

        public Task RenderDataAsync(List<Geometry> data, Dictionary<string, ShapeStyle> styles, ViewInfo viewInfo)
        {
            return RenderDataAsync(data, ConvertStyles(styles), viewInfo, null);
        }

        public Task RenderDataAsync(List<Geometry> data, Dictionary<string, DrawingStyle> styles, ViewInfo viewInfo, StyleColor? backgroundColor)
        {
            return Task.Run(() =>
            {
                RenderData(data, styles, viewInfo, backgroundColor);
            });
        }

        public void RenderData(List<Geometry> data, Dictionary<string, DrawingStyle> styles, ViewInfo viewInfo, StyleColor? backgroundColor)
        {
            try
            {
                if (_bitmap == null || _bitmap.Width != viewInfo.Width || _bitmap.Height != viewInfo.Height)
                {
                    _bitmap = new Bitmap(viewInfo.Width, viewInfo.Height);
                }

                using (Graphics g = Graphics.FromImage(_bitmap))
                {
                    _backgroundColor = backgroundColor;
                    var background = (backgroundColor.HasValue) ? backgroundColor.Value.ToDrawingColor() : Color.Transparent;

                    g.Clear(background);
                    g.Clip = new Region(new Rectangle(0, 0, viewInfo.Width, viewInfo.Height));

                    if (!_isHighSpeed)
                    {
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    }
                    else
                    {
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
                    }

                    if (data != null)
                    {
                        foreach(var geo in data)
                        {
                            DrawGeometery(geo, styles, viewInfo, g);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var t = "";
            }
        }

        public System.IO.MemoryStream GetImageStream(ImageFormat imgFormat)
        {
            System.Drawing.Imaging.ImageFormat format;

            switch (imgFormat)
            {
                case ImageFormat.GIF:
                    format = System.Drawing.Imaging.ImageFormat.Gif;
                    break;
                case ImageFormat.JPEG:
                    format = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;
                case ImageFormat.PNG:
                default:
                    format = System.Drawing.Imaging.ImageFormat.Png;
                    break;
            }

            var ms = new System.IO.MemoryStream();
            _bitmap.Save(ms, format);

            return ms;
        }

        public void SaveImage(ImageFormat imgFormat, System.IO.Stream outputStream)
        {
            System.Drawing.Imaging.ImageFormat format;

            switch (imgFormat)
            {
                case ImageFormat.GIF:
                    format = System.Drawing.Imaging.ImageFormat.Gif;
                    break;
                case ImageFormat.JPEG:
                    format = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;
                case ImageFormat.PNG:
                default:
                    format = System.Drawing.Imaging.ImageFormat.Png;
                    break;
            }

            _bitmap.Save(outputStream, format);
        }

        public Task<bool> IsImageEmpty()
        {
            return Task.Run<bool>(() =>
            {
                var background = (_backgroundColor.HasValue) ? _backgroundColor.Value.ToDrawingColor() : Color.Transparent;
                return IsImageOneColor(_bitmap, background);
            });
        }

        public void Dispose()
        {
            if (_defaultStyle != null)
            {
                _defaultStyle.Dispose();
            }

            _bitmap.Dispose();
        }

        #endregion

        #region Private Methods

        private void DrawGeometery(Geometry geom, Dictionary<string, DrawingStyle> styles, ViewInfo viewInfo, Graphics g)
        {
            DrawingStyle s = null;

            if (styles != null && !string.IsNullOrEmpty(geom.StyleKey) && styles.ContainsKey(geom.StyleKey))
            {
                s = styles[geom.StyleKey];
            }
            else if (_defaultStyle != null)
            {
                s = _defaultStyle;
            }

            DrawGeometery(geom, s, viewInfo, g);
        }

        private void DrawGeometery(Geometry geom, DrawingStyle style, ViewInfo viewInfo, Graphics g)
        {
            if (style != null)
            {
                switch (geom.STGeometryType())
                {
                    case GeometryType.Point:
                        DrawPoint(geom as Point, style, viewInfo, g);
                        break;
                    case GeometryType.LineString:
                        DrawLineString(geom as LineString, style, viewInfo, g);
                        break;
                    case GeometryType.Polygon:
                        DrawPolygon(geom as Polygon, style, viewInfo, g);
                        break;
                    case GeometryType.MultiPoint:
                        DrawMutiPoint(geom as MultiPoint, style, viewInfo, g);
                        break;
                    case GeometryType.MultiLineString:
                        DrawMultiLineString(geom as MultiLineString, style, viewInfo, g);
                        break;
                    case GeometryType.MultiPolygon:
                        DrawMultiPolygon(geom as MultiPolygon, style, viewInfo, g);
                        break;
                    case GeometryType.GeometryCollection:
                        int numGeoms = geom.STNumGeometries();
                        var gc = geom as GeometryCollection;
                        for (int i = 1; i <= numGeoms; i++)
                        {
                            DrawGeometery(gc.Geometries[i], style, viewInfo, g);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        private void DrawPoint(PointF point, DrawingStyle style, Graphics g)
        {
            if (style != null && point != null)
            {
                if (style.Icon != null)
                {
                    var x = (float)(point.X - style.Icon.Width / 2);
                    var y = (float)(point.Y - style.Icon.Height / 2);

                    g.DrawImage(style.Icon, x, y);
                }
                else if (style.IconBrush != null)
                {
                    g.FillEllipse(style.IconBrush, point.X - 15, point.Y - 15, 30, 30);

                    if (style.StrokePen != null)
                    {
                        g.DrawEllipse(style.StrokePen, point.X - 15, point.Y - 15, 30, 30);
                    }
                }
            }
        }

        private void DrawPoint(Point point, DrawingStyle style, ViewInfo viewInfo, Graphics g)
        {
            DrawPoint(viewInfo.LatLongToPointF(point.Coordinate), style, g);
        }

        private void DrawLineString(LineString line, DrawingStyle style, ViewInfo viewInfo, Graphics g)
        {
            if (style.StrokePen != null)
            {
                g.DrawLines(style.StrokePen, viewInfo.RingToPointFList(line.Vertices));
            }
        }

        private void DrawPolygon(Polygon polygon, DrawingStyle style, ViewInfo viewInfo, Graphics g)
        {
            if (style.StrokePen != null || style.FillBrush != null)
            {
                var p = viewInfo.RingToPointFList(polygon.ExteriorRing);

                var path = new GraphicsPath(FillMode.Winding);

                //Draw external ring
                path.AddPolygon(p);

                //Cut out inner polygons
                int numRings = polygon.InteriorRings.Count;
                for (int i = 0; i < numRings; i++)
                {
                    p = viewInfo.RingToPointFList(polygon.InteriorRings[i]);
                    path.AddPolygon(p);
                }

                if (style.FillBrush != null)
                {
                    g.FillPath(style.FillBrush, path);
                }

                if (style.StrokePen != null)
                {
                    g.DrawPath(style.StrokePen, path);
                }
            }
        }

        private void DrawMutiPoint(MultiPoint mPoint, DrawingStyle style, ViewInfo viewInfo, Graphics g)
        {
            foreach (var point in mPoint.Geometries)
            {
                var p = viewInfo.LatLongToPointF(point.Coordinate);
                DrawPoint(p, style, g);
            }
        }

        private void DrawMultiLineString(MultiLineString mLine, DrawingStyle style, ViewInfo viewInfo, Graphics g)
        {
            foreach (var line in mLine.Geometries)
            {
                DrawLineString(line, style, viewInfo, g);
            }
        }

        private void DrawMultiPolygon(MultiPolygon mPolygon, DrawingStyle style, ViewInfo viewInfo, Graphics g)
        {
            foreach (var polygon in mPolygon.Geometries)
            {
                DrawPolygon(polygon, style, viewInfo, g);
            }
        }

        private Dictionary<string, DrawingStyle> ConvertStyles(Dictionary<string, ShapeStyle> styles)
        {
            if (styles != null)
            {
                var newStyles = new Dictionary<string, DrawingStyle>();

                foreach (var key in styles.Keys)
                {
                    newStyles.Add(key, new DrawingStyle(styles[key]));
                }

                return newStyles;
            }

            return null;
        }

        private bool IsImageOneColor(Bitmap img, Color comparisonColor)
        {
            BitmapData bmpData = img.LockBits(new Rectangle(0, 0, img.Width - 1, img.Height - 1), ImageLockMode.ReadOnly, img.PixelFormat);

            int bytes  = Math.Abs(bmpData.Stride);

            var loop = Parallel.For(0, img.Height, (y, loopState) =>
            {
                bool isNotOneColor = false;
                byte[] rgbValues = new byte[bytes];
                Marshal.Copy(bmpData.Scan0 + (y * bytes), rgbValues, 0, bytes);

                for (int x = 0; x <= bytes - 1; x += 4)
                {
                    if (comparisonColor.A == 0)
                    {
                        isNotOneColor |= (comparisonColor.A != rgbValues[x + 3]);
                    }
                    else
                    {
                        isNotOneColor |= (comparisonColor.A != rgbValues[x + 3] ||
                            comparisonColor.B != rgbValues[x] ||
                            comparisonColor.G != rgbValues[x + 1] ||
                            comparisonColor.R != rgbValues[x + 2]);
                    }

                    if (isNotOneColor)
                    {
                        break;
                    }
                }

                if (isNotOneColor)
                {
                    loopState.Stop();
                }
            });

            img.UnlockBits(bmpData);

            return loop.IsCompleted;
        }

        #endregion
    }
}


text:
package com.speedment.runtime.config.mutator.trait;

import com.speedment.runtime.config.Document;
import com.speedment.runtime.config.mutator.DocumentMutator;

public interface BaseTraitMixin<TYPE extends Document, MUTATOR extends DocumentMutator<TYPE>> {

    MUTATOR getMutatorInstance();
}


text:
package org.apache.beam.runners.direct.portable.artifact;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.beam.model.jobmanagement.v1.ArtifactApi.ArtifactChunk;
import org.apache.beam.model.jobmanagement.v1.ArtifactApi.ArtifactMetadata;
import org.apache.beam.model.jobmanagement.v1.ArtifactApi.GetArtifactRequest;
import org.apache.beam.model.jobmanagement.v1.ArtifactApi.GetManifestRequest;
import org.apache.beam.model.jobmanagement.v1.ArtifactApi.GetManifestResponse;
import org.apache.beam.model.jobmanagement.v1.ArtifactApi.Manifest;
import org.apache.beam.model.jobmanagement.v1.ArtifactRetrievalServiceGrpc;
import org.apache.beam.runners.core.construction.ArtifactServiceStager;
import org.apache.beam.runners.core.construction.ArtifactServiceStager.StagedFile;
import org.apache.beam.runners.fnexecution.GrpcFnServer;
import org.apache.beam.runners.fnexecution.InProcessServerFactory;
import org.apache.beam.runners.fnexecution.ServerFactory;
import org.apache.beam.vendor.grpc.v1_13_1.io.grpc.inprocess.InProcessChannelBuilder;
import org.apache.beam.vendor.grpc.v1_13_1.io.grpc.stub.StreamObserver;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link LocalFileSystemArtifactRetrievalService}. */
@RunWith(JUnit4.class)
public class LocalFileSystemArtifactRetrievalServiceTest {
  @Rule public TemporaryFolder tmp = new TemporaryFolder();

  private File root;
  private ServerFactory serverFactory = InProcessServerFactory.create();

  private GrpcFnServer<LocalFileSystemArtifactStagerService> stagerServer;

  private GrpcFnServer<LocalFileSystemArtifactRetrievalService> retrievalServer;
  private ArtifactRetrievalServiceGrpc.ArtifactRetrievalServiceStub retrievalStub;

  @Before
  public void setup() throws Exception {
    root = tmp.newFolder();
    stagerServer =
        GrpcFnServer.allocatePortAndCreateFor(
            LocalFileSystemArtifactStagerService.forRootDirectory(root), serverFactory);
  }

  @After
  public void teardown() throws Exception {
    stagerServer.close();
    retrievalServer.close();
  }

  @Test
  public void retrieveManifest() throws Exception {
    Map<String, byte[]> artifacts = new HashMap<>();
    artifacts.put("foo", "bar, baz, quux".getBytes(UTF_8));
    artifacts.put("spam", new byte[] {127, -22, 5});
    stageAndCreateRetrievalService(artifacts);

    final AtomicReference<Manifest> returned = new AtomicReference<>();
    final CountDownLatch completed = new CountDownLatch(1);
    retrievalStub.getManifest(
        GetManifestRequest.getDefaultInstance(),
        new StreamObserver<GetManifestResponse>() {
          @Override
          public void onNext(GetManifestResponse value) {
            returned.set(value.getManifest());
          }

          @Override
          public void onError(Throwable t) {
            completed.countDown();
          }

          @Override
          public void onCompleted() {
            completed.countDown();
          }
        });

    completed.await();
    assertThat(returned.get(), not(nullValue()));

    List<String> manifestArtifacts = new ArrayList<>();
    for (ArtifactMetadata artifactMetadata : returned.get().getArtifactList()) {
      manifestArtifacts.add(artifactMetadata.getName());
    }
    assertThat(manifestArtifacts, containsInAnyOrder("foo", "spam"));
  }

  @Test
  public void retrieveArtifact() throws Exception {
    Map<String, byte[]> artifacts = new HashMap<>();
    byte[] fooContents = "bar, baz, quux".getBytes(UTF_8);
    artifacts.put("foo", fooContents);
    byte[] spamContents = {127, -22, 5};
    artifacts.put("spam", spamContents);
    stageAndCreateRetrievalService(artifacts);

    final CountDownLatch completed = new CountDownLatch(2);
    ByteArrayOutputStream returnedFooBytes = new ByteArrayOutputStream();
    retrievalStub.getArtifact(
        GetArtifactRequest.newBuilder().setName("foo").build(),
        new MultimapChunkAppender(returnedFooBytes, completed));
    ByteArrayOutputStream returnedSpamBytes = new ByteArrayOutputStream();
    retrievalStub.getArtifact(
        GetArtifactRequest.newBuilder().setName("spam").build(),
        new MultimapChunkAppender(returnedSpamBytes, completed));

    completed.await();
    assertArrayEquals(fooContents, returnedFooBytes.toByteArray());
    assertArrayEquals(spamContents, returnedSpamBytes.toByteArray());
  }

  @Test
  public void retrieveArtifactNotPresent() throws Exception {
    stageAndCreateRetrievalService(
        Collections.singletonMap("foo", "bar, baz, quux".getBytes(UTF_8)));

    final CountDownLatch completed = new CountDownLatch(1);
    final AtomicReference<Throwable> thrown = new AtomicReference<>();
    retrievalStub.getArtifact(
        GetArtifactRequest.newBuilder().setName("spam").build(),
        new StreamObserver<ArtifactChunk>() {
          @Override
          public void onNext(ArtifactChunk value) {
            fail(
                "Should never receive an "
                    + ArtifactChunk.class.getSimpleName()
                    + " for a nonexistent artifact");
          }

          @Override
          public void onError(Throwable t) {
            thrown.set(t);
            completed.countDown();
          }

          @Override
          public void onCompleted() {
            completed.countDown();
          }
        });

    completed.await();
    assertThat(thrown.get(), not(nullValue()));
    assertThat(thrown.get().getMessage(), containsString("No such artifact"));
    assertThat(thrown.get().getMessage(), containsString("spam"));
  }

  private void stageAndCreateRetrievalService(Map<String, byte[]> artifacts) throws Exception {
    List<StagedFile> artifactFiles = new ArrayList<>();
    for (Map.Entry<String, byte[]> artifact : artifacts.entrySet()) {
      File artifactFile = tmp.newFile(artifact.getKey());
      Files.write(artifactFile.toPath(), artifact.getValue());
      artifactFiles.add(StagedFile.of(artifactFile, artifactFile.getName()));
    }
    String stagingSessionToken = "token";

    ArtifactServiceStager stager =
        ArtifactServiceStager.overChannel(
            InProcessChannelBuilder.forName(stagerServer.getApiServiceDescriptor().getUrl())
                .build());
    stager.stage(stagingSessionToken, artifactFiles);

    retrievalServer =
        GrpcFnServer.allocatePortAndCreateFor(
            LocalFileSystemArtifactRetrievalService.forRootDirectory(root), serverFactory);
    retrievalStub =
        ArtifactRetrievalServiceGrpc.newStub(
            InProcessChannelBuilder.forName(retrievalServer.getApiServiceDescriptor().getUrl())
                .build());
  }

  private static class MultimapChunkAppender implements StreamObserver<ArtifactChunk> {
    private final ByteArrayOutputStream target;
    private final CountDownLatch completed;

    private MultimapChunkAppender(ByteArrayOutputStream target, CountDownLatch completed) {
      this.target = target;
      this.completed = completed;
    }

    @Override
    public void onNext(ArtifactChunk value) {
      try {
        target.write(value.getData().toByteArray());
      } catch (IOException e) {
        // This should never happen
        throw new AssertionError(e);
      }
    }

    @Override
    public void onError(Throwable t) {
      completed.countDown();
    }

    @Override
    public void onCompleted() {
      completed.countDown();
    }
  }
}


text:
namespace dragon {

#define OMP_MIN_ITERATORS_PER_CORE 200000

inline int GET_OMP_THREADS(const int N) {
   int threads = std::max(N / OMP_MIN_ITERATORS_PER_CORE, 1);
   return std::min(threads, omp_get_num_procs());
}

}

#endif  // WITH_OMP

#endif  // DRAGON_UTILS_OMP_ALTERNATIVE_H_


text:
package org.musicrecital.webapp.pages;

import org.apache.commons.lang.StringUtils;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.alerts.AlertManager;
import org.apache.tapestry5.alerts.Duration;
import org.apache.tapestry5.alerts.Severity;
import org.apache.tapestry5.annotations.*;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PageRenderLinkSource;
import org.musicrecital.Constants;
import org.musicrecital.model.Role;
import org.musicrecital.model.User;
import org.musicrecital.service.RoleManager;
import org.musicrecital.service.UserExistsException;
import org.musicrecital.service.UserManager;
import org.musicrecital.webapp.components.UserForm;
import org.musicrecital.webapp.pages.admin.UserList;
import org.musicrecital.webapp.services.EmailService;
import org.musicrecital.webapp.services.SecurityContext;
import org.musicrecital.webapp.util.RequestUtil;
import org.slf4j.Logger;
import org.springframework.mail.MailException;
import org.springframework.security.access.AccessDeniedException;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * Allow adding new users or viewing/updating existing users
 *
 * @author Serge Eby
 * @version $Id$
 */
public class UserEdit {

    @Inject
    private Logger logger;

    @PageActivationContext(passivate = false)
    @Property(write = false)
    private User user;

    @Property
    @Persist
    private List<Role> selectedRoles;

    @Inject
    private PageRenderLinkSource pageRenderLinkSource;

    @Inject
    private Messages messages;

    @Inject
    private SecurityContext securityContext;

    @Inject
    private UserManager userManager;

    @Inject
    private RoleManager roleManager;

    @Inject
    private HttpServletRequest request;

    @Inject
    private AlertManager alertManager;

    @Inject
    private EmailService emailService;

    @InjectPage
    private UserList userList;

    @InjectPage
    private Home home;

    @Persist(PersistenceConstants.FLASH)
    @Property
    private Class goBack;

    @Persist
    @Property(write = false)
    private String from;

    @Persist(PersistenceConstants.FLASH)
    @Property(write = false)
    private String infoMessage;

    @Component(id = "edit")
    private UserForm form;

    private boolean delete = false;

    private boolean cancel = false;

    public void setUser(User user) {
        this.user = user;
    }

    public Object initialize(User user, String from, String infoMessage) {
        this.user = user;
        this.from = from;
        this.infoMessage = infoMessage;

        return this;
    }

    public void setInfoMessage(String infoMessage) {
        this.infoMessage = infoMessage;
    }

    Object[] onPassivate() {
        if (user != null && user.getId() != null) {
            return new Object[]{user};
        }
        return new User[]{};
    }

    void setupRender() {
        if (user == null) {
            user = new User();
            // Add default role
            user.addRole(new Role(Constants.USER_ROLE));
        }

        selectedRoles = new ArrayList<Role>(user.getRoles());

        // if user logged in with remember me, display a warning that they
        // can't change passwords
        logger.debug("checking for remember me login...");

        if (securityContext.isRememberMe()) {
            // add warning message
            alertManager.info(messages.get("userProfile.cookieLogin"));
        }

        // Set info message
        form.setInfoMessage(infoMessage);
    }

    public boolean isCookieLogin() {
        return securityContext.isRememberMe();
    }

    // ~ --- Event Handlers

    @Log
    @DiscardAfter
    Object onCanceledFromEdit() {
        //  return pageRenderLinkSource.createPageRenderLink(goBack);

        if (from != null && from.equalsIgnoreCase("list")) {
            return pageRenderLinkSource.createPageRenderLink(UserList.class);
        } else {
            return pageRenderLinkSource.createPageRenderLink(Home.class);
        }
    }

    @Log
    void onValidatePasswordFromEdit() {
        // Ensure the password fields match
        if (form.isValid()) {
            if (!StringUtils.equals(user.getPassword(), user.getConfirmPassword())) {

                String errorMessage = messages.format("errors.twofields",
                        messages.get("user.confirmPassword"),
                        messages.get("user.password"));

                // form.recordError(passwordField, errorMessage);

                alertManager.alert(Duration.TRANSIENT, Severity.ERROR, errorMessage);
            }
        }
    }

    void onPrepare() {
        if (user == null) {
            user = new User();
        }
    }

    @Log
    @DiscardAfter
    Object onSuccess() throws UserExistsException, IOException {

        // Delete Button Clicked
        if (delete) {
            return onDelete();
        }

        // Only Admins can update roles for other users
        if (securityContext.isAdmin()) {
            if (selectedRoles != null && !selectedRoles.isEmpty()) {
                user.getRoles().clear();
                for (int i = 0; selectedRoles != null && i < selectedRoles.size(); i++) {
                    String roleName = selectedRoles.get(i).getName();
                    user.addRole(roleManager.getRole(roleName));
                }
            }
        }

        Integer originalVersion = user.getVersion();

        try {
            user = userManager.saveUser(user);
        } catch (AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
            logger.warn(ade.getMessage());
            return AccessDenied.class;
        } catch (UserExistsException e) {
            // TODO
            //form.recordError(form.getEmailField(), "User exits");
            alertManager.alert(Duration.TRANSIENT, Severity.ERROR,
                    messages.format("errors.existing.user", user.getUsername(), user.getEmail())
            );

            user.setPassword(user.getConfirmPassword());
            user.setVersion(originalVersion);
            return null;
        }

        if (!"list".equalsIgnoreCase(from)) {
            // add success messages
            alertManager.alert(
                    Duration.TRANSIENT,
                    Severity.INFO,
                    messages.format("user.saved", user.getFullName()));
            return Home.class;
        } else {
            // add success messages
            if (originalVersion == null) {
                alertManager.alert(Duration.TRANSIENT, Severity.INFO,
                        messages.format("user.added", user.getFullName()));

                try {
                    String msg = messages.format("newuser.email.message", user.getFullName());
                    String subject = messages.get("signup.email.subject");
                    emailService.send(user, subject, msg, RequestUtil.getAppURL(request), false);
                } catch (MailException me) {
                    alertManager.alert(
                            Duration.TRANSIENT,
                            Severity.ERROR,
                            me.getCause().getLocalizedMessage());
                }
                return UserList.class;
            } else {
                alertManager.alert(Duration.TRANSIENT, Severity.INFO,
                        messages.format("user.updated.byAdmin", user.getFullName()));
            }
        }

        return this;
    }

    @Log
    Object onDelete() {
        // Save full name before deletion
        String fullName = user.getFullName();
        userManager.removeUser(user.getId().toString());
        alertManager.alert(Duration.TRANSIENT, Severity.INFO,
                messages.format("user.deleted", fullName)
        );
        logger.debug("After deletion.. ready to return userList object");
        return UserList.class;
    }

    @Log
    Object onUpdatePassword() {
        Link link = pageRenderLinkSource.createPageRenderLinkWithContext(PasswordUpdate.class);
        link.addParameter("username", user.getUsername());
        return link;
    }

    public void setFrom(String from) {
        this.from = from;
    }

}


text:
import Ember from 'ember';
import ghostPaths from 'ghost/utils/ghost-paths';
import {RequestEntityTooLargeError, UnsupportedMediaTypeError} from 'ghost/services/ajax';

const {
    Component,
    computed,
    inject: {service},
    isBlank,
    run
} = Ember;

export default Component.extend({
    tagName: 'section',
    classNames: ['gh-image-uploader'],
    classNameBindings: ['dragClass'],

    image: null,
    text: 'Upload an image',
    saveButton: true,

    dragClass: null,
    failureMessage: null,
    file: null,
    formType: 'upload',
    url: null,
    uploadPercentage: 0,

    ajax: service(),
    config: service(),

    // TODO: this wouldn't be necessary if the server could accept direct
    // file uploads
    formData: computed('file', function () {
        let file = this.get('file');
        let formData = new FormData();

        formData.append('uploadimage', file);

        return formData;
    }),

    progressStyle: computed('uploadPercentage', function () {
        let percentage = this.get('uploadPercentage');
        let width = '';

        if (percentage > 0) {
            width = `${percentage}%`;
        } else {
            width = '0';
        }

        return Ember.String.htmlSafe(`width: ${width}`);
    }),

    canShowUploadForm: computed('config.fileStorage', function () {
        return this.get('config.fileStorage') !== false;
    }),

    showUploadForm: computed('formType', function () {
        let canShowUploadForm = this.get('canShowUploadForm');
        let formType = this.get('formType');

        return formType === 'upload' && canShowUploadForm;
    }),

    didReceiveAttrs() {
        let image = this.get('image');
        this.set('url', image);
    },

    dragOver(event) {
        let showUploadForm = this.get('showUploadForm');

        if (!event.dataTransfer) {
            return;
        }

        // this is needed to work around inconsistencies with dropping files
        // from Chrome's downloads bar
        let eA = event.dataTransfer.effectAllowed;
        event.dataTransfer.dropEffect = (eA === 'move' || eA === 'linkMove') ? 'move' : 'copy';

        event.stopPropagation();
        event.preventDefault();

        if (showUploadForm) {
            this.set('dragClass', '--drag-over');
        }
    },

    dragLeave(event) {
        let showUploadForm = this.get('showUploadForm');

        event.preventDefault();

        if (showUploadForm) {
            this.set('dragClass', null);
        }
    },

    drop(event) {
        let showUploadForm = this.get('showUploadForm');

        event.preventDefault();

        this.set('dragClass', null);

        if (showUploadForm) {
            if (event.dataTransfer.files) {
                this.send('fileSelected', event.dataTransfer.files);
            }
        }
    },

    uploadStarted() {
        if (typeof this.attrs.uploadStarted === 'function') {
            this.attrs.uploadStarted();
        }
    },

    uploadProgress(event) {
        if (event.lengthComputable) {
            run(() => {
                let percentage = Math.round((event.loaded / event.total) * 100);
                this.set('uploadPercentage', percentage);
            });
        }
    },

    uploadFinished() {
        if (typeof this.attrs.uploadFinished === 'function') {
            this.attrs.uploadFinished();
        }
    },

    uploadSuccess(response) {
        this.set('url', response);
        this.send('saveUrl');
        this.send('reset');
    },

    uploadFailed(error) {
        let message;

        if (error instanceof UnsupportedMediaTypeError) {
            message = 'The image type you uploaded is not supported. Please use .PNG, .JPG, .GIF, .SVG.';
        } else if (error instanceof RequestEntityTooLargeError) {
            message = 'The image you uploaded was larger than the maximum file size your server allows.';
        } else if (error.errors && !isBlank(error.errors[0].message)) {
            message = error.errors[0].message;
        } else {
            message = 'Something went wrong :(';
        }

        this.set('failureMessage', message);
    },

    generateRequest() {
        let ajax = this.get('ajax');
        let formData = this.get('formData');
        let url = `${ghostPaths().apiRoot}/uploads/`;

        this.uploadStarted();

        ajax.post(url, {
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'text',
            xhr: () => {
                let xhr = new window.XMLHttpRequest();

                xhr.upload.addEventListener('progress', (event) => {
                    this.uploadProgress(event);
                }, false);

                return xhr;
            }
        }).then((response) => {
            let url = JSON.parse(response);
            this.uploadSuccess(url);
        }).catch((error) => {
            this.uploadFailed(error);
        }).finally(() => {
            this.uploadFinished();
        });
    },

    actions: {
        fileSelected(fileList) {
            this.set('file', fileList[0]);
            run.schedule('actions', this, function () {
                this.generateRequest();
            });
        },

        onInput(url) {
            this.set('url', url);

            if (typeof this.attrs.onInput === 'function') {
                this.attrs.onInput(url);
            }
        },

        reset() {
            this.set('file', null);
            this.set('uploadPercentage', 0);
        },

        switchForm(formType) {
            this.set('formType', formType);

            if (typeof this.attrs.formChanged === 'function') {
                run.scheduleOnce('afterRender', this, function () {
                    this.attrs.formChanged(formType);
                });
            }
        },

        saveUrl() {
            let url = this.get('url');
            this.attrs.update(url);
        }
    }
});


text:
System.register([], function (_export) {
  var _classCallCheck, State;

  return {
    setters: [],
    execute: function () {
      'use strict';

      _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };

      State = (function () {
        function State(charSpec) {
          _classCallCheck(this, State);

          this.charSpec = charSpec;
          this.nextStates = [];
        }

        State.prototype.get = function get(charSpec) {
          for (var _iterator = this.nextStates, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
            var _ref;

            if (_isArray) {
              if (_i >= _iterator.length) break;
              _ref = _iterator[_i++];
            } else {
              _i = _iterator.next();
              if (_i.done) break;
              _ref = _i.value;
            }

            var child = _ref;

            var isEqual = child.charSpec.validChars === charSpec.validChars && child.charSpec.invalidChars === charSpec.invalidChars;

            if (isEqual) {
              return child;
            }
          }
        };

        State.prototype.put = function put(charSpec) {
          var state = this.get(charSpec);

          if (state) {
            return state;
          }

          state = new State(charSpec);

          this.nextStates.push(state);

          if (charSpec.repeat) {
            state.nextStates.push(state);
          }

          return state;
        };

        State.prototype.match = function match(ch) {
          var nextStates = this.nextStates,
              results = [],
              child,
              charSpec,
              chars;

          for (var i = 0, l = nextStates.length; i < l; i++) {
            child = nextStates[i];

            charSpec = child.charSpec;

            if (typeof (chars = charSpec.validChars) !== 'undefined') {
              if (chars.indexOf(ch) !== -1) {
                results.push(child);
              }
            } else if (typeof (chars = charSpec.invalidChars) !== 'undefined') {
              if (chars.indexOf(ch) === -1) {
                results.push(child);
              }
            }
          }

          return results;
        };

        return State;
      })();

      _export('State', State);

      ;
    }
  };
});