text:
import Protocol from 'devtools-protocol';
import expect from 'expect';
import fs from 'fs';
import os from 'os';
import path from 'path';
import {BrowserFetcher, TimeoutError} from 'puppeteer';
import {Page} from 'puppeteer-core/internal/api/Page.js';
import rimraf from 'rimraf';
import sinon from 'sinon';
import {TLSSocket} from 'tls';
import {promisify} from 'util';
import {getTestState, itOnlyRegularInstall} from './mocha-utils.js';
import utils from './utils.js';

const mkdtempAsync = promisify(fs.mkdtemp);
const readFileAsync = promisify(fs.readFile);
const rmAsync = promisify(rimraf);
const statAsync = promisify(fs.stat);
const writeFileAsync = promisify(fs.writeFile);

const TMP_FOLDER = path.join(os.tmpdir(), 'pptr_tmp_folder-');
const FIREFOX_TIMEOUT = 30 * 1000;

describe('Launcher specs', function () {
  if (getTestState().isFirefox) {
    this.timeout(FIREFOX_TIMEOUT);
  }

  describe('Puppeteer', function () {
    describe('BrowserFetcher', function () {
      it('should download and extract chrome linux binary', async () => {
        const {server} = getTestState();

        const downloadsFolder = await mkdtempAsync(TMP_FOLDER);
        const browserFetcher = new BrowserFetcher({
          platform: 'linux',
          path: downloadsFolder,
          host: server.PREFIX,
        });
        const expectedRevision = '123456';
        let revisionInfo = browserFetcher.revisionInfo(expectedRevision);
        server.setRoute(
          revisionInfo.url.substring(server.PREFIX.length),
          (req, res) => {
            server.serveFile(req, res, '/chromium-linux.zip');
          }
        );

        expect(revisionInfo.local).toBe(false);
        expect(browserFetcher.platform()).toBe('linux');
        expect(browserFetcher.product()).toBe('chrome');
        expect(!!browserFetcher.host()).toBe(true);
        expect(await browserFetcher.canDownload('100000')).toBe(false);
        expect(await browserFetcher.canDownload(expectedRevision)).toBe(true);

        revisionInfo = (await browserFetcher.download(expectedRevision))!;
        expect(revisionInfo.local).toBe(true);
        expect(await readFileAsync(revisionInfo.executablePath, 'utf8')).toBe(
          'LINUX BINARY\n'
        );
        const expectedPermissions = os.platform() === 'win32' ? 0o666 : 0o755;
        expect(
          (await statAsync(revisionInfo.executablePath)).mode & 0o777
        ).toBe(expectedPermissions);
        expect(await browserFetcher.localRevisions()).toEqual([
          expectedRevision,
        ]);
        await browserFetcher.remove(expectedRevision);
        expect(await browserFetcher.localRevisions()).toEqual([]);
        await rmAsync(downloadsFolder);
      });
      it('should download and extract firefox linux binary', async () => {
        const {server} = getTestState();

        const downloadsFolder = await mkdtempAsync(TMP_FOLDER);
        const browserFetcher = new BrowserFetcher({
          platform: 'linux',
          path: downloadsFolder,
          host: server.PREFIX,
          product: 'firefox',
        });
        const expectedVersion = '75.0a1';
        let revisionInfo = browserFetcher.revisionInfo(expectedVersion);
        server.setRoute(
          revisionInfo.url.substring(server.PREFIX.length),
          (req, res) => {
            server.serveFile(
              req,
              res,
              `/firefox-${expectedVersion}.en-US.linux-x86_64.tar.bz2`
            );
          }
        );

        expect(revisionInfo.local).toBe(false);
        expect(browserFetcher.platform()).toBe('linux');
        expect(browserFetcher.product()).toBe('firefox');
        expect(await browserFetcher.canDownload('100000')).toBe(false);
        expect(await browserFetcher.canDownload(expectedVersion)).toBe(true);

        revisionInfo = (await browserFetcher.download(expectedVersion))!;
        expect(revisionInfo.local).toBe(true);
        expect(await readFileAsync(revisionInfo.executablePath, 'utf8')).toBe(
          'FIREFOX LINUX BINARY\n'
        );
        const expectedPermissions = os.platform() === 'win32' ? 0o666 : 0o755;
        expect(
          (await statAsync(revisionInfo.executablePath)).mode & 0o777
        ).toBe(expectedPermissions);
        expect(await browserFetcher.localRevisions()).toEqual([
          expectedVersion,
        ]);
        await browserFetcher.remove(expectedVersion);
        expect(await browserFetcher.localRevisions()).toEqual([]);
        await rmAsync(downloadsFolder);
      });
    });

    describe('Browser.disconnect', function () {
      it('should reject navigation when browser closes', async () => {
        const {server, puppeteer, defaultBrowserOptions} = getTestState();
        server.setRoute('/one-style.css', () => {});
        const browser = await puppeteer.launch(defaultBrowserOptions);
        const remote = await puppeteer.connect({
          browserWSEndpoint: browser.wsEndpoint(),
        });
        const page = await remote.newPage();
        const navigationPromise = page
          .goto(server.PREFIX + '/one-style.html', {timeout: 60000})
          .catch(error_ => {
            return error_;
          });
        await server.waitForRequest('/one-style.css');
        remote.disconnect();
        const error = await navigationPromise;
        expect(
          [
            'Navigation failed because browser has disconnected!',
            'Protocol error (Page.navigate): Target closed.',
          ].includes(error.message)
        ).toBeTruthy();
        await browser.close();
      });
      it('should reject waitForSelector when browser closes', async () => {
        const {server, puppeteer, defaultBrowserOptions} = getTestState();

        server.setRoute('/empty.html', () => {});
        const browser = await puppeteer.launch(defaultBrowserOptions);
        const remote = await puppeteer.connect({
          browserWSEndpoint: browser.wsEndpoint(),
        });
        const page = await remote.newPage();
        const watchdog = page
          .waitForSelector('div', {timeout: 60000})
          .catch(error_ => {
            return error_;
          });
        remote.disconnect();
        const error = await watchdog;
        expect(error.message).toContain('Protocol error');
        await browser.close();
      });
    });
    describe('Browser.close', function () {
      it('should terminate network waiters', async () => {
        const {server, puppeteer, defaultBrowserOptions} = getTestState();

        const browser = await puppeteer.launch(defaultBrowserOptions);
        const remote = await puppeteer.connect({
          browserWSEndpoint: browser.wsEndpoint(),
        });
        const newPage = await remote.newPage();
        const results = await Promise.all([
          newPage.waitForRequest(server.EMPTY_PAGE).catch(error => {
            return error;
          }),
          newPage.waitForResponse(server.EMPTY_PAGE).catch(error => {
            return error;
          }),
          browser.close(),
        ]);
        for (let i = 0; i < 2; i++) {
          const message = results[i].message;
          expect(message).toContain('Target closed');
          expect(message).not.toContain('Timeout');
        }
        await browser.close();
      });
    });
    describe('Puppeteer.launch', function () {
      it('can launch and close the browser', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();
        const browser = await puppeteer.launch(defaultBrowserOptions);
        await browser.close();
      });
      it('should reject all promises when browser is closed', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();
        const browser = await puppeteer.launch(defaultBrowserOptions);
        const page = await browser.newPage();
        let error!: Error;
        const neverResolves = page
          .evaluate(() => {
            return new Promise(() => {});
          })
          .catch(error_ => {
            return (error = error_);
          });
        await browser.close();
        await neverResolves;
        expect(error.message).toContain('Protocol error');
      });
      it('should reject if executable path is invalid', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();

        let waitError!: Error;
        const options = Object.assign({}, defaultBrowserOptions, {
          executablePath: 'random-invalid-path',
        });
        await puppeteer.launch(options).catch(error => {
          return (waitError = error);
        });
        expect(waitError.message).toContain('Failed to launch');
      });
      it('userDataDir option', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();

        const userDataDir = await mkdtempAsync(TMP_FOLDER);
        const options = Object.assign({userDataDir}, defaultBrowserOptions);
        const browser = await puppeteer.launch(options);
        // Open a page to make sure its functional.
        await browser.newPage();
        expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
        await browser.close();
        expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
        // This might throw. See https://github.com/puppeteer/puppeteer/issues/2778
        await rmAsync(userDataDir).catch(() => {});
      });
      it('tmp profile should be cleaned up', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();

        // Set a custom test tmp dir so that we can validate that
        // the profile dir is created and then cleaned up.
        const testTmpDir = await fs.promises.mkdtemp(
          path.join(os.tmpdir(), 'puppeteer_test_chrome_profile-')
        );
        const oldTmpDir = puppeteer.configuration.temporaryDirectory;
        puppeteer.configuration.temporaryDirectory = testTmpDir;

        // Path should be empty before starting the browser.
        expect(fs.readdirSync(testTmpDir).length).toEqual(0);
        const browser = await puppeteer.launch(defaultBrowserOptions);

        // One profile folder should have been created at this moment.
        const profiles = fs.readdirSync(testTmpDir);
        expect(profiles.length).toEqual(1);
        expect(profiles[0]?.startsWith('puppeteer_dev_chrome_profile-')).toBe(
          true
        );

        // Open a page to make sure its functional.
        await browser.newPage();
        await browser.close();
        // Profile should be deleted after closing the browser
        expect(fs.readdirSync(testTmpDir).length).toEqual(0);

        // Restore env var
        puppeteer.configuration.temporaryDirectory = oldTmpDir;
      });
      it('userDataDir option restores preferences', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();

        const userDataDir = await mkdtempAsync(TMP_FOLDER);

        const prefsJSPath = path.join(userDataDir, 'prefs.js');
        const prefsJSContent = 'user_pref("browser.warnOnQuit", true)';
        await writeFileAsync(prefsJSPath, prefsJSContent);

        const options = Object.assign({userDataDir}, defaultBrowserOptions);
        const browser = await puppeteer.launch(options);
        // Open a page to make sure its functional.
        await browser.newPage();
        expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
        await browser.close();
        expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);

        expect(await readFileAsync(prefsJSPath, 'utf8')).toBe(prefsJSContent);

        // This might throw. See https://github.com/puppeteer/puppeteer/issues/2778
        await rmAsync(userDataDir).catch(() => {});
      });
      it('userDataDir argument', async () => {
        const {isChrome, puppeteer, defaultBrowserOptions} = getTestState();

        const userDataDir = await mkdtempAsync(TMP_FOLDER);
        const options = Object.assign({}, defaultBrowserOptions);
        if (isChrome) {
          options.args = [
            ...(defaultBrowserOptions.args || []),
            `--user-data-dir=${userDataDir}`,
          ];
        } else {
          options.args = [
            ...(defaultBrowserOptions.args || []),
            '-profile',
            userDataDir,
          ];
        }
        const browser = await puppeteer.launch(options);
        expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
        await browser.close();
        expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
        // This might throw. See https://github.com/puppeteer/puppeteer/issues/2778
        await rmAsync(userDataDir).catch(() => {});
      });
      it('userDataDir argument with non-existent dir', async () => {
        const {isChrome, puppeteer, defaultBrowserOptions} = getTestState();

        const userDataDir = await mkdtempAsync(TMP_FOLDER);
        await rmAsync(userDataDir);
        const options = Object.assign({}, defaultBrowserOptions);
        if (isChrome) {
          options.args = [
            ...(defaultBrowserOptions.args || []),
            `--user-data-dir=${userDataDir}`,
          ];
        } else {
          options.args = [
            ...(defaultBrowserOptions.args || []),
            '-profile',
            userDataDir,
          ];
        }
        const browser = await puppeteer.launch(options);
        expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
        await browser.close();
        expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
        // This might throw. See https://github.com/puppeteer/puppeteer/issues/2778
        await rmAsync(userDataDir).catch(() => {});
      });
      it('userDataDir option should restore state', async () => {
        const {server, puppeteer, defaultBrowserOptions} = getTestState();

        const userDataDir = await mkdtempAsync(TMP_FOLDER);
        const options = Object.assign({userDataDir}, defaultBrowserOptions);
        const browser = await puppeteer.launch(options);
        const page = await browser.newPage();
        await page.goto(server.EMPTY_PAGE);
        await page.evaluate(() => {
          return (localStorage['hey'] = 'hello');
        });
        await browser.close();

        const browser2 = await puppeteer.launch(options);
        const page2 = await browser2.newPage();
        await page2.goto(server.EMPTY_PAGE);
        expect(
          await page2.evaluate(() => {
            return localStorage['hey'];
          })
        ).toBe('hello');
        await browser2.close();
        // This might throw. See https://github.com/puppeteer/puppeteer/issues/2778
        await rmAsync(userDataDir).catch(() => {});
      });
      it('userDataDir option should restore cookies', async () => {
        const {server, puppeteer, defaultBrowserOptions} = getTestState();

        const userDataDir = await mkdtempAsync(TMP_FOLDER);
        const options = Object.assign({userDataDir}, defaultBrowserOptions);
        const browser = await puppeteer.launch(options);
        const page = await browser.newPage();
        await page.goto(server.EMPTY_PAGE);
        await page.evaluate(() => {
          return (document.cookie =
            'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT');
        });
        await browser.close();

        const browser2 = await puppeteer.launch(options);
        const page2 = await browser2.newPage();
        await page2.goto(server.EMPTY_PAGE);
        expect(
          await page2.evaluate(() => {
            return document.cookie;
          })
        ).toBe('doSomethingOnlyOnce=true');
        await browser2.close();
        // This might throw. See https://github.com/puppeteer/puppeteer/issues/2778
        await rmAsync(userDataDir).catch(() => {});
      });
      it('should return the default arguments', async () => {
        const {isChrome, isFirefox, puppeteer} = getTestState();

        if (isChrome) {
          expect(puppeteer.defaultArgs()).toContain('--no-first-run');
          expect(puppeteer.defaultArgs()).toContain('--headless');
          expect(puppeteer.defaultArgs({headless: false})).not.toContain(
            '--headless'
          );
          expect(puppeteer.defaultArgs({userDataDir: 'foo'})).toContain(
            `--user-data-dir=${path.resolve('foo')}`
          );
        } else if (isFirefox) {
          expect(puppeteer.defaultArgs()).toContain('--headless');
          expect(puppeteer.defaultArgs()).toContain('--no-remote');
          if (os.platform() === 'darwin') {
            expect(puppeteer.defaultArgs()).toContain('--foreground');
          } else {
            expect(puppeteer.defaultArgs()).not.toContain('--foreground');
          }
          expect(puppeteer.defaultArgs({headless: false})).not.toContain(
            '--headless'
          );
          expect(puppeteer.defaultArgs({userDataDir: 'foo'})).toContain(
            '--profile'
          );
          expect(puppeteer.defaultArgs({userDataDir: 'foo'})).toContain('foo');
        } else {
          expect(puppeteer.defaultArgs()).toContain('-headless');
          expect(puppeteer.defaultArgs({headless: false})).not.toContain(
            '-headless'
          );
          expect(puppeteer.defaultArgs({userDataDir: 'foo'})).toContain(
            '-profile'
          );
          expect(puppeteer.defaultArgs({userDataDir: 'foo'})).toContain(
            path.resolve('foo')
          );
        }
      });
      it('should report the correct product', async () => {
        const {isChrome, isFirefox, puppeteer} = getTestState();
        if (isChrome) {
          expect(puppeteer.product).toBe('chrome');
        } else if (isFirefox) {
          expect(puppeteer.product).toBe('firefox');
        }
      });
      it('should work with no default arguments', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();
        const options = Object.assign({}, defaultBrowserOptions);
        options.ignoreDefaultArgs = true;
        const browser = await puppeteer.launch(options);
        const page = await browser.newPage();
        expect(await page.evaluate('11 * 11')).toBe(121);
        await page.close();
        await browser.close();
      });
      it('should filter out ignored default arguments in Chrome', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();
        // Make sure we launch with `--enable-automation` by default.
        const defaultArgs = puppeteer.defaultArgs();
        const browser = await puppeteer.launch(
          Object.assign({}, defaultBrowserOptions, {
            // Ignore first and third default argument.
            ignoreDefaultArgs: [defaultArgs[0]!, defaultArgs[2]],
          })
        );
        const spawnargs = browser.process()!.spawnargs;
        if (!spawnargs) {
          throw new Error('spawnargs not present');
        }
        expect(spawnargs.indexOf(defaultArgs[0]!)).toBe(-1);
        expect(spawnargs.indexOf(defaultArgs[1]!)).not.toBe(-1);
        expect(spawnargs.indexOf(defaultArgs[2]!)).toBe(-1);
        await browser.close();
      });
      it('should filter out ignored default argument in Firefox', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();

        const defaultArgs = puppeteer.defaultArgs();
        const browser = await puppeteer.launch(
          Object.assign({}, defaultBrowserOptions, {
            // Only the first argument is fixed, others are optional.
            ignoreDefaultArgs: [defaultArgs[0]!],
          })
        );
        const spawnargs = browser.process()!.spawnargs;
        if (!spawnargs) {
          throw new Error('spawnargs not present');
        }
        expect(spawnargs.indexOf(defaultArgs[0]!)).toBe(-1);
        expect(spawnargs.indexOf(defaultArgs[1]!)).not.toBe(-1);
        await browser.close();
      });
      it('should have default URL when launching browser', async function () {
        const {defaultBrowserOptions, puppeteer} = getTestState();
        const browser = await puppeteer.launch(defaultBrowserOptions);
        const pages = (await browser.pages()).map(page => {
          return page.url();
        });
        expect(pages).toEqual(['about:blank']);
        await browser.close();
      });
      it('should have custom URL when launching browser', async () => {
        const {server, puppeteer, defaultBrowserOptions} = getTestState();

        const options = Object.assign({}, defaultBrowserOptions);
        options.args = [server.EMPTY_PAGE].concat(options.args || []);
        const browser = await puppeteer.launch(options);
        const pages = await browser.pages();
        expect(pages.length).toBe(1);
        const page = pages[0]!;
        if (page.url() !== server.EMPTY_PAGE) {
          await page.waitForNavigation();
        }
        expect(page.url()).toBe(server.EMPTY_PAGE);
        await browser.close();
      });
      it('should pass the timeout parameter to browser.waitForTarget', async () => {
        const {puppeteer, defaultBrowserOptions} = getTestState();
        const options = Object.assign({}, defaultBrowserOptions, {
          timeout: 1,
        });
        let error!: Error;
        await puppeteer.launch(options).catch(error_ => {
          return (error = error_);
        });
        expect(error).toBeInstanceOf(TimeoutError);
      });
      it('should work with timeout = 0', async () => {
        const {puppeteer, defaultBrowserOptions} = getTestState();
        const options = Object.assign({}, defaultBrowserOptions, {
          timeout: 0,
        });
        const browser = await puppeteer.launch(options);
        await browser.close();
      });
      it('should set the default viewport', async () => {
        const {puppeteer, defaultBrowserOptions} = getTestState();
        const options = Object.assign({}, defaultBrowserOptions, {
          defaultViewport: {
            width: 456,
            height: 789,
          },
        });
        const browser = await puppeteer.launch(options);
        const page = await browser.newPage();
        expect(await page.evaluate('window.innerWidth')).toBe(456);
        expect(await page.evaluate('window.innerHeight')).toBe(789);
        await browser.close();
      });
      it('should disable the default viewport', async () => {
        const {puppeteer, defaultBrowserOptions} = getTestState();
        const options = Object.assign({}, defaultBrowserOptions, {
          defaultViewport: null,
        });
        const browser = await puppeteer.launch(options);
        const page = await browser.newPage();
        expect(page.viewport()).toBe(null);
        await browser.close();
      });
      it('should take fullPage screenshots when defaultViewport is null', async () => {
        const {server, puppeteer, defaultBrowserOptions} = getTestState();

        const options = Object.assign({}, defaultBrowserOptions, {
          defaultViewport: null,
        });
        const browser = await puppeteer.launch(options);
        const page = await browser.newPage();
        await page.goto(server.PREFIX + '/grid.html');
        const screenshot = await page.screenshot({
          fullPage: true,
        });
        expect(screenshot).toBeInstanceOf(Buffer);
        await browser.close();
      });
      it('should set the debugging port', async () => {
        const {puppeteer, defaultBrowserOptions} = getTestState();

        const options = Object.assign({}, defaultBrowserOptions, {
          defaultViewport: null,
          debuggingPort: 9999,
        });
        const browser = await puppeteer.launch(options);
        const url = new URL(browser.wsEndpoint());
        await browser.close();
        expect(url.port).toBe('9999');
      });
      it('should not allow setting debuggingPort and pipe', async () => {
        const {puppeteer, defaultBrowserOptions} = getTestState();

        const options = Object.assign({}, defaultBrowserOptions, {
          defaultViewport: null,
          debuggingPort: 9999,
          pipe: true,
        });

        let error!: Error;
        await puppeteer.launch(options).catch(error_ => {
          return (error = error_);
        });
        expect(error.message).toContain('either pipe or debugging port');
      });
      it('should launch Chrome properly with --no-startup-window and waitForInitialPage=false', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();
        const options = {
          waitForInitialPage: false,
          // This is needed to prevent Puppeteer from adding an initial blank page.
          // See also https://github.com/puppeteer/puppeteer/blob/ad6b736039436fcc5c0a262e5b575aa041427be3/src/node/Launcher.ts#L200
          ignoreDefaultArgs: true,
          ...defaultBrowserOptions,
          args: ['--no-startup-window'],
        };
        const browser = await puppeteer.launch(options);
        const pages = await browser.pages();
        expect(pages.length).toBe(0);
        await browser.close();
      });
    });

    describe('Puppeteer.launch', function () {
      itOnlyRegularInstall('should be able to launch Chrome', async () => {
        const {puppeteer} = getTestState();
        const browser = await puppeteer.launch({product: 'chrome'});
        const userAgent = await browser.userAgent();
        await browser.close();
        expect(userAgent).toContain('Chrome');
      });

      it('should be able to launch Firefox', async function () {
        this.timeout(FIREFOX_TIMEOUT);
        const {puppeteer} = getTestState();
        const browser = await puppeteer.launch({product: 'firefox'});
        const userAgent = await browser.userAgent();
        await browser.close();
        expect(userAgent).toContain('Firefox');
      });
    });

    describe('Puppeteer.connect', function () {
      it('should be able to connect multiple times to the same browser', async () => {
        const {puppeteer, defaultBrowserOptions} = getTestState();

        const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
        const otherBrowser = await puppeteer.connect({
          browserWSEndpoint: originalBrowser.wsEndpoint(),
        });
        const page = await otherBrowser.newPage();
        expect(
          await page.evaluate(() => {
            return 7 * 8;
          })
        ).toBe(56);
        otherBrowser.disconnect();

        const secondPage = await originalBrowser.newPage();
        expect(
          await secondPage.evaluate(() => {
            return 7 * 6;
          })
        ).toBe(42);
        await originalBrowser.close();
      });
      it('should be able to close remote browser', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();

        const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
        const remoteBrowser = await puppeteer.connect({
          browserWSEndpoint: originalBrowser.wsEndpoint(),
        });
        await Promise.all([
          utils.waitEvent(originalBrowser, 'disconnected'),
          remoteBrowser.close(),
        ]);
      });
      it('should be able to connect to a browser with no page targets', async () => {
        const {defaultBrowserOptions, puppeteer} = getTestState();

        const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
        const pages = await originalBrowser.pages();
        await Promise.all(
          pages.map(page => {
            return page.close();
          })
        );
        const remoteBrowser = await puppeteer.connect({
          browserWSEndpoint: originalBrowser.wsEndpoint(),
        });
        await Promise.all([
          utils.waitEvent(originalBrowser, 'disconnected'),
          remoteBrowser.close(),
        ]);
      });
      it('should support ignoreHTTPSErrors option', async () => {
        const {httpsServer, puppeteer, defaultBrowserOptions} = getTestState();

        const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
        const browserWSEndpoint = originalBrowser.wsEndpoint();

        const browser = await puppeteer.connect({
          browserWSEndpoint,
          ignoreHTTPSErrors: true,
        });
        const page = await browser.newPage();
        let error!: Error;
        const [serverRequest, response] = await Promise.all([
          httpsServer.waitForRequest('/empty.html'),
          page.goto(httpsServer.EMPTY_PAGE).catch(error_ => {
            return (error = error_);
          }),
        ]);
        expect(error).toBeUndefined();
        expect(response.ok()).toBe(true);
        expect(response.securityDetails()).toBeTruthy();
        const protocol = (serverRequest.socket as TLSSocket)
          .getProtocol()!
          .replace('v', ' ');
        expect(response.securityDetails().protocol()).toBe(protocol);
        await page.close();
        await browser.close();
      });

      it('should support targetFilter option in puppeteer.launch', async () => {
        const {puppeteer, defaultBrowserOptions} = getTestState();
        const browser = await puppeteer.launch({
          ...defaultBrowserOptions,
          targetFilter: target => {
            return target.type !== 'page';
          },
          waitForInitialPage: false,
        });
        try {
          const targets = browser.targets();
          expect(targets.length).toEqual(1);
          expect(
            targets.find(target => {
              return target.type() === 'page';
            })
          ).toBeUndefined();
        } finally {
          await browser.close();
        }
      });

      // @see https://github.com/puppeteer/puppeteer/issues/4197
      it('should support targetFilter option', async () => {
        const {server, puppeteer, defaultBrowserOptions} = getTestState();

        const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
        const browserWSEndpoint = originalBrowser.wsEndpoint();

        const page1 = await originalBrowser.newPage();
        await page1.goto(server.EMPTY_PAGE);

        const page2 = await originalBrowser.newPage();
        await page2.goto(server.EMPTY_PAGE + '?should-be-ignored');

        const browser = await puppeteer.connect({
          browserWSEndpoint,
          targetFilter: (targetInfo: Protocol.Target.TargetInfo) => {
            return !targetInfo.url?.includes('should-be-ignored');
          },
        });

        const pages = await browser.pages();

        await page2.close();
        await page1.close();
        await browser.disconnect();
        await originalBrowser.close();

        expect(
          pages
            .map((p: Page) => {
              return p.url();
            })
            .sort()
        ).toEqual(['about:blank', server.EMPTY_PAGE]);
      });
      it('should be able to reconnect to a disconnected browser', async () => {
        const {server, puppeteer, defaultBrowserOptions} = getTestState();

        const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
        const browserWSEndpoint = originalBrowser.wsEndpoint();
        const page = await originalBrowser.newPage();
        await page.goto(server.PREFIX + '/frames/nested-frames.html');
        originalBrowser.disconnect();

        const browser = await puppeteer.connect({browserWSEndpoint});
        const pages = await browser.pages();
        const restoredPage = pages.find(page => {
          return page.url() === server.PREFIX + '/frames/nested-frames.html';
        })!;
        expect(utils.dumpFrames(restoredPage.mainFrame())).toEqual([
          'http://localhost:<PORT>/frames/nested-frames.html',
          '    http://localhost:<PORT>/frames/two-frames.html (2frames)',
          '        http://localhost:<PORT>/frames/frame.html (uno)',
          '        http://localhost:<PORT>/frames/frame.html (dos)',
          '    http://localhost:<PORT>/frames/frame.html (aframe)',
        ]);
        expect(
          await restoredPage.evaluate(() => {
            return 7 * 8;
          })
        ).toBe(56);
        await browser.close();
      });
      // @see https://github.com/puppeteer/puppeteer/issues/4197#issuecomment-481793410
      it('should be able to connect to the same page simultaneously', async () => {
        const {puppeteer, defaultBrowserOptions} = getTestState();

        const browserOne = await puppeteer.launch(defaultBrowserOptions);
        const browserTwo = await puppeteer.connect({
          browserWSEndpoint: browserOne.wsEndpoint(),
        });
        const [page1, page2] = await Promise.all([
          new Promise<Page>(x => {
            return browserOne.once('targetcreated', target => {
              return x(target.page());
            });
          }),
          browserTwo.newPage(),
        ]);
        expect(
          await page1.evaluate(() => {
            return 7 * 8;
          })
        ).toBe(56);
        expect(
          await page2.evaluate(() => {
            return 7 * 6;
          })
        ).toBe(42);
        await browserOne.close();
      });
      it('should be able to reconnect', async () => {
        const {puppeteer, server, defaultBrowserOptions} = getTestState();
        const browserOne = await puppeteer.launch(defaultBrowserOptions);
        const browserWSEndpoint = browserOne.wsEndpoint();
        const pageOne = await browserOne.newPage();
        await pageOne.goto(server.EMPTY_PAGE);
        browserOne.disconnect();

        const browserTwo = await puppeteer.connect({
          browserWSEndpoint,
        });
        const pages = await browserTwo.pages();
        const pageTwo = pages.find(page => {
          return page.url() === server.EMPTY_PAGE;
        })!;
        await pageTwo.reload();
        const bodyHandle = await pageTwo.waitForSelector('body', {
          timeout: 10000,
        });
        await bodyHandle!.dispose();
        await browserTwo.close();
      });
    });
    describe('Puppeteer.executablePath', function () {
      itOnlyRegularInstall('should work', async () => {
        const {puppeteer} = getTestState();

        const executablePath = puppeteer.executablePath();
        expect(fs.existsSync(executablePath)).toBe(true);
        expect(fs.realpathSync(executablePath)).toBe(executablePath);
      });
      it('returns executablePath for channel', () => {
        const {puppeteer} = getTestState();

        const executablePath = puppeteer.executablePath('chrome');
        expect(executablePath).toBeTruthy();
      });
      describe('when executable path is configured', () => {
        const sandbox = sinon.createSandbox();

        beforeEach(() => {
          const {puppeteer} = getTestState();
          sandbox
            .stub(puppeteer.configuration, 'executablePath')
            .value('SOME_CUSTOM_EXECUTABLE');
        });

        afterEach(() => {
          sandbox.restore();
        });

        it('its value is used', async () => {
          const {puppeteer} = getTestState();
          try {
            puppeteer.executablePath();
          } catch (error) {
            expect((error as Error).message).toContain(
              'SOME_CUSTOM_EXECUTABLE'
            );
          }
        });
      });

      describe('when the product is chrome, platform is not darwin, and arch is arm64', () => {
        describe('and the executable exists', () => {
          it('returns /usr/bin/chromium-browser', async () => {
            const {puppeteer} = getTestState();
            const osPlatformStub = sinon.stub(os, 'platform').returns('linux');
            const osArchStub = sinon.stub(os, 'arch').returns('arm64');
            const fsExistsStub = sinon.stub(fs, 'existsSync');
            fsExistsStub.withArgs('/usr/bin/chromium-browser').returns(true);

            const executablePath = puppeteer.executablePath();

            expect(executablePath).toEqual('/usr/bin/chromium-browser');

            osPlatformStub.restore();
            osArchStub.restore();
            fsExistsStub.restore();
          });
          describe('and the executable path is configured', () => {
            const sandbox = sinon.createSandbox();

            beforeEach(() => {
              const {puppeteer} = getTestState();
              sandbox
                .stub(puppeteer.configuration, 'executablePath')
                .value('SOME_CUSTOM_EXECUTABLE');
            });

            afterEach(() => {
              sandbox.restore();
            });

            it('its value is used', async () => {
              const {puppeteer} = getTestState();
              try {
                puppeteer.executablePath();
              } catch (error) {
                expect((error as Error).message).toContain(
                  'SOME_CUSTOM_EXECUTABLE'
                );
              }
            });
          });
        });
        describe('and the executable does not exist', () => {
          it('does not return /usr/bin/chromium-browser', async () => {
            const {puppeteer} = getTestState();
            const osPlatformStub = sinon.stub(os, 'platform').returns('linux');
            const osArchStub = sinon.stub(os, 'arch').returns('arm64');
            const fsExistsStub = sinon.stub(fs, 'existsSync');
            fsExistsStub.withArgs('/usr/bin/chromium-browser').returns(false);

            expect(() => {
              return puppeteer.executablePath();
            }).toThrowError();

            osPlatformStub.restore();
            osArchStub.restore();
            fsExistsStub.restore();
          });
        });
      });
    });
  });

  describe('Browser target events', function () {
    it('should work', async () => {
      const {server, puppeteer, defaultBrowserOptions} = getTestState();

      const browser = await puppeteer.launch(defaultBrowserOptions);
      const events: string[] = [];
      browser.on('targetcreated', () => {
        return events.push('CREATED');
      });
      browser.on('targetchanged', () => {
        return events.push('CHANGED');
      });
      browser.on('targetdestroyed', () => {
        return events.push('DESTROYED');
      });
      const page = await browser.newPage();
      await page.goto(server.EMPTY_PAGE);
      await page.close();
      expect(events).toEqual(['CREATED', 'CHANGED', 'DESTROYED']);
      await browser.close();
    });
  });

  describe('Browser.Events.disconnected', function () {
    it('should be emitted when: browser gets closed, disconnected or underlying websocket gets closed', async () => {
      const {puppeteer, defaultBrowserOptions} = getTestState();
      const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
      const browserWSEndpoint = originalBrowser.wsEndpoint();
      const remoteBrowser1 = await puppeteer.connect({
        browserWSEndpoint,
      });
      const remoteBrowser2 = await puppeteer.connect({
        browserWSEndpoint,
      });

      let disconnectedOriginal = 0;
      let disconnectedRemote1 = 0;
      let disconnectedRemote2 = 0;
      originalBrowser.on('disconnected', () => {
        return ++disconnectedOriginal;
      });
      remoteBrowser1.on('disconnected', () => {
        return ++disconnectedRemote1;
      });
      remoteBrowser2.on('disconnected', () => {
        return ++disconnectedRemote2;
      });

      await Promise.all([
        utils.waitEvent(remoteBrowser2, 'disconnected'),
        remoteBrowser2.disconnect(),
      ]);

      expect(disconnectedOriginal).toBe(0);
      expect(disconnectedRemote1).toBe(0);
      expect(disconnectedRemote2).toBe(1);

      await Promise.all([
        utils.waitEvent(remoteBrowser1, 'disconnected'),
        utils.waitEvent(originalBrowser, 'disconnected'),
        originalBrowser.close(),
      ]);

      expect(disconnectedOriginal).toBe(1);
      expect(disconnectedRemote1).toBe(1);
      expect(disconnectedRemote2).toBe(1);
    });
  });
});


text:
package de.tiiunder.flatmate.entities.consumption;

import com.fasterxml.jackson.annotation.JsonProperty;

public class SingleConsumption {

    @JsonProperty
    private Consumption consumption;

    public void setConsumption(Consumption consumption) {
        this.consumption = consumption;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.lithium.ldn.starql.postprocessors;

import com.lithium.ldn.starql.QueryStatement;

public class NoOpPostProcessor implements QlPostProcessor {
	@Override
	public <QueryT extends QueryStatement> QueryT processQueryStatement(QueryT statement) {
		return statement;
	}
}


text:
var rfr = require('rfr');
var data = rfr('lib/models/data');
var errors = rfr('lib/errors');
var logger = rfr('lib/logger');
var Service = data.Service;

function listServices(pantryHouseholdKey, cb) {
  Service
    .query(pantryHouseholdKey)
    .loadAll()
    .exec(
      function(err, queryItems){
        if (err) {
          cb(err);
        } else {
          var res = { items: []};
          for (var i = 0;i<queryItems.Items.length; i++) {
            var matchingService = queryItems.Items[i].get();
            // Delete pantryHouseholdKey fromm resulting items
            if (matchingService.pantryHouseholdKey) {
              delete matchingService.pantryHouseholdKey;
            }
            // Add well-formed service result objects to result items array
            res.items.push(matchingService);
          }
          cb(null, res);
        }
      }
    )
}

function listServicesWithinDateRange(pantryHouseholdKey, startDate, endDate, cb) {
  Service
    .scan()
    .loadAll()
    .where('pantryHouseholdKey').equals(pantryHouseholdKey)
    .where('timeOfService').between(startDate, endDate)
    .exec(
      function(err, results){
        if (err) {
          cb(err);
        } else {
          var res = [];
          for (var i = 0;i<results.Items.length; i++) {
            var matchingService = results.Items[i].get();
            // Delete pantryHouseholdKey fromm resulting items
            if (matchingService.pantryHouseholdKey) {
              delete matchingService.pantryHouseholdKey;
            }
            // Add well-formed service result objects to result items array
            res.push(matchingService);
          }
          cb(null, res);
        }
      }
    )
}

function Create(event, cb) {
  var service = event.body;

  // Update service event body to include concatenated pantry + household UUID key parameter
  service.pantryId = event.pathParams.pantryId;
  service.householdId = event.pathParams.householdId;
  service.pantryHouseholdKey = event.pathParams.pantryId + "+" + event.pathParams.householdId;

  // Set time of service to current time
  if (!service.timeOfService) {
    var now = new Date();
    service.timeOfService = now.toISOString();
  }

  logger.info("Service Create Request: ", service);
  Service.create(service, function(err, dbService) {
    if (err) {
      cb(errors.saveDataFailed(err));
      return;
    }
    var response = dbService.get();

    console.log('Finished creating service successfully!');
    cb(null, response);
  });
}

function Get(event, cb) {
  var pantryHouseholdKey = event.pathParams.pantryId + "+" + event.pathParams.householdId;
  var serviceId = event.pathParams.serviceId;

  logger.info("Service Get Request: ", event);
  Service.get({
    pantryHouseholdKey:pantryHouseholdKey,
    serviceId: serviceId
  }, function(err, dbService) {
    if (err) {
      cb(errors.internalError(err));
      return;
    }
    if (!dbService) {
      cb(errors.notFound(event.pathParams));
      return;
    }
    return cb(null, dbService.get());
  });
}

function List(event, cb) {
  var pantryHouseholdKey = event.pathParams.pantryId + "+" + event.pathParams.householdId;
  listServices(pantryHouseholdKey, cb);
}

function Update(event, cb) {
  // TODO(Justin): Add validation for all service IDs provided in services rendered nested object
  var updatedService = event.body;
  updatedService.pantryId = event.pathParams.pantryId;
  updatedService.householdId = event.pathParams.householdId;
  updatedService.serviceId = event.pathParams.serviceId;
  updatedService.pantryHouseholdKey = updatedService.pantryId + "+" + updatedService.householdId;

  logger.info("Service Update Request: ", event);
  Service.get({
    pantryHouseholdKey: updatedService.pantryHouseholdKey,
    serviceId: updatedService.serviceId
  }, function(err, dbService) {
    if (err) {
      cb(errors.internalError(err));
      return;
    }
    if (!dbService) {
      cb(errors.notFound(event.pathParams));
      return;
    }
    Service.update(event.body, function(err, dbService) {
      if (err) {
        cb(errors.internalError(err));
        return;
      }
      if (!dbService) {
        cb(errors.notFound(event.pathParams));
        return;
      }
      return cb(null, dbService.get());
    });
  });
}

function Delete(event, cb) {
  var pantryHouseholdKey = event.pathParams.pantryId + "+" + event.pathParams.householdId;
  var serviceId = event.pathParams.serviceId;

  logger.info("Service Delete Request: ", event);
  Service.get({
    pantryHouseholdKey: pantryHouseholdKey,
    serviceId: serviceId
  }, function(err, dbService) {
    if (err) {
      cb(errors.internalError(err));
      return;
    }
    if (!dbService) {
      cb(errors.notFound({ "serviceId": serviceId }));
      return;
    }
    Service.destroy(pantryHouseholdKey, serviceId, function(err) {
      if (err) {
        cb(errors.internalError(err));
        return;
      }
      return cb(null, dbService.get());
    });
  });
}

// Upercase since delete is a reserved word in javaServiceript.
module.exports = {
 Create: Create,
 Delete: Delete,
 Get: Get,
 List: List,
 Update: Update,
 listServices: listServices,
 listServicesWithinDateRange: listServicesWithinDateRange
};


text:
<?php

namespace rrsoacis\component\map;

use rrsoacis\component\common\AbstractController;
use rrsoacis\manager\MapManager;

class MapArchivedController extends AbstractController
{
    public function post()
    {

        $map = $_POST['parameter_name'];
        $mapArchived = $_POST['parameter_archived'];

        MapManager::setArchived($map,$mapArchived);

        echo '{"result":"success"}';

    }

}


text:
package com.ferox.renderer;

/**
 * An exception that should be thrown when there is a problem creating a Resource.
 *
 * @author Michael Ludwig
 */
public class ResourceException extends FrameworkException {
    private static final long serialVersionUID = 1L;

    public ResourceException() {
        super();
    }

    public ResourceException(String arg0) {
        super(arg0);
    }

    public ResourceException(Throwable arg0) {
        super(arg0);
    }

    public ResourceException(String arg0, Throwable arg1) {
        super(arg0, arg1);
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Boll. Soc. bot. ital. 2: 59 (1924)

#### Original name
Entyloma dietelianum Bubák, 1903

### Remarks
null


text:
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/holder.js"></script>


text:
/**
 * Log requests for build HAR output
 *
 * Depends on windowPerformance module!
 */
"use strict";

var fs = require("fs");

/**
 * Inspired by phantomHAR
 * @author: Christopher Van (@cvan)
 * @homepage: https://github.com/cvan/phantomHAR
 * @original: https://github.com/cvan/phantomHAR/blob/master/phantomhar.js
 */

function createHAR(page, creator) {
  // @see: https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HAR/Overview.html
  var address = page.address;
  var title = page.title;
  var startTime = page.startTime;
  var resources = page.resources;

  var entries = [];

  resources.forEach(function (resource) {
    var request = resource.request;
    var response = resource.response;

    if (!request || !response) {
      return;
    }

    // Exclude data URIs from the HAR because they aren't
    // included in the spec.
    if (request.url.substring(0, 5).toLowerCase() === "data:") {
      return;
    }

    entries.push({
      cache: {},
      pageref: address,
      request: {
        // Accurate bodySize blocked on https://github.com/ariya/phantomjs/pull/11484
        bodySize: -1,
        cookies: [],
        headers: request.headers,
        // Accurate headersSize blocked on https://github.com/ariya/phantomjs/pull/11484
        headersSize: -1,
        httpVersion: "HTTP/1.1",
        method: request.method,
        queryString: [],
        url: request.url,
      },
      response: {
        bodySize: response.bodySize,
        cookies: [],
        headers: response.headers,
        headersSize: response.headersSize,
        httpVersion: "HTTP/1.1",
        redirectURL: "",
        status: response.status,
        statusText: response.statusText,
        content: {
          mimeType: response.contentType || "",
          size: response.bodySize, // uncompressed
          text: "",
        },
      },
      startedDateTime: resource.startTime && resource.startTime.toISOString(),
      time: response.timeToLastByte,
      timings: {
        blocked: 0,
        dns: -1,
        connect: -1,
        send: 0,
        wait: 0, // response.timeToFirstByte || 0,
        receive: 0, // response.receiveTime,
        ssl: -1,
      },
    });
  });

  return {
    log: {
      creator: creator,
      entries: entries,
      pages: [
        {
          startedDateTime: startTime.toISOString(),
          id: address,
          title: title,
          pageTimings: {
            onLoad: page.onLoad || -1,
            onContentLoad: page.onContentLoad || -1,
          },
        },
      ],
      version: "1.2",
    },
  };
}
/** End **/

module.exports = function (phantomas) {
  var param = phantomas.getParam("har"),
    path = "",
    timeToLastByte;

  if (param === false) {
    return;
  }

  var page = {
    origin: undefined,
    resources: [],
    title: undefined,
    address: undefined,
    startTime: undefined,
    endTime: undefined,
    onDOMReadyTime: undefined,
    windowOnLoadTime: undefined,
    timeToLastByte: undefined,
    onLoad: undefined,
    onContentLoad: undefined,
  };

  var creator = {
    name: "Phantomas - (using phantomHAR)",
    version: phantomas.getVersion(),
  };

  if (typeof param === "undefined") {
    phantomas.log("HAR: no path specified, use --har <path>");
    return;
  }

  // --har
  if (param === true) {
    // defaults to "phantomas_2013-12-07T20:15:01.521Z.har"
    path = "phantomas_" + new Date().toJSON() + ".har";
  }
  // --har [file name]
  else {
    path = param;
  }

  phantomas.log("Will be stored in %s", path);

  phantomas.on("pageBeforeOpen", function (p) {
    page.origin = p;
  });

  phantomas.on("loadFinished", function () {
    page.endTime = new Date();
  });

  phantomas.on("send", (entry) => {
    const resId = entry._requestId;

    page.resources[resId] = {
      id: resId,
      request: entry,
      response: null,
      startTime: new Date(),
    };

    // a first request has been made?
    if (typeof page.startTime === "undefined") {
      page.startTime = new Date();
    }
  });

  phantomas.on("recv", (entry) => {
    const resId = entry.id;

    page.resources[resId].response = entry;
    timeToLastByte = entry.timeToLastByte;
  });

  phantomas.on("metric", function (name, value) {
    switch (name) {
      case "domContentLoaded":
        page.onDOMReadyTime = value;
        break;
      case "domComplete":
        page.windowOnLoadTime = value;
        break;
      case "timeToLastByte":
        page.timeToLastByte = value;
        break;
    }
  });

  phantomas.on("report", () => {
    // make resources list a real array
    page.resources = Object.values(page.resources);

    // Set endTime if page was not finished correctly
    if (!page.endTime) page.endTime = new Date();

    // If metric 'windowOnLoadTime' hasn't been fired, compute it
    //if (!page.windowOnLoadTime)
    //	page.windowOnLoadTime = page.endTime.getTime() - page.startTime.getTime();

    // If metric 'timeToLastByte' hasn't been fired, use last entry
    if (!page.timeToLastByte) page.timeToLastByte = timeToLastByte;

    //page.address = page.origin.url;
    //page.title = page.origin.title;

    // Times (windowOnLoadTime, onDOMReadyTime) are relative to responseEnd entry
    // in NavigationTiming (represented by timeToLastByte metric)
    page.onLoad = page.timeToLastByte + page.windowOnLoadTime;
    page.onContentLoad = page.timeToLastByte + page.onDOMReadyTime;

    phantomas.log('Generating for <%s> ("%s")', page.address, page.title);
    phantomas.log("Page data: %j", page);

    var har, dump;

    try {
      har = createHAR(page, creator);
    } catch (e) {
      console.error(e);
      phantomas.log("Failed to build - %s", e);
      return;
    }

    phantomas.log("Result: %j", har);

    try {
      dump = JSON.stringify(har);
    } catch (e) {
      console.error(e);
      phantomas.log("Failed to stringify HAR to JSON - %s!", e);
      return;
    }

    phantomas.log("Saving to %s ...", path);
    try {
      // https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options
      fs.writeFileSync(path, dump);
    } catch (e) {
      console.error(e);
      phantomas.log("Failed to save HAR - %s!", e);
      return;
    }

    // let clients know that we save a HAR file
    phantomas.emit("har", path);
    phantomas.log("Done");
  });
};


text:
/**********************************************************************
* Felix Winterstein, Imperial College London
*
* File: clustering.h
*
* Revision 1.01
* Additional Comments: distributed under a BSD license, see LICENSE.txt
*
**********************************************************************/

#ifndef __clustering_H__
#define __clustering_H__

#ifdef __cplusplus
    extern "C" {
#endif

#include <stdio.h>
#include <stdlib.h>
//#include <stdbool.h>
#include <time.h>
#include <time.h>
#include "my_util.h"
#include "lloyds.h"
//#include "build_kdTree_it.h"
#include "build_kdTree.h"
#include "filter_it.h"

void buildTree(uint n, uint k, data_type_short *data_set, uint *root, kdTree_type *tree_memory);
void clustering(uint n, uint k, centre_type *initial_centres, data_type_short *data_points, kdTree_type *tree_memory, uint root, data_type_short *output_array, centre_type *centre_output);

#ifdef __cplusplus
    }
#endif

#endif  /* ndef __clustering_H__ */


text:
.PHONY: all templates test test-deps vendor

all: start

start:
	docker-compose up

test:
	docker-compose run platform bundle exec rspec


text:
from django.urls import include, path
from rest_framework.authtoken import views as auth_views
from rest_framework.urlpatterns import format_suffix_patterns

from . import views

creditcard_list = views.CreditCardViewSet.as_view({
    'get': 'list',
    'post': 'create'
})

creditcard_detail = views.CreditCardViewSet.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})

expense_list = views.ExpenseViewSet.as_view({
    'get': 'list',
    'post': 'create'
})

expense_detail = views.ExpenseViewSet.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})

income_list = views.IncomeViewSet.as_view({
    'get': 'list',
    'post': 'create'
})

income_detail = views.IncomeViewSet.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})

overdraft_list = views.OverdraftViewSet.as_view({
    'get': 'list',
    'post': 'create'
})

overdraft_detail = views.OverdraftViewSet.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})

type_list = views.TypeViewSet.as_view({
    'get': 'list',
    'post': 'create'
})

type_detail = views.TypeViewSet.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})

investment_list = views.InvestmentViewSet.as_view({
    'get': 'list',
    'post': 'create'
})

investment_detail = views.InvestmentViewSet.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})

taxbracket_list = views.TaxBracketViewSet.as_view({
    'get': 'list',
    'post': 'create'
})

taxbracket_detail = views.TaxBracketViewSet.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})

user_list = views.UserViewSet.as_view({
    'get': 'list',
    'post': 'create_user'
})

user_detail = views.UserViewSet.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})

# urlpatterns = format_suffix_patterns([
urlpatterns = [
    path('', views.api_root, name='api-root'),
    path('credit-cards/',
        creditcard_list,
        name='creditcard-list'),
    path('credit-cards/<uuid:pk>/',
         creditcard_detail,
         name='creditcard-detail'),
    path('expenses/',
        expense_list,
        name='expense-list'),
    path('expenses/<uuid:pk>/',
         expense_detail,
         name='expense-detail'),
    path('incomes/',
        income_list,
        name='income-list'),
    path('incomes/<uuid:pk>/',
         income_detail,
         name='income-detail'),
    path('overdrafts/',
        overdraft_list,
        name='overdraft-list'),
    path('overdrafts/<uuid:pk>/',
        overdraft_detail,
        name='overdraft-detail'),
    path('types/',
        type_list,
        name='type-list'),
    path('types/<uuid:pk>/',
        type_detail,
        name='type-detail'),
    path('investments/',
        investment_list,
        name='investment-list'),
    path('investments/<uuid:pk>/',
        investment_detail,
        name='investment-detail'),
    path('taxbrackets/',
        taxbracket_list,
        name='taxbracket-list'),
    path('taxbrackets/<uuid:pk>/',
        taxbracket_detail,
        name='taxbracket-detail'),
    path('users/',
        user_list,
        name='user-list'),
    path('users/<int:pk>/',
        user_detail,
        name='user-detail'),
    path('debts/',
        views.get_debts,
        name='get-debts'),
    path('timeline/',
        views.get_debt_timeline,
        name='get-timeline')
]

urlpatterns += [
    path('auth/token/', auth_views.obtain_auth_token, name='auth-token'),
    path('auth/', include('rest_framework.urls', namespace='rest_framework')),
]


text:
package com.caineng.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class IndexController {

	@RequestMapping(value="index", method=RequestMethod.GET)
	public String index(){
		return "index";
	}

}


text:
var fs    = require('fs');
var path  = require('path');

var File = exports.File = function(filePath) {
	this.indent  = null;
	this.data    = void(0);
	this.path    = path.normalize(filePath);
};

exports.read = function(filePath, callback) {
	var file = new File(filePath);
	if (callback) {
		file.read(callback);
	} else {
		file.readSync();
	}
	return file;
};

// ------------------------------------------------------------------
//  File I/O

File.prototype.read = function(callback) {
	fs.readFile(this.path, 'utf8', this._afterRead.bind(this, callback));
};

File.prototype._afterRead = function(callback, err, json) {
	if (err) {
		return callback(err);
	}
	this._processJson(json);
	callback();
};

File.prototype.readSync = function(callback) {
	this._processJson(
		fs.readFileSync(this.path, 'utf8')
	);
};

File.prototype._processJson = function(json) {
	this.data = JSON.parse(json);
	this.indent = determineWhitespace(json);
};

File.prototype.write = function(callback, replacer, space) {
	var space = space || this.indent,
		json = JSON.stringify(this.data, replacer, space);
	fs.writeFile(this.path, json, callback);
};

File.prototype.writeSync = function(replacer, space) {
	var space = space || this.indent,
		json = JSON.stringify(this.data, replacer, space);
	fs.writeFileSync(this.path, json);
};

// ------------------------------------------------------------------
//  Property editing

File.prototype.get = function(key) {
	return this._resolve(key, function(scope, key, value) {
		return value;
	});
};

File.prototype.set = function(key, value) {
	this._resolve(key, function(scope, key) {
		scope[key] = value;
	});
	return this;
};

// Has a callback, but is NOT async
File.prototype._resolve = function(key, callback) {
	var current = this.data;
	var keys = key.split('.');
	key = keys.pop();
	keys.forEach(function(key) {
		current = current[key];
	});
	return callback(current, key, current[key]);
};

// ------------------------------------------------------------------

var findWhitespace = /^(\s+)/;
function determineWhitespace(contents) {
	var whitespace = 0;
	contents = contents.split('\n');
	for (var i = 0, c = contents.length; i < c; i++) {
		var match = findWhitespace.exec(contents);
		if (match && typeof match[1] === 'string') {
			if (match[1][0] === '\t') {
				whitespace = '\t';
				break;
			} else if (match[1].length < whitespace || ! whitespace) {
				whitespace = match[1].length;
			}
		}
	}
}


text:
package com.thetechwarriors.awslambda.cloudformation;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * A base handler that takes care of processing requests from CloudFormation
 * custom resources. Requests made during Create/Update/Delete phase of
 * CloudFormation custom resources will invoke this lambda function. The
 * response of this lambda function does not really matter, instead a
 * CloudFormation endpoint needs to be informated of the results. The endpoint
 * URL is provided by CloudFormation in the request. Extenders of this object
 * need to
 *

 *
validate that the request has all the information they need to process
 * the request

 *
process the request
 *

and generate a response to be sent to Cloudformation

 */

public abstract class CloudFormationHandler implements RequestStreamHandler {

	protected ObjectMapper mapper = new ObjectMapper();

	/**
	 * Processes a request made by CloudFormation custom resource.
	 *
	 * @param req the request from CloudFormation
	 * @param context the lambda execution context
	 * @return the response that should be sent to CloudFormation
	 */
	public abstract CloudFormationResponse process(CloudFormationRequest req, Context context);

	/**
	 * Validates if the CloudFormation request has all the needed parameters to
	 * process this request. This handler will not even attempt to process the
	 * request if it is not valid.
	 *
	 * @param req the request from CloudFormation
	 * @param context the lambda execution context
	 * @return true if request is valid, false
	 *         otherwise
	 */
	public abstract boolean validate(CloudFormationRequest req, Context context);

	/**
	 * The main entry point for all AWS Lambda functions that want to process
	 * requests from CloudFormation custom resources
	 *
	 * @see com.amazonaws.services.lambda.runtime.RequestStreamHandler#handleRequest(java.io.InputStream,
	 *      java.io.OutputStream, com.amazonaws.services.lambda.runtime.Context)
	 */
	public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {

		CloudFormationRequest req = null;

		// parse the request
		try {
			req = mapper.readValue(input, CloudFormationRequest.class);
			logIt(context, "Received: Request=" + mapper.writeValueAsString(req));
		} catch (JsonProcessingException e) {
			logIt(context, "Error parsing request: Error=" + e.getMessage());
		}

		String lambdaResponse = "FAILED";
		if (req != null) {
			// validate the request
			if (validate(req, context)) {
				logIt(context, "Request is valid, attempting to process request");
				// get the response for sending to CFN
				CloudFormationResponse cfnResponse = process(req, context);
				if (cfnResponse != null) {
					// send the response to CFN
					if (sendCloudFormationResponse(req.getResponseURL(), cfnResponse, context)) {
						lambdaResponse = "SUCCESS";
					}
				}
			} else {
				logIt(context, "Request is not valid");
			}
		}

		sendLambdaResponse(lambdaResponse, output);
	}

	protected void sendLambdaResponse(String resp, OutputStream output) throws IOException {
		output.write(resp.getBytes());
		output.flush();
		output.close();
	}

	protected boolean sendCloudFormationResponse(String url, CloudFormationResponse resp, Context context) {
		try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

			String json = mapper.writeValueAsString(resp);
			HttpPut put = new HttpPut(url);
			put.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));

			logIt(context, "About to notify CloudFormation: Message=" + json);
			CloseableHttpResponse httpResponse = httpclient.execute(put);
			return httpResponse.getStatusLine().getStatusCode() == 200;

		} catch (Exception e) {
			logIt(context, "Error notifying CloudFormation: Error=" + e.getMessage());
			return false;
		}
	}

	protected void logIt(Context context, String msg) {
		context.getLogger().log(msg);
	}
}


text:
'use strict';

const _ = require('lodash');
const q = require('q');
const URI = require('urijs');

const webdriverio = require('webdriverio');
const logger = require('./utils').logger;
const signalHandler = require('./signal-handler');

module.exports = class Browser {
    static create(config, id) {
        return new Browser(config, id);
    }

    constructor(config, id) {
        this.id = id;

        this._config = config.forBrowser(this.id);
        this._debug = config.system.debug;
        this._session = null;
        this._meta = {};

        signalHandler.on('exit', () => this.quit());
    }

    init() {
        return q(() => this._session = this._createSession())
            .call()
            .then(() => this._setHttpTimeout(this._config.sessionRequestTimeout))
            .then(() => this._session.init())
            .then(() => this._restoreHttpTimeout())
            .then(() => this._switchOnScreenshotOnReject())
            .thenResolve(this);
    }

    quit() {
        if (!this._session) {
            return q();
        }

        // Не работает без then в виду особенностей реализации в webdriverio.js
        return this._session
            .then(() => this._setHttpTimeout(this._config.sessionQuitTimeout))
            .then(() => this._switchOffScreenshotOnReject())
            .then(() => this._session.end())
            .catch((e) => logger.warn(`WARNING: Can not close session: ${e.message}`));
    }

    get publicAPI() {
        return this._session; // exposing webdriver API as is
    }

    get sessionId() {
        return _.get(this, '_session.requestHandler.sessionID');
    }

    get meta() {
        return this._meta;
    }

    _createSession() {
        const config = this._config;
        const gridUri = new URI(config.gridUrl);

        const session = webdriverio.remote({
            host: this._getGridHost(gridUri),
            port: gridUri.port(),
            path: gridUri.path(),
            desiredCapabilities: config.desiredCapabilities,
            waitforTimeout: config.waitTimeout,
            logLevel: this._debug ? 'verbose' : 'error',
            coloredLogs: true,
            screenshotPath: config.screenshotPath,
            screenshotOnReject: false,
            connectionRetryTimeout: config.httpTimeout,
            connectionRetryCount: 0, // hermione has its own advanced retries
            baseUrl: config.baseUrl
        });

        this._addMetaAccessCommands(session);
        this._addExtendOptionsMethod(session);
        this._decorateUrlMethod(session);

        if (this._config.prepareBrowser) {
            this._config.prepareBrowser(session);
        }

        return session;
    }

    _setHttpTimeout(timeout) {
        this._session.extendOptions({connectionRetryTimeout: timeout});
    }

    _restoreHttpTimeout() {
        this._setHttpTimeout(this._config.httpTimeout);
    }

    _switchOnScreenshotOnReject() {
        this._session.extendOptions({screenshotOnReject: this._getScreenshotOnRejectOpts()});
    }

    _switchOffScreenshotOnReject() {
        this._session.extendOptions({screenshotOnReject: false});
    }

    _getScreenshotOnRejectOpts() {
        const screenshotOnReject = this._config.screenshotOnReject;

        return _.isObject(screenshotOnReject)
            ? {connectionRetryTimeout: screenshotOnReject.httpTimeout}
            : screenshotOnReject;
    }

    _getGridHost(url) {
        return new URI({
            username: url.username(),
            password: url.password(),
            hostname: url.hostname()
        }).toString().slice(2); // URIjs leaves `//` prefix, removing it
    }

    _addMetaAccessCommands(session) {
        session.addCommand('setMeta', (key, value) => this._meta[key] = value);
        session.addCommand('getMeta', (key) => this._meta[key]);
    }

    _addExtendOptionsMethod(session) {
        session.addCommand('extendOptions', (opts) => {
            _.extend(session.requestHandler.defaultOptions, opts);
        });
    }

    _decorateUrlMethod(session) {
        const baseUrlFn = session.url.bind(session);

        session.addCommand('url', (uri) => {
            if (uri) {
                this._meta.url = this._getMetaUrl(uri);
            }

            return baseUrlFn(uri);
        }, true); // overwrite original `url` method
    }

    _getMetaUrl(uri) {
        return this._config.baseUrl && uri[0] === '/'
            ? URI(this._config.baseUrl + uri).normalize().toString()
            : uri;
    }
};


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2011 - 2012   MetaScale SAS
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_PREDICATES_FUNCTIONS_ISSYMETRIC_HPP_INCLUDED
#define NT2_PREDICATES_FUNCTIONS_ISSYMETRIC_HPP_INCLUDED

/*!
  @file
  @brief Defines the issymetric function
**/

#include <nt2/include/functor.hpp>

namespace nt2
{
  namespace tag
  {
    /*!
      @brief Tag for issymetric functor
    **/
    struct issymetric_ : boost::dispatch::tag::formal_
    {
      typedef boost::dispatch::tag::formal_ parent;
    };
  }

  /*!
    @brief Is an expression symmetric ?

    Checks if an expression is a symmetric matrix.

    @param a0 Expression to inspect

    @return Boolean value evaluating to the result of the test
  **/
  NT2_FUNCTION_IMPLEMENTATION(nt2::tag::issymetric_, issymetric, 1)
}

#endif


text:
package org.apache.logging.log4j.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

/**
 * Prints system properties to the console.
 */
public class SystemPropertiesMain {

    /**
     * Prints system properties to the console.
     *
     * @param args
     *            unused
     */
    public static void main(String[] args) {
        @SuppressWarnings("unchecked")
        Enumeration<String> keyEnum = (Enumeration<String>) System.getProperties().propertyNames();
        List<String> list = new ArrayList<>();
        while (keyEnum.hasMoreElements()) {
            list.add(keyEnum.nextElement());
        }
        Collections.sort(list);
        for (String key : list) {
            System.out.println(key + " = " + System.getProperty(key));
        }
    }
}


text:
package usp.ime.line.ivprog.view.utils;

public class DynamicFlowLayout extends java.awt.FlowLayout {
	private static final long serialVersionUID = 1L;
	private java.awt.Dimension lastPreferredSize;
	private java.awt.Component anchorComponent;
	private int anchorConstant = 0;
	private Class anchorClass;

	public DynamicFlowLayout(int align, java.awt.Component anchor, Class anchorClass, int anchorConstant) {
		super(align);
		this.anchorComponent = anchor;
		this.anchorClass = anchorClass;
		this.anchorConstant = anchorConstant;
	}

	public void layoutContainer(java.awt.Container target) {
		synchronized (target.getTreeLock()) {
			java.awt.Insets insets = target.getInsets();
			int hgap = getHgap();
			int vgap = getVgap();
			if (lastPreferredSize == null) {
				lastPreferredSize = preferredLayoutSize(target);
			}
			int maxwidth = lastPreferredSize.width;
			int nmembers = target.getComponentCount();
			int x = 0, y = insets.top + vgap;
			int rowh = 0, start = 0;
			boolean ltr = target.getComponentOrientation().isLeftToRight();
			for (int i = 0; i < nmembers; i++) {
				java.awt.Component m = target.getComponent(i);
				if (m.isVisible()) {
					java.awt.Dimension d = m.getPreferredSize();
					m.setSize(d.width, d.height);
					if ((x == 0) || ((x + d.width) <= maxwidth)) {
						if (x > 0) {
							x += hgap;
						}
						x += d.width;
						rowh = Math.max(rowh, d.height);
					} else {
						moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, i, ltr);
						x = d.width;
						y += vgap + rowh;
						rowh = d.height;
						start = i;
					}
				}
			}
			moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, nmembers, ltr);
		}
	}

	private void moveComponents(java.awt.Container target, int x, int y, int width, int height, int rowStart, int rowEnd, boolean ltr) {
		synchronized (target.getTreeLock()) {
			switch (getAlignment()) {
			case LEFT:
				x += ltr ? 0 : width;
				break;
			case CENTER:
				x += width / 2;
				break;
			case RIGHT:
				x += ltr ? width : 0;
				break;
			case LEADING:
				break;
			case TRAILING:
				x += width;
				break;
			}
			for (int i = rowStart; i < rowEnd; i++) {
				java.awt.Component m = target.getComponent(i);
				if (target.isVisible()) {
					if (ltr) {
						m.setLocation(x, y + (height - m.getHeight()) / 2);
					} else {
						m.setLocation(target.getWidth() - x - m.getWidth(), y + (height - m.getHeight()) / 2);
					}
					x += m.getWidth() + getHgap();
				}
			}
		}
	}

	public java.awt.Dimension preferredLayoutSize(java.awt.Container target) {
		java.awt.Insets insets = target.getInsets();
		int hgap = getHgap();
		int vgap = getVgap();
		if (anchorComponent == null) {
			anchorComponent = getAnchor(target);
		}
		int maxwidth = 0;
		if (anchorComponent == null) {
			maxwidth = (target.getWidth() - (insets.left + insets.right + hgap * 2));
		} else {
			maxwidth = anchorComponent.getWidth() - (insets.left + insets.right + hgap * 2) - anchorConstant;
		}
		int nmembers = target.getComponentCount();
		int x = 0, y = insets.top + vgap;
		int rowh = 0;
		if (maxwidth < 0) {
			maxwidth = 0;
			for (int i = 0; i < nmembers; i++) {
				java.awt.Component m = target.getComponent(i);
				if (m.isVisible()) {
					java.awt.Dimension d = m.getPreferredSize();
					y = Math.max(y, d.height);
					if (d.width > 0 && d.height > 0) {
						if (maxwidth > 0) {
							maxwidth += hgap;
						}
						maxwidth += d.width;
					}
				}
			}
		} else {
			target.getComponentOrientation().isLeftToRight();
			for (int i = 0; i < nmembers; i++) {
				java.awt.Component m = target.getComponent(i);
				if (m.isVisible()) {
					java.awt.Dimension d = m.getPreferredSize();
					if ((x == 0) || ((x + d.width) <= maxwidth)) {
						if (x > 0) {
							x += hgap;
						}
						x += d.width;
						rowh = Math.max(rowh, d.height);
					} else {
						x = d.width;
						y += vgap + rowh;
						rowh = d.height;
					}
				}
			}
		}
		lastPreferredSize = new java.awt.Dimension(maxwidth, y + rowh + vgap);
		return lastPreferredSize;
	}

	public java.awt.Dimension minimumLayoutSize(java.awt.Container target) {
		return preferredLayoutSize(target);
	}

	private java.awt.Component getAnchor(java.awt.Component current) {
		if (current == null || anchorClass.isAssignableFrom(current.getClass())) {
			return current;
		} else {
			return getAnchor(current.getParent());
		}
	}
}


text:
package com.bulletphysics.util;

import com.badlogic.gdx.math.Vector3;
import com.bulletphysics.linearmath.Transform;

public class Suppliers {

	public static final Supplier<Vector3> NEW_VECTOR3_SUPPLIER = new Supplier<Vector3>() {
		@Override
		public Vector3 get() {
			return new Vector3();
		}
	};

	public static final Supplier<Transform> NEW_TRANSFORM_SUPPLIER = new Supplier<Transform>() {
		@Override
		public Transform get() {
			return new Transform();
		}
	};

}


text:
package intersectables;

import base.HitRecord;
import base.Intersectable;
import base.Ray;
import constants.HitSentinel;
import util.VectorMath;

import javax.vecmath.Matrix4f;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3f;

/**
 * Allows to render multiple copies of an intersectable without having to make copies of the intersectable.
 * This can be achieved by applying different transformations to the same intersectable.
 * <p/>
 * Created by simplaY on 06.01.2015.
 */
public class Instance implements Intersectable {

    // Intersectable we want to instance.
    private final PrimitiveGeometry baseGeometry;

    // Homogeneous Transformation applied to a given intersectable.
    private final Matrix4f T;

    // inverse Homogeneous Transformation of T.
    private final Matrix4f invT;

    // transposed inverse of T.
    private final Matrix4f tinvT;

    /**
     * Create an Instance of a given intersectable using a certain transformation.
     *
     * @param baseGeometry intersectable we want to instance.
     * @param T            homogeneous transformation matrix applied to intersectable.
     */
    public Instance(PrimitiveGeometry baseGeometry, Matrix4f T) {
        this.baseGeometry = baseGeometry;
        this.T = T;
        invT = new Matrix4f(T);
        invT.invert();
        tinvT = new Matrix4f(invT);
        tinvT.transpose();
    }

    @Override
    public HitRecord intersect(Ray ray) {

        // transform origin and direction of ray
        // (instead of the geometry) by applying the inverse transformation to the ray.
        Vector3f transformedInstanceDir = VectorMath.transformed(invT, ray.getDirection());
        Point3f transformedInstanceOrigin = VectorMath.transformed(invT, ray.getOrigin());

        Ray instanceRay = new Ray(transformedInstanceOrigin, transformedInstanceDir, ray.getT());
        HitRecord instanceRayHit = baseGeometry.intersect(instanceRay);

        if (instanceRayHit.hasIntersection()) {
            return transformBack(instanceRayHit);
        } else {
            return HitSentinel.getInstance();
        }
    }

    /**
     * Transforms HitRecord Data for transformed tay back to original coordinate system.
     *
     * @param hit Hit record of ray transformed to same coordinate system as Instance has.
     * @return re-transformed Hit record data.
     */
    private HitRecord transformBack(HitRecord hit) {
        Point3f position = VectorMath.transformed(T, hit.getPosition());

        Vector3f normal = VectorMath.transformed(tinvT, hit.getNormal());
        normal.normalize();

        Vector3f wIn = VectorMath.transformed(tinvT, hit.getW());
        wIn.normalize();

        return new HitRecord(hit.getT(), position, normal, wIn, hit.getIntersectable(),
                baseGeometry.getMaterial(), hit.getU(), hit.getV(), hit.getTangent());
    }
}


text:
Esta es la implementación en Erlang del desafío 4.

## Ejecución

Para probarlo debes hacer:

	$ erlc huffman.erl
	$ erl -noshell -s huffman  main [c|d] archivo_entrada archivo_salida -s init stop

## Compilación

 	$ erlc huffman.erl

Esto genera un archivo vectores.beam que se ejecuta con la VM de Erlang.

## Uso

Generado el archivo .beam puedes ejecutarlo  haciendo:

	$ erl -noshell -s huffman  main [c|d] archivo_entrada archivo_salida -s init stop

## Documentación

En el directorio doc se encuentra un documento que describe las particularidades de este implementación.

## Licencia

Copyright © 2015, 2016, 2017 Eduardo Díaz

Distribuido bajo licencia MIT (ver archivo LICENSE para los detalles).


text:
Ext.override(Ext.grid.RowEditor, {
    getFloatingButtons: function() {
       var me = this,
           cssPrefix = Ext.baseCSSPrefix,
           btnsCss = cssPrefix + 'grid-row-editor-buttons',
           plugin = me.editingPlugin,
           btns;

       if (!me.floatingButtons) {
           btns = me.floatingButtons = new Ext.Container({
               renderTpl: [
                   '{literal}

',
                   '

',
                   '

',
                   '

',
                   '

',
                   '{%this.renderContainer(out,values)%}{/literal}'
               ],
               width: 200,
               renderTo: me.el,
               baseCls: btnsCss,
               layout: {
                   type: 'hbox',
                   align: 'middle'
               },
               defaults: {
                   flex: 1,
                   margins: '0 1 0 1'
               },
               items: [{
                   itemId: 'update',
                   xtype: 'button',
                   cls: 'primary small',
                   handler: plugin.completeEdit,
                   scope: plugin,
                   text: me.saveBtnText,
                   disabled: !me.isValid,
                   minWidth: Ext.panel.Panel.prototype.minButtonWidth
               }, {
                   xtype: 'button',
                   handler: plugin.cancelEdit,
                   scope: plugin,
                   cls: 'secondary small',
                   text: me.cancelBtnText,
                   minWidth: Ext.panel.Panel.prototype.minButtonWidth
               }]
           });

           // Prevent from bubbling click events to the grid view
           me.mon(btns.el, {
               // BrowserBug: Opera 11.01
               //   causes the view to scroll when a button is focused from mousedown
               mousedown: Ext.emptyFn,
               click: Ext.emptyFn,
               stopEvent: true
           });
       }
       return me.floatingButtons;
   }
})


text:
.barras div {
  font: 10px sans-serif;
  background-color: green;
  text-align: right;
  padding: 3px;
  margin: 1px;
  color: white;
}


text:
<?php declare(strict_types=1);

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter;
use Swift_Message;
use Swift;

/**
 * SwiftMailerHandler uses Swift_Mailer to send the emails
 *
 * @author Gyula Sallai
 */
class SwiftMailerHandler extends MailHandler
{
    protected $mailer;
    private $messageTemplate;

    /**
     * @param \Swift_Mailer          $mailer  The mailer to use
     * @param callable|Swift_Message $message An example message for real messages, only the body will be replaced
     * @param string|int             $level   The minimum logging level at which this handler will be triggered
     * @param bool                   $bubble  Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct(\Swift_Mailer $mailer, $message, $level = Logger::ERROR, bool $bubble = true)
    {
        parent::__construct($level, $bubble);

        $this->mailer = $mailer;
        $this->messageTemplate = $message;
    }

    /**
     * {@inheritdoc}
     */
    protected function send(string $content, array $records): void
    {
        $this->mailer->send($this->buildMessage($content, $records));
    }

    /**
     * Gets the formatter for the Swift_Message subject.
     *
     * @param string $format The format of the subject
     */
    protected function getSubjectFormatter(string $format): FormatterInterface
    {
        return new LineFormatter($format);
    }

    /**
     * Creates instance of Swift_Message to be sent
     *
     * @param  string        $content formatted email body to be sent
     * @param  array         $records Log records that formed the content
     * @return Swift_Message
     */
    protected function buildMessage(string $content, array $records): Swift_Message
    {
        $message = null;
        if ($this->messageTemplate instanceof Swift_Message) {
            $message = clone $this->messageTemplate;
            $message->generateId();
        } elseif (is_callable($this->messageTemplate)) {
            $message = call_user_func($this->messageTemplate, $content, $records);
        }

        if (!$message instanceof Swift_Message) {
            throw new \InvalidArgumentException('Could not resolve message as instance of Swift_Message or a callable returning it');
        }

        if ($records) {
            $subjectFormatter = $this->getSubjectFormatter($message->getSubject());
            $message->setSubject($subjectFormatter->format($this->getHighestRecord($records)));
        }

        $mime = 'text/plain';
        if ($this->isHtmlBody($content)) {
            $mime = 'text/html';
        }

        $message->setBody($content, $mime);
        if (version_compare(Swift::VERSION, '6.0.0', '>=')) {
            $message->setDate(new \DateTimeImmutable());
        } else {
            $message->setDate(time());
        }

        return $message;
    }
}


text:
package org.devocative.wickomp.formatter;

import org.apache.wicket.model.ResourceModel;

public class OBooleanFormatter implements OFormatter {
	private static final long serialVersionUID = -5789921480586802442L;

	private static String stTrue, stFalse;

	@Override
	public String format(Object value) {
		if (stTrue == null) {
			stTrue = new ResourceModel("label.true", "True").getObject();
			stFalse = new ResourceModel("label.false", "False").getObject();
		}

		if (value instanceof Number) {
			Number no = (Number) value;
			return fromNumber(no);
		}

		if (value instanceof Boolean) {
			Boolean b = (Boolean) value;
			return fromBoolean(b);
		}

		if (value instanceof String) {
			try {
				int intValue = Integer.parseInt(value.toString());
				return fromNumber(intValue);
			} catch (NumberFormatException ignored) {
			}

			return fromBoolean(Boolean.valueOf(value.toString()));
		}
		return null;
	}

	private String fromBoolean(Boolean b) {
		return b ? stTrue : stFalse;
	}

	private String fromNumber(Number no) {
		return no.intValue() == 0 ? stFalse : stTrue;
	}

	private static final OBooleanFormatter BOOLEAN = new OBooleanFormatter();

	public static OBooleanFormatter bool() {
		return BOOLEAN;
	}
}


text:
package Paws::Kinesis::ListTagsForStream;
  use Moose;
  has ExclusiveStartTagKey => (is => 'ro', isa => 'Str');
  has Limit => (is => 'ro', isa => 'Int');
  has StreamName => (is => 'ro', isa => 'Str', required => 1);

  use MooseX::ClassAttribute;

  class_has _api_call => (isa => 'Str', is => 'ro', default => 'ListTagsForStream');
  class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::Kinesis::ListTagsForStreamOutput');
  class_has _result_key => (isa => 'Str', is => 'ro');
1;

### main pod documentation begin ###

=head1 NAME

Paws::Kinesis::ListTagsForStream - Arguments for method ListTagsForStream on Paws::Kinesis

=head1 DESCRIPTION

This class represents the parameters used for calling the method ListTagsForStream on the
Amazon Kinesis service. Use the attributes of this class
as arguments to method ListTagsForStream.

You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ListTagsForStream.

As an example:

  $service_obj->ListTagsForStream(Att1 => $value1, Att2 => $value2, ...);

Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.

=head1 ATTRIBUTES

=head2 ExclusiveStartTagKey => Str

The key to use as the starting point for the list of tags. If this
parameter is set, C<ListTagsForStream> gets all tags that occur after
C<ExclusiveStartTagKey>.

=head2 Limit => Int

The number of tags to return. If this number is less than the total
number of tags associated with the stream, C<HasMoreTags> is set to
C<true>. To list additional tags, set C<ExclusiveStartTagKey> to the
last key in the response.

=head2 B<REQUIRED> StreamName => Str

The name of the stream.

=head1 SEE ALSO

This class forms part of L<Paws>, documenting arguments for method ListTagsForStream in L<Paws::Kinesis>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
package com.lightcrafts.utils.xml;

import java.util.ArrayList;
import java.util.Base64;

import lombok.val;

import org.w3c.dom.*;

import static com.lightcrafts.utils.xml.XMLUtil.asList;
import static com.lightcrafts.utils.xml.XMLUtil.asReversedArray;

/**
 * A limited wrapper around Element, to prevent users from exploring XML
 * features.  The wrapper has just a name, attributes, and children, plus
 * a "version" feature.
 */

public class XmlNode {

    // XmlNodes can have a version number.  See setVersion() and getVersion().
    private final static String VersionTag = "version";

    private Element element;
    private ArrayList<XmlNode> children;

    XmlNode(Element element) {
        this.element = element;
        children = new ArrayList<XmlNode>();
        val nodes = asList(element.getChildNodes());
        for (val node : nodes) {
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                val child = new XmlNode((Element) node);
                children.add(child);
            }
        }
    }

    /**
     * Hunt up the tree for a version attribute, parse it as an integer,
     * and return it.  If no such attribute is present, return -1.
     */
    public int getVersion() {
        Node e = element;
        while (e instanceof Element) {
            String s = ((Element) e).getAttribute(VersionTag);
            if (s != null) {
                try {
                    return Integer.parseInt(s);
                }
                catch (NumberFormatException ex) {
                    // Keep looking.
                }
            }
            e = e.getParentNode();
        }
        return -1;
    }

    /**
     * Set the version attribute on this node, so that it will be returned
     * by getVersion() on this node and all its descendants, until one of the
     * descendants has its version attribute set.
     */
    public void setVersion(int version) {
        setAttribute(VersionTag, Integer.toString(version));
    }

    public String getName() {
        return element.getTagName();
    }

    /** Test whether this XmlNode has an attribute with the given name.
     */
    public boolean hasAttribute(String key) {
        return element.hasAttribute(key);
    }

    /** Get the value of an attribute under this XmlNode.  If no attribute
      * with the given name is found, it's an XMLException.
      */
    public String getAttribute(String key) throws XMLException {
        if (! hasAttribute(key)) {
            String message =
                "Expected attribute \"" + key +
                "\" under \"" + getName() + "\"";
            throw new XMLException(message);
        }
        return element.getAttribute(key);
    }

    /** Set an attribute key-value pair on this XmlNode.
     */
    public void setAttribute(String key, String value) {
        element.setAttribute(key, value);
    }

    /** Get all attribute keys on this XmlNode.
     */
    public String[] getAttributes() {
        NamedNodeMap map = element.getAttributes();
        int length = map.getLength();
        String[] keys = new String[length];
        for (int n=0; n<length; n++) {
            Node item = map.item(n);
            keys[n] = item.getNodeName();
        }
        return keys;
    }

    /** Create a new XmlNode as a child of this one with the given name.
     */
    public XmlNode addChild(String name) {
        Document doc = element.getOwnerDocument();
        Element e = doc.createElement(name);
        element.appendChild(e);
        XmlNode child = new XmlNode(e);
        children.add(child);
        return child;
    }

    /** Test whether this XmlNode has a child element with the given name.
     */
    public boolean hasChild(String name) {
        for (XmlNode child : children) {
            if (child.getName().equals(name)) {
                return true;
            }
        }
        return false;
    }

    /** Get the first child of this XmlNode that has the given name.
     * If no child with this name is found, it's an XMLException.
     */
    public XmlNode getChild(String name) throws XMLException {
        for (XmlNode child : children) {
            if (child.getName().equals(name)) {
                return child;
            }
        }
        String message =
            "Expected child \"" + name + "\" under \"" + getName() + "\"";
        throw new XMLException(message);
    }

    /** Get all children of this XmlNode.
     */
    public XmlNode[] getChildren() {
        return children.toArray(new XmlNode[0]);
    }

    /*** Get all children of this XmlNode that have the given name.
     * If none have this name, it's a zero-length array and not an
     * XMLException.
     */
    public XmlNode[] getChildren(String name) {
        final ArrayList<XmlNode> nameChildren = new ArrayList<XmlNode>();
        for (final XmlNode child : children) {
            if (child.getName().equals(name))
                nameChildren.add(child);
        }
        return nameChildren.toArray(new XmlNode[0]);
    }

    public void removeChild(XmlNode child) {
        if (children.contains(child)) {
            children.remove(child);
            element.removeChild(child.element);
        }
    }

    /**
     * Stuff binary data into this XmlNode as a child text node using Base64
     * encoding.  To recover these data, use getData().
     */
    public void setData(byte[] data) {
        String s = Base64.getEncoder().encodeToString(data);
        clearData();
        Document doc = element.getOwnerDocument();
        Text text = doc.createTextNode(s);
        element.appendChild(text);
    }

    /**
     * Get binary data from this XmlNode that has been previously saved by
     * setData().  This works by normalizing text node children
     * and then decoding the result as Base64.  If a child text node exists
     * but does not contain valid Base64-encoded data, then this method
     * returns null.
     */
    public byte[] getData() {
        val sb = new StringBuilder();
        val nodes = asList(element.getChildNodes());
        for (val node : nodes) {
            if ( node.getNodeType() == Node.TEXT_NODE ) {
                val text = (Text)node;
                sb.append( text.getData() );
            }
        }
        return Base64.getDecoder().decode(sb.toString());
    }

    /**
     * Remove all text node children of this XmlNode.  This undoes all effects
     * of setData(), so that getData() will return
     * null.
     */
    public void clearData() {
        val nodes = asReversedArray(element.getChildNodes());
        for (val node : nodes) {
            if (node.getNodeType() == Node.TEXT_NODE) {
                element.removeChild(node);
            }
        }
    }
}
/* vim:set et sw=4 ts=4: */


text: require_relative 'thrift_client'


text:
import CreateMethodProperty = require('../2016/CreateMethodProperty');
export = CreateMethodProperty;


text:
'use strict';

var assert = require('assert');
var ControllerInterface = require('../lib/controller-interface');

describe('controller-interface', function() {
    beforeEach(function() {
        this.controllerInterface = new ControllerInterface(
            './test-controller.fcl');
    });

    it('it should give an expected output on input', function(done) {
        this.controllerInterface.runController([-0.4, 3.1],
            function(err, result) {
                assert.ifError(err);
                assertFloatEqual(result, 0.5);
                done();
        });
    });

    it('it should give an expected output on input', function(done) {
        this.controllerInterface.runController([0.2, 1.1],
            function(err, result) {
                assert.ifError(err);
                assertFloatEqual(result, 1.5);
                done();
        });
    });
});

function assertFloatEqual(actual, expected) {
    assert(Math.abs(actual - expected) < 1e-5, 'expected ' + expected + ', got ' + actual);
}


text:
package jqian.util;

import java.io.File;
import java.util.*;

/**
 *
 */
public class Utils {
    /** Calculate the time between two events */
    public static String getTimeConsumed(Date start, Date end){
        long time = end.getTime()-start.getTime();
        return ""+time/1000+"."+(time/100)%10+"s";
    }

	/** Transfer a free style string into a string that is valid as a file path. */
	public static String toValidFilepath(String str){
        StringBuffer strBuf = new StringBuffer(str);
        for (int i = 0; i < strBuf.length(); i++) {
            if (strBuf.charAt(i) == '<')
                strBuf.setCharAt(i, '_');
            if (strBuf.charAt(i) == '>')
                strBuf.setCharAt(i, '_');
        }
        return strBuf.toString();
	}

	/** Get entry class of the application. Use exception mechanism for implementation.*/
	public static String getEntryClass(){
		StackTraceElement stack[]  =  (new Throwable()).getStackTrace();
		return stack[stack.length-1].getClassName();
	}

	static void clearFile(File file){
		if(file.isDirectory()){
			for(File f: file.listFiles()){
				clearFile(f);
			}
		}

		file.delete();
	}

	public static void clearDirectory(String dir){
		File dirFile = new File(dir);
		File[] files = dirFile.listFiles();
		if(files!=null){
			for(File f: files){
				clearFile(f);
			}
		}
	}

	public static void assureDirectory(String filepath){
		File f = new File(filepath);
		File dir = f.getParentFile();
		if (!dir.exists()) {
			dir.mkdirs();
		}
	}
}