<commit_before>/*
Copyright 2020 The Matrix.org Foundation C.I.C.

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.
*/

import { MatrixClientPeg } from './MatrixClientPeg';
import SettingsStore from './settings/SettingsStore';
import * as sdk from './index';
import { _t } from './languageHandler';
import ToastStore from './stores/ToastStore';

function toastKey(device) {
    return 'newsession_' + device.deviceId;
}

export default class DeviceListener {
    static sharedInstance() {
        if (!global.mx_DeviceListener) global.mx_DeviceListener = new DeviceListener();
        return global.mx_DeviceListener;
    }

    constructor() {
        // device IDs for which the user has dismissed the verify toast ('Later')
        this._dismissed = new Set();
    }

    start() {
        MatrixClientPeg.get().on('crypto.devicesUpdated', this._onDevicesUpdated);
        MatrixClientPeg.get().on('deviceVerificationChanged', this._onDeviceVerificationChanged);
        this.recheck();
    }

    stop() {
        if (MatrixClientPeg.get()) {
            MatrixClientPeg.get().removeListener('crypto.devicesUpdated', this._onDevicesUpdated);
            MatrixClientPeg.get().removeListener('deviceVerificationChanged', this._onDeviceVerificationChanged);
        }
        this._dismissed.clear();
    }

    dismissVerification(deviceId) {
        this._dismissed.add(deviceId);
        this.recheck();
    }

    _onDevicesUpdated = (users) => {
        if (!users.includes(MatrixClientPeg.get().getUserId())) return;
        if (!SettingsStore.isFeatureEnabled("feature_cross_signing")) return;
        this.recheck();
    }

    _onDeviceVerificationChanged = (users) => {
        if (!users.includes(MatrixClientPeg.get().getUserId())) return;
        if (!SettingsStore.isFeatureEnabled("feature_cross_signing")) return;
        this.recheck();
    }

    async recheck() {
        const cli = MatrixClientPeg.get();

        if (!cli.isCryptoEnabled()) return false;

        const devices = await cli.getStoredDevicesForUser(cli.getUserId());
        for (const device of devices) {
            if (device.deviceId == cli.deviceId) continue;

            const deviceTrust = await cli.checkDeviceTrust(cli.getUserId(), device.deviceId);
            if (deviceTrust.isVerified() || this._dismissed.has(device.deviceId)) {
                ToastStore.sharedInstance().dismissToast(toastKey(device));
            } else {
                ToastStore.sharedInstance().addOrReplaceToast({
                    key: toastKey(device),
                    title: _t("New Session"),
                    icon: "verification_warning",
                    props: {deviceId: device.deviceId},
                    component: sdk.getComponent("toasts.NewSessionToast"),
                });
            }
        }
    }
}
<commit_msg>Move feature flag check for new session toast<commit_after>/*
Copyright 2020 The Matrix.org Foundation C.I.C.

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.
*/

import { MatrixClientPeg } from './MatrixClientPeg';
import SettingsStore from './settings/SettingsStore';
import * as sdk from './index';
import { _t } from './languageHandler';
import ToastStore from './stores/ToastStore';

function toastKey(device) {
    return 'newsession_' + device.deviceId;
}

export default class DeviceListener {
    static sharedInstance() {
        if (!global.mx_DeviceListener) global.mx_DeviceListener = new DeviceListener();
        return global.mx_DeviceListener;
    }

    constructor() {
        // device IDs for which the user has dismissed the verify toast ('Later')
        this._dismissed = new Set();
    }

    start() {
        MatrixClientPeg.get().on('crypto.devicesUpdated', this._onDevicesUpdated);
        MatrixClientPeg.get().on('deviceVerificationChanged', this._onDeviceVerificationChanged);
        this.recheck();
    }

    stop() {
        if (MatrixClientPeg.get()) {
            MatrixClientPeg.get().removeListener('crypto.devicesUpdated', this._onDevicesUpdated);
            MatrixClientPeg.get().removeListener('deviceVerificationChanged', this._onDeviceVerificationChanged);
        }
        this._dismissed.clear();
    }

    dismissVerification(deviceId) {
        this._dismissed.add(deviceId);
        this.recheck();
    }

    _onDevicesUpdated = (users) => {
        if (!users.includes(MatrixClientPeg.get().getUserId())) return;
        this.recheck();
    }

    _onDeviceVerificationChanged = (users) => {
        if (!users.includes(MatrixClientPeg.get().getUserId())) return;
        this.recheck();
    }

    async recheck() {
        if (!SettingsStore.isFeatureEnabled("feature_cross_signing")) return;
        const cli = MatrixClientPeg.get();

        if (!cli.isCryptoEnabled()) return false;

        const devices = await cli.getStoredDevicesForUser(cli.getUserId());
        for (const device of devices) {
            if (device.deviceId == cli.deviceId) continue;

            const deviceTrust = await cli.checkDeviceTrust(cli.getUserId(), device.deviceId);
            if (deviceTrust.isVerified() || this._dismissed.has(device.deviceId)) {
                ToastStore.sharedInstance().dismissToast(toastKey(device));
            } else {
                ToastStore.sharedInstance().addOrReplaceToast({
                    key: toastKey(device),
                    title: _t("New Session"),
                    icon: "verification_warning",
                    props: {deviceId: device.deviceId},
                    component: sdk.getComponent("toasts.NewSessionToast"),
                });
            }
        }
    }
}
<|endoftext|>


<commit_before>import 'emission';
import './storybook';

<commit_msg>[Typescript] removes storybook from Example app entrypoint<commit_after>import 'emission';

<|endoftext|>


<commit_before>/**
 * New Relic agent configuration.
 *
 * See lib/config.defaults.js in the agent distribution for a more complete
 * description of configuration variables and their potential values.
 */
var config = require('./app/config/config');

exports.config = {
  /**
   * Array of application names.
   */
  app_name : ['server_web_app'],
  /**
   * Your New Relic license key.
   */
  license_key : config.newRelicKey,
  logging : {
    /**
     * Level at which to log. 'trace' is most useful to New Relic when diagnosing
     * issues with the agent, 'info' and higher will impose the least overhead on
     * production applications.
     */
    level : 'trace'
  },
  rules: {
    name: [
      { pattern: "/api/secure-service/admin/users/.*", name: "/admin/users/:user" },
      { pattern: "/api/auth/users", name: "/auth/users" },
      { pattern: "/api/auth/users/.*", name: "/auth/users/:user" },
      { pattern: "/api/auth/clients", name: "/auth/clients" },
      { pattern: "/api/auth/clients/.*", name: "/auth/clients:client" },
      { pattern: "/api/auth/oauth2/token", name: "/auth/oauth2/token" },
      { pattern: "/api/auth/password/change", name: "/auth/password/change" },
      { pattern: "/api/auth/password/reset", name: "/auth/password/reset" },
      { pattern: "/api/auth/password/reset/validate-token", name: "/auth/password/reset/validate-token" },
      { pattern: "/api/secure-service/my/clubcards", name: "/my/clubcards" },
      { pattern: "/api/secure-service/clubcards/validation", name: "/clubcards/validation" },
      { pattern: "/api/secure-service/my/creditcards", name: "/my/creditcards" },
      { pattern: "/api/secure-service/my/baskets", name: "/my/baskets" },
      { pattern: "/api/secure-service/my/baskets/items", name: "/my/baskets/items" },
      { pattern: "/api/secure-service/my/payments", name: "/my/payments" },
      { pattern: "/api/secure-service/my/credit", name: "/my/credit" },
      { pattern: "/api/secure-service/my/library", name: "/my/library" },
      { pattern: "/api/local/signout", name: "/local/signout" },
      { pattern: "/api/local/config", name: "/local/config" },
      { pattern: "/api/secure-service/admin/users/.*/credit", name: "/admin/users/:user/credit" },
      { pattern: "/api/secure-service/admin/users/.*/purchases", name: "/admin/users/:user/purchases" }
    ]
  }
};
<commit_msg>Improved Configuration <commit_after>/**
 * New Relic agent configuration.
 *
 * See lib/config.defaults.js in the agent distribution for a more complete
 * description of configuration variables and their potential values.
 */
var config = require('./app/config/config');

exports.config = {
  /**
   * Array of application names.
   */
  app_name : ['server_web_app'],
  capture_params : true,
  /**
   * Your New Relic license key.
   */
  license_key : config.newRelicKey,
  logging : {
    /**
     * Level at which to log. 'trace' is most useful to New Relic when diagnosing
     * issues with the agent, 'info' and higher will impose the least overhead on
     * production applications.
     */
    level : 'trace'
  },
  rules: {
    name: [
      { pattern: "/api/secure-service/admin/users/.*", name: "/admin/users/:user" },
      { pattern: "/api/auth/users", name: "/auth/users" },
      { pattern: "/api/auth/users/.*", name: "/auth/users/:user" },
      { pattern: "/api/auth/clients", name: "/auth/clients" },
      { pattern: "/api/auth/clients/.*", name: "/auth/clients:client" },
      { pattern: "/api/auth/oauth2/token", name: "/auth/oauth2/token" },
      { pattern: "/api/auth/password/change", name: "/auth/password/change" },
      { pattern: "/api/auth/password/reset", name: "/auth/password/reset" },
      { pattern: "/api/auth/password/reset/validate-token", name: "/auth/password/reset/validate-token" },
      { pattern: "/api/secure-service/my/clubcards", name: "/my/clubcards" },
      { pattern: "/api/secure-service/clubcards/validation", name: "/clubcards/validation" },
      { pattern: "/api/secure-service/my/creditcards", name: "/my/creditcards" },
      { pattern: "/api/secure-service/my/baskets", name: "/my/baskets" },
      { pattern: "/api/secure-service/my/baskets/items", name: "/my/baskets/items" },
      { pattern: "/api/secure-service/my/payments", name: "/my/payments" },
      { pattern: "/api/secure-service/my/credit", name: "/my/credit" },
      { pattern: "/api/secure-service/my/library", name: "/my/library" },
      { pattern: "/api/local/signout", name: "/local/signout" },
      { pattern: "/api/local/config", name: "/local/config" },
      { pattern: "/api/secure-service/admin/users/.*/credit", name: "/admin/users/:user/credit" },
      { pattern: "/api/secure-service/admin/users/.*/purchases", name: "/admin/users/:user/purchases" }
    ],
    enforce_backstop : false
  }
};
<|endoftext|>


<commit_before>/**
* Mock permissions endpoints responses for tests.
*
* NOTE: For simplicity we assume that ROOT_URL is empty string.
*/

// /api/v2/permissions/
const permissions = {
  'count': 9,
  'next': null,
  'previous': null,
  'results': [
    {
      'url': '/api/v2/permissions/add_submissions/',
      'codename': 'add_submissions',
      'implied': [
        '/api/v2/permissions/view_asset/'
      ],
      'contradictory': [],
      'name': '',
      'description': 'Can submit data to asset'
    },
    {
      'url': '/api/v2/permissions/change_asset/',
      'codename': 'change_asset',
      'implied': [
        '/api/v2/permissions/view_asset/'
      ],
      'contradictory': [],
      'name': '',
      'description': 'Can change asset'
    },
    {
      'url': '/api/v2/permissions/change_submissions/',
      'codename': 'change_submissions',
      'implied': [
        '/api/v2/permissions/view_asset/',
        '/api/v2/permissions/view_submissions/'
      ],
      'contradictory': [
        '/api/v2/permissions/partial_submissions/'
      ],
      'name': '',
      'description': 'Can modify submitted data for asset'
    },
    {
      'url': '/api/v2/permissions/partial_submissions/',
      'codename': 'partial_submissions',
      'implied': [
        '/api/v2/permissions/view_asset/'
      ],
      'contradictory': [
        '/api/v2/permissions/view_submissions/',
        '/api/v2/permissions/change_submissions/',
        '/api/v2/permissions/validate_submissions/'
      ],
      'name': '',
      'description': 'Can make partial actions onsubmitted data for asset for specific users'
    },
    {
      'url': '/api/v2/permissions/validate_submissions/',
      'codename': 'validate_submissions',
      'implied': [
        '/api/v2/permissions/view_asset/',
        '/api/v2/permissions/view_submissions/'
      ],
      'contradictory': [
        '/api/v2/permissions/partial_submissions/'
      ],
      'name': '',
      'description': 'Can validate submitted data asset'
    },
    {
      'url': '/api/v2/permissions/view_asset/',
      'codename': 'view_asset',
      'implied': [],
      'contradictory': [],
      'name': '',
      'description': 'Can view asset'
    },
    {
      'url': '/api/v2/permissions/view_submissions/',
      'codename': 'view_submissions',
      'implied': [
        '/api/v2/permissions/view_asset/'
      ],
      'contradictory': [
        '/api/v2/permissions/partial_submissions/'
      ],
      'name': '',
      'description': 'Can view submitted data for asset'
    },
    {
      'url': '/api/v2/permissions/change_collection/',
      'codename': 'change_collection',
      'implied': [
        '/api/v2/permissions/view_collection/'
      ],
      'contradictory': [],
      'name': '',
      'description': 'Can change collection'
    },
    {
      'url': '/api/v2/permissions/view_collection/',
      'codename': 'view_collection',
      'implied': [],
      'contradictory': [],
      'name': '',
      'description': 'Can view collection'
    }
  ]
};

// /api/v2/assets/<uid>/permissions/
const assetWithAnonymousUser = {
  'count': 7,
  'next': null,
  'previous': null,
  'results': [
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pTi9qyEax49ZA5RP9KnNHB/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/add_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pATUgtDW6v44QG4dDDpnEV/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pUUcqTtQ6FgEDfHUiQbS24/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/p5BjfEz9JDQtQTzkT7fHA5/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/validate_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pBjfyz5Zxj95866GtEtsR2/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pQGiudmuLvN6iHEdH8dJAs/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pV9kCoWAQT9QUeV2EsTLqj/',
      'user': '/api/v2/users/AnonymousUser/',
      'permission': '/api/v2/permissions/view_asset/'
    }
  ]
};

// /api/v2/assets/<uid>/permissions/
const assetWithMultipleUsers = {
  'count': 9,
  'next': null,
  'previous': null,
  'results': [
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pTi9qyEax49ZA5RP9KnNHB/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/add_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pATUgtDW6v44QG4dDDpnEV/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pUUcqTtQ6FgEDfHUiQbS24/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/p5BjfEz9JDQtQTzkT7fHA5/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/validate_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pBjfyz5Zxj95866GtEtsR2/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pQGiudmuLvN6iHEdH8dJAs/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pETvxGayAJwvPaCnt5biVD/',
      'user': '/api/v2/users/oliver/',
      'permission': '/api/v2/permissions/view_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/p6KekjhZabd7ao9MBQwN7X/',
      'user': '/api/v2/users/john/',
      'permission': '/api/v2/permissions/view_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pxp7BPnP9fohF5ZoH5Uwfa/',
      'user': '/api/v2/users/john/',
      'permission': '/api/v2/permissions/view_asset/'
    }
  ]
};

// /api/v2/assets/<uid>/permissions/
const assetWithPartial = {
  'count': 8,
  'next': null,
  'previous': null,
  'results': [
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pTi9qyEax49ZA5RP9KnNHB/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/add_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pATUgtDW6v44QG4dDDpnEV/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pUUcqTtQ6FgEDfHUiQbS24/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/p5BjfEz9JDQtQTzkT7fHA5/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/validate_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pBjfyz5Zxj95866GtEtsR2/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pQGiudmuLvN6iHEdH8dJAs/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/p6KekjhZabd7ao9MBQwN7X/',
      'user': '/api/v2/users/leszek/',
      'permission': '/api/v2/permissions/view_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pxp7BPnP9fohF5ZoH5Uwfa/',
      'user': '/api/v2/users/leszek/',
      'permission': '/api/v2/permissions/partial_submissions/',
      'partial_permissions': [
        {
          'url': '/api/v2/permissions/view_submissions/',
          'filters': [
            {'_submitted_by': {'$in': ['john', 'oliver']}}
          ]
        },
      ]
    }
  ]
};

export default {
  permissions: permissions,
  assetWithAnon: assetWithAnonymousUser,
  assetWithMulti: assetWithMultipleUsers,
  assetWithPartial: assetWithPartial
};
<commit_msg>Fix a few typos causing front-end tests to fail<commit_after>/**
* Mock permissions endpoints responses for tests.
*
* NOTE: For simplicity we assume that ROOT_URL is empty string.
*/

// /api/v2/permissions/
const permissions = {
  'count': 9,
  'next': null,
  'previous': null,
  'results': [
    {
      'url': '/api/v2/permissions/add_submissions/',
      'codename': 'add_submissions',
      'implied': [
        '/api/v2/permissions/view_asset/'
      ],
      'contradictory': [],
      'name': '',
      'description': 'Can submit data to asset'
    },
    {
      'url': '/api/v2/permissions/change_asset/',
      'codename': 'change_asset',
      'implied': [
        '/api/v2/permissions/view_asset/'
      ],
      'contradictory': [],
      'name': '',
      'description': 'Can change asset'
    },
    {
      'url': '/api/v2/permissions/change_submissions/',
      'codename': 'change_submissions',
      'implied': [
        '/api/v2/permissions/view_asset/',
        '/api/v2/permissions/view_submissions/'
      ],
      'contradictory': [
        '/api/v2/permissions/partial_submissions/'
      ],
      'name': '',
      'description': 'Can modify submitted data for asset'
    },
    {
      'url': '/api/v2/permissions/partial_submissions/',
      'codename': 'partial_submissions',
      'implied': [
        '/api/v2/permissions/view_asset/'
      ],
      'contradictory': [
        '/api/v2/permissions/view_submissions/',
        '/api/v2/permissions/change_submissions/',
        '/api/v2/permissions/validate_submissions/'
      ],
      'name': '',
      'description': 'Can make partial actions onsubmitted data for asset for specific users'
    },
    {
      'url': '/api/v2/permissions/validate_submissions/',
      'codename': 'validate_submissions',
      'implied': [
        '/api/v2/permissions/view_asset/',
        '/api/v2/permissions/view_submissions/'
      ],
      'contradictory': [
        '/api/v2/permissions/partial_submissions/'
      ],
      'name': '',
      'description': 'Can validate submitted data asset'
    },
    {
      'url': '/api/v2/permissions/view_asset/',
      'codename': 'view_asset',
      'implied': [],
      'contradictory': [],
      'name': '',
      'description': 'Can view asset'
    },
    {
      'url': '/api/v2/permissions/view_submissions/',
      'codename': 'view_submissions',
      'implied': [
        '/api/v2/permissions/view_asset/'
      ],
      'contradictory': [
        '/api/v2/permissions/partial_submissions/'
      ],
      'name': '',
      'description': 'Can view submitted data for asset'
    },
    {
      'url': '/api/v2/permissions/change_collection/',
      'codename': 'change_collection',
      'implied': [
        '/api/v2/permissions/view_collection/'
      ],
      'contradictory': [],
      'name': '',
      'description': 'Can change collection'
    },
    {
      'url': '/api/v2/permissions/view_collection/',
      'codename': 'view_collection',
      'implied': [],
      'contradictory': [],
      'name': '',
      'description': 'Can view collection'
    }
  ]
};

// /api/v2/assets/<uid>/permissions/
const assetWithAnonymousUser = {
  'count': 7,
  'next': null,
  'previous': null,
  'results': [
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pTi9qyEax49ZA5RP9KnNHB/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/add_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pATUgtDW6v44QG4dDDpnEV/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pUUcqTtQ6FgEDfHUiQbS24/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/p5BjfEz9JDQtQTzkT7fHA5/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/validate_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pBjfyz5Zxj95866GtEtsR2/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pQGiudmuLvN6iHEdH8dJAs/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pV9kCoWAQT9QUeV2EsTLqj/',
      'user': '/api/v2/users/AnonymousUser/',
      'permission': '/api/v2/permissions/view_asset/'
    }
  ]
};

// /api/v2/assets/<uid>/permissions/
const assetWithMultipleUsers = {
  'count': 9,
  'next': null,
  'previous': null,
  'results': [
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pTi9qyEax49ZA5RP9KnNHB/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/add_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pATUgtDW6v44QG4dDDpnEV/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pUUcqTtQ6FgEDfHUiQbS24/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/p5BjfEz9JDQtQTzkT7fHA5/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/validate_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pBjfyz5Zxj95866GtEtsR2/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pQGiudmuLvN6iHEdH8dJAs/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pETvxGayAJwvPaCnt5biVD/',
      'user': '/api/v2/users/olivier/',
      'permission': '/api/v2/permissions/view_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/p6KekjhZabd7ao9MBQwN7X/',
      'user': '/api/v2/users/john/',
      'permission': '/api/v2/permissions/view_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pxp7BPnP9fohF5ZoH5Uwfa/',
      'user': '/api/v2/users/john/',
      'permission': '/api/v2/permissions/view_asset/'
    }
  ]
};

// /api/v2/assets/<uid>/permissions/
const assetWithPartial = {
  'count': 8,
  'next': null,
  'previous': null,
  'results': [
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pTi9qyEax49ZA5RP9KnNHB/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/add_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pATUgtDW6v44QG4dDDpnEV/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pUUcqTtQ6FgEDfHUiQbS24/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/change_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/p5BjfEz9JDQtQTzkT7fHA5/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/validate_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pBjfyz5Zxj95866GtEtsR2/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pQGiudmuLvN6iHEdH8dJAs/',
      'user': '/api/v2/users/kobo/',
      'permission': '/api/v2/permissions/view_submissions/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/p6KekjhZabd7ao9MBQwN7X/',
      'user': '/api/v2/users/leszek/',
      'permission': '/api/v2/permissions/view_asset/'
    },
    {
      'url': '/api/v2/assets/arMB2dNgwewktv954wmo9e/permissions/pxp7BPnP9fohF5ZoH5Uwfa/',
      'user': '/api/v2/users/leszek/',
      'permission': '/api/v2/permissions/partial_submissions/',
      'partial_permissions': [
        {
          'url': '/api/v2/permissions/view_submissions/',
          'filters': [
            {'_submitted_by': {'$in': ['john', 'olivier']}}
          ]
        },
      ]
    }
  ]
};

export default {
  permissions: permissions,
  assetWithAnon: assetWithAnonymousUser,
  assetWithMulti: assetWithMultipleUsers,
  assetWithPartial: assetWithPartial
};
<|endoftext|>


<commit_before><commit_msg>delineate your lists vs public lists<commit_after><|endoftext|>


<commit_before>define(["dojo/_base/declare", "dojo/_base/array", "dojo/_base/lang", "dojo/Stateful"],
	function(declare, arr, lang, Stateful){

	/*=====
	var Stateful = dojo.Stateful;
	=====*/

	return declare("dojox.widget.Selection", Stateful, {
		// summary:
		//		Base class for widgets that manage a list of selected data items.

		constructor: function(){
			this.selectedItems = [];
		},

		//	selectionMode: String
		//		Valid values are "none", "single", "multiple".
		//		- "none": No selection can be done.
		//		- "single": Only one item can be selected at a time.
		//		- "multiple": Several item can be selected using the control key modifier.
		//		Default value is "single".
		selectionMode: "single",

		_setSelectionModeAttr: function(value){
			if(value != "none" && value != "single" && value != "multiple"){
				value = "single"; //default value
			}
			if(value != this.selectionMode){
				this.selectionMode = value;
				if(value == "none"){
					this.set("selectedItems", null);
				}else if(value == "single"){
					this.set("selectedItem", this.selectedItem); // null or last selected item
				}
			}
		},

		//	selectedItem: Object
		//		In single selection mode, the selected item or in multiple selection mode the last selected item.
		//		Warning: Do not use this property directly, make sure to call set() or get() methods.
		selectedItem: null,

		_setSelectedItemAttr: function(value){
			if(this.selectedItem != value){
				this._set("selectedItem", value);
				this.set("selectedItems", value ? [value] : null);
			}
		},

		//	selectedItems: Object[]
		//		The list of selected items.
		//		Warning: Do not use this property directly, make sure to call set() or get() methods.
		selectedItems: null,

		_setSelectedItemsAttr: function(value){
			var oldSelectedItems = this.selectedItems;

			this.selectedItems = value;
			this.selectedItem = null;

			if(oldSelectedItems != null && oldSelectedItems.length>0){
				this.updateRenderers(oldSelectedItems, true);
			}
			if(this.selectedItems && this.selectedItems.length>0){
				this.selectedItem = this.selectedItems[0];
				this.updateRenderers(this.selectedItems, true);
			}
		},

		_getSelectedItemsAttr: function(){
			return this.selectedItems == null ? [] : this.selectedItems.concat();
		},

		isItemSelected: function(item){
			// summary:
			//		Returns wether an item is selected or not.
			// item: Object
			//		The item to test the selection for.
			if(this.selectedItems == null || this.selectedItems.length== 0){
				return false;
			}

			return arr.some(this.selectedItems, lang.hitch(this, function(sitem){
				return this.getIdentity(sitem) == this.getIdentity(item);
			}));
		},

		getIdentity: function(item){
			//	summary:
			//		This function must be implemented to return the id of a item.
		},

		setItemSelected: function(item, value){
			//	summary:
			//		Change the selection state of an item.
			//	item: Object
			//		The item to change the selection state for.
			//	value: Boolean
			//		True to select the item, false to deselect it.

			if(this.selectionMode == "none" || item == null){
				return;
			}

			// copy is returned
			var sel = this.get("selectedItems");
			var old = this.get("selectedItems");

			if(this.selectionMode == "single"){
				if(value){
					this.set("selectedItem", item);
				}else if(isItemSelected(item)){
					this.set("selectedItems", null);
				}
			}else{ // multiple
				if(value){
					if(this.isItemSelected(item)){
						return; // already selected
					}
					if(sel == null){
						sel = [item];
					}else{
						sel.unshift(item);
					}
					this.set("selectedItems", sel);
				}else{
					var res = arr.filter(sel, function(sitem){
						return sitem.id != item.id;
					});
					if(res == null || res.length == sel.length){
						return; // already not selected
					}
					this.set("selectedItems", res);
				}
			}
		},

		selectFromEvent: function(e, item, renderer, dispatch){
			//	summary:
			//		Applies selection triggered by an user interaction
			//	e: Event
			//		The source event of the user interaction.
			//	item: Object
			//		The render item that has been selected/deselected.
			//	renderer: Object
			//		The visual renderer of the selected/deselected item.
			//	dispatch: Boolean
			//		Whether an event must be dispatched or not.
			//	returns: Boolean
			//		Returns true if the selection has changed and false otherwise.
			//	tags
			//		protected

			if(this.selectionMode == "none"){
				return false;
			}

			var changed;
			var oldSelectedItem = this.get("selectedItem");
			var selected = item ? this.isItemSelected(item): false;

			if(item == null){
				if(!e.ctrlKey && this.selectedItem != null){
					this.set("selectedItem", null);
					changed = true;
				}
			}else if(this.selectionMode == "multiple"){
				 if(e.ctrlKey){
					this.setItemSelected(item, !selected);
					changed = true;
				}else{
					this.set("selectedItem", item);
					changed = true;
				}
			}else{ // single
				if(e.ctrlKey){
					//if the object is selected deselects it.
					this.set("selectedItem", selected ? null : item);
					changed = true;
				}else{
					if(!selected){
						this.set("selectedItem", item);
						changed = true;
					}
				}
			}

			if(dispatch && changed){
				this.dispatchChange(oldSelectedItem, this.get("selectedItem"), renderer, e);
			}

			return changed;
		},

		dispatchChange: function(oldSelectedItem, newSelectedItem, renderer, triggerEvent){
			//	summary:
			//		Dispatch a selection change event.
			//	oldSelectedItem: Object
			//		The previously selectedItem
			//	newSelectedItem: Object
			//		The new selectedItem.
			//	render: Object
			//		The visual renderer of the selected/deselected item.
			//	triggerEvent: Event
			//		The event that lead to the selection of the item.
			this.onChange({
				oldValue: oldSelectedItem,
				newValue: newSelectedItem,
				renderer: renderer,
				triggerEvent: triggerEvent
			});
		},

		onChange: function(){
			// summary:
			//		Called when the selection changed.
			// tags:
			//		callback
		}
	});
});
<commit_msg>fixed missing this reference. !strict.<commit_after>define(["dojo/_base/declare", "dojo/_base/array", "dojo/_base/lang", "dojo/Stateful"],
	function(declare, arr, lang, Stateful){

	/*=====
	var Stateful = dojo.Stateful;
	=====*/

	return declare("dojox.widget.Selection", Stateful, {
		// summary:
		//		Base class for widgets that manage a list of selected data items.

		constructor: function(){
			this.selectedItems = [];
		},

		//	selectionMode: String
		//		Valid values are "none", "single", "multiple".
		//		- "none": No selection can be done.
		//		- "single": Only one item can be selected at a time.
		//		- "multiple": Several item can be selected using the control key modifier.
		//		Default value is "single".
		selectionMode: "single",

		_setSelectionModeAttr: function(value){
			if(value != "none" && value != "single" && value != "multiple"){
				value = "single"; //default value
			}
			if(value != this.selectionMode){
				this.selectionMode = value;
				if(value == "none"){
					this.set("selectedItems", null);
				}else if(value == "single"){
					this.set("selectedItem", this.selectedItem); // null or last selected item
				}
			}
		},

		//	selectedItem: Object
		//		In single selection mode, the selected item or in multiple selection mode the last selected item.
		//		Warning: Do not use this property directly, make sure to call set() or get() methods.
		selectedItem: null,

		_setSelectedItemAttr: function(value){
			if(this.selectedItem != value){
				this._set("selectedItem", value);
				this.set("selectedItems", value ? [value] : null);
			}
		},

		//	selectedItems: Object[]
		//		The list of selected items.
		//		Warning: Do not use this property directly, make sure to call set() or get() methods.
		selectedItems: null,

		_setSelectedItemsAttr: function(value){
			var oldSelectedItems = this.selectedItems;

			this.selectedItems = value;
			this.selectedItem = null;

			if(oldSelectedItems != null && oldSelectedItems.length>0){
				this.updateRenderers(oldSelectedItems, true);
			}
			if(this.selectedItems && this.selectedItems.length>0){
				this.selectedItem = this.selectedItems[0];
				this.updateRenderers(this.selectedItems, true);
			}
		},

		_getSelectedItemsAttr: function(){
			return this.selectedItems == null ? [] : this.selectedItems.concat();
		},

		isItemSelected: function(item){
			// summary:
			//		Returns wether an item is selected or not.
			// item: Object
			//		The item to test the selection for.
			if(this.selectedItems == null || this.selectedItems.length== 0){
				return false;
			}

			return arr.some(this.selectedItems, lang.hitch(this, function(sitem){
				return this.getIdentity(sitem) == this.getIdentity(item);
			}));
		},

		getIdentity: function(item){
			//	summary:
			//		This function must be implemented to return the id of a item.
		},

		setItemSelected: function(item, value){
			//	summary:
			//		Change the selection state of an item.
			//	item: Object
			//		The item to change the selection state for.
			//	value: Boolean
			//		True to select the item, false to deselect it.

			if(this.selectionMode == "none" || item == null){
				return;
			}

			// copy is returned
			var sel = this.get("selectedItems");
			var old = this.get("selectedItems");

			if(this.selectionMode == "single"){
				if(value){
					this.set("selectedItem", item);
				}else if(this.isItemSelected(item)){
					this.set("selectedItems", null);
				}
			}else{ // multiple
				if(value){
					if(this.isItemSelected(item)){
						return; // already selected
					}
					if(sel == null){
						sel = [item];
					}else{
						sel.unshift(item);
					}
					this.set("selectedItems", sel);
				}else{
					var res = arr.filter(sel, function(sitem){
						return sitem.id != item.id;
					});
					if(res == null || res.length == sel.length){
						return; // already not selected
					}
					this.set("selectedItems", res);
				}
			}
		},

		selectFromEvent: function(e, item, renderer, dispatch){
			//	summary:
			//		Applies selection triggered by an user interaction
			//	e: Event
			//		The source event of the user interaction.
			//	item: Object
			//		The render item that has been selected/deselected.
			//	renderer: Object
			//		The visual renderer of the selected/deselected item.
			//	dispatch: Boolean
			//		Whether an event must be dispatched or not.
			//	returns: Boolean
			//		Returns true if the selection has changed and false otherwise.
			//	tags
			//		protected

			if(this.selectionMode == "none"){
				return false;
			}

			var changed;
			var oldSelectedItem = this.get("selectedItem");
			var selected = item ? this.isItemSelected(item): false;

			if(item == null){
				if(!e.ctrlKey && this.selectedItem != null){
					this.set("selectedItem", null);
					changed = true;
				}
			}else if(this.selectionMode == "multiple"){
				 if(e.ctrlKey){
					this.setItemSelected(item, !selected);
					changed = true;
				}else{
					this.set("selectedItem", item);
					changed = true;
				}
			}else{ // single
				if(e.ctrlKey){
					//if the object is selected deselects it.
					this.set("selectedItem", selected ? null : item);
					changed = true;
				}else{
					if(!selected){
						this.set("selectedItem", item);
						changed = true;
					}
				}
			}

			if(dispatch && changed){
				this.dispatchChange(oldSelectedItem, this.get("selectedItem"), renderer, e);
			}

			return changed;
		},

		dispatchChange: function(oldSelectedItem, newSelectedItem, renderer, triggerEvent){
			//	summary:
			//		Dispatch a selection change event.
			//	oldSelectedItem: Object
			//		The previously selectedItem
			//	newSelectedItem: Object
			//		The new selectedItem.
			//	render: Object
			//		The visual renderer of the selected/deselected item.
			//	triggerEvent: Event
			//		The event that lead to the selection of the item.
			this.onChange({
				oldValue: oldSelectedItem,
				newValue: newSelectedItem,
				renderer: renderer,
				triggerEvent: triggerEvent
			});
		},

		onChange: function(){
			// summary:
			//		Called when the selection changed.
			// tags:
			//		callback
		}
	});
});
<|endoftext|>


<commit_before><commit_msg>load saved settings<commit_after><|endoftext|>


<commit_before>angular.module('orderController', [])

	// a filter for the crew names
	.filter('byCrewName', function() {
		// when using ng-repeat, the input that gets passed is each item in the list
		return function(input, crew) {
			//create an empty array for output of items
			var out = [];
			//use Angular's forEach to loop through each item.  'job' here can be called
			//anything because it is just the callback item variable name
			angular.forEach(input, function(job) {
				if (job.crew == crew) out.push(job);
			})
			return out;
		}
	})

	// inject the Order service factory into our controller
	.controller('mainController', ['$scope','$filter','$http','Orders', function($scope, $filter, $http, Orders) {
		$scope.formData = {};
		$scope.formData.date = $filter("date")(Date.now(), 'yyyy-MM-dd');
		/*
		$scope.filterFn = function(crew) {
			if(formData.crew = crew) return true;
			return false;
		};
		*/

		/*
		// get the count of jobs by crew for the Date in datePicker
		$scope.getTotalByCrew = function(crew) {
			return Orders.getTotalByCrew(crew, $scope.formData.date);
		};
		*/

		$scope.loading = true;

		// GET =====================================================================
		// when landing on the page, get all orders and show them
		// use the service to get all the orders
		console.log("*** controllers/main/ Orders.getByDate($scope.formData.date) ***" + Date.now());
		Orders.getByDate($scope.formData.date)
		//Orders.get()
			.success(function(data) {
				//console.log("*** controllers/main/ Orders.getByDate($scope.dormData.date) ***");
				console.log("*** controllers/main/ Orders.getByDate().success ***" + Date.now());
				$scope.orders = data;
				$scope.loading = false;
			});

		// get all orders by date
		$scope.getOrdersByDate = function() {
			$scope.loading = true;

			console.log("*** controllers/main/ Orders.getByDate($scope.formData.date) ***" + Date.now());
			Orders.getByDate($scope.formData.date)
			//Orders.get()
				.success(function(data) {
					//console.log("*** controllers/main/ Orders.getByDate($scope.dormData.date) ***");
					console.log("*** controllers/main/ Orders.getByDate().success ***" + Date.now());
					$scope.orders = data;
					$scope.loading = false;
				});
		};

		// CREATE ==================================================================
		// when submitting the add form, send the text to the node API
		$scope.createOrder = function() {

			// let Address field be blank
			if ($scope.formData.date == undefined) {
				$scope.formData.date = Date.now();
			}
			// let Address field be blank
			if ($scope.formData.crew == undefined) {
				$scope.formData.crew = '';
			}
			// let Address field be blank
			if ($scope.formData.address == undefined) {
				$scope.formData.address = '';
			}
			// let Notes field be blank
			if ($scope.formData.total === undefined) {
				$scope.formData.total = 0;
			}
			// let Notes field be blank
			if ($scope.formData.confirm == undefined) {
				$scope.formData.confirm = '';
			}
			// let Notes field be blank
			if ($scope.formData.notes == undefined) {
				$scope.formData.notes = '';
			}
			// validate the formData to make sure that something is there
			// if form is empty, nothing will happen
			if ($scope.formData.custName != undefined) {
				$scope.loading = true;

				// call the create function from our service (returns a promise object)
				Orders.create($scope.formData)

					// if successful creation, call our get function to get all the new orders
					.success(function(data) {
						$scope.loading = false;
						// clear the form so our user is ready to enter another
						$scope.formData.custName = '';
						$scope.formData.address = '';
						$scope.formData.total = undefined;
						$scope.formData.confirm = undefined;
						$scope.formData.notes = '';
						$scope.orders = data; // assign our new list of orders
					});
			}
		};

		// DELETE ==================================================================
		// delete an order after checking it
		$scope.deleteOrder = function(id, date) {
			$scope.loading = true;

			Orders.delete(id, date)
				// if successful creation, call our get function to get all the new orders
				.success(function(data) {
					$scope.loading = false;
					$scope.orders = data; // assign our new list of orders
				});
		};
	}]);
<commit_msg>ADD Order.getByDate() to main controller so it get called immediately on load of controller<commit_after>angular.module('orderController', [])

	// a filter for the crew names
	.filter('byCrewName', function() {
		// when using ng-repeat, the input that gets passed is each item in the list
		return function(input, crew) {
			//create an empty array for output of items
			var out = [];
			//use Angular's forEach to loop through each item.  'job' here can be called
			//anything because it is just the callback item variable name
			angular.forEach(input, function(job) {
				if (job.crew == crew) out.push(job);
			})
			return out;
		}
	})

	// inject the Order service factory into our controller
	.controller('mainController', ['$scope','$filter','$http','Orders', function($scope, $filter, $http, Orders) {
		$scope.formData = {};
		$scope.formData.crews = [{ foreman : 'Ken'}, { foreman : 'Gary'}, { foreman : 'Jim'}, { foreman : 'David'}];
		$scope.formData.date = $filter("date")(Date.now(), 'yyyy-MM-dd');

		$scope.loading = true;

		// when landing on the page, get all orders and show them
		Orders.getByDate($scope.formData.date)
			.success(function(data) {
				$scope.orders = data;
				$scope.loading = false;
			});

		// get the count of jobs by crew for the Date in datePicker
		$scope.getTotalByCrew = function(crew) {
			//return Orders.getTotalByCrew(crew, $scope.formData.date);
			return 5;
		};

		// GET BY DATE & CREW ======================================================
		// get all orders by date
		$scope.getOrdersByDateAndCrew = function(crew) {

			Orders.getByDateAndCrew($scope.formData.date, crew)
				.success(function(data) {
					return data;
				});
			//return an empty array if getByDateAndCrew() fails
			return [];
		};

		// GET BY DATE =============================================================
		// when landing on the page, get all orders and show them
		// get all orders by date
		$scope.getOrdersByDate = function() {
			$scope.loading = true;

			Orders.getByDate($scope.formData.date)
				.success(function(data) {
					$scope.orders = data;
					$scope.loading = false;
				});
		};

		// CREATE ==================================================================
		// when submitting the add form, send the text to the node API
		$scope.createOrder = function() {

			// let Address field be blank
			if ($scope.formData.date == undefined) {
				$scope.formData.date = Date.now();
			}
			// let Address field be blank
			if ($scope.formData.crew == undefined) {
				$scope.formData.crew = '';
			}
			// let Address field be blank
			if ($scope.formData.address == undefined) {
				$scope.formData.address = '';
			}
			// let Notes field be blank
			if ($scope.formData.total === undefined) {
				$scope.formData.total = 0;
			}
			// let Notes field be blank
			if ($scope.formData.confirm == undefined) {
				$scope.formData.confirm = '';
			}
			// let Notes field be blank
			if ($scope.formData.notes == undefined) {
				$scope.formData.notes = '';
			}
			// validate the formData to make sure that something is there
			// if form is empty, nothing will happen
			if ($scope.formData.custName != undefined) {
				$scope.loading = true;

				// call the create function from our service (returns a promise object)
				Orders.create($scope.formData)

					// if successful creation, call our get function to get all the new orders
					.success(function(data) {
						$scope.loading = false;
						// clear the form so our user is ready to enter another
						$scope.formData.custName = '';
						$scope.formData.address = '';
						$scope.formData.total = undefined;
						$scope.formData.confirm = undefined;
						$scope.formData.notes = '';
						$scope.orders = data; // assign our new list of orders
					});
			}
		};

		// DELETE ==================================================================
		// delete an order after checking it
		$scope.deleteOrder = function(id, date) {
			$scope.loading = true;

			Orders.delete(id, date)
				// if successful creation, call our get function to get all the new orders
				.success(function(data) {
					$scope.loading = false;
					$scope.orders = data; // assign our new list of orders
				});
		};
	}]);
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');

var BOOT2DOCKER = 'Boot2Docker';

var PROVIDER_URL_V1_4_1 =
  'https://github.com/boot2docker/osx-installer/releases/download/v1.4.1/' +
  'Boot2Docker-1.4.1.pkg';
var PROVIDER_URL_PACKAGE = PROVIDER_URL_V1_4_1;

var PROVIDER_URL_PROFILE =
  'https://raw.githubusercontent.com/' +
  'kalabox/kalabox-boot2docker/master/profile';

module.exports = function(kbox) {

  var sysProfiler = kbox.install.sysProfiler;

  // Boot2docker installed?
  kbox.install.registerStep(function(step) {
    step.name = 'is-boot2docker-installed';
    step.description = 'Check if boot2docker is installed.';
    step.deps = [];
    step.all.darwin = function(state, done) {
      sysProfiler.isAppInstalled(BOOT2DOCKER, function(err, isInstalled) {
        if (err) {
          done(err);
        } else {
          state.isBoot2DockerInstalled = isInstalled;
          state.log(BOOT2DOCKER + ' is installed?: ' + isInstalled);
          done();
        }
      });
    };
  });

  // Boot2docker profile set?
  kbox.install.registerStep(function(step) {
    step.name = 'is-boot2docker-profile-set';
    step.description = 'Check if boot2docker profile is set.';
    step.deps = [];
    step.all.darwin = function(state, done) {
      state.boot2dockerProfileFilepath = path.join(
        state.config.sysProviderRoot,
        'profile'
      );
      fs.exists(state.boot2dockerProfileFilepath, function(exists) {
        state.isBoot2dockerProfileSet = exists;
        state.log('Boot2docker profile set?: ' + exists);
        done();
      });
    };
  });

  // Download docker dependencies
  kbox.install.registerStep(function(step) {
    step.name = 'download-boot2docker-dependencies';
    step.description = 'Download docker dependencies';
    step.deps = [
      'is-boot2docker-installed',
      'is-boot2docker-profile-set',
      'internet'
    ];
    step.all.darwin = function(state, done) {

      // Init.
      if (!state.downloadDir) {
        state.downloadDir = kbox.util.disk.getTempDir();
      }
      state.dockerDependencyDownloads = [];

      // Boot2docker profile.
      if (!state.isBoot2dockerProfileSet) {
        state.dockerDependencyDownloads.push(PROVIDER_URL_PROFILE);
        state.boot2dockerProfileDownloadFilepath = path.join(
          state.downloadDir,
          path.basename(PROVIDER_URL_PROFILE)
        );
      }

      // Boot2docker package.
      if (!state.isBoot2DockerInstalled) {
        state.dockerDependencyDownloads.push(PROVIDER_URL_PACKAGE);
        state.boot2dockerPackageDownloadFilepath = path.join(
          state.downloadDir,
          path.basename(PROVIDER_URL_PACKAGE)
        );
      }

      // Download dependencies/
      var urls = state.dockerDependencyDownloads;
      urls.forEach(function(url) {
        state.log(url);
      });
      if (urls.length > 0) {
        kbox.util.download.downloadFiles(urls, state.downloadDir, function(err) {
          if (err) {
            state.log(state.status.notOk);
            done(err);
          } else {
            state.log(state.status.ok);
            done();
          }
        });
      } else {
        done();
      }

    };
  });

  // Setup Boot2docker profile.
  kbox.install.registerStep(function(step) {
    step.name = 'boot2docker-profile';
    step.description = 'Setup the boot2docker profile.';
    step.deps = ['download-boot2docker-dependencies'];
    step.all.darwin = function(state, done) {
      if (!state.isBoot2dockerProfileSet) {
        mkdirp.sync(state.config.sysProviderRoot);
        var src = state.boot2dockerProfileDownloadFilepath;
        var dst = state.boot2dockerProfileFilepath;
        fs.rename(src, dst, function(err) {
          if (err) {
            state.log(state.status.notOk);
            done(err);
          } else {
            state.log(state.status.ok);
            done();
          }
        });
      } else {
        state.log(state.status.ok);
        done();
      }
    };
  });

  // Install Boot2docker.
  kbox.install.registerStep(function(step) {
    step.name = 'install-engine';
    step.description  = 'Install boot2docker package.';
    step.deps = [
      'boot2docker-profile',
      'download-boot2docker-dependencies'
    ];
    step.all.darwin = function(state, done) {
      if (!state.isBoot2DockerInstalled) {
        kbox.util.disk.getMacVolume(function(err, volume) {
          if (err) {
            state.log(state.status.notOk);
            done(err);
          } else {
            var pkg = state.boot2dockerPackageDownloadFilepath;
            var cmd = kbox.install.cmd.buildInstallCmd(pkg, volume);
            var cmds = [cmd];
            var child = kbox.install.cmd.runCmdsAsync(cmds);
            child.stdout.on('data', function(data) {
              state.log(data);
            });
            child.stdout.on('end', function() {
              state.log(state.status.ok);
              done();
            });
            child.stderr.on('data', function(data) {
              state.log(state.status.notOk);
              done(new Error(data));
            });
          }
        });
      } else {
        state.log(state.status.ok);
        done();
      }
    };
  });

  // Init and start Boot2docker.
  kbox.install.registerStep(function(step) {
    step.name = 'init-engine';
    step.description = 'Init and start boot2docker';
    step.deps = ['install-engine'];
    step.all.darwin = function(state, done) {
      var iso = path.join(state.config.sysProviderRoot, 'boot2docker.iso');
      console.log('iso -> ' + iso);
      var exists = fs.existsSync(iso);
      console.log('exists -> ' + exists);
      if (exists) {
        fs.unlinkSync(iso);
      }
      kbox.engine.provider.up(function(err, data) {
        if (data) {
          state.log(data);
        }

        if (err) {
          state.log(state.status.notOk);
          done(err);
        } else {
          state.log(state.status.ok);
          done();
        }
      });
    };
  });

};
<commit_msg>Fixing code styling errors.<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');

var BOOT2DOCKER = 'Boot2Docker';

var PROVIDER_URL_V1_4_1 =
  'https://github.com/boot2docker/osx-installer/releases/download/v1.4.1/' +
  'Boot2Docker-1.4.1.pkg';
var PROVIDER_URL_PACKAGE = PROVIDER_URL_V1_4_1;

var PROVIDER_URL_PROFILE =
  'https://raw.githubusercontent.com/' +
  'kalabox/kalabox-boot2docker/master/profile';

module.exports = function(kbox) {

  var sysProfiler = kbox.install.sysProfiler;

  // Boot2docker installed?
  kbox.install.registerStep(function(step) {
    step.name = 'is-boot2docker-installed';
    step.description = 'Check if boot2docker is installed.';
    step.deps = [];
    step.all.darwin = function(state, done) {
      sysProfiler.isAppInstalled(BOOT2DOCKER, function(err, isInstalled) {
        if (err) {
          done(err);
        } else {
          state.isBoot2DockerInstalled = isInstalled;
          state.log(BOOT2DOCKER + ' is installed?: ' + isInstalled);
          done();
        }
      });
    };
  });

  // Boot2docker profile set?
  kbox.install.registerStep(function(step) {
    step.name = 'is-boot2docker-profile-set';
    step.description = 'Check if boot2docker profile is set.';
    step.deps = [];
    step.all.darwin = function(state, done) {
      state.boot2dockerProfileFilepath = path.join(
        state.config.sysProviderRoot,
        'profile'
      );
      fs.exists(state.boot2dockerProfileFilepath, function(exists) {
        state.isBoot2dockerProfileSet = exists;
        state.log('Boot2docker profile set?: ' + exists);
        done();
      });
    };
  });

  // Download docker dependencies
  kbox.install.registerStep(function(step) {
    step.name = 'download-boot2docker-dependencies';
    step.description = 'Download docker dependencies';
    step.deps = [
      'is-boot2docker-installed',
      'is-boot2docker-profile-set',
      'internet'
    ];
    step.all.darwin = function(state, done) {

      // Init.
      if (!state.downloadDir) {
        state.downloadDir = kbox.util.disk.getTempDir();
      }
      state.dockerDependencyDownloads = [];

      // Boot2docker profile.
      if (!state.isBoot2dockerProfileSet) {
        state.dockerDependencyDownloads.push(PROVIDER_URL_PROFILE);
        state.boot2dockerProfileDownloadFilepath = path.join(
          state.downloadDir,
          path.basename(PROVIDER_URL_PROFILE)
        );
      }

      // Boot2docker package.
      if (!state.isBoot2DockerInstalled) {
        state.dockerDependencyDownloads.push(PROVIDER_URL_PACKAGE);
        state.boot2dockerPackageDownloadFilepath = path.join(
          state.downloadDir,
          path.basename(PROVIDER_URL_PACKAGE)
        );
      }

      // Download dependencies/
      var urls = state.dockerDependencyDownloads;
      urls.forEach(function(url) {
        state.log(url);
      });
      if (urls.length > 0) {
        var dir = state.downloadDir;
        kbox.util.download.downloadFiles(urls, dir, function(err) {
          if (err) {
            state.log(state.status.notOk);
            done(err);
          } else {
            state.log(state.status.ok);
            done();
          }
        });
      } else {
        done();
      }

    };
  });

  // Setup Boot2docker profile.
  kbox.install.registerStep(function(step) {
    step.name = 'boot2docker-profile';
    step.description = 'Setup the boot2docker profile.';
    step.deps = ['download-boot2docker-dependencies'];
    step.all.darwin = function(state, done) {
      if (!state.isBoot2dockerProfileSet) {
        mkdirp.sync(state.config.sysProviderRoot);
        var src = state.boot2dockerProfileDownloadFilepath;
        var dst = state.boot2dockerProfileFilepath;
        fs.rename(src, dst, function(err) {
          if (err) {
            state.log(state.status.notOk);
            done(err);
          } else {
            state.log(state.status.ok);
            done();
          }
        });
      } else {
        state.log(state.status.ok);
        done();
      }
    };
  });

  // Install Boot2docker.
  kbox.install.registerStep(function(step) {
    step.name = 'install-engine';
    step.description  = 'Install boot2docker package.';
    step.deps = [
      'boot2docker-profile',
      'download-boot2docker-dependencies'
    ];
    step.all.darwin = function(state, done) {
      if (!state.isBoot2DockerInstalled) {
        kbox.util.disk.getMacVolume(function(err, volume) {
          if (err) {
            state.log(state.status.notOk);
            done(err);
          } else {
            var pkg = state.boot2dockerPackageDownloadFilepath;
            var cmd = kbox.install.cmd.buildInstallCmd(pkg, volume);
            var cmds = [cmd];
            var child = kbox.install.cmd.runCmdsAsync(cmds);
            child.stdout.on('data', function(data) {
              state.log(data);
            });
            child.stdout.on('end', function() {
              state.log(state.status.ok);
              done();
            });
            child.stderr.on('data', function(data) {
              state.log(state.status.notOk);
              done(new Error(data));
            });
          }
        });
      } else {
        state.log(state.status.ok);
        done();
      }
    };
  });

  // Init and start Boot2docker.
  kbox.install.registerStep(function(step) {
    step.name = 'init-engine';
    step.description = 'Init and start boot2docker';
    step.deps = ['install-engine'];
    step.all.darwin = function(state, done) {
      var iso = path.join(state.config.sysProviderRoot, 'boot2docker.iso');
      console.log('iso -> ' + iso);
      var exists = fs.existsSync(iso);
      console.log('exists -> ' + exists);
      if (exists) {
        fs.unlinkSync(iso);
      }
      kbox.engine.provider.up(function(err, data) {
        if (data) {
          state.log(data);
        }

        if (err) {
          state.log(state.status.notOk);
          done(err);
        } else {
          state.log(state.status.ok);
          done();
        }
      });
    };
  });

};
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');

var ignoreRegex = process.env.IGNORE ? new RegExp(process.env.IGNORE) : null;

function wgetDirCmd(rootPath, destination , trimToDestination, prefix)
{
    //Plug app copy in template
    var cmd = prefix ? prefix : "";
    var addedOne = false;
    var acceptExtensionFlag = "";

    fs.readdirSync(rootPath).forEach((filename) => {
        if(filename != "node_modules" && (ignoreRegex && (!ignoreRegex.test(filename))))
        {
            if(fs.lstatSync(path.join(rootPath, filename)).isDirectory())
            {
                var cmdForDir = wgetDirCmd(path.join(rootPath, filename), destination, trimToDestination, "");
                if((!addedOne) && cmdForDir != "")
                {
                    addedOne = true;
                }
                else
                {
                    cmd += " && ";
                }
                cmd += (" " + cmdForDir)
            }
            else
            {
                if(!addedOne)
                {
                    addedOne = true;

                }
                else
                {
                    cmd += " && ";
                }

                acceptExtensionFlag = path.extname(filename) != '' ? '-A'+path.extname(filename) : '';

                cmd += ("mkdir -p "+rootPath.replace(trimToDestination, destination)+" && wget 'http://"+process.env.DOCKER_LOCALHOST+":"+process.env.EXTERNAL_PORT+path.join(rootPath, filename) + "' --output-document=\"" + path.join(destination, path.join(rootPath, filename).replace(trimToDestination+"/", ""))+"\"");
            }
        }
    });

    return cmd;
}

module.exports = wgetDirCmd;
<commit_msg>Bug fix in image builder<commit_after>const fs = require('fs');
const path = require('path');

var ignoreRegex = process.env.IGNORE ? new RegExp(process.env.IGNORE) : null;

function wgetDirCmd(rootPath, destination , trimToDestination, prefix)
{
    //Plug app copy in template
    var cmd = prefix ? prefix : "";
    var addedOne = false;
    var acceptExtensionFlag = "";

    fs.readdirSync(rootPath).forEach((filename) => {
        if(filename != "node_modules" && (ignoreRegex && (!ignoreRegex.test(filename))))
        {
            if(fs.lstatSync(path.join(rootPath, filename)).isDirectory())
            {
                var cmdForDir = wgetDirCmd(path.join(rootPath, filename), destination, trimToDestination, "");
                if(cmdForDir != "")
                {
                    if((!addedOne))
                    {
                        addedOne = true;
                        cmd += " ";
                    }
                    else
                    {
                        cmd += " && ";
                    }
                    cmd += cmdForDir;
                }
            }
            else
            {
                if(!addedOne)
                {
                    addedOne = true;

                }
                else
                {
                    cmd += " && ";
                }

                acceptExtensionFlag = path.extname(filename) != '' ? '-A'+path.extname(filename) : '';

                cmd += ("mkdir -p "+rootPath.replace(trimToDestination, destination)+" && wget 'http://"+process.env.DOCKER_LOCALHOST+":"+process.env.EXTERNAL_PORT+path.join(rootPath, filename) + "' --output-document=\"" + path.join(destination, path.join(rootPath, filename).replace(trimToDestination+"/", ""))+"\"");
            }
        }
    });

    return cmd;
}

module.exports = wgetDirCmd;
<|endoftext|>


<commit_before>#!/usr/bin/env node

// Dependencies
var sys = require("sys");
var exec = require("child_process").exec;
var pkg = require("./package.json");

// Display Banner
console.log();
console.log("=====");
console.log("===== "+pkg.name+", "+pkg.version);
console.log("===== "+pkg.description);
console.log("=====");
console.log();

// Helpers
function hasWhiteSpace(s) {
      return s.indexOf(' ') >= 0;
}

// Check for White Space in Path, Issue #11.
try {
    require('nodegit') // Checking if nodegit is successfully installed
} catch (e) {
    // nodegit not found
    if (
            hasWhiteSpace(__dirname) // if nodegit is not installed, verify the installation path does not contain spaces
            ) {
        console.error("Your installation directory has white space characters.");
        console.log("See issue at https://github.com/Glavin001/Coders-Classroom/issues/11");
        console.log("We recommend changing your path from: ")
        console.log("> '"+__dirname+"'");
        console.log("to: ");
        console.log("> '"+__dirname.replace(/\s/g, "_")+"'");
        console.log("such that you use underscores ('_') instead of spaces.");
        console.log();

        process.exit(1);
    }
}

// NPM Install
var npmInstall = function(package, callback) {
    exec('npm install '+(package||""), function(error, stdout, stderr) {
        callback(error,stdout,stderr);
    });
};

// Bower Install
var bowerInstall = function(package, callback) {
    exec('bower install '+(package||""), function(error, stdout, stderr) {
        callback(error,stdout,stderr);
    });
};

// Install Dependencies
console.log("Installing dependencies...");
//yesno.ask("Would you like to install all node dependencies with 'npm install'?", true, function(npmOk) {
    //yesno.ask("Would you like to install all bower dependencies with 'npm install'?", true, function(bowerOk) {
        if (true || npmOk) {
            npmInstall(null, function(error, stdout, stderr) {
                if (error) {
                    console.log(error, stderr);
                    console.log();
                    console.log("For more information, run `npm install` again on your own.");
                } else {
                    console.log("NPM successfully installed dependencies.");
                }
            });
        }
        if (true || bowerOk) {
            bowerInstall(null, function(error, stdout, stderr) {
                if (error) {
                    console.log(error, stderr);
                    console.log();
                    console.log("For more information, run `bower install` again on your own.");
                } else {
                    console.log("Bower successfully installed dependencies.");
                }
            });
        }
    //});
//});

<commit_msg>Closes #12. Checks if Bower is installed before installing Bower dependencies.<commit_after>#!/usr/bin/env node

// Dependencies
var sys = require("sys");
var exec = require("child_process").exec;
var pkg = require("./package.json");

// Display Banner
console.log();
console.log("=====");
console.log("===== "+pkg.name+", "+pkg.version);
console.log("===== "+pkg.description);
console.log("=====");
console.log();

// Helpers
function hasWhiteSpace(s) {
      return s.indexOf(' ') >= 0;
}

// Check for White Space in Path, Issue #11.
try {
    require('nodegit') // Checking if nodegit is successfully installed
} catch (e) {
    // nodegit not found
    if (
            hasWhiteSpace(__dirname) // if nodegit is not installed, verify the installation path does not contain spaces
            ) {
        console.error("Your installation directory has white space characters.");
        console.log("See issue at https://github.com/Glavin001/Coders-Classroom/issues/11");
        console.log("We recommend changing your path from: ")
        console.log("> '"+__dirname+"'");
        console.log("to: ");
        console.log("> '"+__dirname.replace(/\s/g, "_")+"'");
        console.log("such that you use underscores ('_') instead of spaces.");
        console.log();

        process.exit(1);
    }
}

// NPM Install
var npmInstall = function(package, callback) {
    exec('npm install '+(package||""), function(error, stdout, stderr) {
        callback(error,stdout,stderr);
    });
};

// Bower Install
var bowerInstall = function(package, callback) {
    try {
        require('bower') // Checking if bower is successfully installed

        var bowerCmd = "./node_modules/bower/bin/bower";
        exec(bowerCmd+' install '+(package||""), function(error, stdout, stderr) {
            callback(error,stdout,stderr);
        });
    } catch (e) {
        callback(e, null, "Bower not installed.");
    }
};

// Install Dependencies
console.log("Installing NPM dependencies.");
npmInstall(null, function(error, stdout, stderr) {
    if (error) {
        console.log(error, stderr);
        console.log();
        console.log("For more information, run `npm install` again on your own.");
    } else {
        console.log("=> NPM successfully installed dependencies.");
        console.log();
        console.log("Installing Bower dependencies.");
        bowerInstall(null, function(error, stdout, stderr) {
            if (error) {
                console.log(error, stderr);
                console.log();
                console.log("For more information, run `bower install` again on your own.");
            } else {
                console.log("=> Bower successfully installed dependencies.");
                console.log();
            }
        });

    }
});

<|endoftext|>


<commit_before>(function($){
 	$.fn.fontface = function(options) {
		var stacks = {
				serif : ", Times New Roman , serif",
				sansserif : ", Helvetica, Arial, sans-serif"
			},
			 defaults = {
				filePath: "/fonts/All/",//change this to your font directory location
				fontFamily: "sans-serif",
				fontStack: false,
				fontStretch: "normal",
				fontStyle: "normal",
				fontVariant: "normal",
				fontWeight: "normal"
			},
			options = $.extend(defaults, options);

		options.fontFile = options.filePath + options.fileName;

		if (options.fontStack || options.fontFamily === "sans-serif") {
			if (options.fontStack && options.fontStack.indexOf(", ") === -1) {
				options.fontFamily = options.fontName + stacks[options.fontStack];
			}
			else if (options.fontStack && options.fontStack.indexOf(", ") !== -1) {
				var concat = (options.fontStack.substring(0,2) !== ", ") ? "" : ", ";
				options.fontFamily = options.fontName + concat + options.fontStack;
			}
			else {
				options.fontFamily = options.fontName + stacks.sansserif
			}
		}

		if (typeof options.fontFamily === "object") {
			options.fontFamily = options.fontFamily.join(", ");
		}

		if ($("#jQueryFontFace").length === 0) {//haven't already made one
			$("head").prepend($("<style type=\"text/css\" id=\"jQueryFontFace\"/>"));
		}

		var FF = {
			selector: function (obj) {
				var tag = obj.tagName,
					className = (obj.className) ? "." + obj.className.split(" ").join(".") : "",
					id = ($(obj).attr("id")) ? "#" + $(obj).attr("id") : "";

				return tag + id + className;
			},
			create: function (obj) {
				var fontFace = "",
					rule = "",
					fontfamily = options.fontFamily.replace(/\s/g,"").replace(/,/g,""),
					fontfamilyStyleWeight = fontfamily + options.fontStyle + options.fontWeight,
					selector = FF.selector(obj);

				if (!$("#jQueryFontFace").data(fontfamilyStyleWeight)) {
					fontFace = [
						"@font-face {",
							"\tfont-family: \"" + options.fontName + "\";",
							"\tsrc: url('" + options.fontFile + ".eot');",
							"\tsrc: local('â˜º'), url('" + options.fontFile + ".woff') format('woff'), url('" + options.fontFile + ".ttf') format('truetype'), url('" + options.fontFile + ".svg#" + fontfamily + "') format('svg');",
							"\tfont-stretch: " + options.fontStretch + ";",
							"\tfont-style: " + options.fontStyle + ";",
							"\tfont-variant: " + options.fontVariant + ";",
							"\tfont-weight: " + options.fontWeight + ";",
						"}"
					].join("\n");
					$("#jQueryFontFace").data(fontfamilyStyleWeight, true);
				}

				if (!$("#jQueryFontFace").data(selector)) {
					rule = [
						selector + " {",
							"\tfont-family: " + FF.quote(options.fontFamily) + " !important;",
						"}"
					].join("\n");
					$("#jQueryFontFace").data(selector, selector);
				}

				return (fontFace.length || rule.length) ? fontFace + "\n" + rule + "\n" : "";
			},
			quote: function (string) {
				var split = string.split(", "),
					length = split.length;
				for (var i = 0; i < length; i += 1) {
					if (split[i].indexOf(" ") !== -1) {
						split[i] = '"' + split[i] + '"';
					}
				}
				return split.join(", ");
			}
		};

		return this.each(function() {
			$("#jQueryFontFace").text($("#jQueryFontFace").text() + FF.create(this));
		});
	};
})(jQuery);

/* ----------------------- */
/* ----------------------- */
/* ----------------------- */

$(document).ready(function (){
  $(".flama-bold-italic").fontface({
    fontName : "Flama-BoldItalic",
    fileName : "hinted-Flama-BoldItalic",
    fontWeight : "bold"
  });
  $(".flama").fontface({
    fontName : "Flama",
    fileName : "hinted-Flama",
    fontWeight : "bold"
  });
  $(".flama-book-italic").fontface({
    fontName : "FlamaBook",
    fileName : "hinted-Flama-Medium",
    fontWeight : "normal",
    fontStyle: "italic"
  });

  $(".ag-medium").fontface({
    fontName : "Akzidenz Grotesk BE",
    fileName : "hinted-AkzidenzGroteskBE-Md",
    fontWeight : "500"
  });
  $(".ag-regular").fontface({
    fontName : "Akzidenz Grotesk BE",
    fileName : "hinted-AkzidenzGroteskBE-Regular",
    fontWeight : "normal"
  });
});
<commit_msg>fontUtils.js clases añadidas<commit_after>( function ( $ ) {
  $.fn.fontface = function ( options ) {
    var stacks = {
        serif: ", Times New Roman , serif",
        sansserif: ", Helvetica, Arial, sans-serif"
      },
      defaults = {
        filePath: "/fonts/All/", //change this to your font directory location
        fontFamily: "sans-serif",
        fontStack: false,
        fontStretch: "normal",
        fontStyle: "normal",
        fontVariant: "normal",
        fontWeight: "normal"
      },
      options = $.extend( defaults, options );

    options.fontFile = options.filePath + options.fileName;

    if ( options.fontStack || options.fontFamily === "sans-serif" ) {
      if ( options.fontStack && options.fontStack.indexOf( ", " ) === -1 ) {
        options.fontFamily = options.fontName + stacks[ options.fontStack ];
      }
      else if ( options.fontStack && options.fontStack.indexOf( ", " ) !== -1 ) {
        var concat = ( options.fontStack.substring( 0, 2 ) !== ", " ) ? "" : ", ";
        options.fontFamily = options.fontName + concat + options.fontStack;
      }
      else {
        options.fontFamily = options.fontName + stacks.sansserif
      }
    }

    if ( typeof options.fontFamily === "object" ) {
      options.fontFamily = options.fontFamily.join( ", " );
    }

    if ( $( "#jQueryFontFace" ).length === 0 ) { //haven't already made one
      $( "head" ).prepend( $( "<style type=\"text/css\" id=\"jQueryFontFace\"/>" ) );
    }

    var FF = {
      selector: function ( obj ) {
        var tag = obj.tagName,
          className = ( obj.className ) ? "." + obj.className.split( " " ).join( "." ) : "",
          id = ( $( obj ).attr( "id" ) ) ? "#" + $( obj ).attr( "id" ) : "";

        return tag + id + className;
      },
      create: function ( obj ) {
        var fontFace = "",
          rule = "",
          fontfamily = options.fontFamily.replace( /\s/g, "" ).replace( /,/g, "" ),
          fontfamilyStyleWeight = fontfamily + options.fontStyle + options.fontWeight,
          selector = FF.selector( obj );

        if ( !$( "#jQueryFontFace" ).data( fontfamilyStyleWeight ) ) {
          fontFace = [
						"@font-face {",
							"\tfont-family: \"" + options.fontName + "\";",
							"\tsrc: url('" + options.fontFile + ".eot');",
							"\tsrc: local('â˜º'), url('" + options.fontFile + ".woff') format('woff'), url('" + options.fontFile + ".ttf') format('truetype'), url('" + options.fontFile + ".svg#" + fontfamily + "') format('svg');",
							"\tfont-stretch: " + options.fontStretch + ";",
							"\tfont-style: " + options.fontStyle + ";",
							"\tfont-variant: " + options.fontVariant + ";",
							"\tfont-weight: " + options.fontWeight + ";",
						"}"
					].join( "\n" );
          $( "#jQueryFontFace" ).data( fontfamilyStyleWeight, true );
        }

        if ( !$( "#jQueryFontFace" ).data( selector ) ) {
          rule = [
						selector + " {",
							"\tfont-family: " + FF.quote( options.fontFamily ) + " !important;",
						"}"
					].join( "\n" );
          $( "#jQueryFontFace" ).data( selector, selector );
        }

        return ( fontFace.length || rule.length ) ? fontFace + "\n" + rule + "\n" : "";
      },
      quote: function ( string ) {
        var split = string.split( ", " ),
          length = split.length;
        for ( var i = 0; i < length; i += 1 ) {
          if ( split[ i ].indexOf( " " ) !== -1 ) {
            split[ i ] = '"' + split[ i ] + '"';
          }
        }
        return split.join( ", " );
      }
    };

    return this.each( function () {
      $( "#jQueryFontFace" ).text( $( "#jQueryFontFace" ).text() + FF.create( this ) );
    } );
  };
} )( jQuery );

/* ----------------------- */
/* ----------------------- */

/* Flama */

$( document ).ready( function () {
  $( ".flama-bold-italic" ).fontface( {
    fontName: "Flama-BoldItalic",
    fileName: "hinted-Flama-BoldItalic",
    fontWeight: "bold",
    fontStyle: "normal"
  } );

  $( ".flama" ).fontface( {
    fontName: "Flama",
    fileName: "hinted-Flama",
    fontWeight: "bold",
    fontStyle: "normal"
  } );

  $( ".flama-book-italic" ).fontface( {
    fontName: "FlamaBook",
    fileName: "hinted-Flama-Book-Italic",
    fontWeight: "normal",
    fontStyle: "italic"
  } );

  $( ".flama-medium" ).fontface( {
    fontName: "FlamaMedium",
    fileName: "hinted-Flama-Medium",
    fontWeight: "500",
    fontStyle: "normal"
  } );

  $( ".flama-medium-italic" ).fontface( {
    fontName: "FlamaMedium",
    fileName: "hinted-Flama-Medium-Italic",
    fontWeight: "500",
    fontStyle: "italic"
  } );

  $( ".flama-light" ).fontface( {
    fontName: "FlamaLight",
    fileName: "hinted-Flama-Light",
    fontWeight: "300",
    fontStyle: "normal"
  } );

  $( ".flama-black-italic" ).fontface( {
    fontName: "FlamaBlack",
    fileName: "hinted-Flama-Black",
    fontWeight: "900",
    fontStyle: "italic"
  } );

  $( ".flama-black" ).fontface( {
    fontName: "FlamaBlack",
    fileName: "hinted-Flama-Black",
    fontWeight: "900",
    fontStyle: "normal"
  } );

  $( ".flama-book" ).fontface( {
    fontName: "FlamaBook",
    fileName: "hinted-Flama-Book",
    fontWeight: "normal",
    fontStyle: "normal"
  } );

  $( ".flama-italic" ).fontface( {
    fontName: "Flama",
    fileName: "hinted-Flama-Italic",
    fontWeight: "normal",
    fontStyle: "italic"
  } );

  $( ".flama-bold" ).fontface( {
    fontName: "Flama",
    fileName: "hinted-Flama-Bold",
    fontWeight: "bold",
    fontStyle: "normal"
  } );

  $( ".flama-light-italic" ).fontface( {
    fontName: "FlamaLight",
    fileName: "hinted-Flama-Light-Italic",
    fontWeight: "300",
    fontStyle: "italic"
  } );

  /* Akzidenz */

  $( ".ag-extra-bold-cond-it" ).fontface( {
    fontName: "Akzidenz Grotesk BE XBdCn",
    fileName: "hinted-AkzidenzGroteskBE-XBdCnIT",
    fontWeight: "900",
    font - style: "italic"
  } );

  $( ".ag-bold" ).fontface( {
    fontName: "Akzidenz Grotesk BE",
    fileName: "hinted-AkzidenzGroteskBE-Bold",
    fontWeight: "bold",
    font - style: "normal"
  } );

  $( ".ag-extra-bold-cond" ).fontface( {
    fontName: "Akzidenz Grotesk BE XBdCn",
    fileName: "hinted-AkzidenzGroteskBE-XBdCn",
    fontWeight: "900",
    font - style: "normal"
  } );

  $( ".ag-italic" ).fontface( {
    fontName: "Akzidenz Grotesk BE",
    fileName: "hinted-AkzidenzGroteskBE-It",
    fontWeight: "normal",
    font - style: "italic"
  } );

  $( ".ag-bold-ext-it" ).fontface( {
    fontName: "Akzidenz Grotesk BE BoldEx",
    fileName: "hinted-AkzidenzGroteskBE-BoldExIt",
    fontWeight: "900",
    font - style: "normal"
  } );

  $( ".ag-medium" ).fontface( {
    fontName: "Akzidenz Grotesk BE",
    fileName: "hinted-AkzidenzGroteskBE-Md",
    fontWeight: "500"
  } );
  $( ".ag-regular" ).fontface( {
    fontName: "Akzidenz Grotesk BE",
    fileName: "hinted-AkzidenzGroteskBE-Regular",
    fontWeight: "normal"
  } );
} );
<|endoftext|>


<commit_before><commit_msg>trim vestigial functionality<commit_after><|endoftext|>


<commit_before>/** =========================================================================
 * Processor
 * Modify the prepared source ready to be written to an iframe
 * ========================================================================== */

var processor = (function () {

  var processor = {};

  processor.blockingMethods = {
    kill: '',
    restore: ''
  };

  /**
   * Grab the doctype from a string.
   *
   * Returns an object with doctype and tail keys.
   */
  processor.getDoctype = (function () {
    // Cached regex
    // [\s\S] matches multiline doctypes
    var regex = /<!doctype [\s\S]*?>/i;
    return function (str) {
      var doctype = (str.match(regex) || [''])[0],
          tail = str.substr(doctype.length);
      return {
        doctype: doctype,
        tail: tail
      };
    };
  }());

  /**
   * Replace HTML characters with encoded equivatents for debug mode.
   */
  processor.debug = function (source) {
    return '
' + source.replace(/[<>&]/g, function (m) {
      if (m == '<') return '<';
      if (m == '>') return '>';
      if (m == '"') return '"';
    }) + '
';
  };

  /**
   * Render – build the final source code to be written to the iframe. Takes
   * the original source and an options object.
   */
  processor.render = function (source, options) {

    options = options || [];
    source = source || '';

    var combinedSource = [],
        realtime = (options.requested !== true),
        noRealtimeJs = (options.includeJsInRealtime === false);

    // If the render was realtime and we don't want javascript in realtime
    // renders – Auto-run JS is unchecked – then strip out the Javascript
    if (realtime && noRealtimeJs) {
      source = source.replace(/',
    // RS: the empty comment in the end of the harness, ensures any
    // open comments are closed, and will ensure the harness is hidden
    // from the user.
    restore: ''
  };

  /**
   * Grab the doctype from a string.
   *
   * Returns an object with doctype and tail keys.
   */
  processor.getDoctype = (function () {
    // Cached regex
    // [\s\S] matches multiline doctypes
    var regex = /<!doctype [\s\S]*?>/i;
    return function (str) {
      var doctype = (str.match(regex) || [''])[0],
          tail = str.substr(doctype.length);
      return {
        doctype: doctype,
        tail: tail
      };
    };
  }());

  /**
   * Replace HTML characters with encoded equivatents for debug mode.
   */
  processor.debug = function (source) {
    return '
' + source.replace(/[<>&]/g, function (m) {
      if (m == '<') return '<';
      if (m == '>') return '>';
      if (m == '"') return '"';
    }) + '
';
  };

  /**
   * Render – build the final source code to be written to the iframe. Takes
   * the original source and an options object.
   */
  processor.render = function (source, options) {

    options = options || [];
    source = source || '';

    var combinedSource = [],
        realtime = (options.requested !== true),
        noRealtimeJs = (options.includeJsInRealtime === false);

    // If the render was realtime and we don't want javascript in realtime
    // renders – Auto-run JS is unchecked – then strip out the Javascript
    if (realtime && noRealtimeJs) {
      source = source.replace(/