text:
import {APP_BASE_HREF, DOCUMENT, HashLocationStrategy, LocationStrategy, ɵgetDOM as getDOM} from '@angular/common';
import {ApplicationRef, Component, CUSTOM_ELEMENTS_SCHEMA, destroyPlatform, Injectable, NgModule} from '@angular/core';
import {inject} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {NavigationEnd, provideRouter, Resolve, Router, RouterModule, withEnabledBlockingInitialNavigation} from '@angular/router';

// This is needed, because all files under `packages/` are compiled together as part of the
// [legacy-unit-tests-saucelabs][1] CI job, including the `lib.webworker.d.ts` typings brought in by
// [service-worker/worker/src/service-worker.d.ts][2].
//
// [1]:
// https://github.com/angular/angular/blob/ffeea63f43e6a7fd46be4a8cd5a5d254c98dea08/.circleci/config.yml#L681
// [2]:
// https://github.com/angular/angular/blob/316dc2f12ce8931f5ff66fa5f8da21c0d251a337/packages/service-worker/worker/src/service-worker.d.ts#L9
declare var window: Window;

describe('bootstrap', () => {
  if (isNode) {
    // Jasmine will throw if there are no tests.
    it('should pass', () => {});
    return;
  }

  let log: any[] = [];
  let testProviders: any[] = null!;

  @Component({template: 'simple'})
  class SimpleCmp {
  }

  @Component({selector: 'test-app', template: 'root <router-outlet></router-outlet>'})
  class RootCmp {
    constructor() {
      log.push('RootCmp');
    }
  }

  @Component({selector: 'test-app2', template: 'root <router-outlet></router-outlet>'})
  class SecondRootCmp {
  }

  @Injectable({providedIn: 'root'})
  class TestResolver implements Resolve<any> {
    resolve() {
      let resolve: any = null;
      const res = new Promise(r => resolve = r);
      setTimeout(() => resolve('test-data'), 0);
      return res;
    }
  }

  beforeEach(inject([DOCUMENT], (doc: any) => {
    destroyPlatform();

    const el1 = getDOM().createElement('test-app', doc);
    const el2 = getDOM().createElement('test-app2', doc);
    doc.body.appendChild(el1);
    doc.body.appendChild(el2);

    log = [];
    testProviders = [{provide: APP_BASE_HREF, useValue: ''}];
  }));

  afterEach(inject([DOCUMENT], (doc: any) => {
    const oldRoots = doc.querySelectorAll('test-app,test-app2');
    for (let i = 0; i < oldRoots.length; i++) {
      getDOM().remove(oldRoots[i]);
    }
  }));

  it('should complete resolvers when initial navigation fails and initialNavigation = enabledBlocking',
     async () => {
       @NgModule({
         imports: [BrowserModule],
         declarations: [RootCmp],
         bootstrap: [RootCmp],
         providers: [
           ...testProviders, {provide: LocationStrategy, useClass: HashLocationStrategy},
           provideRouter(
               [{
                 matcher: () => {
                   throw new Error('error in matcher');
                 },
                 children: []
               }],
               withEnabledBlockingInitialNavigation())
         ],
         schemas: [CUSTOM_ELEMENTS_SCHEMA]
       })
       class TestModule {
         constructor(router: Router) {
           log.push('TestModule');
           router.events.subscribe(e => log.push(e.constructor.name));
         }
       }

       await platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
         const router = res.injector.get(Router);
         expect(router.navigated).toEqual(false);
         expect(router.getCurrentNavigation()).toBeNull();
         expect(log).toContain('TestModule');
         expect(log).toContain('NavigationError');
       });
     });

  it('should wait for redirect when initialNavigation = enabledBlocking', async () => {
    @Injectable({providedIn: 'root'})
    class Redirect {
      constructor(private router: Router) {}
      canActivate() {
        this.router.navigateByUrl('redirectToMe');
        return false;
      }
    }
    @NgModule({
      imports: [
        BrowserModule,
        RouterModule.forRoot(
            [
              {path: 'redirectToMe', children: [], resolve: {test: TestResolver}},
              {path: '**', canActivate: [Redirect], children: []}
            ],
            {useHash: true, initialNavigation: 'enabledBlocking'})
      ],
      declarations: [RootCmp],
      bootstrap: [RootCmp],
      providers: [...testProviders],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    class TestModule {
      constructor(router: Router) {
        log.push('TestModule');
      }
    }

    await platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
      const router = res.injector.get(Router);
      expect(router.navigated).toEqual(true);
      expect(router.url).toContain('redirectToMe');
      expect(log).toContain('TestModule');
    });
  });

  it('should wait for redirect with UrlTree when initialNavigation = enabledBlocking', async () => {
    @Injectable({providedIn: 'root'})
    class Redirect {
      constructor(private router: Router) {}
      canActivate() {
        return this.router.createUrlTree(['/redirectToMe']);
      }
    }
    @NgModule({
      imports: [
        BrowserModule,
        RouterModule.forRoot(
            [
              {path: 'redirectToMe', children: [], resolve: {test: TestResolver}},
              {path: '**', canActivate: [Redirect], children: []}
            ],
            {useHash: true, initialNavigation: 'enabledBlocking'})
      ],
      declarations: [RootCmp],
      bootstrap: [RootCmp],
      providers: [...testProviders],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    class TestModule {
      constructor(router: Router) {
        log.push('TestModule');
      }
    }

    await platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
      const router = res.injector.get(Router);
      expect(router.navigated).toEqual(true);
      expect(router.url).toContain('redirectToMe');
      expect(log).toContain('TestModule');
    });
  });

  it('should wait for resolvers to complete when initialNavigation = enabledBlocking', (done) => {
    @Component({selector: 'test', template: 'test'})
    class TestCmpEnabled {
    }

    @NgModule({
      imports: [
        BrowserModule,
        RouterModule.forRoot(
            [{path: '**', component: TestCmpEnabled, resolve: {test: TestResolver}}],
            {useHash: true, initialNavigation: 'enabledBlocking'})
      ],
      declarations: [RootCmp, TestCmpEnabled],
      bootstrap: [RootCmp],
      providers: [...testProviders, TestResolver],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    class TestModule {
      constructor(router: Router) {}
    }

    platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
      const router = res.injector.get(Router);
      const data = router.routerState.snapshot.root.firstChild!.data;
      expect(data['test']).toEqual('test-data');
      done();
    });
  });

  it('should NOT wait for resolvers to complete when initialNavigation = enabledNonBlocking',
     (done) => {
       @Component({selector: 'test', template: 'test'})
       class TestCmpLegacyEnabled {
       }

       @NgModule({
         imports: [
           BrowserModule,
           RouterModule.forRoot(
               [{path: '**', component: TestCmpLegacyEnabled, resolve: {test: TestResolver}}],
               {useHash: true, initialNavigation: 'enabledNonBlocking'})
         ],
         declarations: [RootCmp, TestCmpLegacyEnabled],
         bootstrap: [RootCmp],
         providers: [...testProviders, TestResolver],
         schemas: [CUSTOM_ELEMENTS_SCHEMA]
       })
       class TestModule {
         constructor(router: Router) {
           log.push('TestModule');
           router.events.subscribe(e => log.push(e.constructor.name));
         }
       }

       platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
         const router: Router = res.injector.get(Router);
         expect(router.routerState.snapshot.root.firstChild).toBeNull();
         // ResolveEnd has not been emitted yet because bootstrap returned too early
         expect(log).toEqual([
           'TestModule', 'RootCmp', 'NavigationStart', 'RoutesRecognized', 'GuardsCheckStart',
           'ChildActivationStart', 'ActivationStart', 'GuardsCheckEnd', 'ResolveStart'
         ]);

         router.events.subscribe((e) => {
           if (e instanceof NavigationEnd) {
             done();
           }
         });
       });
     });

  it('should NOT wait for resolvers to complete when initialNavigation is not set', (done) => {
    @Component({selector: 'test', template: 'test'})
    class TestCmpLegacyEnabled {
    }

    @NgModule({
      imports: [
        BrowserModule,
        RouterModule.forRoot(
            [{path: '**', component: TestCmpLegacyEnabled, resolve: {test: TestResolver}}],
            {useHash: true})
      ],
      declarations: [RootCmp, TestCmpLegacyEnabled],
      bootstrap: [RootCmp],
      providers: [...testProviders, TestResolver],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    class TestModule {
      constructor(router: Router) {
        log.push('TestModule');
        router.events.subscribe(e => log.push(e.constructor.name));
      }
    }

    platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
      const router: Router = res.injector.get(Router);
      expect(router.routerState.snapshot.root.firstChild).toBeNull();
      // ResolveEnd has not been emitted yet because bootstrap returned too early
      expect(log).toEqual([
        'TestModule', 'RootCmp', 'NavigationStart', 'RoutesRecognized', 'GuardsCheckStart',
        'ChildActivationStart', 'ActivationStart', 'GuardsCheckEnd', 'ResolveStart'
      ]);

      router.events.subscribe((e) => {
        if (e instanceof NavigationEnd) {
          done();
        }
      });
    });
  });

  it('should not run navigation when initialNavigation = disabled', (done) => {
    @Component({selector: 'test', template: 'test'})
    class TestCmpDiabled {
    }

    @NgModule({
      imports: [
        BrowserModule,
        RouterModule.forRoot(
            [{path: '**', component: TestCmpDiabled, resolve: {test: TestResolver}}],
            {useHash: true, initialNavigation: 'disabled'})
      ],
      declarations: [RootCmp, TestCmpDiabled],
      bootstrap: [RootCmp],
      providers: [...testProviders, TestResolver],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    class TestModule {
      constructor(router: Router) {
        log.push('TestModule');
        router.events.subscribe(e => log.push(e.constructor.name));
      }
    }

    platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
      const router = res.injector.get(Router);
      expect(log).toEqual(['TestModule', 'RootCmp']);
      done();
    });
  });

  it('should not init router navigation listeners if a non root component is bootstrapped',
     (done) => {
       @NgModule({
         imports: [BrowserModule, RouterModule.forRoot([], {useHash: true})],
         declarations: [SecondRootCmp, RootCmp],
         bootstrap: [RootCmp],
         providers: testProviders,
         schemas: [CUSTOM_ELEMENTS_SCHEMA]
       })
       class TestModule {
       }

       platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
         const router = res.injector.get(Router);
         spyOn(router as any, 'resetRootComponentType').and.callThrough();

         const appRef: ApplicationRef = res.injector.get(ApplicationRef);
         appRef.bootstrap(SecondRootCmp);

         expect((router as any).resetRootComponentType).not.toHaveBeenCalled();

         done();
       });
     });

  it('should reinit router navigation listeners if a previously bootstrapped root component is destroyed',
     (done) => {
       @NgModule({
         imports: [BrowserModule, RouterModule.forRoot([], {useHash: true})],
         declarations: [SecondRootCmp, RootCmp],
         bootstrap: [RootCmp],
         providers: testProviders,
         schemas: [CUSTOM_ELEMENTS_SCHEMA]
       })
       class TestModule {
       }

       platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
         const router = res.injector.get(Router);
         spyOn(router as any, 'resetRootComponentType').and.callThrough();

         const appRef: ApplicationRef = res.injector.get(ApplicationRef);
         appRef.components[0].onDestroy(() => {
           appRef.bootstrap(SecondRootCmp);
           expect((router as any).resetRootComponentType).toHaveBeenCalled();
           done();
         });

         appRef.components[0].destroy();
       });
     });

  it('should restore the scrolling position', async () => {
    @Component({
      selector: 'component-a',
      template: `

      `
    })
    class TallComponent {
    }
    @NgModule({
      imports: [
        BrowserModule,
        RouterModule.forRoot(
            [
              {path: '', pathMatch: 'full', redirectTo: '/aa'},
              {path: 'aa', component: TallComponent}, {path: 'bb', component: TallComponent},
              {path: 'cc', component: TallComponent},
              {path: 'fail', component: TallComponent, canActivate: ['returnFalse']}
            ],
            {
              useHash: true,
              scrollPositionRestoration: 'enabled',
              anchorScrolling: 'enabled',
              scrollOffset: [0, 100],
              onSameUrlNavigation: 'reload'
            })
      ],
      declarations: [TallComponent, RootCmp],
      bootstrap: [RootCmp],
      providers: [...testProviders, {provide: 'returnFalse', useValue: () => false}],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    class TestModule {
    }

    function resolveAfter(milliseconds: number) {
      return new Promise<void>((resolve) => {
        setTimeout(() => {
          resolve();
        }, milliseconds);
      });
    }

    const res = await platformBrowserDynamic([]).bootstrapModule(TestModule);
    const router = res.injector.get(Router);

    await router.navigateByUrl('/aa');
    window.scrollTo(0, 5000);

    await router.navigateByUrl('/fail');
    expect(window.pageYOffset).toEqual(5000);

    await router.navigateByUrl('/bb');
    window.scrollTo(0, 3000);

    expect(window.pageYOffset).toEqual(3000);

    await router.navigateByUrl('/cc');
    await resolveAfter(100);
    expect(window.pageYOffset).toEqual(0);

    await router.navigateByUrl('/aa#marker2');
    await resolveAfter(100);
    expect(window.pageYOffset).toBeGreaterThanOrEqual(5900);
    expect(window.pageYOffset).toBeLessThan(6000);  // offset

    await router.navigateByUrl('/aa#marker3');
    await resolveAfter(100);
    expect(window.pageYOffset).toBeGreaterThanOrEqual(8900);
    expect(window.pageYOffset).toBeLessThan(9000);
  });

  it('should cleanup "popstate" and "hashchange" listeners', async () => {
    @NgModule({
      imports: [BrowserModule, RouterModule.forRoot([])],
      declarations: [RootCmp],
      bootstrap: [RootCmp],
      providers: testProviders,
    })
    class TestModule {
    }

    spyOn(window, 'addEventListener').and.callThrough();
    spyOn(window, 'removeEventListener').and.callThrough();

    const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule);
    ngModuleRef.destroy();

    expect(window.addEventListener).toHaveBeenCalledTimes(2);

    expect(window.addEventListener)
        .toHaveBeenCalledWith('popstate', jasmine.any(Function), jasmine.any(Boolean));
    expect(window.addEventListener)
        .toHaveBeenCalledWith('hashchange', jasmine.any(Function), jasmine.any(Boolean));

    expect(window.removeEventListener).toHaveBeenCalledWith('popstate', jasmine.any(Function));
    expect(window.removeEventListener).toHaveBeenCalledWith('hashchange', jasmine.any(Function));
  });

  it('can schedule a navigation from the NavigationEnd event #37460', (done) => {
    @NgModule({
      imports: [
        BrowserModule,
        RouterModule.forRoot(
            [
              {path: 'a', component: SimpleCmp},
              {path: 'b', component: SimpleCmp},
            ],
            )
      ],
      declarations: [RootCmp, SimpleCmp],
      bootstrap: [RootCmp],
      providers: [...testProviders],
    })
    class TestModule {
    }

    (async () => {
      const res = await platformBrowserDynamic([]).bootstrapModule(TestModule);
      const router = res.injector.get(Router);
      router.events.subscribe(async (e) => {
        if (e instanceof NavigationEnd && e.url === '/b') {
          await router.navigate(['a']);
          done();
        }
      });
      await router.navigateByUrl('/b');
    })();
  });
});


text:
# inline-source-map-comment

[![Build Status](https://travis-ci.org/shinnn/inline-source-map-comment.svg?branch=master)](https://travis-ci.org/shinnn/inline-source-map-comment)
[![Build status](https://ci.appveyor.com/api/projects/status/57fmdhy41qainu8g)](https://ci.appveyor.com/project/ShinnosukeWatanabe/inline-source-map-comment)
[![Coverage Status](https://img.shields.io/coveralls/shinnn/inline-source-map-comment.svg)](https://coveralls.io/r/shinnn/inline-source-map-comment)
[![Dependency Status](https://david-dm.org/shinnn/inline-source-map-comment.svg)](https://david-dm.org/shinnn/inline-source-map-comment)
[![devDependency Status](https://david-dm.org/shinnn/inline-source-map-comment/dev-status.svg)](https://david-dm.org/shinnn/inline-source-map-comment#info=devDependencies)

Create an inline source map comment from a source map object or string

```javascript
var inlineSourceMapComment = require('inline-source-map-comment');

var fixture = {
  version:3,
  file: 'output.js.map',
  sources: ['input.js'],
  names: [],
  mappings: 'AAAA'
};

inlineSourceMapComment(fixture); //=> "//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib3V0cHV0LmpzLm1hcCIsInNvdXJjZXMiOlsiaW5wdXQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEifQ=="
```

## Installation

### Package managers

#### [npm](https://www.npmjs.org/) [![NPM version](https://badge.fury.io/js/inline-source-map-comment.svg)](https://www.npmjs.com/package/inline-source-map-comment)

```sh
npm install inline-source-map-comment
```

#### [bower](http://bower.io/) [![Bower version](https://badge.fury.io/bo/inline-source-map-comment.svg)](https://github.com/shinnn/inline-source-map-comment/releases)

```sh
bower install inline-source-map-comment
```

#### [Duo](http://duojs.org/)

```javascript
var inlineSourceMapComment = require('shinnn/inline-source-map-comment');
```

### Standalone

[Download the script file directly.](https://raw.githubusercontent.com/shinnn/inline-source-map-comment/master/inline-source-map-comment.js)

## API

### inlineSourceMapComment(*sourceMap* [, *options*])

*sourceMap*: `String` or `Object`
*options*: `Object`
Return: `String`

It returns a line comment of [base64](http://wikipedia.org/wiki/Base64)-encoded [source map](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k).

Argument can be an object of source map or a JSON string.

```javascript
var map = '{"version":3,"file":"foo.js.map","sources":["bar.js"],"names":[],"mappings":"AAAA"}';

inlineSourceMapComment(map); //=> "//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzLm1hcCIsInNvdXJjZXMiOlsiYmFyLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBIn0="

inlineSourceMapComment(JSON.parse(map)); //=> (Same as `inlineSourceMapComment.js(map)`)
```

It automatically removes `sourcesContent` property from result. Use [`sourcesContent` option](#optionssourcescontent) if you want to preserve `sourcesContent` property.

```javascript
var map = '{"version":3,"file":"foo.js.map","sources":["bar.js"], ...';
var one = inlineSourceMapComment(map);

map.sourcesContent = 'foo';
var another inlineSourceMapComment(map);

one === another; //=> true
```

#### options.block

Type: `Boolean`
Default: `false`

Returns a block comment instead of a line comment.

It can be used for creating an inline source map of CSS.

```javascript
var map = '{"version":3,"file":"foo.css.map","sources":["bar.js"], ...';

inlineSourceMapComment(map, {block: true}) //=> "/* sourceMappingURL=data:application/json;base64,eyJ2ZXJ ... */"
```

#### options.sourcesContent

Type: `Boolean`
Default: `false`

Preserves `sourcesContent` property.

### inlineSourceMapComment.prefix

Type: `String`

The prefix string of base64-encoded source map.

```javascript
inlineSourceMapComment.prefix; //=> "# sourceMappingURL=data:application/json;base64,"
```

## CLI

You can use this module as a CLI tool by installing it [globally](https://docs.npmjs.com/files/folders#global-installation).

```sh
npm install -g inline-source-map-comment
```

### Usage

```sh
Usage1: inline-source-map-comment <source map string>
Usage2: inline-source-map-comment --in <source map file>
Usage3: cat <source map file> | inline-source-map-comment

Options:
--block, --css,    -b, -c  Print a block comment instead of line comment
--sources-content, -s      Preserve sourcesContent property
--in, --input,     -i      Use a JSON file as a source
--help,            -h      Print usage information
--version,         -v      Print version
```

## License

Copyright (c) 2014 [Shinnosuke Watanabe](https://github.com/shinnn)

Licensed under [the MIT License](./LICENSE).

redpajama_set_name: RedPajamaGithub


text:
namespace media {
namespace cast {

static const int64 kStartMillisecond = 123456789;

using testing::_;

static void RelaseFrame(const PcmAudioFrame* frame) {
  delete frame;
}

class AudioSenderTest : public ::testing::Test {
 protected:
  AudioSenderTest() {
    testing_clock_.Advance(
        base::TimeDelta::FromMilliseconds(kStartMillisecond));
  }

  virtual void SetUp() {
    task_runner_ = new test::FakeTaskRunner(&testing_clock_);
    cast_thread_ = new CastThread(task_runner_, task_runner_, task_runner_,
                                  task_runner_, task_runner_);
    AudioSenderConfig audio_config;
    audio_config.codec = kOpus;
    audio_config.use_external_encoder = false;
    audio_config.frequency = 48000;
    audio_config.channels = 2;
    audio_config.bitrate = 64000;
    audio_config.rtp_payload_type = 127;

    audio_sender_.reset(
        new AudioSender(cast_thread_, audio_config, &mock_transport_));
    audio_sender_->set_clock(&testing_clock_);
  }

  ~AudioSenderTest() {}

  base::SimpleTestTickClock testing_clock_;
  MockPacedPacketSender mock_transport_;
  scoped_refptr<test::FakeTaskRunner> task_runner_;
  scoped_ptr<AudioSender> audio_sender_;
  scoped_refptr<CastThread> cast_thread_;
};

TEST_F(AudioSenderTest, Encode20ms) {
  EXPECT_CALL(mock_transport_, SendPacket(_, _)).Times(1);

  PcmAudioFrame* audio_frame = new PcmAudioFrame();
  audio_frame->channels = 2;
  audio_frame->frequency = 48000;
  audio_frame->samples.insert(audio_frame->samples.begin(), 480 * 2 * 2, 123);

  base::TimeTicks recorded_time;
  audio_sender_->InsertRawAudioFrame(audio_frame, recorded_time,
      base::Bind(&RelaseFrame, audio_frame));

  task_runner_->RunTasks();
}

TEST_F(AudioSenderTest, RtcpTimer) {
  EXPECT_CALL(mock_transport_, SendRtcpPacket(_)).Times(1);

  // Make sure that we send at least one RTCP packet.
  base::TimeDelta max_rtcp_timeout =
      base::TimeDelta::FromMilliseconds(1 + kDefaultRtcpIntervalMs * 3 / 2);
  testing_clock_.Advance(max_rtcp_timeout);
  task_runner_->RunTasks();
}

}  // namespace cast
}  // namespace media


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

require_once('../config.php');
require_once('lib.php');
require_once('autogroup_form.php');

if (!defined('AUTOGROUP_MIN_RATIO')) {
    define('AUTOGROUP_MIN_RATIO', 0.7); // means minimum member count is 70% in the smallest group
}

$courseid = required_param('courseid', PARAM_INT);
$PAGE->set_url('/group/autogroup.php', array('courseid' => $courseid));

if (!$course = $DB->get_record('course', array('id'=>$courseid))) {
    print_error('invalidcourseid');
}

// Make sure that the user has permissions to manage groups.
require_login($course);

$context       = context_course::instance($courseid);
require_capability('moodle/course:managegroups', $context);

$returnurl = $CFG->wwwroot.'/group/index.php?id='.$course->id;

$strgroups           = get_string('groups');
$strparticipants     = get_string('participants');
$strautocreategroups = get_string('autocreategroups', 'group');

$PAGE->set_title($strgroups);
$PAGE->set_heading($course->fullname. ': '.$strgroups);
$PAGE->set_pagelayout('admin');
navigation_node::override_active_url(new moodle_url('/group/index.php', array('id' => $courseid)));

// Print the page and form
$preview = '';
$error = '';

/// Get applicable roles - used in menus etc later on
$rolenames = role_fix_names(get_profile_roles($context), $context, ROLENAME_ALIAS, true);

/// Create the form
$editform = new autogroup_form(null, array('roles' => $rolenames));
$editform->set_data(array('courseid' => $courseid, 'seed' => time()));

/// Handle form submission
if ($editform->is_cancelled()) {
    redirect($returnurl);

} elseif ($data = $editform->get_data()) {

    /// Allocate members from the selected role to groups
    switch ($data->allocateby) {
        case 'no':
        case 'random':
        case 'lastname':
            $orderby = 'lastname, firstname'; break;
        case 'firstname':
            $orderby = 'firstname, lastname'; break;
        case 'idnumber':
            $orderby = 'idnumber'; break;
        default:
            print_error('unknoworder');
    }
    $users = groups_get_potential_members($data->courseid, $data->roleid, $data->cohortid, $orderby);
    $usercnt = count($users);

    if ($data->allocateby == 'random') {
        srand($data->seed);
        shuffle($users);
    }

    $groups = array();

    // Plan the allocation
    if ($data->groupby == 'groups') {
        $numgrps    = $data->number;
        $userpergrp = floor($usercnt/$numgrps);

    } else { // members
        $numgrps    = ceil($usercnt/$data->number);
        $userpergrp = $data->number;

        if (!empty($data->nosmallgroups) and $usercnt % $data->number != 0) {
            // If there would be one group with a small number of member reduce the number of groups
            $missing = $userpergrp * $numgrps - $usercnt;
            if ($missing > $userpergrp * (1-AUTOGROUP_MIN_RATIO)) {
                // spread the users from the last small group
                $numgrps--;
                $userpergrp = floor($usercnt/$numgrps);
            }
        }
    }

    // allocate the users - all groups equal count first
    for ($i=0; $i<$numgrps; $i++) {
        $groups[$i] = array();
        $groups[$i]['name']    = groups_parse_name(trim($data->namingscheme), $i);
        $groups[$i]['members'] = array();
        if ($data->allocateby == 'no') {
            continue; // do not allocate users
        }
        for ($j=0; $j<$userpergrp; $j++) {
            if (empty($users)) {
                break 2;
            }
            $user = array_shift($users);
            $groups[$i]['members'][$user->id] = $user;
        }
    }
    // now distribute the rest
    if ($data->allocateby != 'no') {
        for ($i=0; $i<$numgrps; $i++) {
            if (empty($users)) {
                break 1;
            }
            $user = array_shift($users);
            $groups[$i]['members'][$user->id] = $user;
        }
    }

    if (isset($data->preview)) {
        $table = new html_table();
        if ($data->allocateby == 'no') {
            $table->head  = array(get_string('groupscount', 'group', $numgrps));
            $table->size  = array('100%');
            $table->align = array('left');
            $table->width = '40%';
        } else {
            $table->head  = array(get_string('groupscount', 'group', $numgrps), get_string('groupmembers', 'group'), get_string('usercounttotal', 'group', $usercnt));
            $table->size  = array('20%', '70%', '10%');
            $table->align = array('left', 'left', 'center');
            $table->width = '90%';
        }
        $table->data  = array();

        foreach ($groups as $group) {
            $line = array();
            if (groups_get_group_by_name($courseid, $group['name'])) {
                $line[] = ''.get_string('groupnameexists', 'group', $group['name']).'';
                $error = get_string('groupnameexists', 'group', $group['name']);
            } else {
                $line[] = $group['name'];
            }
            if ($data->allocateby != 'no') {
                $unames = array();
                foreach ($group['members'] as $user) {
                    $unames[] = fullname($user, true);
                }
                $line[] = implode(', ', $unames);
                $line[] = count($group['members']);
            }
            $table->data[] = $line;
        }

        $preview .= html_writer::table($table);

    } else {
        $grouping = null;
        $createdgrouping = null;
        $createdgroups = array();
        $failed = false;

        // prepare grouping
        if (!empty($data->grouping)) {
            if ($data->grouping < 0) {
                $grouping = new stdClass();
                $grouping->courseid = $COURSE->id;
                $grouping->name     = trim($data->groupingname);
                $grouping->id = groups_create_grouping($grouping);
                $createdgrouping = $grouping->id;
            } else {
                $grouping = groups_get_grouping($data->grouping);
            }
        }

        // Save the groups data
        foreach ($groups as $key=>$group) {
            if (groups_get_group_by_name($courseid, $group['name'])) {
                $error = get_string('groupnameexists', 'group', $group['name']);
                $failed = true;
                break;
            }
            $newgroup = new stdClass();
            $newgroup->courseid = $data->courseid;
            $newgroup->name     = $group['name'];
            $groupid = groups_create_group($newgroup);
            $createdgroups[] = $groupid;
            foreach($group['members'] as $user) {
                groups_add_member($groupid, $user->id);
            }
            if ($grouping) {
                // Ask this function not to invalidate the cache, we'll do that manually once at the end.
                groups_assign_grouping($grouping->id, $groupid, null, false);
            }
        }

        // Invalidate the course groups cache seeing as we've changed it.
        cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));

        if ($failed) {
            foreach ($createdgroups as $groupid) {
                groups_delete_group($groupid);
            }
            if ($createdgrouping) {
                groups_delete_grouping($createdgrouping);
            }
        } else {
            redirect($returnurl);
        }
    }
}

$PAGE->navbar->add($strparticipants, new moodle_url('/user/index.php', array('id'=>$courseid)));
$PAGE->navbar->add($strgroups, new moodle_url('/group/index.php', array('id'=>$courseid)));
$PAGE->navbar->add($strautocreategroups);

echo $OUTPUT->header();
echo $OUTPUT->heading($strautocreategroups);

if ($error != '') {
    echo $OUTPUT->notification($error);
}

/// Display the form
$editform->display();

if($preview !== '') {
    echo $OUTPUT->heading(get_string('groupspreview', 'group'));

    echo $preview;
}

echo $OUTPUT->footer();


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

from collections import defaultdict, namedtuple

from pants.backend.jvm.targets.import_jars_mixin import ImportJarsMixin

class JarImportProducts(object):
  """Represents the products of jar import resolutions.

  Jar imports are jars containing source code to be unpacked and used locally.
  """

  JarImport = namedtuple('JarImport', ['coordinate', 'jar'])
  """Represents a jar containing source imports.

  Each jar import has a `coordinate` :class:`pants.java.jar_utls.M2Coordinate`
  and a `jar` path that points to the resolved jar import for the `coordinate`.
  """

  def __init__(self):
    self._imports = defaultdict(list)

  def imported(self, target, coordinate, jar):
    """Registers a :class`JarImportProducts.JarImport` for the given target.

    :param target: The :class:`pants.backend.jvm.targets.import_jars_mixin.ImportJarsMixin` target
                   whose `imported_jar_library_specs` were resolved.
    :param coordinate: The maven coordinate of the import jar.
    :type coordinate: :class:`pants.java.jar_utls.M2Coordinate`
    :param string jar: The path of the resolved import jar.
    """
    if not isinstance(target, ImportJarsMixin):
      raise ValueError('The given target is not an `ImportJarsMixin`: {}'.format(target))
    self._imports[target].append(self.JarImport(coordinate, jar))

  def imports(self, target):
    """Returns a list of :class:`JarImportProducts.JarImport`s for the given target.

    Will be an empty list if the target has no jar imports.

    :rtype: list
    """
    return self._imports[target]

  def __repr__(self):
    return 'JarImportProducts({!r})'.format(self._imports)


text:
/************************************************************
 * Student Name:     Maxim Vainshtein                       *
 * Exercise Name:    Ex2                                    *
 * File description: Declaration of UDPServer Class         *
 ***********************************************************/

#ifndef __Ex2__UDPServer__
#define __Ex2__UDPServer__

#include <stdio.h>
#include "Server.h"

/********************************************************************************************
 * UDPServer Class: Represents a Server. It has the ability to accept incoming connections, *
 *               and repsond to those connections (that are represented by                  *
 *               connection class). Uses the UDP protocol.                                  *
 *******************************************************************************************/

class UDPServer : public Server {

private:

    friend class Server;

    //  ---                         PRIVATE FUNCTIONS                       ---   //

    /************************************************************************************************
     * function name: UDPServer Constructor                                                         *
     * The Input: const string (reference), int                                                     *
     * The output: none                                                                             *
     * The Function Opertion: Initializes the Server with input as port and IP address.             *
     * *********************************************************************************************/

    UDPServer(const std::string& strAddress, uint16_t usPort);

public:

    //  ---                         PUBLIC FUNCTIONS                       ---   //

    /**********************************************************************************************
     * function name: TCPServer Destructor                                                        *
     * The Input: none                                                                            *
     * The output: none                                                                           *
     * The Function Opertion: Destroys the current object.                                        *
     * *******************************************************************************************/

    ~UDPServer();

    /**********************************************************************************************
     * function name: start                                                                       *
     * The Input: none                                                                            *
     * The output: int                                                                            *
     * The Function Opertion: Sets the created server to listen for incoming transmissions.       *
     *                        Returns 0 if there was no error, or values smaller than 0 for error.*
     * *******************************************************************************************/

    virtual int start();

    /**********************************************************************************************
     * function name: connection                                                                  *
     * The Input: none                                                                            *
     * The output: const Connection object (pointer)                                              *
     * The Function Opertion: Returns a connection object that is a link to this server           *
     * *******************************************************************************************/

    virtual const Connection* connection() const;
};

#endif


text:
U_NAMESPACE_BEGIN

CaseFoldingUTextIterator::CaseFoldingUTextIterator(UText &text) :
   fUText(text), fcsp(NULL), fFoldChars(NULL), fFoldLength(0) {
   fcsp = ucase_getSingleton();
}

CaseFoldingUTextIterator::~CaseFoldingUTextIterator() {}

UChar32 CaseFoldingUTextIterator::next() {
    UChar32  foldedC;
    UChar32  originalC;
    if (fFoldChars == NULL) {
        // We are not in a string folding of an earlier character.
        // Start handling the next char from the input UText.
        originalC = UTEXT_NEXT32(&fUText);
        if (originalC == U_SENTINEL) {
            return originalC;
        }
        fFoldLength = ucase_toFullFolding(fcsp, originalC, &fFoldChars, U_FOLD_CASE_DEFAULT);
        if (fFoldLength >= UCASE_MAX_STRING_LENGTH || fFoldLength < 0) {
            // input code point folds to a single code point, possibly itself.
            // See comment in ucase.h for explanation of return values from ucase_toFullFoldings.
            if (fFoldLength < 0) {
                fFoldLength = ~fFoldLength;
            }
            foldedC = (UChar32)fFoldLength;
            fFoldChars = NULL;
            return foldedC;
        }
        // String foldings fall through here.
        fFoldIndex = 0;
    }

    U16_NEXT(fFoldChars, fFoldIndex, fFoldLength, foldedC);
    if (fFoldIndex >= fFoldLength) {
        fFoldChars = NULL;
    }
    return foldedC;
}

UBool CaseFoldingUTextIterator::inExpansion() {
    return fFoldChars != NULL;
}

CaseFoldingUCharIterator::CaseFoldingUCharIterator(const UChar *chars, int64_t start, int64_t limit) :
   fChars(chars), fIndex(start), fLimit(limit), fcsp(NULL), fFoldChars(NULL), fFoldLength(0) {
   fcsp = ucase_getSingleton();
}

CaseFoldingUCharIterator::~CaseFoldingUCharIterator() {}

UChar32 CaseFoldingUCharIterator::next() {
    UChar32  foldedC;
    UChar32  originalC;
    if (fFoldChars == NULL) {
        // We are not in a string folding of an earlier character.
        // Start handling the next char from the input UText.
        if (fIndex >= fLimit) {
            return U_SENTINEL;
        }
        U16_NEXT(fChars, fIndex, fLimit, originalC);

        fFoldLength = ucase_toFullFolding(fcsp, originalC, &fFoldChars, U_FOLD_CASE_DEFAULT);
        if (fFoldLength >= UCASE_MAX_STRING_LENGTH || fFoldLength < 0) {
            // input code point folds to a single code point, possibly itself.
            // See comment in ucase.h for explanation of return values from ucase_toFullFoldings.
            if (fFoldLength < 0) {
                fFoldLength = ~fFoldLength;
            }
            foldedC = (UChar32)fFoldLength;
            fFoldChars = NULL;
            return foldedC;
        }
        // String foldings fall through here.
        fFoldIndex = 0;
    }

    U16_NEXT(fFoldChars, fFoldIndex, fFoldLength, foldedC);
    if (fFoldIndex >= fFoldLength) {
        fFoldChars = NULL;
    }
    return foldedC;
}

UBool CaseFoldingUCharIterator::inExpansion() {
    return fFoldChars != NULL;
}

int64_t CaseFoldingUCharIterator::getIndex() {
    return fIndex;
}

// Assemble a pcode instruction from the opcode and operand values.
// Out-of-range values should not occur - if they do it is from an internal
// error in the regex compiler.

// TODO: move into regexcmp, where it has access to fStatus.
//       NOP cleanly if U_FAILURE.
//       Set U_REGEX_INTERNAL_ERROR on bad operands.

int32_t URX_BUILD(int32_t type, int32_t val) {
    if (type < 0 || type > 255) {
        U_ASSERT(FALSE);
        type = URX_RESERVED_OP;
    }
    if (val > 0x00ffffff) {
        U_ASSERT(FALSE);
        val = 0;
    }
    return (type << 24) | val;
}

U_NAMESPACE_END

#endif


text:
layout: post
title:  "Stateless Email Verification"
date:   2014-04-18 10:20:50
categories: security stateless
---

My preference has always been stateless approach, but the approach mentioned needs a bit more work. You want the link to expire in some time - so when you generate the signature, you append a timestamp into it as well.

Stateless email verification should be something like this -

1. Make a JSON Object with {"email": "sripathi@kickdrumtech.com", "timestamp": "1395139162"}
2. Base64 encode JSON Object with URL Safe Encoder. Call the string as "payload"
3. Compute a signature, which is SHA1(payload + secret key). MD5 is also fine for this purpose.
4. Generate a link - https://example.com/verify_email?payload=<payload>&signature=<signature> and email the user.
5. When the user clicks the link, extract the payload and verify the signature. If signature mismatch - raise hell
6. Extract timestamp and verify it hasn't expired
7. Finally, confirm the email. Optionally, log in the database when the email was confirmed.


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:paddingBottom="0dp"
    >

    <TextView
        android:id="@+id/contributionSequenceNumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="98sp"
        android:textColor="#33FFFFFF"
        android:typeface="serif"
        android:layout_gravity="end|bottom"
        />

    <fr.free.nrw.commons.MediaWikiImageView
        android:id="@+id/contributionImage"
        android:layout_width="match_parent"
        android:layout_height="240dp"
        app:actualImageScaleType="centerCrop"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|bottom"
        android:background="#AA000000"
        android:orientation="vertical"
        android:padding="@dimen/small_gap"
        >
        <ProgressBar
            android:id="@+id/contributionProgress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/ProgressBar"
            android:indeterminateOnly="false"
            android:max="100"
            android:visibility="gone"
            />

        <TextView
            android:id="@+id/contributionState"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="?android:textAppearanceSmall"
            android:textColor="#FFFFFFFF"
            android:visibility="gone"
            />

        <TextView
            android:id="@+id/contributionTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FFFFFFFF"
            style="?android:textAppearanceMedium"
            android:maxLines="2"
            android:ellipsize="end"
            />
    </LinearLayout>

</FrameLayout>


text:
package jMapGen;

import java.util.Random;
import java.util.Vector;

import jMapGen.com.nodename.Delaunay.DelaunayUtil;
import jMapGen.graph.Center;
import jMapGen.graph.Edge;

public class NoisyEdges
{
	static public double NOISY_LINE_TRADEOFF = 0.5;  // low: jagged vedge; high: jagged dedge

	public Vector<Vector<Point>> path0;  // edge index -> Vector.<Point>
	public Vector<Vector<Point>> path1;  // edge index -> Vector.<Point>

	public NoisyEdges() {path0 = new Vector<Vector<Point>>(); path1 = new Vector<Vector<Point>>();}

	// Build noisy line paths for each of the Voronoi edges. There are
	// two noisy line paths for each edge, each covering half the
	// distance: path0 is from v0 to the midpoint and path1 is from v1
	// to the midpoint. When drawing the polygons, one or the other
	// must be drawn in reverse order.
	public void buildNoisyEdges(Map map, Lava lava, Random random) {
		Center p;
		Edge edge;
		for(int i = 0; i < map.centers.size(); i++)
		{
			p = map.centers.get(i);
			for(int j = 0; j < p.borders.size(); j++)
			{
				edge = p.borders.get(j);

				if (edge.dCenter0 != null && edge.dCenter1 != null && edge.vCorner0 != null && edge.vCorner1 != null && DelaunayUtil.getAtPosition(path0, edge.index) == null)
				{
					double f = NOISY_LINE_TRADEOFF;
					Point t = Point.interpolate(edge.vCorner0.point, edge.dCenter0.point, f);
					Point q = Point.interpolate(edge.vCorner0.point, edge.dCenter1.point, f);
					Point r = Point.interpolate(edge.vCorner1.point, edge.dCenter0.point, f);
					Point s = Point.interpolate(edge.vCorner1.point, edge.dCenter1.point, f);

					int minLength = 10;
					if (edge.dCenter0.biome != edge.dCenter1.biome) minLength = 3;
					if (edge.dCenter0.ocean && edge.dCenter1.ocean) minLength = 100;
					if (edge.dCenter0.coast || edge.dCenter1.coast) minLength = 1;
					//if (edge.river == 1 || lava.lava.get(edge.index) != null) minLength = 1;

					DelaunayUtil.setAtPosition(path0, edge.index, buildNoisyLineSegments(random, edge.vCorner0.point, t, edge.midpoint, q, minLength));
					DelaunayUtil.setAtPosition(path1, edge.index, buildNoisyLineSegments(random, edge.vCorner1.point, s, edge.midpoint, r, minLength));
				}
			}
		}
	}

	// Helper function: build a single noisy line in a quadrilateral A-B-C-D,
	// and store the output points in a Vector.
	static public Vector<Point> buildNoisyLineSegments(Random random, Point A, Point B, Point C, Point D, double minLength)
	{
		Vector<Point> points = new Vector<Point>();
		points.add(A);
		subdivide(random, A, B, C, D, minLength, points);
		points.add(C);
		return points;
	}

	static void subdivide(Random random, Point A, Point B, Point C, Point D, double minLength, Vector<Point> points)
	{
		if (A.minus(C).getLength() < minLength || B.minus(D).getLength()  < minLength)
		{
			return;
		}

		// Subdivide the quadrilateral
		double p = 0.2 + random.nextDouble()*0.6;  // vertical (along A-D and B-C)
		double q = 0.2 + random.nextDouble()*0.6;  // horizontal (along A-B and D-C)

		// Midpoints
		Point E = Point.interpolate(A, D, p);
		Point F = Point.interpolate(B, C, p);
		Point G = Point.interpolate(A, B, q);
		Point I = Point.interpolate(D, C, q);

		// Central point
		Point H = Point.interpolate(E, F, q);

		// Divide the quad into subquads, but meet at H
		double s = 1.0 - (-0.4 + random.nextDouble() * 0.8);
		double t = 1.0 - (-0.4 + random.nextDouble() * 0.8);

		subdivide(random, A, Point.interpolate(G, B, s), H, Point.interpolate(E, D, t), minLength, points);
		points.add(H);
		subdivide(random, H, Point.interpolate(F, C, s), C, Point.interpolate(I, D, t), minLength, points);
	}
}


text:
<?php

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* LANGUAGE */

$transliterate_language[0] = 'Escribe en tu idioma';
$transliterate_language[1] = '¿A qué idioma te gustaría transliterar?';
$transliterate_language[2] = 'Escribe en inglés y usa el espacio para transliterar a tu idioma';
$transliterate_language[3] = 'Enviar';
$transliterate_language[4] = '(cambiar idioma)';

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


text:
package com.amazonaws.services.redshift.model;

import javax.annotation.Generated;

/**
 * <p>
 * The endpoint name doesn't refer to an existing endpoint.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class EndpointNotFoundException extends com.amazonaws.services.redshift.model.AmazonRedshiftException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new EndpointNotFoundException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public EndpointNotFoundException(String message) {
        super(message);
    }

}


text:
package org.forpdi.planning.plan;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import br.com.caelum.vraptor.boilerplate.SimpleEntity;
import br.com.caelum.vraptor.serialization.SkipSerialization;

/**
 * @author Renato R. R. de Oliveira
 *
 */
@Entity(name = PlanMacroField.TABLE)
@Table(
	name = PlanMacroField.TABLE
)
public class PlanMacroField extends SimpleEntity {
	public static final String TABLE = "fpdi_plan_macro_field";
	private static final long serialVersionUID = 1L;

	@Column(nullable = false, length=255)
	private String label;

	@Column(nullable = true, length=10000)
	private String value;

	@Column(nullable = false, length=32)
	private String type;

	@SkipSerialization
	@ManyToOne(targetEntity=PlanMacro.class, optional=false, fetch=FetchType.EAGER)
	private PlanMacro macro;

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public PlanMacro getMacro() {
		return macro;
	}

	public void setMacro(PlanMacro macro) {
		this.macro = macro;
	}

}


text:
import _Global = require("../../Core/_Global");

import _Control = require("../../Utilities/_Control");
import _ElementUtilities = require("../../Utilities/_ElementUtilities");

import XYFocus = require("../../XYFocus");

require(["require-style!less/styles-scrollviewer"]);
require(["require-style!less/colors-scrollviewer"]);

"use strict";

var SMALL_SCROLL_AMOUNT = 200;
var PERCENTAGE_OF_PAGE_TO_SCROLL = 0.8;
var THRESHOLD_TO_SHOW_TOP_ARROW = 50;
var DelayBeforeCheckingSizeOfScrollableRegion = 500;

var Keys = _ElementUtilities.Key;

export var ScrollMode = {
    /// <field type="String" locid="WinJS.UI.ScrollMode.text" helpKeyword="WinJS.UI.ScrollMode.text">
    /// Indicates the ScrollViewer contains text and must be invoked with the A button, then the contents can be scrolled
    /// using directional navigation.
    /// </field>
    text: "text",
    /// <field type="String" locid="WinJS.UI.ScrollMode.nonModalText" helpKeyword="WinJS.UI.ScrollMode.nonModalText">
    /// This mode is similar to text mode except the user does not need to press A to begin scrolling. Instead they move
    /// focus to the ScrollViewer and are able to scroll text. This mode should only be used if there are no focusable
    /// UI elements above or below the control.
    /// </field>
    nonModalText: "nonModalText",
    /// <field type="String" locid="WinJS.UI.ScrollMode.list" helpKeyword="WinJS.UI.ScrollMode.list">
    /// Indicates the ScrollViewer contains focusable elements and those elements that are off-screen are scrolled into view
    /// when the user selects those elements.
    /// </field>
    list: "list"
};

export class ScrollViewer {
    static supportedForProcessing = true;

    private _element: HTMLElement;
    private _canScrollDown = false;
    private _canScrollUp = false;
    private _disposed = false;
    private _previousFocusRoot: HTMLElement;
    private _scrollingContainer: HTMLElement;
    private _scrollingIndicatorElement: HTMLElement;
    private _scrollMode: string;
    private _vuiActive = false;
    private _vuiPageUpElement: HTMLElement;
    private _vuiPageDownElement: HTMLElement;

    /// <field type="HTMLElement" domElement="true" hidden="true" locid="WinJS.UI.ScrollViewer.element" helpKeyword="WinJS.UI.ScrollViewer.element">
    /// Gets the DOM element that hosts the ScrollViewer.
    /// </field>
    get element() {
        return this._element;
    }

    /// <field type="String" locid="WinJS.UI.ScrollViewer.interactionMode" helpKeyword="WinJS.UI.ScrollViewer.interactionMode">
    /// Gets or sets a property that indicates whether there are focusable elements within the ScrollViewer. The default value is false.
    /// </field>
    get scrollMode() {
        return this._scrollMode;
    }
    set scrollMode(value: string) {
        this._scrollMode = value;

        // If there are no focusable elements then we need to listen for the A button.
        if (this._scrollMode === ScrollMode.list) {
            _ElementUtilities.removeClass(this._element, "win-scrollviewer-scrollmode-text");
            _ElementUtilities.removeClass(this._scrollingContainer, "win-xyfocus-togglemode");
            _ElementUtilities.addClass(this._element, "win-scrollviewer-scrollmode-list");
            this._element.removeEventListener("keydown", this._handleKeyDown, true);
            this._setInactive();
        } else {
            _ElementUtilities.removeClass(this._element, "win-scrollviewer-scrollmode-list");
            _ElementUtilities.addClass(this._element, "win-scrollviewer-scrollmode-text");
            _ElementUtilities.addClass(this._scrollingContainer, "win-xyfocus-togglemode");
            this._element.addEventListener("keydown", this._handleKeyDown, true);
        }
    }

    constructor(element?: HTMLElement, options: any = {}) {
        this._element = element || document.createElement("div");
        options = options || {};
        this._element["winControl"] = this;

        _ElementUtilities.addClass(this._element, "win-disposable win-scrollviewer");

        this._handleFocus = this._handleFocus.bind(this);
        this._handleFocusOut = this._handleFocusOut.bind(this);
        this._handleKeyDown = this._handleKeyDown.bind(this);
        this._handleListeningStateChanged = this._handleListeningStateChanged.bind(this);
        this._handleScroll = this._handleScroll.bind(this);
        this._scrollDownBySmallAmount = this._scrollDownBySmallAmount.bind(this);
        this._scrollUpBySmallAmount = this._scrollUpBySmallAmount.bind(this);
        this._scrollDownByLargeAmount = this._scrollDownByLargeAmount.bind(this);
        this._scrollUpByLargeAmount = this._scrollUpByLargeAmount.bind(this);

        this._scrollingIndicatorElement = document.createElement("div");
        this._scrollingIndicatorElement.className = "win-scrollindicator";

        this._scrollingIndicatorElement.innerHTML =
        "
" +
        "

" +
        "

" +
        "
" +
        "
" +
        "

" +
        "

" +
        "
";
        this._scrollingIndicatorElement.addEventListener("listeningstatechanged", this._handleListeningStateChanged);

        this._vuiPageUpElement = <HTMLElement>this._scrollingIndicatorElement.querySelector(".win-overlay-pageupindicator");
        this._vuiPageUpElement.addEventListener("click", this._scrollUpByLargeAmount);

        this._vuiPageDownElement = <HTMLElement>this._scrollingIndicatorElement.querySelector(".win-overlay-pagedownindicator");
        this._vuiPageDownElement.addEventListener("click", this._scrollDownByLargeAmount);

        this._scrollingContainer = document.createElement("div");
        this._scrollingContainer.tabIndex = 0;
        _ElementUtilities.addClass(this._scrollingContainer, "win-scrollviewer-contentelement");

        // Put the contents in a scrolling container
        var child = this._element.firstChild;
        while (child) {
            var sibling = child.nextSibling;
            this._scrollingContainer.appendChild(child);
            child = sibling;
        }

        this._element.appendChild(this._scrollingContainer);
        this._element.appendChild(this._scrollingIndicatorElement);

        this._scrollingContainer.addEventListener("scroll", this._handleScroll, false);
        this._scrollingContainer.addEventListener("focus", this._handleFocus, false);
        this._element.addEventListener("focusout", this._handleFocusOut, false);

        // Set the default scroll mode
        this.scrollMode = ScrollMode.text;
        _Control.setOptions(this, options);

        this._refreshVisuals();

        // The scroll viewer has two interaction modes:
        //   1. Normal - In this state there is focusable content within the scrollable
        //      region. Automatic focus handles directional navigation and scrolls
        //      elements into view.
        //   2. Text - In this state there is no focusable content within the scrollable
        //      region. Typically, this case is free text. In this case, the ScrollViewer
        //      handles directional navigation and scrolls up and down.
        //
        //   To determine which mode we are in, we look for focusable content. If there
        //   is no focusable content, then we know we are in "Text" mode.

        // We need to wait for processAll to finish on the inner contents of the scrollable region, because we need accurate
        // sizing information to determine if a region is scrollable or not.
        _Global.setTimeout(() => {
            if (this._disposed) {
                return;
            }
            this._refreshVisuals();
        }, DelayBeforeCheckingSizeOfScrollableRegion);
    }

    /// <signature helpKeyword="WinJS.UI.ScrollViewer.dispose">
    ///
    /// Disposes the control.
    ///
    /// </signature>
    dispose() {
        if (this._disposed) {
            return;
        }
        this._disposed = true;

        _ElementUtilities.removeClass(this._element, "win-xyfocus-suspended");
        _ElementUtilities.disposeSubTree(this.element);
    }

    /// <signature helpKeyword="WinJS.UI.ScrollViewer.refresh">
    ///
    /// Call this function whenever the contents of the ScrollViewer changes.
    ///
    /// </signature>
    refresh() {
        this._refreshVisuals();
    }

    private _refreshVisuals() {
        // We call this function any time the size of the contents within the ScrollViewer changes. This function
        // determines if we need to display the visual treatment for "more content".
        _Global.setTimeout(() => {
            if (this._disposed) {
                return;
            }

            // Set initial visibility for the arrow indicators if the contents of the scrollable region
            // is bigger than the viewable area.
            if (this._scrollingContainer.clientHeight < this._scrollingContainer.scrollHeight) {
                if (this._scrollingContainer.scrollTop > 0) {
                    this._canScrollUp = true;
                } else {
                    this._canScrollUp = false;
                }
                if (this._scrollingContainer.scrollTop >= (this._scrollingContainer.scrollHeight - this._element.clientHeight)) {
                    this._canScrollDown = false;
                } else {
                    this._canScrollDown = true;
                }

                if (!this._canScrollUp && !this._canScrollDown) {
                    _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-down");
                    _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-up");

                    _ElementUtilities.addClass(this._vuiPageUpElement, "win-voice-disableoverride");
                    _ElementUtilities.addClass(this._vuiPageDownElement, "win-voice-disableoverride");
                } else if (!this._canScrollUp && this._canScrollDown) {
                    _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disableoverride");
                    _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disableoverride");

                    _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-up");
                    _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-down");

                    _ElementUtilities.addClass(this._vuiPageUpElement, "win-voice-disabledlabel");
                    _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disabledlabel");
                } else if (this._canScrollUp && !this._canScrollDown) {
                    _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disableoverride");
                    _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disableoverride");

                    _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-up");
                    _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-down");

                    _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disabledlabel");
                    _ElementUtilities.addClass(this._vuiPageDownElement, "win-voice-disabledlabel");
                } else {
                    _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disableoverride");
                    _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disableoverride");

                    _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-down");
                    _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-up");

                    _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disabledlabel");
                    _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disabledlabel");
                }

                // We only make the ScrollViewer focusable if it has text content and the
                // text content does not fit on the screen. If the text content does fit
                // on the screen then there is no reason to make the user scroll because
                // they can see all of the text.
                if (this._scrollMode === ScrollMode.text ||
                    this._scrollMode === ScrollMode.nonModalText) {
                    _ElementUtilities.addClass(this._scrollingContainer, "win-focusable");
                }

                // Add a class to indicate that the content within the ScrollViewer is bigger than
                // the visible area which means the ScrollViewer will need to be able to Scroll.
                _ElementUtilities.addClass(this._element, "win-scrollable");
            } else {
                _ElementUtilities.removeClass(this._element, "win-scrollable");
                _ElementUtilities.addClass(this._vuiPageUpElement, "win-voice-disableoverride");
                _ElementUtilities.addClass(this._vuiPageDownElement, "win-voice-disableoverride");
            }
        });
    }

    private _scrollDownBySmallAmount() {
        if (this._isActive()) {
            _ElementUtilities._zoomTo(this._scrollingContainer, { contentX: 0, contentY: this._scrollingContainer.scrollTop + SMALL_SCROLL_AMOUNT, viewportX: 0, viewportY: 0 });
        }
    }

    private _scrollUpBySmallAmount() {
        if (this._isActive()) {
            _ElementUtilities._zoomTo(this._scrollingContainer, { contentX: 0, contentY: this._scrollingContainer.scrollTop - SMALL_SCROLL_AMOUNT, viewportX: 0, viewportY: 0 });
        }
    }

    private _scrollDownByLargeAmount() {
        if (this._isActive() || this._vuiActive) {
            _ElementUtilities._zoomTo(this._scrollingContainer, { contentX: 0, contentY: this._scrollingContainer.scrollTop + (PERCENTAGE_OF_PAGE_TO_SCROLL * this._scrollingContainer.clientHeight), viewportX: 0, viewportY: 0 });
        }
    }

    private _scrollUpByLargeAmount() {
        if (this._isActive() || this._vuiActive) {
            _ElementUtilities._zoomTo(this._scrollingContainer, { contentX: 0, contentY: this._scrollingContainer.scrollTop - (PERCENTAGE_OF_PAGE_TO_SCROLL * this._scrollingContainer.clientHeight), viewportX: 0, viewportY: 0 });
        }
    }

    private _isActive() {
        return _ElementUtilities.hasClass(this._scrollingContainer, "win-xyfocus-togglemode-active");
    }

    private _setActive() {
        _ElementUtilities.addClass(this._scrollingContainer, "win-xyfocus-togglemode-active");
    }

    private _setInactive() {
        _ElementUtilities.removeClass(this._scrollingContainer, "win-xyfocus-togglemode-active");
    }

    private _handleFocus(ev: FocusEvent) {
        if (this._scrollMode === ScrollMode.nonModalText) {
            this._setActive();
        } else if (this._scrollMode === ScrollMode.list) {
            _ElementUtilities._focusFirstFocusableElement(this._scrollingContainer, false, this._scrollingContainer);
        }
    }

    private _handleFocusOut(ev: FocusEvent) {
        // If focus leaves the ScrollViewer & it was in the "invoked" state,
        // we need to reset it's state.
        if (this._isActive() && !this._element.contains(<HTMLElement>document.activeElement)) {
            this._setInactive();
        }
    }

    private _handleKeyDown(ev: KeyboardEvent) {
        // Only set handled = true for shoulder button cases so that
        // scroll viewer doesn't trigger a hub interaction.
        var handled = false;

        switch (ev.keyCode) {
            case Keys.upArrow:
            case Keys.GamepadDPadUp:
            case Keys.GamepadLeftThumbstickUp:
                if (this._scrollMode === ScrollMode.nonModalText) {
                    if (this._scrollingContainer.scrollTop >= THRESHOLD_TO_SHOW_TOP_ARROW) {
                        // No-op - the user can scroll up.
                    } else {
                        var nextFocusElement = XYFocus.findNextFocusElement("up");
                        if (nextFocusElement) {
                            nextFocusElement.focus();
                        }
                    }
                }
                this._scrollUpBySmallAmount();
                break;
            case Keys.downArrow:
            case Keys.GamepadDPadDown:
            case Keys.GamepadLeftThumbstickDown:
                if (this._scrollMode === ScrollMode.nonModalText) {
                    if (this._scrollingContainer.scrollTop >= (this._scrollingContainer.scrollHeight - this._element.clientHeight)) {
                        var nextFocusElement = XYFocus.findNextFocusElement("down");
                        if (nextFocusElement) {
                            nextFocusElement.focus();
                        }
                    } else {
                        // No-op - the user can scroll down
                    }
                }
                this._scrollDownBySmallAmount();
                break;
            case Keys.leftArrow:
            case Keys.GamepadDPadLeft:
            case Keys.GamepadLeftThumbstickLeft:
                var direction = "left";
            case Keys.rightArrow:
            case Keys.GamepadDPadRight:
            case Keys.GamepadLeftThumbstickRight:
                var direction = direction || "right";
                // If we successfully move focus to a new target element, then set the ScrollViewer as inactive
                if (this._isActive()) {
                    var previousFocusRectangleObject = this._scrollingContainer.getBoundingClientRect();
                    var previousFocusRectangle = {
                        top: previousFocusRectangleObject.top,
                        left: previousFocusRectangleObject.left,
                        width: previousFocusRectangleObject.width,
                        height: previousFocusRectangleObject.height
                    };

                    var nextFocusElement = XYFocus.moveFocus(direction, { referenceRect: previousFocusRectangle });
                    if (nextFocusElement) {
                        this._setInactive();
                        // Sound: Choose one of the 4 focus sounds to play at random
                    }
                }
                break;
            case Keys.pageUp:
            case Keys.GamepadLeftShoulder:
                this._scrollUpByLargeAmount();
                handled = true;
                break;
            case Keys.pageDown:
            case Keys.GamepadRightShoulder:
                this._scrollDownByLargeAmount();
                handled = true;
                break;
            default:
                break;
        }

        if (handled) {
            ev.stopPropagation();
        }
    }

    private _handleListeningStateChanged(e: any) {
        if (e.state === "inactive") {
            _ElementUtilities.removeClass(this._element, "win-voice-voicemodeactive");
            this._vuiActive = false;
        } else {
            _ElementUtilities.addClass(this._element, "win-voice-voicemodeactive");
            this._vuiActive = true;
        }
    }

    private _handleScroll(ev: MouseEvent) {
        if (this._scrollingContainer.scrollTop >= THRESHOLD_TO_SHOW_TOP_ARROW) {
            this._canScrollUp = true;
        } else {
            this._canScrollUp = false;
        }
        if (this._scrollingContainer.scrollTop >= (this._scrollingContainer.scrollHeight - this._element.clientHeight)) {
            this._canScrollDown = false;
        } else {
            this._canScrollDown = true;
        }

        // Note: We remove the classes in order so we can avoid labels flashing
        if (!this._canScrollUp && !this._canScrollDown) {
            _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-down");
            _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-up");

            _ElementUtilities.addClass(this._vuiPageUpElement, "win-voice-disableoverride");
            _ElementUtilities.addClass(this._vuiPageDownElement, "win-voice-disableoverride");
        } else if (!this._canScrollUp && this._canScrollDown) {
            _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disableoverride");
            _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disableoverride");

            _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-up");
            _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-down");

            _ElementUtilities.addClass(this._vuiPageUpElement, "win-voice-disabledlabel");
            _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disabledlabel");
        } else if (this._canScrollUp && !this._canScrollDown) {
            _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-up");
            _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-down");

            _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disabledlabel");
            _ElementUtilities.addClass(this._vuiPageDownElement, "win-voice-disabledlabel");

            _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disableoverride");
            _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disableoverride");
        } else {
            _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-up");
            _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-down");

            _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disabledlabel");
            _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disabledlabel");

            _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disableoverride");
            _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disableoverride");
        }
    }
}


text:
{% extends "app/layout.html" %}

{% block content %}

{{ ministry.name }}

{{ ministry.description }}

Integrantes:

            {% for member in ministry.members.all %}

{{ member.name }}

{{ member.description }}

            {% endfor %}

{% endblock %}


text:
/**************************************************************************************************/
/*                                                                                */
/* Module  : GOTOMOVEDIALOG.C                                                                     */
/* Purpose : This module implements the goto move dialog.                                         */
/*                                                                                */
/**************************************************************************************************/

/*
Copyright (c) 2011, Ole K. Christensen
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

¥ Redistributions of source code must retain the above copyright notice, this list of conditions
  and the following disclaimer.

¥ Redistributions in binary form must reproduce the above copyright notice, this list of conditions
  and the following disclaimer in the documentation and/or other materials provided with the
  distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "GotoMoveDialog.h"

class CGotoMoveDialog : public CDialog
{
public:
   CGotoMoveDialog (CRect frame, COLOUR initPlayer, INT initMoveNo, INT lastMove);
   virtual void HandlePushButton (CPushButton *ctrl);

   INT min, max;
   LONG move;
   CEditControl *cedit_Move;
};

/**************************************************************************************************/
/*                                                                                */
/*                                      RUN GAME INFO DIALOG                                      */
/*                                                                                */
/**************************************************************************************************/

INT GotoMoveDialog (COLOUR initPlayer, INT initMoveNo, INT lastMove)
{
   CRect frame(0,0,290,70);
   if (RunningOSX()) frame.right += 65, frame.bottom += 30;
   theApp->CentralizeRect(&frame);

   CGotoMoveDialog *dialog = new CGotoMoveDialog(frame, initPlayer, initMoveNo, lastMove);
   dialog->Run();
   INT move = (dialog->reply == cdialogReply_OK ? dialog->move : -1);
   delete dialog;

   return (move >= 1 ? Max(0, (move - initMoveNo)*2 - (initPlayer >> 4)) : -1);
} /* PromotionDialog */

/**************************************************************************************************/
/*                                                                                */
/*                                     CONSTRUCTOR/DESTRUCTOR                                     */
/*                                                                                */
/**************************************************************************************************/

/*----------------------------------------- Constructor ------------------------------------------*/

CGotoMoveDialog::CGotoMoveDialog (CRect frame, COLOUR initPlayer, INT initMoveNo, INT lastMove)
 : CDialog (nil, "Goto Move", frame, cdialogType_Modal)
{
   CRect inner = InnerRect();

   if (initPlayer == black) lastMove--;
   min = initMoveNo;
   max = initMoveNo + (lastMove + (initPlayer >> 4))/2;

   CRect r = inner;
   CHAR prompt[100];
   r.bottom = r.top + 2*controlHeight_Text;
   r.right -= 48;
   Format(prompt, "Enter a move number between %d and %d", min, max);
   new CTextControl(this, prompt, r);

   r = inner;
   r.bottom = r.top + controlHeight_Edit;
   r.left = r.right - 43;
   if (! RunningOSX()) r.Offset(0, -3);
   cedit_Move = new CEditControl(this, "", r, 3);

   cbutton_Cancel   = new CPushButton(this, "Cancel", CancelRect());
   cbutton_Default  = new CPushButton(this, "OK", DefaultRect());
   SetDefaultButton(cbutton_Default);

   CurrControl(cedit_Move);
} /* CGotoMoveDialog::CGotoMoveDialog */

/**************************************************************************************************/
/*                                                                                */
/*                                         EVENT HANDLING                                         */
/*                                                                                */
/**************************************************************************************************/

void CGotoMoveDialog::HandlePushButton (CPushButton *ctrl)
{
   // Perform validation if user clicks "OK":

   if (ctrl == cbutton_Default)
   {
      if (! cedit_Move->GetLong(&move) || move < min || move > max)
      {  CurrControl(cedit_Move);
         CHAR s[100]; Format(s, "Please enter a valid move number between %d and %d...", min, max);
         NoteDialog(this, "Invalid Move Number", s, cdialogIcon_Error);
         return;
      }
   }

   // Validation succeeded (or user pressed "Cancel") -> Call inherited function:
   CDialog::HandlePushButton(ctrl);
} /* CGotoMoveDialog::HandlePushButton */


text:
<?php namespace App\Domains;

use Symfony\Component\Yaml\Yaml;

class FileDirectoryAstRepository implements \App\Interpreter\AstRepository
{
    private static $asts = [];
    private $ast_path;

    public function __construct()
    {
        $this->ast_path = 'app/Domains/Ecommerce/AST/';
    }

    public function fetch($id)
    {
        if (count(self::$asts) == 0) {
            $this->preload_asts();
        }
        return self::$asts[$id];
    }

    public function store($ast)
    {
        if (isset(self::$asts[$ast->id])) {
            throw new \Exception("ID '$ast->id' is already in use.");
        }
        self::$asts[$ast->id] = $ast;
    }

    protected function load_ast($ast_file)
    {
        $file_path = $this->ast_path.$ast_file;
        $full_file_path = base_path($file_path);

        if (!is_file($full_file_path)) {
            throw new \Exception("Cannot find AST '$ast_file'");
        }
        $yaml = file_get_contents($full_file_path);
        $ast = Yaml::parse($yaml, Yaml::PARSE_OBJECT_FOR_MAP);
        return $ast;
    }

    protected function preload_asts()
    {
        $folder_path = base_path($this->ast_path);

        $asts_files = array_diff(scandir($folder_path), array('..', '.'));

        foreach ($asts_files as $ast_file) {
            $ast = $this->load_ast($ast_file);
            if (isset($ast->id)) {
                $this->store($ast);
            }
        }
    }
}


text:
using System.Web.Mvc;

namespace $rootnamespace$.Controllers
{
    //[Admin] or [Themed] for a default layout. Can be placed on the controller or methods
    public class $safeitemname$ : Controller
    {
        private readonly I$fileinputname$WorkerService _workerService;

        public $safeitemname$(I$fileinputname$WorkerService workerService)
        {
            _workerService = workerService;
        }
    }
}