text:
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';

import {installMockChrome, MockCommandLinePrivate} from '../../common/js/mock_chrome.js';
import {MockDirectoryEntry, MockFileEntry, MockFileSystem} from '../../common/js/mock_entry.js';
import {assertRejected, reportPromise, waitUntil} from '../../common/js/test_error_reporting.js';
import {VolumeManagerCommon} from '../../common/js/volume_manager_types.js';

import {VolumeInfoImpl} from './volume_info_impl.js';
import {volumeManagerFactory} from './volume_manager_factory.js';
import {VolumeManagerImpl} from './volume_manager_impl.js';
import {volumeManagerUtil} from './volume_manager_util.js';

let mockChrome;
let createVolumeInfoOriginal;

export function setUp() {
  loadTimeData.getString = id => id;
  loadTimeData.resetForTesting({});

  // Set up mock of chrome.fileManagerPrivate APIs.
  mockChrome = {
    runtime: {lastError: undefined},
    fileManagerPrivate: {
      DriveConnectionStateType: {
        ONLINE: 'ONLINE',
        OFFLINE: 'OFFLINE',
        METERED: 'METERED',
      },
      DriveOfflineReason: {
        NOT_READY: 'NOT_READY',
        NO_NETWORK: 'NO_NETWORK',
        NO_SERVICE: 'NO_SERVICE',
      },
      mountSourcePath_: null,
      onMountCompletedListeners_: [],
      onDriveConnectionStatusChangedListeners_: [],
      driveConnectionState_: 'ONLINE',
      volumeMetadataList_: [],
      password: undefined,
      addMount: function(fileUrl, password, callback) {
        mockChrome.fileManagerPrivate.password = password;
        callback(mockChrome.fileManagerPrivate.mountSourcePath_);
      },
      getVolumeRoot: function(options, callback) {
        if (!(options.volumeId in chrome.fileManagerPrivate.fileSystemMap_)) {
          chrome.runtime.lastError = {message: 'Not found.'};
        }
        callback(
            chrome.fileManagerPrivate.fileSystemMap_[options.volumeId].root);
      },
      removeMount: function(volumeId, callback) {
        const event = {
          eventType: 'unmount',
          status: 'success',
          volumeMetadata: {volumeId: volumeId},
        };
        mockChrome.fileManagerPrivate.onMountCompleted.dispatchEvent(event);
        callback();
      },
      onDriveConnectionStatusChanged: {
        addListener: function(listener) {
          mockChrome.fileManagerPrivate.onDriveConnectionStatusChangedListeners_
              .push(listener);
        },
        dispatchEvent: function(event) {
          mockChrome.fileManagerPrivate.onDriveConnectionStatusChangedListeners_
              .forEach(listener => {
                listener(event);
              });
        },
      },
      onMountCompleted: {
        addListener: function(listener) {
          mockChrome.fileManagerPrivate.onMountCompletedListeners_.push(
              listener);
        },
        dispatchEvent: function(event) {
          mockChrome.fileManagerPrivate.onMountCompletedListeners_.forEach(
              listener => {
                listener(event);
              });
        },
      },
      getDriveConnectionState: function(callback) {
        callback(mockChrome.fileManagerPrivate.driveConnectionState_);
      },
      getVolumeMetadataList: function(callback) {
        callback(mockChrome.fileManagerPrivate.volumeMetadataList_);
      },
      set driveConnectionState(state) {
        mockChrome.fileManagerPrivate.driveConnectionState_ = state;
        mockChrome.fileManagerPrivate.onDriveConnectionStatusChanged
            .dispatchEvent(null);
      },
    },
  };
  installMockChrome(mockChrome);
  new MockCommandLinePrivate();
  chrome.fileManagerPrivate.volumeMetadataList_ = [
    {
      volumeId: 'download:Downloads',
      volumeLabel: '',
      volumeType: VolumeManagerCommon.VolumeType.DOWNLOADS,
      isReadOnly: false,
      profile: getMockProfile(),
      configurable: false,
      watchable: true,
      source: VolumeManagerCommon.Source.SYSTEM,
    },
    {
      volumeId: 'drive:drive-foobar%40chromium.org-hash',
      volumeLabel: '',
      volumeType: VolumeManagerCommon.VolumeType.DRIVE,
      isReadOnly: false,
      profile: getMockProfile(),
      configurable: false,
      watchable: true,
      source: VolumeManagerCommon.Source.NETWORK,
    },
    {
      volumeId: 'android_files:0',
      volumeLabel: '',
      volumeType: VolumeManagerCommon.VolumeType.ANDROID_FILES,
      isReadOnly: false,
      provile: getMockProfile(),
      configurable: false,
      watchable: true,
      source: VolumeManagerCommon.Source.SYSTEM,
    },
  ];
  chrome.fileManagerPrivate.fileSystemMap_ = {
    'download:Downloads': new MockFileSystem('download:Downloads'),
    'drive:drive-foobar%40chromium.org-hash':
        new MockFileSystem('drive:drive-foobar%40chromium.org-hash'),
    'android_files:0': new MockFileSystem('android_files:0'),
  };

  createVolumeInfoOriginal = volumeManagerUtil.createVolumeInfo;
}

export function tearDown() {
  volumeManagerFactory.revokeInstanceForTesting();
  // To avoid a closure warning assigning to |chrome|, tearDown() does not
  // balance the call to installMockChrome() here.

  // Restore the createVolumeInfo() function.
  volumeManagerUtil.createVolumeInfo = createVolumeInfoOriginal;
}

async function waitAllVolumes(volumeManager) {
  // Drive + Downloads + Android:
  await waitUntil(() => volumeManager.volumeInfoList.length === 3);
}

/**
 * Returns a mock profile.
 *
 * @return {{displayName:string, isCurrentProfile:boolean, profileId:string}}
 *     Mock profile
 */
function getMockProfile() {
  return {
    displayName: 'foobar@chromium.org',
    isCurrentProfile: true,
    profileId: '',
  };
}

export async function testGetVolumeInfo(done) {
  const volumeManager = await volumeManagerFactory.getInstance();

  const entry = MockFileEntry.create(
      new MockFileSystem('download:Downloads'), '/foo/bar/bla.zip');

  await waitAllVolumes(volumeManager);

  const volumeInfo = volumeManager.getVolumeInfo(entry);
  assertEquals('download:Downloads', volumeInfo.volumeId);
  assertEquals(VolumeManagerCommon.VolumeType.DOWNLOADS, volumeInfo.volumeType);

  done();
}

/**
 * Tests that an unresponsive volume doesn't lock the whole Volume Manager
 * initialization.
 */
export async function testUnresponsiveVolumeStartUp(done) {
  let unblock;
  const fileManagerPrivate = mockChrome.fileManagerPrivate;

  // Replace chrome.fileManagerPrivate.getVolumeRoot() to emulate 1
  // volume not resolving.
  const origGetVolumeRoot = fileManagerPrivate.getVolumeRoot;

  fileManagerPrivate.getVolumeRoot = (options, callback) => {
    if (options.volumeId === 'download:Downloads') {
      console.log(`blocking the resolve for ${options.volumeId}`);
      unblock = () => origGetVolumeRoot(options, callback);
      return;
    }
    return origGetVolumeRoot(options, callback);
  };

  // getInstance() calls and waits for initialize(), which shouldn't get stuck
  // waiting for the all volumes to resolve.
  const volumeManager = await volumeManagerFactory.getInstance();

  // Wait 2 out 3 volumes to be ready.
  await waitUntil(() => volumeManager.volumeInfoList.length === 2);

  // Unblock the unresponsive volume and check if it gets available:
  unblock();
  await waitUntil(() => volumeManager.volumeInfoList.length === 3);

  done();
}

export function testGetDriveConnectionState(callback) {
  reportPromise(
      volumeManagerFactory.getInstance().then(volumeManager => {
        // Default connection state is online
        assertEquals(
            chrome.fileManagerPrivate.DriveConnectionStateType.ONLINE,
            volumeManager.getDriveConnectionState());

        // Sets it to offline.
        chrome.fileManagerPrivate.driveConnectionState =
            chrome.fileManagerPrivate.DriveConnectionStateType.OFFLINE;
        assertEquals(
            chrome.fileManagerPrivate.DriveConnectionStateType.OFFLINE,
            volumeManager.getDriveConnectionState());

        // Sets it back to online
        chrome.fileManagerPrivate.driveConnectionState =
            chrome.fileManagerPrivate.DriveConnectionStateType.ONLINE;
        assertEquals(
            chrome.fileManagerPrivate.DriveConnectionStateType.ONLINE,
            volumeManager.getDriveConnectionState());
      }),
      callback);
}

export function testMountArchiveAndUnmount(callback) {
  const test = async () => {
    // Set states of mock fileManagerPrivate APIs.
    const mountSourcePath = '/usr/local/home/test/Downloads/foobar.zip';
    chrome.fileManagerPrivate.mountSourcePath_ = mountSourcePath;
    chrome.fileManagerPrivate.fileSystemMap_['archive:foobar.zip'] =
        new MockFileSystem('archive:foobar.zip');

    const volumeManager = await volumeManagerFactory.getInstance();

    // Drive + Downloads + Android.
    const numberOfVolumes = 3;
    await waitAllVolumes(volumeManager);

    // Mount an archive
    const password = 'My Password';
    const mounted = volumeManager.mountArchive(
        'filesystem:chrome-extension://extensionid/external/' +
            'Downloads-test/foobar.zip',
        password);

    mockChrome.fileManagerPrivate.onMountCompleted.dispatchEvent({
      eventType: 'mount',
      status: 'success',
      volumeMetadata: {
        volumeId: 'archive:foobar.zip',
        volumeLabel: 'foobar.zip',
        volumeType: VolumeManagerCommon.VolumeType.ARCHIVE,
        isReadOnly: true,
        sourcePath: mountSourcePath,
        profile: getMockProfile(),
        configurable: false,
        watchable: true,
        source: VolumeManagerCommon.Source.FILE,
      },
    });

    await mounted;

    assertEquals(numberOfVolumes + 1, volumeManager.volumeInfoList.length);
    assertEquals(password, mockChrome.fileManagerPrivate.password);

    // Unmount the mounted archive
    const entry = MockFileEntry.create(
        new MockFileSystem('archive:foobar.zip'), '/foo.txt');
    const volumeInfo = volumeManager.getVolumeInfo(entry);
    await volumeManager.unmount(volumeInfo);

    await waitUntil(
        () => volumeManager.volumeInfoList.length === numberOfVolumes);
    assertEquals(numberOfVolumes, volumeManager.volumeInfoList.length);
  };

  reportPromise(test(), callback);
}

export function testCancelMountingArchive(callback) {
  const test = async () => {
    // Set states of mock fileManagerPrivate APIs.
    const mountSourcePath = '/usr/local/home/test/Downloads/foobar.zip';
    chrome.fileManagerPrivate.mountSourcePath_ = mountSourcePath;
    chrome.fileManagerPrivate.fileSystemMap_['archive:foobar.zip'] =
        new MockFileSystem('archive:foobar.zip');

    const volumeManager = await volumeManagerFactory.getInstance();

    // Drive + Downloads + Android.
    const numberOfVolumes = 3;
    await waitAllVolumes(volumeManager);

    setTimeout(
        () => mockChrome.fileManagerPrivate.onMountCompleted.dispatchEvent({
          eventType: 'mount',
          status: VolumeManagerCommon.VolumeError.CANCELLED,
          volumeMetadata: {
            volumeId: null,
            volumeLabel: null,
            volumeType: null,
            isReadOnly: null,
            sourcePath: mountSourcePath,
            profile: null,
            configurable: null,
            watchable: null,
            source: null,
          },
        }));

    try {
      await volumeManager.mountArchive(
          'filesystem:chrome-extension://extensionid/external/' +
              'Downloads-test/foobar.zip',
          'My Password');
    } catch (error) {
      assertEquals(error, VolumeManagerCommon.VolumeError.CANCELLED);
    }

    assertEquals(numberOfVolumes, volumeManager.volumeInfoList.length);
  };

  reportPromise(test(), callback);
}

export async function testGetCurrentProfileVolumeInfo(done) {
  const volumeManager = await volumeManagerFactory.getInstance();
  await waitAllVolumes(volumeManager);

  const volumeInfo = volumeManager.getCurrentProfileVolumeInfo(
      VolumeManagerCommon.VolumeType.DRIVE);

  assertEquals('drive:drive-foobar%40chromium.org-hash', volumeInfo.volumeId);
  assertEquals(VolumeManagerCommon.VolumeType.DRIVE, volumeInfo.volumeType);

  done();
}

export async function testGetLocationInfo(done) {
  const volumeManager = await volumeManagerFactory.getInstance();
  await waitAllVolumes(volumeManager);

  const downloadEntry = MockFileEntry.create(
      new MockFileSystem('download:Downloads'), '/foo/bar/bla.zip');
  const downloadLocationInfo = volumeManager.getLocationInfo(downloadEntry);
  assertEquals(
      VolumeManagerCommon.RootType.DOWNLOADS, downloadLocationInfo.rootType);
  assertFalse(downloadLocationInfo.hasFixedLabel);
  assertFalse(downloadLocationInfo.isReadOnly);
  assertFalse(downloadLocationInfo.isRootEntry);

  const driveEntry = MockFileEntry.create(
      new MockFileSystem('drive:drive-foobar%40chromium.org-hash'), '/root');
  const driveLocationInfo = volumeManager.getLocationInfo(driveEntry);
  assertEquals(VolumeManagerCommon.RootType.DRIVE, driveLocationInfo.rootType);
  assertTrue(driveLocationInfo.hasFixedLabel);
  assertFalse(driveLocationInfo.isReadOnly);
  assertTrue(driveLocationInfo.isRootEntry);

  const teamDrivesGrandRoot = MockFileEntry.create(
      new MockFileSystem('drive:drive-foobar%40chromium.org-hash'),
      '/team_drives');
  const teamDrivesGrandRootLocationInfo =
      volumeManager.getLocationInfo(teamDrivesGrandRoot);
  assertEquals(
      VolumeManagerCommon.RootType.SHARED_DRIVES_GRAND_ROOT,
      teamDrivesGrandRootLocationInfo.rootType);
  assertTrue(teamDrivesGrandRootLocationInfo.hasFixedLabel);
  assertTrue(teamDrivesGrandRootLocationInfo.isReadOnly);
  assertTrue(teamDrivesGrandRootLocationInfo.isRootEntry);

  const teamDrive = MockFileEntry.create(
      new MockFileSystem('drive:drive-foobar%40chromium.org-hash'),
      '/team_drives/MyTeamDrive');
  const teamDriveLocationInfo = volumeManager.getLocationInfo(teamDrive);
  assertEquals(
      VolumeManagerCommon.RootType.SHARED_DRIVE,
      teamDriveLocationInfo.rootType);
  assertFalse(teamDriveLocationInfo.hasFixedLabel);
  assertFalse(teamDriveLocationInfo.isReadOnly);
  assertTrue(teamDriveLocationInfo.isRootEntry);

  const driveFilesByIdDirectoryEntry = MockDirectoryEntry.create(
      new MockFileSystem('drive:drive-foobar%40chromium.org-hash'),
      '/.files-by-id/123');
  const driveFilesByIdDirectoryLocationInfo =
      volumeManager.getLocationInfo(driveFilesByIdDirectoryEntry);
  assertEquals(
      VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME,
      driveFilesByIdDirectoryLocationInfo.rootType);
  assertFalse(driveFilesByIdDirectoryLocationInfo.hasFixedLabel);
  assertTrue(driveFilesByIdDirectoryLocationInfo.isReadOnly);
  assertFalse(driveFilesByIdDirectoryLocationInfo.isRootEntry);

  const driveFilesByIdEntry = MockFileEntry.create(
      new MockFileSystem('drive:drive-foobar%40chromium.org-hash'),
      '/.files-by-id/123/foo.txt');
  const driveFilesByIdLocationInfo =
      volumeManager.getLocationInfo(driveFilesByIdEntry);
  assertEquals(
      VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME,
      driveFilesByIdLocationInfo.rootType);
  assertFalse(driveFilesByIdLocationInfo.hasFixedLabel);
  assertFalse(driveFilesByIdLocationInfo.isReadOnly);
  assertFalse(driveFilesByIdLocationInfo.isRootEntry);

  const driveShortcutTargetsByIdDirectoryEntry = MockDirectoryEntry.create(
      new MockFileSystem('drive:drive-foobar%40chromium.org-hash'),
      '/.shortcut-targets-by-id/abcdef');
  const driveShortcutTargetsByIdDirectoryLocationInfo =
      volumeManager.getLocationInfo(driveShortcutTargetsByIdDirectoryEntry);
  assertEquals(
      VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME,
      driveShortcutTargetsByIdDirectoryLocationInfo.rootType);
  assertFalse(driveShortcutTargetsByIdDirectoryLocationInfo.hasFixedLabel);
  assertTrue(driveShortcutTargetsByIdDirectoryLocationInfo.isReadOnly);
  assertFalse(driveShortcutTargetsByIdDirectoryLocationInfo.isRootEntry);

  const driveShortcutTargetsByIdEntry = MockDirectoryEntry.create(
      new MockFileSystem('drive:drive-foobar%40chromium.org-hash'),
      '/.shortcut-targets-by-id/abcdef/foo');
  const driveShortcutTargetsByIdLocationInfo =
      volumeManager.getLocationInfo(driveShortcutTargetsByIdEntry);
  assertEquals(
      VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME,
      driveShortcutTargetsByIdLocationInfo.rootType);
  assertFalse(driveShortcutTargetsByIdLocationInfo.hasFixedLabel);
  assertFalse(driveShortcutTargetsByIdLocationInfo.isReadOnly);
  assertFalse(driveShortcutTargetsByIdLocationInfo.isRootEntry);

  const androidRoot =
      MockFileEntry.create(new MockFileSystem('android_files:0'), '/');
  const androidRootLocationInfo = volumeManager.getLocationInfo(androidRoot);
  assertTrue(androidRootLocationInfo.isReadOnly);
  assertTrue(androidRootLocationInfo.isRootEntry);

  const androidSubFolder =
      MockFileEntry.create(new MockFileSystem('android_files:0'), '/Pictures');
  const androidSubFolderLocationInfo =
      volumeManager.getLocationInfo(androidSubFolder);
  assertFalse(androidSubFolderLocationInfo.isReadOnly);
  assertFalse(androidSubFolderLocationInfo.isRootEntry);

  const computersGrandRoot = MockFileEntry.create(
      new MockFileSystem('drive:drive-foobar%40chromium.org-hash'),
      '/Computers');
  const computersGrandRootLocationInfo =
      volumeManager.getLocationInfo(computersGrandRoot);
  assertEquals(
      VolumeManagerCommon.RootType.COMPUTERS_GRAND_ROOT,
      computersGrandRootLocationInfo.rootType);
  assertTrue(computersGrandRootLocationInfo.hasFixedLabel);
  assertTrue(computersGrandRootLocationInfo.isReadOnly);
  assertTrue(computersGrandRootLocationInfo.isRootEntry);

  const computer = MockFileEntry.create(
      new MockFileSystem('drive:drive-foobar%40chromium.org-hash'),
      '/Computers/MyComputer');
  const computerLocationInfo = volumeManager.getLocationInfo(computer);
  assertEquals(
      VolumeManagerCommon.RootType.COMPUTER, computerLocationInfo.rootType);
  assertFalse(computerLocationInfo.hasFixedLabel);
  assertTrue(computerLocationInfo.isReadOnly);
  assertTrue(computerLocationInfo.isRootEntry);

  done();
}

export function testWhenReady(callback) {
  volumeManagerFactory.getInstance().then((volumeManager) => {
    const promiseBeforeAdd = volumeManager.whenVolumeInfoReady('volumeId');
    const volumeInfo = new VolumeInfoImpl(
        /* volumeType */ VolumeManagerCommon.VolumeType.MY_FILES,
        /* volumeId */ 'volumeId',
        /* fileSystem */ null,
        /* error */ undefined,
        /* deviceType */ undefined,
        /* devicePath */ undefined,
        /* isReadOnly */ false,
        /* isReadOnlyRemovableDevice */ false,
        /* profile */ {displayName: '', isCurrentProfile: true},
        /* label */ 'testLabel',
        /* extensionid */ undefined,
        /* hasMedia */ false,
        /* configurable */ false,
        /* watchable */ true,
        /* source */ VolumeManagerCommon.Source.FILE,
        /* diskFileSystemType */ VolumeManagerCommon.FileSystemType.UNKNOWN,
        /* iconSet */ {},
        /* driveLabel */ 'TEST_DRIVE_LABEL',
        /* remoteMountPath*/ '',
        /* vmType*/ undefined);
    volumeManager.volumeInfoList.add(volumeInfo);
    const promiseAfterAdd = volumeManager.whenVolumeInfoReady('volumeId');
    reportPromise(
        Promise.all([promiseBeforeAdd, promiseAfterAdd]).then((volumes) => {
          assertEquals(volumeInfo, volumes[0]);
          assertEquals(volumeInfo, volumes[1]);
        }),
        callback);
  });
}

export function testDriveMountedDuringInitialization(callback) {
  const test = async () => {
    const sendVolumeMetadataListPromise = new Promise(resolve => {
      chrome.fileManagerPrivate.getVolumeMetadataList = resolve;
    });

    // Start volume manager initialization.
    const volumeManagerPromise = volumeManagerFactory.getInstance();

    // Drive is mounted during initialization.
    mockChrome.fileManagerPrivate.onMountCompleted.dispatchEvent({
      eventType: 'mount',
      status: 'success',
      volumeMetadata: {
        volumeId: 'drive:drive-foobar%40chromium.org-hash',
        volumeType: VolumeManagerCommon.VolumeType.DRIVE,
        sourcePath: '/drive',
        profile: getMockProfile(),
      },
    });

    // Wait until volume manager initialization calls getVolumeMetadataList().
    const sendVolumeMetadataList = await sendVolumeMetadataListPromise;

    // Inject the callback value for getVolumeMetadataList(), making the
    // initialization continue and finish.
    sendVolumeMetadataList([]);

    // Wait for volume manager to finish initializing.
    const volumeManager = await volumeManagerPromise;

    await waitUntil(() => volumeManager.volumeInfoList.length === 1);

    // Check volume manager.
    assertTrue(!!volumeManager.getCurrentProfileVolumeInfo(
        VolumeManagerCommon.VolumeType.DRIVE));
  };

  reportPromise(test(), callback);
}

export function testErrorPropagatedDuringInitialization(done) {
  chrome.fileManagerPrivate.getVolumeMetadataList = () => {
    throw new Error('Dummy error for test purpose');
  };

  reportPromise(assertRejected(volumeManagerFactory.getInstance()), done);
}

/**
 * Tests that an error initializing one volume doesn't stop other volumes to be
 * initialized. crbug.com/1041340
 */
export async function testErrorInitializingVolume(done) {
  // Confirm that a Drive volume is on faked getVolumeMetadataList().
  assertTrue(
      chrome.fileManagerPrivate.volumeMetadataList_.some(volumeMetadata => {
        return volumeMetadata.volumeType ===
            VolumeManagerCommon.VolumeType.DRIVE;
      }));

  // Replace createVolumeInfo() to fail to create Drive volume.
  const createVolumeInfoFake = (volumeMetadata) => {
    if (volumeMetadata.volumeType === VolumeManagerCommon.VolumeType.DRIVE) {
      throw new Error('Fake security error');
    }

    // For any other volume return normal value.
    return createVolumeInfoOriginal(volumeMetadata);
  };
  volumeManagerUtil.createVolumeInfo = createVolumeInfoFake;

  // Wait for initialization to populate volumeInfoList.
  const volumeManager = new VolumeManagerImpl();
  await volumeManager.initialize();

  // VolumeInfoList should contain only Android and MyFiles.
  await waitUntil(() => volumeManager.volumeInfoList.length === 2);

  assertEquals(2, volumeManager.volumeInfoList.length);
  assertEquals(
      VolumeManagerCommon.VolumeType.DOWNLOADS,
      volumeManager.volumeInfoList.item(0).volumeType);
  assertEquals(
      VolumeManagerCommon.VolumeType.ANDROID_FILES,
      volumeManager.volumeInfoList.item(1).volumeType);

  done();
}

/**
 * Tests VolumeInfoImpl doesn't raise exception if null is passed for
 * filesystem. crbug.com/1041340
 */
export async function testDriveWithNullFilesystem(done) {
  // Get Drive volume metadata from faked getVolumeMetadataList().
  const driveVolumeMetadata =
      chrome.fileManagerPrivate.volumeMetadataList_.find(volumeMetadata => {
        return volumeMetadata.volumeType ===
            VolumeManagerCommon.VolumeType.DRIVE;
      });
  assertTrue(!!driveVolumeMetadata);

  const localizedLabel = 'DRIVE LABEL';
  const expectedError = 'EXPECTED ERROR DESCRIPTION';

  // Create a VolumeInfo with null filesystem, in the same way that happens on
  // volumeManagerUtil.createVolumeInfo().
  const volumeInfo = new VolumeInfoImpl(
      /** @type {VolumeManagerCommon.VolumeType} */
      (driveVolumeMetadata.volumeType), driveVolumeMetadata.volumeId,
      null,  // File system is not found.
      expectedError, driveVolumeMetadata.deviceType,
      driveVolumeMetadata.devicePath, driveVolumeMetadata.isReadOnly,
      driveVolumeMetadata.isReadOnlyRemovableDevice,
      driveVolumeMetadata.profile, localizedLabel,
      driveVolumeMetadata.providerId, driveVolumeMetadata.hasMedia,
      driveVolumeMetadata.configurable, driveVolumeMetadata.watchable,
      /** @type {VolumeManagerCommon.Source} */
      (driveVolumeMetadata.source),
      /** @type {VolumeManagerCommon.FileSystemType} */
      (driveVolumeMetadata.diskFileSystemType), driveVolumeMetadata.iconSet,
      driveVolumeMetadata.driveLabel, driveVolumeMetadata.remoteMountPath,
      driveVolumeMetadata.vmType);

  // Wait for trying to resolve display root, it should fail with
  // |expectedError| if not re-throw to make the test fail.
  await volumeInfo.resolveDisplayRoot().catch(error => {
    if (error !== expectedError) {
      throw error;
    }
  });

  done();
}


text:
class Event():
    def __init__(self,**kwargs):
        for key,value in kwargs.iteritems():
            setattr(self,key,value)

redpajama_set_name: RedPajamaGithub


text:
package com.linuxtek.kona.app.sales.service;

import java.util.List;

import com.linuxtek.kona.app.sales.entity.KCartItem;
import com.linuxtek.kona.app.sales.entity.KInvoice;
import com.linuxtek.kona.app.sales.entity.KInvoiceItem;
import com.linuxtek.kona.data.service.KDataService;
import com.linuxtek.kona.remote.service.KService;

public interface KInvoiceItemService<INVOICE_ITEM extends KInvoiceItem,
									 INVOICE extends KInvoice,
									 CART_ITEM extends KCartItem>
        extends KService, KDataService<INVOICE_ITEM> {

    public static final String SERVICE_PATH = "rpc/KInvoiceItemService";

	public List<INVOICE_ITEM> fetchByInvoiceId(Long invoiceId);

	public List<INVOICE_ITEM> getInvoiceItemList(INVOICE invoice);

	public INVOICE_ITEM createInvoiceItem(INVOICE invoice, CART_ITEM cartItem);

	public void updateInvoiceItem(INVOICE_ITEM item);

}


text:
#ifndef itkPNGImageIO_h
#define itkPNGImageIO_h
#include "ITKIOPNGExport.h"

#include "itkImageIOBase.h"

namespace itk
{
/** \class PNGImageIO
 *
 * \brief ImageIO object for reading and writing PNG images
 *
 * \ingroup IOFilters
 *
 * \ingroup ITKIOPNG
 */
class ITKIOPNG_EXPORT PNGImageIO:public ImageIOBase
{
public:
  /** Standard class typedefs. */
  typedef PNGImageIO           Self;
  typedef ImageIOBase          Superclass;
  typedef SmartPointer< Self > Pointer;

  typedef RGBPixel< unsigned char >   RGBPixelType;
  typedef std::vector< RGBPixelType > PaletteType;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(PNGImageIO, ImageIOBase);

  /** Set/Get the level of compression for the output images.
   *  0-9; 0 = none, 9 = maximum. */
  itkSetMacro(CompressionLevel, int);
  itkGetConstMacro(CompressionLevel, int);

  /** Get a const ref to the palette of the image. In the case of non palette
    * image or ExpandRGBPalette set to true, a vector of size
    * 0 is returned */
  itkGetConstReferenceMacro(ColorPalette, PaletteType);

  /*-------- This part of the interface deals with reading data. ------ */

  /** Determine the file type. Returns true if this ImageIO can read the
   * file specified. */
  virtual bool CanReadFile(const char *) ITK_OVERRIDE;

  /** Set the spacing and dimension information for the set filename. */
  virtual void ReadImageInformation() ITK_OVERRIDE;

  /** Reads the data from disk into the memory buffer provided. */
  virtual void Read(void *buffer) ITK_OVERRIDE;

  /** Reads 3D data from multiple files assuming one slice per file. */
  virtual void ReadVolume(void *buffer);

  /*-------- This part of the interfaces deals with writing data. ----- */

  /** Determine the file type. Returns true if this ImageIO can write the
   * file specified. */
  virtual bool CanWriteFile(const char *) ITK_OVERRIDE;

  /** Writes the spacing and dimensions of the image.
   * Assumes SetFileName has been called with a valid file name. */
  virtual void WriteImageInformation() ITK_OVERRIDE;

  /** Writes the data to disk from the memory buffer provided. Make sure
   * that the IORegion has been set properly. */
  virtual void Write(const void *buffer) ITK_OVERRIDE;

protected:
  PNGImageIO();
  ~PNGImageIO();
  virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE;

  void WriteSlice(const std::string & fileName, const void *buffer);

  /** Determines the level of compression for written files.
   *  Range 0-9; 0 = none, 9 = maximum , default = 4 */
  int m_CompressionLevel;

  PaletteType m_ColorPalette;

private:
  ITK_DISALLOW_COPY_AND_ASSIGN(PNGImageIO);
};
} // end namespace itk

#endif // itkPNGImageIO_h


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.orc.writer;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.slice.Slice;
import io.trino.orc.checkpoint.BooleanStreamCheckpoint;
import io.trino.orc.checkpoint.LongStreamCheckpoint;
import io.trino.orc.metadata.ColumnEncoding;
import io.trino.orc.metadata.CompressedMetadataWriter;
import io.trino.orc.metadata.CompressionKind;
import io.trino.orc.metadata.OrcColumnId;
import io.trino.orc.metadata.RowGroupIndex;
import io.trino.orc.metadata.Stream;
import io.trino.orc.metadata.Stream.StreamKind;
import io.trino.orc.metadata.statistics.ColumnStatistics;
import io.trino.orc.metadata.statistics.LongValueStatisticsBuilder;
import io.trino.orc.metadata.statistics.TimestampStatisticsBuilder;
import io.trino.orc.stream.LongOutputStream;
import io.trino.orc.stream.LongOutputStreamV2;
import io.trino.orc.stream.PresentOutputStream;
import io.trino.orc.stream.StreamDataOutput;
import io.trino.spi.block.Block;
import io.trino.spi.type.LongTimestamp;
import io.trino.spi.type.LongTimestampWithTimeZone;
import io.trino.spi.type.Type;
import org.openjdk.jol.info.ClassLayout;

import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static io.trino.orc.metadata.ColumnEncoding.ColumnEncodingKind.DIRECT_V2;
import static io.trino.orc.metadata.CompressionKind.NONE;
import static io.trino.orc.metadata.Stream.StreamKind.DATA;
import static io.trino.orc.metadata.Stream.StreamKind.SECONDARY;
import static io.trino.spi.type.DateTimeEncoding.unpackMillisUtc;
import static io.trino.spi.type.TimestampType.TIMESTAMP_MICROS;
import static io.trino.spi.type.TimestampType.TIMESTAMP_MILLIS;
import static io.trino.spi.type.TimestampType.TIMESTAMP_NANOS;
import static io.trino.spi.type.TimestampWithTimeZoneType.TIMESTAMP_TZ_MICROS;
import static io.trino.spi.type.TimestampWithTimeZoneType.TIMESTAMP_TZ_MILLIS;
import static io.trino.spi.type.TimestampWithTimeZoneType.TIMESTAMP_TZ_NANOS;
import static io.trino.spi.type.Timestamps.MICROSECONDS_PER_MILLISECOND;
import static io.trino.spi.type.Timestamps.MICROSECONDS_PER_SECOND;
import static io.trino.spi.type.Timestamps.MILLISECONDS_PER_SECOND;
import static io.trino.spi.type.Timestamps.NANOSECONDS_PER_MICROSECOND;
import static io.trino.spi.type.Timestamps.NANOSECONDS_PER_MILLISECOND;
import static io.trino.spi.type.Timestamps.PICOSECONDS_PER_NANOSECOND;
import static java.lang.Math.floorDiv;
import static java.lang.Math.floorMod;
import static java.time.ZoneOffset.UTC;
import static java.util.Objects.requireNonNull;

// The ORC encoding erroneously uses normal integer division to compute seconds,
// rather than floor modulus, which produces the wrong result for negative values
// (those that are before the epoch). Readers must correct for this. It also makes
// it impossible to represent values less than one second before the epoch, which
// must also be handled in OrcWriteValidation.
//
// The sub-second value (nanoseconds) typically has a large number of trailing zeroes,
// as many systems only record millisecond or microsecond precision. To optimize storage,
// if the value has at least two trailing zeros, the trailing decimal zero digits are
// removed, and the last three bits record how many zeros were removed, minus one:
//
//   # Trailing 0s   Last 3 Bits   Example nanos       Example encoding
//         0            0b000        123456789     (123456789 << 3) | 0b000
//         1            0b000        123456780     (123456780 << 3) | 0b000
//         2            0b001        123456700       (1234567 << 3) | 0b001
//         3            0b010        123456000        (123456 << 3) | 0b010
//         4            0b011        123450000         (12345 << 3) | 0b011
//         5            0b100        123400000          (1234 << 3) | 0b100
//         6            0b101        123000000           (123 << 3) | 0b101
//         7            0b110        120000000            (12 << 3) | 0b110
//         8            0b111        100000000             (1 << 3) | 0b111

public class TimestampColumnWriter
        implements ColumnWriter
{
    private enum TimestampKind
    {
        TIMESTAMP_MILLIS,
        TIMESTAMP_MICROS,
        TIMESTAMP_NANOS,
        INSTANT_MILLIS,
        INSTANT_MICROS,
        INSTANT_NANOS,
    }

    private static final int INSTANCE_SIZE = ClassLayout.parseClass(TimestampColumnWriter.class).instanceSize();

    private static final long ORC_EPOCH_IN_SECONDS = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, UTC).toEpochSecond();

    private final OrcColumnId columnId;
    private final Type type;
    private final TimestampKind timestampKind;
    private final boolean compressed;
    private final ColumnEncoding columnEncoding;
    private final LongOutputStream secondsStream;
    private final LongOutputStream nanosStream;
    private final PresentOutputStream presentStream;

    private final List<ColumnStatistics> rowGroupColumnStatistics = new ArrayList<>();

    private final Supplier<TimestampStatisticsBuilder> statisticsBuilderSupplier;
    private LongValueStatisticsBuilder statisticsBuilder;

    private boolean closed;

    public TimestampColumnWriter(OrcColumnId columnId, Type type, CompressionKind compression, int bufferSize, Supplier<TimestampStatisticsBuilder> statisticsBuilderSupplier)
    {
        this.columnId = requireNonNull(columnId, "columnId is null");
        this.type = requireNonNull(type, "type is null");
        this.timestampKind = timestampKindForType(type);
        this.compressed = requireNonNull(compression, "compression is null") != NONE;
        this.columnEncoding = new ColumnEncoding(DIRECT_V2, 0);
        this.secondsStream = new LongOutputStreamV2(compression, bufferSize, true, DATA);
        this.nanosStream = new LongOutputStreamV2(compression, bufferSize, false, SECONDARY);
        this.presentStream = new PresentOutputStream(compression, bufferSize);
        this.statisticsBuilderSupplier = requireNonNull(statisticsBuilderSupplier, "statisticsBuilderSupplier is null");
        this.statisticsBuilder = statisticsBuilderSupplier.get();
    }

    private static TimestampKind timestampKindForType(Type type)
    {
        if (type.equals(TIMESTAMP_MILLIS)) {
            return TimestampKind.TIMESTAMP_MILLIS;
        }
        if (type.equals(TIMESTAMP_MICROS)) {
            return TimestampKind.TIMESTAMP_MICROS;
        }
        if (type.equals(TIMESTAMP_NANOS)) {
            return TimestampKind.TIMESTAMP_NANOS;
        }
        if (type.equals(TIMESTAMP_TZ_MILLIS)) {
            return TimestampKind.INSTANT_MILLIS;
        }
        if (type.equals(TIMESTAMP_TZ_MICROS)) {
            return TimestampKind.INSTANT_MICROS;
        }
        if (type.equals(TIMESTAMP_TZ_NANOS)) {
            return TimestampKind.INSTANT_NANOS;
        }
        throw new IllegalArgumentException("Unsupported type for ORC timestamp writer: " + type);
    }

    @Override
    public Map<OrcColumnId, ColumnEncoding> getColumnEncodings()
    {
        return ImmutableMap.of(columnId, columnEncoding);
    }

    @Override
    public void beginRowGroup()
    {
        presentStream.recordCheckpoint();
        secondsStream.recordCheckpoint();
        nanosStream.recordCheckpoint();
    }

    @Override
    public void writeBlock(Block block)
    {
        checkState(!closed);
        checkArgument(block.getPositionCount() > 0, "Block is empty");

        // record nulls
        for (int position = 0; position < block.getPositionCount(); position++) {
            presentStream.writeBoolean(!block.isNull(position));
        }

        // record values
        switch (timestampKind) {
            case TIMESTAMP_MILLIS:
            case TIMESTAMP_MICROS:
                writeTimestampMicros(block);
                break;
            case TIMESTAMP_NANOS:
                writeTimestampNanos(block);
                break;
            case INSTANT_MILLIS:
                writeInstantShort(block);
                break;
            case INSTANT_MICROS:
            case INSTANT_NANOS:
                writeInstantLong(block);
                break;
        }
    }

    @Override
    public Map<OrcColumnId, ColumnStatistics> finishRowGroup()
    {
        checkState(!closed);
        ColumnStatistics statistics = statisticsBuilder.buildColumnStatistics();
        rowGroupColumnStatistics.add(statistics);
        statisticsBuilder = statisticsBuilderSupplier.get();
        return ImmutableMap.of(columnId, statistics);
    }

    @Override
    public void close()
    {
        closed = true;
        secondsStream.close();
        nanosStream.close();
        presentStream.close();
    }

    @Override
    public Map<OrcColumnId, ColumnStatistics> getColumnStripeStatistics()
    {
        checkState(closed);
        return ImmutableMap.of(columnId, ColumnStatistics.mergeColumnStatistics(rowGroupColumnStatistics));
    }

    @Override
    public List<StreamDataOutput> getIndexStreams(CompressedMetadataWriter metadataWriter)
            throws IOException
    {
        checkState(closed);

        ImmutableList.Builder<RowGroupIndex> rowGroupIndexes = ImmutableList.builder();

        List<LongStreamCheckpoint> secondsCheckpoints = secondsStream.getCheckpoints();
        List<LongStreamCheckpoint> nanosCheckpoints = nanosStream.getCheckpoints();
        Optional<List<BooleanStreamCheckpoint>> presentCheckpoints = presentStream.getCheckpoints();
        for (int i = 0; i < rowGroupColumnStatistics.size(); i++) {
            int groupId = i;
            ColumnStatistics columnStatistics = rowGroupColumnStatistics.get(groupId);
            LongStreamCheckpoint secondsCheckpoint = secondsCheckpoints.get(groupId);
            LongStreamCheckpoint nanosCheckpoint = nanosCheckpoints.get(groupId);
            Optional<BooleanStreamCheckpoint> presentCheckpoint = presentCheckpoints.map(checkpoints -> checkpoints.get(groupId));
            List<Integer> positions = createTimestampColumnPositionList(compressed, secondsCheckpoint, nanosCheckpoint, presentCheckpoint);
            rowGroupIndexes.add(new RowGroupIndex(positions, columnStatistics));
        }

        Slice slice = metadataWriter.writeRowIndexes(rowGroupIndexes.build());
        Stream stream = new Stream(columnId, StreamKind.ROW_INDEX, slice.length(), false);
        return ImmutableList.of(new StreamDataOutput(slice, stream));
    }

    private static List<Integer> createTimestampColumnPositionList(
            boolean compressed,
            LongStreamCheckpoint secondsCheckpoint,
            LongStreamCheckpoint nanosCheckpoint,
            Optional<BooleanStreamCheckpoint> presentCheckpoint)
    {
        ImmutableList.Builder<Integer> positionList = ImmutableList.builder();
        presentCheckpoint.ifPresent(booleanStreamCheckpoint -> positionList.addAll(booleanStreamCheckpoint.toPositionList(compressed)));
        positionList.addAll(secondsCheckpoint.toPositionList(compressed));
        positionList.addAll(nanosCheckpoint.toPositionList(compressed));
        return positionList.build();
    }

    @Override
    public List<StreamDataOutput> getBloomFilters(CompressedMetadataWriter metadataWriter)
    {
        return ImmutableList.of();
    }

    @Override
    public List<StreamDataOutput> getDataStreams()
    {
        checkState(closed);

        ImmutableList.Builder<StreamDataOutput> outputDataStreams = ImmutableList.builder();
        presentStream.getStreamDataOutput(columnId).ifPresent(outputDataStreams::add);
        outputDataStreams.add(secondsStream.getStreamDataOutput(columnId));
        outputDataStreams.add(nanosStream.getStreamDataOutput(columnId));
        return outputDataStreams.build();
    }

    @Override
    public long getBufferedBytes()
    {
        return secondsStream.getBufferedBytes() + nanosStream.getBufferedBytes() + presentStream.getBufferedBytes();
    }

    @Override
    public long getRetainedBytes()
    {
        long retainedBytes = INSTANCE_SIZE + secondsStream.getRetainedBytes() + nanosStream.getRetainedBytes() + presentStream.getRetainedBytes();
        for (ColumnStatistics statistics : rowGroupColumnStatistics) {
            retainedBytes += statistics.getRetainedSizeInBytes();
        }
        return retainedBytes;
    }

    @Override
    public void reset()
    {
        closed = false;
        secondsStream.reset();
        nanosStream.reset();
        presentStream.reset();
        rowGroupColumnStatistics.clear();
        statisticsBuilder = statisticsBuilderSupplier.get();
    }

    private void writeTimestampMicros(Block block)
    {
        for (int i = 0; i < block.getPositionCount(); i++) {
            if (!block.isNull(i)) {
                long micros = type.getLong(block, i);

                // ORC erroneously uses normal division for seconds
                long seconds = micros / MICROSECONDS_PER_SECOND;
                long microsFraction = floorMod(micros, MICROSECONDS_PER_SECOND);
                long nanosFraction = microsFraction * NANOSECONDS_PER_MICROSECOND;

                long millis = floorDiv(micros, MICROSECONDS_PER_MILLISECOND);

                writeValues(seconds, nanosFraction);
                statisticsBuilder.addValue(millis);
            }
        }
    }

    private void writeTimestampNanos(Block block)
    {
        for (int i = 0; i < block.getPositionCount(); i++) {
            if (!block.isNull(i)) {
                LongTimestamp timestamp = (LongTimestamp) type.getObject(block, i);

                // ORC erroneously uses normal division for seconds
                long seconds = timestamp.getEpochMicros() / MICROSECONDS_PER_SECOND;
                long microsFraction = floorMod(timestamp.getEpochMicros(), MICROSECONDS_PER_SECOND);
                long nanosFraction = (microsFraction * NANOSECONDS_PER_MICROSECOND) +
                        // no rounding since the data has nanosecond precision, at most
                        (timestamp.getPicosOfMicro() / PICOSECONDS_PER_NANOSECOND);

                long millis = floorDiv(timestamp.getEpochMicros(), MICROSECONDS_PER_MILLISECOND);

                writeValues(seconds, nanosFraction);
                statisticsBuilder.addValue(millis);
            }
        }
    }

    private void writeInstantShort(Block block)
    {
        for (int i = 0; i < block.getPositionCount(); i++) {
            if (!block.isNull(i)) {
                writeMillis(unpackMillisUtc(type.getLong(block, i)));
            }
        }
    }

    private void writeInstantLong(Block block)
    {
        for (int i = 0; i < block.getPositionCount(); i++) {
            if (!block.isNull(i)) {
                LongTimestampWithTimeZone timestamp = (LongTimestampWithTimeZone) type.getObject(block, i);
                long millis = timestamp.getEpochMillis();

                // ORC erroneously uses normal division for seconds
                long seconds = millis / MILLISECONDS_PER_SECOND;
                long millisFraction = floorMod(millis, MILLISECONDS_PER_SECOND);
                long nanosFraction = (millisFraction * NANOSECONDS_PER_MILLISECOND) +
                        (timestamp.getPicosOfMilli() / PICOSECONDS_PER_NANOSECOND);

                writeValues(seconds, nanosFraction);
                statisticsBuilder.addValue(millis);
            }
        }
    }

    private void writeMillis(long millis)
    {
        // ORC erroneously uses normal division for seconds
        long seconds = millis / MILLISECONDS_PER_SECOND;
        long millisFraction = floorMod(millis, MILLISECONDS_PER_SECOND);
        long nanosFraction = millisFraction * NANOSECONDS_PER_MILLISECOND;

        writeValues(seconds, nanosFraction);
        statisticsBuilder.addValue(millis);
    }

    private void writeValues(long seconds, long nanosFraction)
    {
        secondsStream.writeLong(seconds - ORC_EPOCH_IN_SECONDS);
        nanosStream.writeLong(encodeNanos(nanosFraction));
    }

    // this comes from the Apache ORC code
    private static long encodeNanos(long nanos)
    {
        if (nanos == 0) {
            return 0;
        }
        if ((nanos % 100) != 0) {
            return nanos << 3;
        }
        nanos /= 100;
        int trailingZeros = 1;
        while (((nanos % 10) == 0) && (trailingZeros < 7)) {
            nanos /= 10;
            trailingZeros++;
        }
        return (nanos << 3) | trailingZeros;
    }
}


text:
<?xml version="1.0" ?>
<xliff version="1.0">
  <file orginal="global" source-language="en" datatype="plaintext">
    <body>
      <trans-unit id="">
        <source>Click following URL, please. You finish register if you inputs your password at here.</source>
        <target>以下のURLをクリックし、パスワードを入力して登録を完了してください。</target>
      </trans-unit>
      <trans-unit id="">
        <source>If the mail address is registered, it is changed to a new mail address.</source>
        <target>メールアドレスが登録されている場合、新しいメールアドレスに変更されます。</target>
      </trans-unit>
      <trans-unit id="">
        <source>Hello! This is information from %1%.</source>
        <target>こんにちは!%1% からのお知らせです。</target>
      </trans-unit>
      <trans-unit id="">
        <source>We've just accepted your registration.</source>
        <target>当サイトへの登録を受け付けました。</target>
      </trans-unit>
      <trans-unit id="">
        <source>We hope that using %1% is useful for your future.</source>
        <target>%1% が、あなたの今後に役立ちますように、是非、ご活用いただければと思います。</target>
      </trans-unit>
      <trans-unit id="">
        <source>-------- Don't you remember this registration? --------</source>
        <target>◆登録した覚えがない方へ</target>
      </trans-unit>
      <trans-unit id="">
        <source>If you think that any your friends shouldn't invite you and you haven't tried registration, please inform to the following e-mail address.</source>
        <target>あなたが誰からの紹介も受けた覚えがなく、当サイトに登録した記憶もないという場合、下記までご連絡ください。</target>
      </trans-unit>
      <trans-unit id="">
        <source>Your information in this site will be deleted.</source>
        <target>お預かりしている情報は責任を持って削除させていただきます。</target>
      </trans-unit>
      <trans-unit id="">
        <source>%1% is inviting in %2% you.</source>
        <target>%1% があなたを%2% へ招待しています。</target>
      </trans-unit>
      <trans-unit id="">
        <source>---------- The message to you from < %1% > ----------</source>
        <target>---------- < %1% > からあなたへのメッセージ ----------</target>
      </trans-unit>
      <trans-unit id="">
        <source>---------------------------------------------------</source>
        <target>---------------------------------------------------</target>
      </trans-unit>
      <trans-unit id="">
        <source>If you register(free) of member by the following URL,%br%you can participate in %1%.</source>
        <target>下記のURLから、会員登録(無料)をおこなうと、%br%%1% に参加できます。</target>
      </trans-unit>
      <trans-unit id="">
        <source>* Participate in %1%</source>
        <target>■ %1% に参加する</target>
      </trans-unit>
      <trans-unit id="">
        <source>Please click following URL, input the password, and complete registration.</source>
        <target>以下のURLをクリックし、パスワードを入力して登録を完了してください。</target>
      </trans-unit>
      <trans-unit id="">
        <source>%1% has just joined your %community%</source>
        <target>%1% さんが %community% に参加しました。</target>
      </trans-unit>
      <trans-unit id="">
        <source>%1% registered your %community%, "%2%".</source>
        <target>%1% さんが %2% %community% に参加しました。</target>
      </trans-unit>
      <trans-unit id="">
        <source>"%1%" %community% page:</source>
        <target>◆%1% %community% のページ</target>
      </trans-unit>
      <trans-unit id="">
        <source>"%1%"'s profile page:</source>
        <target>◇%1% さんのページ</target>
      </trans-unit>
      <trans-unit id="">
        <source>%1% accepted your %friend% link request</source>
        <target>%1% さんがあなたの%friend%リンクリクエストを承諾しました</target>
      </trans-unit>
      <trans-unit id="">
        <source>%1% accepted your %friend% link request.</source>
        <target>%1% さんがあなたの%friend%リンクリクエストを承諾しました。</target>
      </trans-unit>
      <trans-unit id="">
        <source>Leaving from this site is finished</source>
        <target>退会手続きが完了しました</target>
      </trans-unit>
      <trans-unit id="">
        <source>%1%, your leaving process was finished.</source>
        <target>%1%さんの退会手続きが完了しました。</target>
      </trans-unit>
      <trans-unit id="">
        <source>Thank you for your using.</source>
        <target>ご利用いただきありがとうございます。</target>
      </trans-unit>
      <trans-unit id="">
        <source>Thank you for your using.</source>
        <target>ご利用いただきありがとうございます。</target>
      </trans-unit>
      <trans-unit id="">
        <source>Notification of Confirmation of Changing Your PC E-mail Address</source>
        <target>PCメールアドレス変更確認メール</target>
      </trans-unit>
      <trans-unit id="">
        <source>Notification of Confirmation of Changing Your Mobile E-mail Address</source>
        <target>携帯メールアドレス変更確認メール</target>
      </trans-unit>
      <trans-unit id="">
        <source>Notification of Confirmation of Changing Password</source>
        <target>パスワード再発行メール</target>
      </trans-unit>
      <trans-unit id="">
        <source>Notification of Someone's Joining Your Community</source>
        <target>コミュニティ参加お知らせメール</target>
      </trans-unit>
      <trans-unit id="">
        <source>Notification of Completion of Friend Link</source>
        <target>フレンドリンク承認完了メール</target>
      </trans-unit>
      <trans-unit id="">
        <source>Notification of Login URL</source>
        <target>携帯版ログインURLお知らせメール</target>
      </trans-unit>
      <trans-unit id="">
        <source>Notification of Completion of Your Registration</source>
        <target>登録完了メール</target>
      </trans-unit>
      <trans-unit id="">
        <source>Notification of Completion of Leaving From the SNS</source>
        <target>退会完了メール</target>
      </trans-unit>
      <trans-unit id="">
        <source>Notification of Registration URL</source>
        <target>新規登録URLお知らせメール</target>
      </trans-unit>
      <trans-unit id="">
        <source>Signature</source>
        <target>署名</target>
      </trans-unit>
      <trans-unit id="">
        <source>Daily News</source>
        <target>デイリー・ニュース</target>
      </trans-unit>
      <trans-unit id="">
        <source>There is %1%'s %my_friend% that its birthday is coming soon.</source>
        <target>%1% さんの %my_friend% に誕生日の近い方がいます!</target>
      </trans-unit>
      <trans-unit id="">
        <source>We suggest you to send birthday message to your friend.</source>
        <target>日ごろの感謝をこめて、誕生日の日にお祝いのメッセージを送ってみてはいかがですか。</target>
      </trans-unit>
      <trans-unit id="">
        <source>Birthday</source>
        <target>誕生日</target>
      </trans-unit>
      <trans-unit id="">
        <source>Birthday</source>
        <target>誕生日</target>
      </trans-unit>
      <trans-unit id="">
        <source>There is your %my_friend% that its birthday is coming soon</source>
        <target>誕生日の近い %my_friend% がいます!</target>
      </trans-unit>
      <trans-unit id="">
        <source>Notification of Friend Birthday</source>
        <target>フレンドの誕生日お知らせメール</target>
      </trans-unit>
      <trans-unit id="">
        <source>Your password was reissued.</source>
        <target>パスワードを再発行しました。</target>
      </trans-unit>
      <trans-unit id="">
        <source>MailAddress</source>
        <target>メールアドレス</target>
      </trans-unit>
      <trans-unit id="">
        <source>New Password</source>
        <target>新しいパスワード</target>
      </trans-unit>
      <trans-unit id="">
        <source>Today News</source>
        <target>本日の最新情報</target>
      </trans-unit>
      <trans-unit id="">
        <source>Hi, %1%!</source>
        <target>%1% さん</target>
      </trans-unit>
      <trans-unit id="">
        <source>This is daily news in %1%.</source>
        <target>%1% からの本日の最新情報のお知らせです。</target>
      </trans-unit>
      <trans-unit id="">
        <source>Login</source>
        <target>ログイン</target>
      </trans-unit>
      <trans-unit id="">
        <source>Saved configuration successfully.</source>
        <target>設定を正常に保存しました。</target>
      </trans-unit>
      <trans-unit id="">
        <source>Sent a mail for your mail address. Please click URL in the mail for completing configuration.</source>
        <target>メールを送信しました。メール内の URL をクリックして設定を完了してください。</target>
      </trans-unit>
      <trans-unit id="">
        <source>The public_flag for your age can be configure at "Settings" page.</source>
        <target>年齢の公開範囲は「設定変更」ページにて設定することができます。</target>
      </trans-unit>
      <trans-unit id="">
        <source>Age</source>
        <target>年齢</target>
      </trans-unit>
      <trans-unit id="">
        <source>%1% years old</source>
        <target>%1% 歳</target>
      </trans-unit>
      <trans-unit id="">
        <source>Captcha</source>
        <target>確認キーワード</target>
      </trans-unit>
      <trans-unit id="">
        <source>Please input the below keyword.</source>
        <target>上に表示されているキーワードを入力してください。</target>
      </trans-unit>
    </body>
  </file>
</xliff>


text:
module Options.Types.Internal
    (
    ) where


text:
// Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaPreCompiled.h"
#include "ColorTimelineModel.h"

MEDUSA_BEGIN;

ColorTimelineModel::ColorTimelineModel(const FileIdRef& fileId, float duration /*= 0.f*/)
	:ITimelineModel(fileId, duration)
{

}

ColorTimelineModel::~ColorTimelineModel(void)
{
}

void ColorTimelineModel::AddColor(float time, const Color4F& color)
{
	mColors.Add(color);
	AddFrame(time, (uint)mColors.Count() - 1);
}

Color4F ColorTimelineModel::GetColor(float time) const
{
	if (mIsPrecomputed)
	{
		intp index = GetPrecomputedIndex(time);
		return mPrecomputedColors[index];
	}

	uint outPrevFrameIndex;
	uint outNextFrameIndex;
	float outPercent;
	if (TryGetFrame(time, outPrevFrameIndex, outNextFrameIndex, outPercent))
	{
		if (outNextFrameIndex != outPrevFrameIndex)
		{
			return mColors[outPrevFrameIndex] * (1.f - outPercent) + mColors[outNextFrameIndex] * outPercent;
		}
		else
		{
			return mColors[outNextFrameIndex];
		}
	}

	return Color4F::White;
}

void ColorTimelineModel::OnPrecomputeBegin()
{
	mPrecomputedColors.Clear();
}

void ColorTimelineModel::AddPrecomputedItem(bool isFound, uint prevFrameIndex, uint nextFrameIndex, float percent)
{
	Color4F color = Color4F::White;
	if (isFound)
	{
		if (nextFrameIndex != prevFrameIndex)
		{
			color = mColors[prevFrameIndex] * (1.f - percent) + mColors[nextFrameIndex] * percent;
		}
		else
		{
			color = mColors[nextFrameIndex];
		}
	}
	mPrecomputedColors.Add(color);

}

void ColorTimelineModel::RemovePrecomputed()
{
	ITimelineModel::RemovePrecomputed();
	mPrecomputedColors.Clear();
}

MEDUSA_END;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Can. J. Bot. 66(7): 1269 (1988)

#### Original name
Pertusaria subplicans Nyl.

### Remarks
null


text:
import CompositeComponent from "../CompositeComponent";
import OptionComponent from "./OptionComponent";
import LabelComponent from "../LabelComponent";
import LocalizedLabelComponent from "../LocalizedLabelComponent";
import Menu from "../../model/menu/options/Menu";
import Component from "../Component";

export default class MenuComponent extends CompositeComponent {
  private menu: Menu;

  constructor(context: CanvasRenderingContext2D, menu: Menu, absX = 0, absY = 0, absWidth = 0, absHeight = 0) {
    super(
      (<Component[]> [new LocalizedLabelComponent(context, menu.label)]).concat(
          menu.getItems().map(
            (item) => new OptionComponent(context, item)
          )
      ),
      absX, absY, absWidth, absHeight,
      false,
    );
    this.menu = menu;
    this.refresh();
  }

  refresh() {
    if (this.components.length === 0) {
      return;
    }

    let labelHeight = this.absHeight / (this.components.length + 1.0);
    let y = this.absY + labelHeight;
    const label = <LabelComponent> this.components[0];
    label.textAlign = "center";
    label.textBaseline = "middle";
    label.move(this.absX, y);
    label.resize(this.absWidth, labelHeight);
    y += labelHeight;

    for (let i = 1; i < this.components.length; i += 1) {
      const option = <OptionComponent> this.components[i];
      option.move(this.absX, y);
      option.resize(this.absWidth, labelHeight);
      option.selected = false;
      y += labelHeight;
    }

    this.menu.getSelectedIndexes().forEach(
      (index) => (<OptionComponent> this.components[index + 1]).selected = true
    );
    super.refresh();
  }
}


text:
from __future__ import unicode_literals

from os.path import dirname, abspath, join

BASE_DIR = dirname(abspath(__file__))

INSTALLED_APPS = [
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "markitup",
    "tests",
    "tests.test_migration",
]

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3"
    }
}

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            join(BASE_DIR, 'templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

STATIC_URL = "/static/"

ROOT_URLCONF = "tests.urls"

# Use str so this isn't unicode on python 2
MARKITUP_FILTER = (str("tests.filter.testfilter"), {"arg": "replacement"})

SECRET_KEY = 'test-secret'

MIDDLEWARE_CLASSES = []


text:
category: event
title: LambdaConf 2017
logo: /resources/img/lambdaconf.png
location: Boulder, Colorado, US
description: "(Truly) Advanced Scala & Other Functional Programming"
start: 25 May 2017
end: 27 May 2017
link-out: http://lambdaconf.us
---


text:
<?php

// Loader
$loader = include_once 'vendor/autoload.php';

// Configs
$configs = include_once 'app/configs/testing.php';

\Application\ServiceContainer::getInstance()->setConfigs($configs);


text:
package com.RSen.Commandr.builtincommands;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;

import com.RSen.Commandr.R;
import com.RSen.Commandr.core.MostWantedCommand;
import com.RSen.Commandr.util.SMSUtils;
import com.RSen.Commandr.util.SmsMmsMessage;
import com.RSen.Commandr.util.TTSService;

import java.util.ArrayList;

/**
 * @author Ryan Senanayake
 *         Commandr for Google Now
 *         FlashlightCommand.java
 * @version 1.0
 *          5/28/14
 */
public class ReadLastSMSFromContactCommand extends MostWantedCommand {

    private static String TITLE;
    private static String DEFAULT_PHRASE;
    private static Context ctx;

    public ReadLastSMSFromContactCommand(Context ctx) {
        DEFAULT_PHRASE = ctx.getString(R.string.read_last_sms_phrase);
        TITLE = ctx.getString(R.string.last_sms_title);
        this.ctx = ctx;
    }

    /**
     * Execute this command (turn on flashlight)
     */
    @Override
    public void execute(Context context, String predicate) {

        SmsMmsMessage message = SMSUtils.getRecentMessageFromSender(context, predicate.toLowerCase().trim());
        if (message == null) {
            Intent i = new Intent(context, TTSService.class);
            i.putExtra("toSpeak", context.getString(R.string.no_messages_found));
            context.startService(i);
        } else {
            Intent i = new Intent(context, TTSService.class);
            i.putExtra("toSpeak", message.getContactName() + " sent " + message.getMessageBody());
            context.startService(i);
        }
    }

    /**
     * It is enabled if the phone has a flash feature
     */
    @Override
    public boolean isAvailable(Context context) {
        return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
    }

    @Override
    public String getTitle() {
        return TITLE;
    }

    @Override
    public String getPredicateHint() {
        return ctx.getString(R.string.sender_name);
    }

    @Override
    public String getDefaultPhrase() {
        return DEFAULT_PHRASE;
    }

}


text:
rss: true
layout: update
published: true
title: 'Using requestIdleCallback'
date: 2015-08-27
article:
  written_on: 2015-08-27
  updated_on: 2015-08-27
authors:
- paullewis
collection: updates
category: chrome
product: chrome
type: news
tags:
- performance
- update
description: requestIdleCallback is new performance API for scheduling work when the user is idle.
featured-image: /web/updates/images/2015-08-27-using-requestidlecallback/featured.jpg
permalink: /updates/2015/08/27/using-requestidlecallback.html
---

Many sites and apps have a lot of scripts to execute. Your JavaScript often needs to be run as soon as possible, but at the same time you don't want it to get in the user's way. If you send analytics data when the user is scrolling the page, or you append elements to the DOM while they happen to be tapping on the button, your web app can become unresponsive, resulting in a poor user experience.

![Using requestIdleCallback to schedule non-essential work](/web/updates/images/2015-08-27-using-requestidlecallback/main.png)

The good news is that there's now an API that can help: **`requestIdleCallback`**. In the same way that adopting `requestAnimationFrame` allowed us to schedule animations properly and maximize our chances of hitting 60fps, `requestIdleCallback` will schedule work when there is free time at the end of a frame, or when the user is inactive. This means that there's an opportunity to do your work without getting in the user's way. It's available in Chrome Canary (M46+) behind a flag (head over to chrome://flags/#enable-experimental-web-platform-features to enable it), so you can give it a whirl today! Do bear in mind, however, that this is an _experimental feature_, and the spec is still in flux, so things could change at any time.

## Why should I use requestIdleCallback?

Scheduling non-essential work yourself is very difficult to do. It's impossible to figure out exactly how much frame time remains because after `requestAnimationFrame` callbacks execute there are style calculations, layout, paint, and other browser internals that need to run. A home-rolled solution can't account for any of those. In order to be sure that a user _isn't_ interacting in some way you would also need to attach listeners to every kind of interaction event (`scroll`, `touch`, `click`), even if you don't need them for functionality, _just_ so that you can be absolutely sure that the user isn't interacting. The browser, on the other hand, knows exactly how much time is available at the end of the frame, and if the user is interacting, and so through `requestIdleCallback` we gain an API that allows us to make use of any spare time in the most efficient way possible.

Let's take a look at it in a little more detail and see how we can make use of it.

## Checking for requestIdleCallback
It's early days for `requestIdleCallback`, so before using it you should check that it's available for use:

{% highlight javascript %}
if ('requestIdleCallback' in window) {
  // Use requestIdleCallback to schedule work.
} else {
  // Do what you'd do today.
}
{% endhighlight %}

For now, though, let's assume that it exists.

## Using requestIdleCallback
Calling `requestIdleCallback` is very similar to `requestAnimationFrame` in that it takes a callback function as its first parameter:

{% highlight javascript %}
requestIdleCallback(myNonEssentialWork);
{% endhighlight %}

When `myNonEssentialWork` is called, it will be given a `deadline` object which contains a function which returns a number indicating how much time remains for your work:

{% highlight javascript %}
function myNonEssentialWork (deadline) {
  while (deadline.timeRemaining() > 0)
    doWorkIfNeeded();
}
{% endhighlight %}

The `timeRemaining` function can be called to get the latest value. When `timeRemaining()` returns zero you can schedule another `requestIdleCallback` if you still have more work to do:

{% highlight javascript %}
function myNonEssentialWork (deadline) {
  while (deadline.timeRemaining() > 0 && tasks.length > 0)
    doWorkIfNeeded();

  if (tasks.length > 0)
    requestIdleCallback(myNonEssentialWork);
}
{% endhighlight %}

## Guaranteeing your function is called

What do you do if things are really busy? You might be concerned that your callback may never be called. Well, although `requestIdleCallback` resembles `requestAnimationFrame`, it also differs in that it takes a second parameter: **a timeout**. This timeout is an optional parameter which, if set, gives the browser a time in milliseconds by which it must execute the callback:

{% highlight javascript %}
// Wait at most two seconds before processing events.
requestIdleCallback(processPendingAnalyticsEvents, 2000);
{% endhighlight %}

If your callback is executed because of the timeout firing you'll notice two things:

* `timeRemaining()` will return zero.
* The `didTimeout` property of the `deadline` object will be true.

If you see that the `didTimeout` is true, you will most likely just want to run the work and be done with it:

{% highlight javascript %}
function myNonEssentialWork (deadline) {

  // Use any remaining time, or, if timed out, just run through the tasks.
  while ((deadline.timeRemaining() > 0 || deadline.didTimeout) &&
         tasks.length > 0)
    doWorkIfNeeded();

  if (tasks.length > 0)
    requestIdleCallback(myNonEssentialWork);
}
{% endhighlight %}

Because of the potential disruption this timeout can cause to your users (the work could cause your app to become unresponsive or janky) be cautious with setting this parameter. Where you can, let the browser decide when to call the callback.

## Using requestIdleCallback for sending analytics data

Let's take a look using `requestIdleCallback` to send analytics data. In this case, we probably would want to track an event like -- say -- tapping on a navigation menu. However, because they normally animate onto the screen, we will want to avoid sending this event to Google Analytics immediately. We will create an array of events to send and request that they get sent at some point in the future:

{% highlight javascript %}
var eventsToSend = [];

function onNavOpenClick () {

  // Animate the menu.
  menu.classList.add('open');

  // Store the event for later.
  eventsToSend.push(
    {
      category: 'button',
      action: 'click',
      label: 'nav',
      value: 'open'
    });

  schedulePendingEvents();
}
{% endhighlight %}

Now we will need to use `requestIdleCallback` to process any pending events:

{% highlight javascript %}
function schedulePendingEvents() {

  // Only schedule the rIC if one has not already been set.
  if (isRequestIdleCallbackScheduled)
    return;

  isRequestIdleCallbackScheduled = true;

  if ('requestIdleCallback' in window) {
    // Wait at most two seconds before processing events.
    requestIdleCallback(processPendingAnalyticsEvents, 2000);
  } else {
    processPendingAnalyticsEvents();
  }
}
{% endhighlight %}

Here you can see I've set a timeout of 2 seconds, but this value would depend on your application. For analytics data, it makes sense that a timeout would be used to ensure data is reported in a reasonable timeframe rather than just at some point in the future.

Finally we need to write the function that `requestIdleCallback` will execute.

{% highlight javascript %}
function processPendingAnalyticsEvents (deadline) {

  // Reset the boolean so future rICs can be set.
  isRequestIdleCallbackScheduled = false;

  // If there is no deadline, just run as long as necessary.
  // This will be the case if requestIdleCallback doesn't exist.
  if (typeof deadline === 'undefined')
    deadline = { timeRemaining: function () { return Number.MAX_VALUE } };

  // Go for as long as there is time remaining and work to do.
  while (deadline.timeRemaining() > 0 && eventsToSend.length > 0) {
    var evt = eventsToSend.pop();

    ga('send', 'event',
        evt.category,
        evt.action,
        evt.label,
        evt.value);
  }

  // Check if there are more events still to send.
  if (eventsToSend.length > 0)
    schedulePendingEvents();
}
{% endhighlight %}

For this example I assumed that if `requestIdleCallback` didn't exist that the analytics data should be sent immediately. In a production application, however, it would likely be better to delay the send with a timeout to ensure it doesn't conflict with any interactions and cause jank.

## Using requestIdleCallback to make DOM changes

Another situation where `requestIdleCallback` can really help performance is when you have non-essential DOM changes to make, such as adding items to the end of an ever-growing, lazy-loaded list. Let's look at how `requestIdleCallback` actually fits into a typical frame.

![A typical frame](/web/updates/images/2015-08-27-using-requestidlecallback/frame.jpg)

It's possible that the browser will be too busy to run any callbacks in a given frame, so you shouldn't expect that there will be _any_ free time at the end of a frame to do any more work. That makes it different to something like `setImmediate`, which _does_ run per frame.

If the callback _is_ fired at the end of the frame, it will be scheduled to go after the current frame has been committed, which means that style changes will have been applied, and, importantly, layout calculated. If we make DOM changes inside of the idle callback, those layout calculations will be invalidated. If there are any kind of layout reads in the next frame, e.g. `getBoundingClientRect`, `clientWidth`, etc, the browser will have to perform a [Forced Synchronous Layout](https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing#avoid-forced-synchronous-layouts), which is a potential performance bottleneck.

Another reason not trigger DOM changes in the idle callback is that the time impact of changing the DOM is unpredictable, and as such we could easily go past the deadline the browser provided.

The best practice is to only make DOM changes inside of a `requestAnimationFrame` callback, since it is scheduled by the browser with that type of work in mind. That means that our code will need to use a document fragment, which can then be appended in the next `requestAnimationFrame` callback. If you are using a VDOM library, you would use `requestIdleCallback` to make changes, but you would _apply_ the DOM patches in the next `requestAnimationFrame` callback, not the idle callback.

So with that in mind, let's take a look at the code:

{% highlight javascript %}
function processPendingElements (deadline) {

  // If there is no deadline, just run as long as necessary.
  if (typeof deadline === 'undefined')
    deadline = { timeRemaining: function () { return Number.MAX_VALUE } };

  if (!documentFragment)
    documentFragment = document.createDocumentFragment();

  // Go for as long as there is time remaining and work to do.
  while (deadline.timeRemaining() > 0 && elementsToAdd.length > 0) {

    // Create the element.
    var elToAdd = elementsToAdd.pop();
    var el = document.createElement(elToAdd.tag);
    el.textContent = elToAdd.content;

    // Add it to the fragment.
    documentFragment.appendChild(el);

    // Don't append to the document immediately, wait for the next
    // requestAnimationFrame callback.
    scheduleVisualUpdateIfNeeded();
  }

  // Check if there are more events still to send.
  if (elementsToAdd.length > 0)
    scheduleElementCreation();
}
{% endhighlight %}

Here I create the element and use the `textContent` property to populate it, but chances are your element creation code would be more involved! After creating the element `scheduleVisualUpdateIfNeeded` is called, which will set up a single `requestAnimationFrame` callback that will, in turn, append the document fragment to the body:

{% highlight javascript %}
function scheduleVisualUpdateIfNeeded() {

  if (isVisualUpdateScheduled)
    return;

  isVisualUpdateScheduled = true;

  requestAnimationFrame(appendDocumentFragment);
}

function appendDocumentFragment() {
  // Append the fragment and reset.
  document.body.appendChild(documentFragment);
  documentFragment = null;
}
{% endhighlight %}

All being well we will now see much less jank when appending items to the DOM. Excellent!

## FAQ

* **Is there a polyfill?**
    Sadly not. The reason this API exists is because it plugs a very real gap in the web platform. Inferring a lack of activity is difficult, but no JavaScript APIs exist to determine the amount of free space at the end of the frame, so at best you have to make guesses. APIs like `setTimeout`, `setInterval`, or `setImmediate` can be used to schedule work, but they are not timed to avoid user interaction in the way that `requestIdleCallback` is.
* **What happens if I overrun the deadline?**
    If `timeRemaining()` returns zero, but you opt to run for longer, you can do so without fear of the browser halting your work. However, the browser gives you the deadline to try and ensure a smooth experience for your users, so unless there's a very good reason, you should always adhere to the deadline.
* **Is there maximum value that `timeRemaining()` will return?**
    Yes, it's currently 50ms. When trying to maintain a responsive application, all responses to user interactions should be kept under 100ms. Should the user interact the 50ms window should, in most cases, allow for the idle callback to complete, and for the browser to respond to the user's interactions. You may get multiple idle callbacks scheduled back-to-back (if the browser determines that there's enough time to run them).
* **Is there any kind of work I shouldn't do in a requestIdleCallback?**
    Ideally the work you do should be in small chunks (microtasks) that have relatively predictable characteristics. For example, changing the DOM in particular will have unpredictable execution times, since it will trigger style calculations, layout, painting, and compositing. As such you should only make DOM changes in a `requestAnimationFrame` callback as suggested above. Another thing to be wary of is resolving (or rejecting) Promises, as the callbacks will execute immediately after the idle callback has finished, even if there is no more time remaining.
* **Will I always get a `requestIdleCallback` at the end of a frame?**
    No, not always. The browser will schedule the callback whenever there is free time at the end of a frame, or in periods where the user is inactive. You shouldn't expect the callback to be called per frame, and if you require it to run within a given timeframe you should make use of the timeout parameter.
* **Can I have multiple `requestIdleCallback` callbacks?**
    Yes, you can, very much as you can have multiple `requestAnimationFrame` callbacks. It's worth remembering, though, that if your first callback uses up the time remaining during its callback then there will be no more time left for any other callbacks. The other callbacks will then have to wait until the browser is next idle before they can be run. Depending on the work you're trying to get done, it may be better to have a single idle callback and divide the work in there. Alternatively you can make use of the timeout parameter to ensure that no callbacks get starved for time.
* **What happens if I set a new idle callback inside of another?**
    The new idle callback will be scheduled to run as soon as possible, starting from the _next_ frame (rather than the current one).

## Idle on!
`requestIdleCallback` is an awesome way to make sure you can run your code, but without getting in the user's way. It's simple to use, and very flexible. It's still early days, though, and the spec isn't fully settled, so any feedback you have is welcome.

Switch it on in Chrome Canary, give it a spin for your projects, and let us know how you get on!


text:
/**
 * The examples provided by Oculus are for non-commercial testing and
 * evaluation purposes only.
 *
 * Oculus reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * OCULUS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

'use strict';

/**
 * ModelSample loads and displays a spinning model in React VR.
 *
 * To do this, object model is loaded and placed in the scene with the <Model> tag; it
 * is also illuminated with a <PointLight>. Rotation is achieved based on a React state
 * variable that is applied as a rotation transform.
 */

import React from 'react';
import {AppRegistry, asset, Model, Pano, PointLight, Text, View} from 'react-vr';

class ModelSample extends React.Component {
  constructor() {
    super();
    this.state = {rotation: 0};
    this.lastUpdate = Date.now();
    this.rotate = this.rotate.bind(this);
  }

  /**
   * After kickoff in componentDidMount(), rotate is called every frame through
   * requestAnimationFrame. It updates the state.rotation variable used to rotate
   * the model based om on time measurement; this is important to account for
   * different VR headset framerates.
   */
  rotate() {
    const now = Date.now();
    const delta = now - this.lastUpdate;
    this.lastUpdate = now;

    this.setState({rotation: this.state.rotation + delta / 20});
    this.frameHandle = requestAnimationFrame(this.rotate);
  }

  componentDidMount() {
    this.rotate();
  }

  componentWillUnmount() {
    if (this.frameHandle) {
      cancelAnimationFrame(this.frameHandle);
      this.frameHandle = null;
    }
  }

  render() {
    // We build the scene out of three elements:
    //   - A model that displays a rotating object
    //   - A point light, useful for adding color to the model material which would otherwise be dark.
    //   - Text message positioned above the creature
    // A chain of transformations is applied to the model, which are executed from right to left.
    // In out case, the model was too large for the scene and oriented sideways, so we scaled it and
    // rotated it into place. This would not be necessary if your object had correct size ot begin with.
    // We are also applying a new rotation around the Y axis every frame to produce the desired animation.
    return (
      <View>
        <Pano source={asset('chess-world.jpg')} />
        <Model
          style={{
            transform: [
              {translate: [0, -15, -70]},
              {scale: 0.1},
              {rotateY: this.state.rotation},
              {rotateX: -90},
            ],
          }}
          source={{
            obj: asset('creature.obj'),
            mtl: asset('creature.mtl'),
          }}
          lit={true}
        />
        <PointLight style={{color: 'white', transform: [{translate: [0, 400, 700]}]}} />
        <Text
          style={{
            backgroundColor: 'grey',
            padding: 0.1,
            textAlign: 'center',
            textAlignVertical: 'center',
            fontSize: 0.4,
            position: 'absolute',
            transform: [{translate: [0, -2.5, -7]}],
            layoutOrigin: [0.5, 0.5],
          }}
        >
          Creature
        </Text>
      </View>
    );
  }
}

AppRegistry.registerComponent('ModelSample', () => ModelSample);


text:
function [x, fx] = cppsolver(x0, @objective, [args])
% CPPSOLVER  minimize a given objective, when starting in x0
%   x = CPPSOLVER(x0, @objective, [args]) returns the argmin
%   [x, fx]  = CPPSOLVER(x0, @objective, [args]) returns the argmin and min
%
%   https://github.com/PatWie/CppNumericalSolvers
%
%
%   ARGUMENTS:
%
%   "x0"                   :  intial guess
%   "@objective"           :  handle of Matlab-function that returns the objective value in x
%
%   The following arguments are optional
%
%   "solver"               :  selects the solving algorithm
%       -   "gradientdescent"    , gradient descent
%       -   "newton"             , newton descent
%       *   "bfgs"               , Broyden-Fletcher–Goldfarb-Shanno
%       -   "l-bfgs"             , limited Broyden-Fletcher–Goldfarb-Shanno
%       -   "l-bfgs-b"           , limited Broyden-Fletcher–Goldfarb-Shanno with bounds
%
%       example "(...,'solver','l-bfgs')"
%
%   "@gradient"            :  handle of Matlab-function that returns the gradient in x
%   "@hessian"             :  handle of Matlab-function that returns the hessian  in x
%   "skip_gradient_check"  :  specify whether the gradient should be verfied once
%       *   "true"               , check || numerical approximation - given gradient ||_2    < 1e-5
%       -   "false"              , skip check
%
%       example "(...,'skip_gradient_check','true')"
%
%   "skip_hessian_check"   :  specify whether the hessian should be verfied once
%       -   "true"               , check || numerical approximation - given hessian  ||_frob < 1e-3
%       *   "false"              , skip check
%
%       example "(...,'skip_hessian_check','false')"
%
%   "ub"                   :  define an upper bound (for L-BFGS-b)
%
%       example "(...,'ub',[3;3;3])"
%
%   "lb"                   :  define a lower bound (for L-BFGS-b)
%
%       example "(...,'lb',[-1;-1;-1])"
%
%
%  EXAMPLES:
%   Assume that the objective function f: IR^2 -> IR is a Matlab-function called "objective"
%          that the gradient  function f: IR^2 -> IR^2 is a Matlab-function called "gradient"
%          that the hessian   function f: IR^2 -> IR^(2x2) is a Matlab-function called "hessian"
%
%   simple call (bfgs)
%      x0      = [0;0];
%      [x, fx] = cppsolver(x0,@objective)
%
%   Newton-Descent
%      x0      = [0;0];
%      [x, fx] = cppsolver(x0,@objective,'gradient',@gradient,'hessian',@hessian)
%
%   L-BFGS-B
%      x0      = [0;0];
%      ub      = [100;150];
%      lb      = [0;1];
%      [x, fx] = cppsolver(x0,@objective,'gradient',@gradient,'ub',ub,'lb',lb)


text:
/*global define*/

define([
    'underscore',
    'backbone',
    'models/Analysis/AnalysisTypeModel'
], function (_, Backbone, AnalysisTypeModel) {
    'use strict';

    var AnalysisTypeCollection = Backbone.Collection.extend({
    	url: '/api/analysis/type',
        model: AnalysisTypeModel,
        // localStorage: new Store('networks')
    });

    return AnalysisTypeCollection;
});


text:
'use strict';

import React, { PropTypes } from 'react';

class UsersRepos extends React.Component {

  renderActivity() {
    let grammar = (count) => {
      return count !== 1 ? 's' : '';
    };

    return this.props.repos.map((repo, i) => {
      let {open_issues, forks, stargazers_count} = repo;

      return (

            {repo.full_name}

{repo.description}

          Clone: {repo.ssh_url}

              {open_issues}

Open Issue{grammar(open_issues)}

              {forks}

Fork{grammar(forks)}

              {stargazers_count}

Star{grammar(stargazers_count)}

      );
    });
  }

  render() {
    return (

Github Activity

          {this.renderActivity()}

    );
  }

}

export default UsersRepos;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
All Classes
</TITLE>

<META NAME="date" CONTENT="2013-03-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

Cursor

CursorSimulation

MouseMovement

PredefinedCursor

PredefinedLoopCursor

RandomCursor


text:
-- phpMyAdmin SQL Dump
-- version 4.4.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: 19-Jan-2016 às 03:17
-- Versão do servidor: 5.6.26
-- PHP Version: 5.6.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `dbmf`
--

-- --------------------------------------------------------

--
-- Estrutura da tabela `nivel`
--

DROP TABLE IF EXISTS `nivel`;
CREATE TABLE IF NOT EXISTS `nivel` (
  `id` int(11) NOT NULL,
  `nome` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `descricao` varchar(300) COLLATE utf8_unicode_ci DEFAULT NULL,
  `hierarquia` int(3) NOT NULL DEFAULT '1'
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Extraindo dados da tabela `nivel`
--

REPLACE INTO `nivel` (`id`, `nome`, `descricao`, `hierarquia`) VALUES
(1, 'Administrador Master', 'Acesso a todos os menus', 1),
(2, 'Administrador', '', 1);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `nivel`
--
ALTER TABLE `nivel`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `nome` (`nome`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `nivel`
--
ALTER TABLE `nivel`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
Wuzlstats
=========

Web application to track our company-internal Wuzl statistics.


text:
- sudo apt-get installl motion

## requirements
```
Debian/Ubuntu/Raspbian
Required
sudo apt-get install autoconf automake build-essential pkgconf libtool git libzip-dev libjpeg-dev gettext libmicrohttpd-dev
```
## configuration
- /etc/modules
  - bcm2835-v4l2

## run / start / stop / daemon
- sudo systemctl status ( start / stop ) motion
- hostname
- crontab for maintanance
  - 9 2 * * * /var/www/html/cam/motion/cleanup_file.sh > /home/pi/devel/BerePi/apps/debug/debug_motion.log 2>&1
  - 30 */4 * * * /var/www/html/cam/motion/del_sort.sh > /home/pi/devel/BerePi/apps/debug/debug_motion.log 2>&1

## Performance, run fact-info
- 30 Min (DESK shot)
  - generation 69MB JPG files
  - 4351 pics
- One day in office
  - light change effect : less 5 time or slightly more

# Resource
## Source code
- Motion Project Homepage
  - https://motion-project.github.io/index.html
  - Repo : https://github.com/Motion-Project/motion

## Links (howto)
- https://www.bouvet.no/bouvet-deler/utbrudd/building-a-motion-activated-security-camera-with-the-raspberry-pi-zero
  - https://learn.adafruit.com/cloud-cam-connected-raspberry-pi-security-camera?view=all
  - https://www.instructables.com/id/Raspberry-Pi-Motion-Detection-Security-Camera/#step5

# Copying camera capture files to SERVER
- scp -P 22 -pr /var/lib/motion tinyos@IP:webdav/gw/cam


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

namespace SF.Auth.IdentityServices.Internals
{

}


text:
"""Evaluation framework configurations."""
import collections

_SketchEstimatorConfig = collections.namedtuple(
    'EstimatorConfig', ['name', 'sketch_factory', 'estimator', 'sketch_noiser',
                        'estimate_noiser', 'max_frequency'])

# This class exists as a placeholder for a docstring.
class SketchEstimatorConfig(_SketchEstimatorConfig):
  """A subclass of namedtuple for providing a sketch and estimator config."""

  def __new__(cls, name, sketch_factory, estimator, sketch_noiser=None,
              estimate_noiser=None, max_frequency=1):
    """Generate a sketch estimator configuration with default parameters.

    Args:
      name: A string that represents the name of the sketch and estimator.
      sketch_factory: A callable that takes as a single argument a
        numpy.random.RandomState and returns a class that conforms to
        cardinality_estimator_base.Sketch.
      estimator: A class that conforms to cardinality_estimator_base.Estimator.
      sketch_noiser: A class that conforms to
        cardinality_estimator_base.SketchNoiser.
      estimate_noiser: A class that conforms to
        cardinality_estimator_base.EstimateNoiser.
      max_frequency: The maximum frequency for which estimates should be
        produced.

    Returns:
      A namedtuple of sketch estimator configuration.
    """
    return super(cls, SketchEstimatorConfig).__new__(
        cls, name, sketch_factory, estimator, sketch_noiser, estimate_noiser,
        max_frequency)

_ScenarioConfig = collections.namedtuple(
    'ScenarioConfig', ['name', 'set_generator_factory'])

# This class exists as a placeholder for a docstring.
class ScenarioConfig(_ScenarioConfig):
  """A namedtuple subclass providing a scenario config to the EvaluationConfig.

  The arguments to the named tuple are as follows:
    name: the name of the scenario.
    set_generator_factory: A callable that takes as a single argument a
      numpy.random.RandomState and returns a class that conforms to
      set_generator.SetGeneratorBase.
  """
  pass

_EvaluationConfig = collections.namedtuple(
    'EvaluationConfig', ['name', 'num_runs', 'scenario_config_list'])

# For documenting the arguments.
class EvaluationConfig(_EvaluationConfig):
  """A namedtuple subclass of the evaluation configurations.

  It needs the following arguments:
    name: the name of the evaluation config.
    num_runs: the number of runs for each scenario.
    scenario_config_list: a sequence of ScenarioConfig.
  """
  pass


text:
import os
import sys
import csv,codecs,cStringIO

class UTF8Recoder:
    """
    Iterator that reads an encoded stream and reencodes the input to UTF-8
    """
    def __init__(self, f, encoding):
        self.reader = codecs.getreader(encoding)(f)

    def __iter__(self):
        return self

    def next(self):
        return self.reader.next().encode("utf-8")

class unicodeReader:
    """
    A CSV reader which will iterate over lines in the CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        f = UTF8Recoder(f, encoding)
        self.reader = csv.reader(f, dialect=dialect, **kwds)

    def next(self):
        row = self.reader.next()
        return [unicode(s, "utf-8") for s in row]

    def __iter__(self):
        return self

class unicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)


text:
The IoT installation uses several components to get the job done. These
components are mostly included in the NatureBytes kit but some other
things are bought somewhere else.

## I. How does thing work?

1. PIR sensor detects a bird.
2. The Raspberry Pi wakes up.
3. The Raspberry Pi Camera takes a picture.
4. A 4G connection is initiated.
5. The picture and the meta data is send to the API.

## II. Hardware

- NatureBytes kit (enclosure, Raspberry Pi A+, Raspberry Pi Camera V2, PIR sensor)
- Solar kit
- Arduino UNO (Battery Guard)
- A few resistors (2x 20K Ohm and 2x 10K Ohm) and some wires
- 5V Relay
- 4G router
- Waterproof box

An alternative setup could be achieved using a 3G/4G network shield for example: [Adafruit FONA 3G + GPS](https://learn.adafruit.com/adafruit-fona-3g-cellular-gps-breakout/overview) which also includes GPS. With this shield the setup becomes smaller and easier to hide.
However, a separate 5V power supply will be needed to provide enough power for the shield while sending data over the cellular network.

You can find more information about the solar kit [here](https://github.com/oSoc17/code9000/blob/develop/hardware/SOLARKIT.md).

## III. Installation

You can find the installation instructions for both the hardware and the software [here](https://github.com/oSoc17/code9000/blob/develop/hardware/SETUP.md).

## IV. Deployment

You can find the deployment instructions [here](https://github.com/oSoc17/code9000/blob/develop/hardware/DEPLOYMENT.md).

## V. Maintenance

You can find the maintenance instructions [here](https://github.com/oSoc17/code9000/blob/develop/hardware/MAINTENANCE.md).