<commit_before>"use strict";

const path = require("path");
const CleanWebpackPlugin = require("clean-webpack-plugin").default;
const webpack = require("webpack");

/** @type WebpackOptions */
const config = {
  target: "node",
  entry: "./src/extension.ts",
  output: {
    filename: "extension.js",
    path: path.resolve(__dirname, "../out"),
    libraryTarget: "commonjs2",
    devtoolModuleFilenameTemplate: "file:///[absolute-resource-path]"
  },
  resolve: {
    extensions: [".ts", ".js"],
    alias: {
      deepmerge$: path.resolve(__dirname, "../node_modules/deepmerge/dist/umd.js")
    }
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        loader: "ts-loader"
      }
    ]
  },
  externals: {
    vscode: "commonjs vscode",
    "vscode-fsevents": "commonjs vscode-fsevents",
    "original-fs": "commonjs original-fs"
  },
  plugins: [new CleanWebpackPlugin()]
};

module.exports = config;
<commit_msg>fix(clean-webpack-plugin): (#901)<commit_after>"use strict";

const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const webpack = require("webpack");

/** @type WebpackOptions */
const config = {
  target: "node",
  entry: "./src/extension.ts",
  output: {
    filename: "extension.js",
    path: path.resolve(__dirname, "../out"),
    libraryTarget: "commonjs2",
    devtoolModuleFilenameTemplate: "file:///[absolute-resource-path]"
  },
  resolve: {
    extensions: [".ts", ".js"],
    alias: {
      deepmerge$: path.resolve(__dirname, "../node_modules/deepmerge/dist/umd.js")
    }
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        loader: "ts-loader"
      }
    ]
  },
  externals: {
    vscode: "commonjs vscode",
    "vscode-fsevents": "commonjs vscode-fsevents",
    "original-fs": "commonjs original-fs"
  },
  plugins: [new CleanWebpackPlugin()]
};

module.exports = config;
<|endoftext|>


<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// TODO(xunjieli): When URLSearchParams is stable and implemented, switch this
// (and a lot of other test code) to it. https://crbug.com/303152
var url = decodeURIComponent(/url=([^&]*)/.exec(location.search)[1]);
var filter = {urls: ['http://www.example.com/*'], types: ['xmlhttprequest']};

chrome.webRequest.onCompleted.addListener(function(details) {
  chrome.test.notifyFail();
}, filter);

chrome.webRequest.onErrorOccurred.addListener(function(details) {
  chrome.test.assertEq('net::ERR_TEMPORARILY_THROTTLED', details.error);
  chrome.test.notifyPass();
}, filter);

chrome.runtime.sendMessage({type: 'xhr', method: 'GET', url: url});
<commit_msg>Fix ExtensionRequestLimitingThrottleBrowserTest.ThrottleRequest_Redirect<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// TODO(xunjieli): When URLSearchParams is stable and implemented, switch this
// (and a lot of other test code) to it. https://crbug.com/303152
var url = decodeURIComponent(/url=([^&]*)/.exec(location.search)[1]);
var filter = {urls: ['http://www.example.com/*'], types: ['xmlhttprequest']};

chrome.webRequest.onCompleted.addListener(function(details) {
  chrome.test.notifyFail('Unexpected.');
}, filter);

chrome.webRequest.onErrorOccurred.addListener(function(details) {
  chrome.test.assertEq('net::ERR_TEMPORARILY_THROTTLED', details.error);
  chrome.test.notifyPass();
}, filter);

chrome.runtime.sendMessage({type: 'xhr', method: 'GET', url: url});
<|endoftext|>


<commit_before>'use babel';

import manager from './atom-ternjs-manager';
import packageConfig from './atom-ternjs-package-config';
import path from 'path';
import fs from 'fs';
import navigation from './services/navigation';

const tags = {

  '&': '&',
  '<': '<',
  '>': '>'
};

const grammars = [

  'JavaScript',
  'JavaScript (JSX)',
  'Babel ES6 JavaScript'
];

export function isValidEditor(editor) {

  const isTextEditor = atom.workspace.isTextEditor(editor);

  if (!isTextEditor || editor.isMini()) {

    return false;
  }

  const grammar = editor.getGrammar();

  if (!grammars.includes(grammar.name)) {

    return false;
  }

  return true;
}

export function focusEditor() {

  const editor = atom.workspace.getActiveTextEditor();

  if (!editor) {

    return;
  }

  const view = atom.views.getView(editor);

  view && view.focus && view.focus();
}

export function replaceTag(tag) {

  return tags[tag];
}

export function replaceTags(str) {

  if (!str) {

    return '';
  }

  return str.replace(/[&<>]/g, replaceTag);
}

export function formatType(data) {

  if (!data.type) {

    return '';
  }

  data.type = data.type.replace(/->/g, ':').replace('<top>', 'window');

  if (!data.exprName) {

    return data.type;
  }

  data.type = data.type.replace(/^fn/, data.exprName);

  return data.type;
}

export function prepareType(data) {

  if (!data.type) {

    return;
  }

  return data.type.replace(/->/g, ':').replace('<top>', 'window');
}

export function prepareInlineDocs(data) {

  return data
    .replace(/@param/, '@param')
    .replace(/@param/g, '@param')
    .replace(/@return/, '@return')
    ;
}

export function buildDisplayText(params, name) {

  if (params.length === 0) {

    return `${name}()`;
  }

  let suggestionParams = params.map((param) => {

    param = param.replace('}', '\\}');
    param = param.replace(/'"/g, '');

    return param;
  });

  return `${name}(${suggestionParams.join(',')})`;
}

export function buildSnippet(params, name) {

  if (params.length === 0) {

    return `${name}()`;
  }

  let suggestionParams = params.map((param, i) => {

    param = param.replace('}', '\\}');

    return `\${${i + 1}:${param}}`;
  });

  return `${name}(${suggestionParams.join(',')})`;
}

export function extractParams(type) {

  if (!type) {

    return [];
  }

  let start = type.indexOf('(') + 1;
  let params = [];
  let inside = 0;

  for (let i = start; i < type.length; i++) {

    if (type[i] === ':' && inside === -1) {

      params.push(type.substring(start, i - 2));

      break;
    }

    if (i === type.length - 1) {

      const param = type.substring(start, i);

      if (param.length) {

        params.push(param);
      }

      break;
    }

    if (type[i] === ',' && inside === 0) {

      params.push(type.substring(start, i));
      start = i + 1;

      continue;
    }

    if (type[i].match(/[{\[\(]/)) {

      inside++;

      continue;
    }

    if (type[i].match(/[}\]\)]/)) {

      inside--;
    }
  }

  return params;
}

export function formatTypeCompletion(obj, isProperty, isObjectKey, isInFunDef) {

  if (obj.isKeyword) {

    obj._typeSelf = 'keyword';
  }

  if (obj.type === 'string') {

    obj.name = obj.name ? obj.name.replace(/(^"|"$)/g, '') : null;

  } else {

    obj.name = obj.name ? obj.name.replace(/["']/g, '') : null;
    obj.name = obj.name ? obj.name.replace(/^..\//, '') : null;
  }

  if (!obj.type) {

    obj._displayText = obj.name;
    obj._snippet = obj.name;

    return obj;
  }

  if (!obj.type.startsWith('fn')) {

    if (isProperty) {

      obj._typeSelf = 'property';

    } else {

      obj._typeSelf = 'variable';
    }
  }

  obj.type = obj.rightLabel = prepareType(obj);

  if (obj.type.replace(/fn\(.+\)/, '').length === 0) {

    obj.leftLabel = '';

  } else {

    if (obj.type.indexOf('fn') === -1) {

      obj.leftLabel = obj.type;

    } else {

      obj.leftLabel = obj.type.replace(/fn\(.{0,}\)/, '').replace(' : ', '');
    }
  }

  if (obj.rightLabel.startsWith('fn')) {

    let params = extractParams(obj.rightLabel);

    if (
      packageConfig.options.useSnippets ||
      packageConfig.options.useSnippetsAndFunction
    ) {

      if (!isInFunDef) {

        obj._snippet = buildSnippet(params, obj.name);
      }

      obj._hasParams = params.length ? true : false;

    } else {

      if (!isInFunDef) {

        obj._snippet = params.length ? `${obj.name}(\${${0}:\${}})` : `${obj.name}()`;
      }

      obj._displayText = buildDisplayText(params, obj.name);
    }

    obj._typeSelf = 'function';
  }

  if (obj.name) {

    if (obj.leftLabel === obj.name) {

      obj.leftLabel = null;
      obj.rightLabel = null;
    }
  }

  if (obj.leftLabel === obj.rightLabel) {

    obj.rightLabel = null;
  }

  return obj;
}

export function disposeAll(disposables) {

  disposables.forEach(disposable => disposable.dispose());
}

export function openFileAndGoToPosition(position, file) {

  atom.workspace.open(file).then((textEditor) => {

    const cursor = textEditor.getLastCursor();

    if (!cursor) {

      return;
    }

    cursor.setBufferPosition(position);
  });
}

export function openFileAndGoTo(start, file) {

  atom.workspace.open(file).then((textEditor) => {

    const buffer = textEditor.getBuffer();
    const cursor = textEditor.getLastCursor();

    if (
      !buffer ||
      !cursor
    ) {

      return;
    }

    const bufferPosition = buffer.positionForCharacterIndex(start);

    cursor.setBufferPosition(buffer.positionForCharacterIndex(start));

    navigation.append(textEditor, buffer, bufferPosition);

    markDefinitionBufferRange(cursor, textEditor);
  });
}

export function updateTernFile(content) {

  const projectRoot = manager.server && manager.server.projectDir;

  if (!projectRoot) {

    return;
  }

  writeFile(path.resolve(__dirname, projectRoot + '/.tern-project'), content);
}

export function writeFile(filePath, content) {

  fs.writeFile(filePath, content, (error) => {

    atom.workspace.open(filePath);

    if (!error) {

      const server = manager.server;
      server && server.restart();

      return;
    }

    const message = 'Could not create/update .tern-project file. Use the README to manually create a .tern-project file.';

    atom.notifications.addInfo(message, {

      dismissable: true
    });
  });
}

export function isDirectory(dir) {

  try {

    return fs.statSync(dir).isDirectory();

  } catch (error) {

    return false;
  }
}

export function fileExists(path) {

  try {

    fs.accessSync(path, fs.F_OK, (error) => {

      console.error(error);
    });

  } catch (error) {

    return false;
  }
}

export function getFileContent(filePath, root) {

  const _filePath = root + filePath;
  const resolvedPath = path.resolve(__dirname, _filePath);

  if (fileExists(resolvedPath) !== undefined) {

    return false;
  }

  return readFile(resolvedPath);
}

export function readFile(path) {

  return fs.readFileSync(path, 'utf8');
}

export function markDefinitionBufferRange(cursor, editor) {

  const range = cursor.getCurrentWordBufferRange();
  const marker = editor.markBufferRange(range, {invalidate: 'touch'});

  const decoration = editor.decorateMarker(marker, {

    type: 'highlight',
    class: 'atom-ternjs-definition-marker',
    invalidate: 'touch'
  });

  if (!decoration) {

    return;
  }

  setTimeout(() => {

    decoration.setProperties({

      type: 'highlight',
      class: 'atom-ternjs-definition-marker active',
      invalidate: 'touch'
    });

  }, 1);

  setTimeout(() => {

    decoration.setProperties({

      type: 'highlight',
      class: 'atom-ternjs-definition-marker',
      invalidate: 'touch'
    });

  }, 1501);

  setTimeout(() => {

    marker.destroy();

  }, 2500);
}

export function getPackagePath() {

  const packagPath = atom.packages.resolvePackagePath('atom-ternjs');

  return packagPath;
}
<commit_msg>also remove the current directory. this should fix the issue '././' produced by path completion<commit_after>'use babel';

import manager from './atom-ternjs-manager';
import packageConfig from './atom-ternjs-package-config';
import path from 'path';
import fs from 'fs';
import navigation from './services/navigation';

const tags = {

  '&': '&',
  '<': '<',
  '>': '>'
};

const grammars = [

  'JavaScript',
  'JavaScript (JSX)',
  'Babel ES6 JavaScript'
];

export function isValidEditor(editor) {

  const isTextEditor = atom.workspace.isTextEditor(editor);

  if (!isTextEditor || editor.isMini()) {

    return false;
  }

  const grammar = editor.getGrammar();

  if (!grammars.includes(grammar.name)) {

    return false;
  }

  return true;
}

export function focusEditor() {

  const editor = atom.workspace.getActiveTextEditor();

  if (!editor) {

    return;
  }

  const view = atom.views.getView(editor);

  view && view.focus && view.focus();
}

export function replaceTag(tag) {

  return tags[tag];
}

export function replaceTags(str) {

  if (!str) {

    return '';
  }

  return str.replace(/[&<>]/g, replaceTag);
}

export function formatType(data) {

  if (!data.type) {

    return '';
  }

  data.type = data.type.replace(/->/g, ':').replace('<top>', 'window');

  if (!data.exprName) {

    return data.type;
  }

  data.type = data.type.replace(/^fn/, data.exprName);

  return data.type;
}

export function prepareType(data) {

  if (!data.type) {

    return;
  }

  return data.type.replace(/->/g, ':').replace('<top>', 'window');
}

export function prepareInlineDocs(data) {

  return data
    .replace(/@param/, '@param')
    .replace(/@param/g, '@param')
    .replace(/@return/, '@return')
    ;
}

export function buildDisplayText(params, name) {

  if (params.length === 0) {

    return `${name}()`;
  }

  let suggestionParams = params.map((param) => {

    param = param.replace('}', '\\}');
    param = param.replace(/'"/g, '');

    return param;
  });

  return `${name}(${suggestionParams.join(',')})`;
}

export function buildSnippet(params, name) {

  if (params.length === 0) {

    return `${name}()`;
  }

  let suggestionParams = params.map((param, i) => {

    param = param.replace('}', '\\}');

    return `\${${i + 1}:${param}}`;
  });

  return `${name}(${suggestionParams.join(',')})`;
}

export function extractParams(type) {

  if (!type) {

    return [];
  }

  let start = type.indexOf('(') + 1;
  let params = [];
  let inside = 0;

  for (let i = start; i < type.length; i++) {

    if (type[i] === ':' && inside === -1) {

      params.push(type.substring(start, i - 2));

      break;
    }

    if (i === type.length - 1) {

      const param = type.substring(start, i);

      if (param.length) {

        params.push(param);
      }

      break;
    }

    if (type[i] === ',' && inside === 0) {

      params.push(type.substring(start, i));
      start = i + 1;

      continue;
    }

    if (type[i].match(/[{\[\(]/)) {

      inside++;

      continue;
    }

    if (type[i].match(/[}\]\)]/)) {

      inside--;
    }
  }

  return params;
}

export function formatTypeCompletion(obj, isProperty, isObjectKey, isInFunDef) {

  if (obj.isKeyword) {

    obj._typeSelf = 'keyword';
  }

  if (obj.type === 'string') {

    obj.name = obj.name ? obj.name.replace(/(^"|"$)/g, '') : null;

  } else {

    obj.name = obj.name ? obj.name.replace(/["']/g, '') : null;
  }

  obj.name = obj.name ? obj.name.replace(/^..?\//, '') : null;

  if (!obj.type) {

    obj._displayText = obj.name;
    obj._snippet = obj.name;

    return obj;
  }

  if (!obj.type.startsWith('fn')) {

    if (isProperty) {

      obj._typeSelf = 'property';

    } else {

      obj._typeSelf = 'variable';
    }
  }

  obj.type = obj.rightLabel = prepareType(obj);

  if (obj.type.replace(/fn\(.+\)/, '').length === 0) {

    obj.leftLabel = '';

  } else {

    if (obj.type.indexOf('fn') === -1) {

      obj.leftLabel = obj.type;

    } else {

      obj.leftLabel = obj.type.replace(/fn\(.{0,}\)/, '').replace(' : ', '');
    }
  }

  if (obj.rightLabel.startsWith('fn')) {

    let params = extractParams(obj.rightLabel);

    if (
      packageConfig.options.useSnippets ||
      packageConfig.options.useSnippetsAndFunction
    ) {

      if (!isInFunDef) {

        obj._snippet = buildSnippet(params, obj.name);
      }

      obj._hasParams = params.length ? true : false;

    } else {

      if (!isInFunDef) {

        obj._snippet = params.length ? `${obj.name}(\${${0}:\${}})` : `${obj.name}()`;
      }

      obj._displayText = buildDisplayText(params, obj.name);
    }

    obj._typeSelf = 'function';
  }

  if (obj.name) {

    if (obj.leftLabel === obj.name) {

      obj.leftLabel = null;
      obj.rightLabel = null;
    }
  }

  if (obj.leftLabel === obj.rightLabel) {

    obj.rightLabel = null;
  }

  return obj;
}

export function disposeAll(disposables) {

  disposables.forEach(disposable => disposable.dispose());
}

export function openFileAndGoToPosition(position, file) {

  atom.workspace.open(file).then((textEditor) => {

    const cursor = textEditor.getLastCursor();

    if (!cursor) {

      return;
    }

    cursor.setBufferPosition(position);
  });
}

export function openFileAndGoTo(start, file) {

  atom.workspace.open(file).then((textEditor) => {

    const buffer = textEditor.getBuffer();
    const cursor = textEditor.getLastCursor();

    if (
      !buffer ||
      !cursor
    ) {

      return;
    }

    const bufferPosition = buffer.positionForCharacterIndex(start);

    cursor.setBufferPosition(buffer.positionForCharacterIndex(start));

    navigation.append(textEditor, buffer, bufferPosition);

    markDefinitionBufferRange(cursor, textEditor);
  });
}

export function updateTernFile(content) {

  const projectRoot = manager.server && manager.server.projectDir;

  if (!projectRoot) {

    return;
  }

  writeFile(path.resolve(__dirname, projectRoot + '/.tern-project'), content);
}

export function writeFile(filePath, content) {

  fs.writeFile(filePath, content, (error) => {

    atom.workspace.open(filePath);

    if (!error) {

      const server = manager.server;
      server && server.restart();

      return;
    }

    const message = 'Could not create/update .tern-project file. Use the README to manually create a .tern-project file.';

    atom.notifications.addInfo(message, {

      dismissable: true
    });
  });
}

export function isDirectory(dir) {

  try {

    return fs.statSync(dir).isDirectory();

  } catch (error) {

    return false;
  }
}

export function fileExists(path) {

  try {

    fs.accessSync(path, fs.F_OK, (error) => {

      console.error(error);
    });

  } catch (error) {

    return false;
  }
}

export function getFileContent(filePath, root) {

  const _filePath = root + filePath;
  const resolvedPath = path.resolve(__dirname, _filePath);

  if (fileExists(resolvedPath) !== undefined) {

    return false;
  }

  return readFile(resolvedPath);
}

export function readFile(path) {

  return fs.readFileSync(path, 'utf8');
}

export function markDefinitionBufferRange(cursor, editor) {

  const range = cursor.getCurrentWordBufferRange();
  const marker = editor.markBufferRange(range, {invalidate: 'touch'});

  const decoration = editor.decorateMarker(marker, {

    type: 'highlight',
    class: 'atom-ternjs-definition-marker',
    invalidate: 'touch'
  });

  if (!decoration) {

    return;
  }

  setTimeout(() => {

    decoration.setProperties({

      type: 'highlight',
      class: 'atom-ternjs-definition-marker active',
      invalidate: 'touch'
    });

  }, 1);

  setTimeout(() => {

    decoration.setProperties({

      type: 'highlight',
      class: 'atom-ternjs-definition-marker',
      invalidate: 'touch'
    });

  }, 1501);

  setTimeout(() => {

    marker.destroy();

  }, 2500);
}

export function getPackagePath() {

  const packagPath = atom.packages.resolvePackagePath('atom-ternjs');

  return packagPath;
}
<|endoftext|>


<commit_before>/**
 * Analytics GA4 Property Notice component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import SettingsNotice, { TYPE_INFO } from '../../../../components/SettingsNotice';
import Link from '../../../../components/Link';

export default function GA4PropertyNotice( { notice, children } ) {
	return (
		<SettingsNotice type={ TYPE_INFO }>
			{ notice }
			{ ' ' }
			<Link
				href="https://sitekit.withgoogle.com/documentation/ga4-analytics-property/"
				external
				inherit
			>
				{ __( 'Learn more here.', 'google-site-kit' ) }
			</Link>
			{ children }
		</SettingsNotice>
	);
}

GA4PropertyNotice.propTypes = { // eslint-disable-line sitekit/acronym-case
	children: PropTypes.node,
	notice: PropTypes.string.isRequired,
};
<commit_msg>Use new props.<commit_after>/**
 * Analytics GA4 Property Notice component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import SettingsNotice, { TYPE_INFO } from '../../../../components/SettingsNotice';
import Link from '../../../../components/Link';

const LearnMore = () => (
	<Link
		href="https://sitekit.withgoogle.com/documentation/ga4-analytics-property/"
		external
		inherit
	>
		{ __( 'Learn more here.', 'google-site-kit' ) }
	</Link>
);

export default function GA4PropertyNotice( { notice, children } ) {
	return (
		<SettingsNotice type={ TYPE_INFO } LearnMore={ LearnMore }>
			{ notice }
			{ children }
		</SettingsNotice>
	);
}

GA4PropertyNotice.propTypes = { // eslint-disable-line sitekit/acronym-case
	children: PropTypes.node,
	notice: PropTypes.string.isRequired,
};
<|endoftext|>


<commit_before>/*
 * Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */
/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import { dataFontEm } from '../../../../units';

const DEFAULT_PRESET = {
  id: 'default-text',
  content: __('Fill in some text', 'web-stories'),
  fontSize: dataFontEm(1),
  fontWeight: 400,
  font: {
    family: 'Roboto',
    service: 'fonts.google.com',
  },
  lineHeight: '24px',
};

const PRESETS = [
  {
    id: 'heading',
    title: __('Heading', 'web-stories'),
    content: `${__(
      'Heading',
      'web-stories'
    )}`,
    fontSize: dataFontEm(2),
    font: {
      family: 'Open Sans',
      service: 'fonts.google.com',
    },
  },
  {
    id: 'subheading',
    title: __('Subheading', 'web-stories'),
    content: `${__(
      'Subheading',
      'web-stories'
    )}`,
    fontSize: dataFontEm(1.5),
    font: {
      family: 'Open Sans',
      service: 'fonts.google.com',
    },
  },
  {
    id: 'body-text',
    title: __('Body text', 'web-stories'),
    content: __(
      'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
      'web-stories'
    ),
    fontSize: dataFontEm(1.1),
    font: {
      family: 'Roboto',
      service: 'fonts.google.com',
    },
  },
];

export { DEFAULT_PRESET, PRESETS };
<commit_msg>Update textPresets.js<commit_after>/*
 * Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */
/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import { dataFontEm } from '../../../../units';
import { TEXT_ELEMENT_DEFAULT_FONT } from '../==../../app/font/defaultFonts';

const DEFAULT_PRESET = {
  id: 'default-text',
  content: `${__(
    'Fill in some text',
    'web-stories'
  )}`,
  fontSize: dataFontEm(1),
  font: TEXT_ELEMENT_DEFAULT_FONT,
  lineHeight: 1.5,
};

const PRESETS = [
  {
    id: 'heading',
    title: __('Heading', 'web-stories'),
    content: `${__(
      'Heading',
      'web-stories'
    )}`,
    fontSize: dataFontEm(2),
    font: {
      family: 'Open Sans',
      service: 'fonts.google.com',
    },
  },
  {
    id: 'subheading',
    title: __('Subheading', 'web-stories'),
    content: `${__(
      'Subheading',
      'web-stories'
    )}`,
    fontSize: dataFontEm(1.5),
    font: {
      family: 'Open Sans',
      service: 'fonts.google.com',
    },
  },
  {
    id: 'body-text',
    title: __('Body text', 'web-stories'),
    content: __(
      'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
      'web-stories'
    ),
    fontSize: dataFontEm(1.1),
    font: TEXT_ELEMENT_DEFAULT_FONT,
  },
];

export { DEFAULT_PRESET, PRESETS };
<|endoftext|>


<commit_before>// Wax for Google Maps API v3
// --------------------------

// Wax header
var wax = wax || {};
wax.g = wax.g || {};

// Wax Google Maps MapType: takes an object of options in the form
//
//     {
//       name: '',
//       filetype: '.png',
//       layerName: 'world-light',
//       alt: '',
//       zoomRange: [0, 18],
//       baseUrl: 'a url',
//     }
wax.g.connector = function(options) {
    options = options || {};

    this.options = {
        tiles: options.tiles,
        scheme: options.scheme || 'xyz',
        blankImage: options.blankImage || 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
    };

    this.minZoom = options.minzoom || 0;
    this.maxZoom = options.maxzoom || 22;

    this.name = options.name || '';
    this.description = options.description || '';

    // non-configurable options
    this.interactive = true;
    this.tileSize = new google.maps.Size(256, 256);

    // DOM element cache
    this.cache = {};
};

// Get a tile element from a coordinate, zoom level, and an ownerDocument.
wax.g.connector.prototype.getTile = function(coord, zoom, ownerDocument) {
    var key = zoom + '/' + coord.x + '/' + coord.y;
    if (!this.cache[key]) {
        var img = this.cache[key] = new Image(256, 256);
        this.cache[key].src = this.getTileUrl(coord, zoom);
        this.cache[key].setAttribute('gTileKey', key);
        this.cache[key].onerror = function() { img.style.display = 'none'; };
    }
    return this.cache[key];
};

// Remove a tile that has fallen out of the map's viewport.
//
// TODO: expire cache data in the gridmanager.
wax.g.connector.prototype.releaseTile = function(tile) {
    var key = tile.getAttribute('gTileKey');
    if (this.cache[key]) delete this.cache[key];
    if (tile.parentNode) tile.parentNode.removeChild(tile);
};

// Get a tile url, based on x, y coordinates and a z value.
wax.g.connector.prototype.getTileUrl = function(coord, z) {
    // Y coordinate is flipped in Mapbox, compared to Google
    var mod = Math.pow(2, z),
        y = (this.options.scheme === 'tms') ?
            (mod - 1) - coord.y :
            coord.y,
        x = (coord.x % mod);

    x = (x < 0) ? (coord.x % mod) + mod : x;

    if (y < 0) return this.options.blankImage;

    return this.options.tiles
        [parseInt(x + y, 10) %
            this.options.tiles.length]
                .replace(/\{z\}/g, z)
                .replace(/\{x\}/g, x)
                .replace(/\{y\}/g, y);
};
<commit_msg>add opacity parameter to the layer<commit_after>// Wax for Google Maps API v3
// --------------------------

// Wax header
var wax = wax || {};
wax.g = wax.g || {};

// Wax Google Maps MapType: takes an object of options in the form
//
//     {
//       name: '',
//       filetype: '.png',
//       layerName: 'world-light',
//       alt: '',
//       zoomRange: [0, 18],
//       baseUrl: 'a url',
//     }
wax.g.connector = function(options) {
    options = options || {};

    this.options = {
        tiles: options.tiles,
        scheme: options.scheme || 'xyz',
        blankImage: options.blankImage || 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
    };

    this.opacity = options.opacity || 0;
    this.minZoom = options.minzoom || 0;
    this.maxZoom = options.maxzoom || 22;

    this.name = options.name || '';
    this.description = options.description || '';

    // non-configurable options
    this.interactive = true;
    this.tileSize = new google.maps.Size(256, 256);

    // DOM element cache
    this.cache = {};
};

// Get a tile element from a coordinate, zoom level, and an ownerDocument.
wax.g.connector.prototype.getTile = function(coord, zoom, ownerDocument) {
    var key = zoom + '/' + coord.x + '/' + coord.y;
    if (!this.cache[key]) {
        var img = this.cache[key] = new Image(256, 256);
        this.cache[key].src = this.getTileUrl(coord, zoom);
        this.cache[key].setAttribute('gTileKey', key);
        this.cache[key].setAttribute("style","opacity: "+this.opacity+"; filter: alpha(opacity="+(this.opacity*100)+");");
        this.cache[key].onerror = function() { img.style.display = 'none'; };
    }
    return this.cache[key];
};

// Remove a tile that has fallen out of the map's viewport.
//
// TODO: expire cache data in the gridmanager.
wax.g.connector.prototype.releaseTile = function(tile) {
    var key = tile.getAttribute('gTileKey');
    if (this.cache[key]) delete this.cache[key];
    if (tile.parentNode) tile.parentNode.removeChild(tile);
};

// Get a tile url, based on x, y coordinates and a z value.
wax.g.connector.prototype.getTileUrl = function(coord, z) {
    // Y coordinate is flipped in Mapbox, compared to Google
    var mod = Math.pow(2, z),
        y = (this.options.scheme === 'tms') ?
            (mod - 1) - coord.y :
            coord.y,
        x = (coord.x % mod);

    x = (x < 0) ? (coord.x % mod) + mod : x;

    if (y < 0) return this.options.blankImage;

    return this.options.tiles
        [parseInt(x + y, 10) %
            this.options.tiles.length]
                .replace(/\{z\}/g, z)
                .replace(/\{x\}/g, x)
                .replace(/\{y\}/g, y);
};
<|endoftext|>


<commit_before>'use strict';

/* global Connector */

/** note: the discover page doesn't display the track artist for compilation albums.  This connector
    currently passes 'Various Artist' (or other variant) as the artist name so tracks on albums with
    various artists played on the discover page will most likely not be recognized.*/

// wire audio element to fire state changes
$('audio').bind('playing pause timeupdate', Connector.onStateChanged);

/**
 * remove zero width characters & trim
 * @param  {string} text to clean up
 * @return {string} cleaned up text
 */
function cleanText(input) {
	if (input === null) {
		return input;
	}
	return input.replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
}

function getArtist() {
	var artist = $('.detail_item_link_2').text() ||
				$('span[itemprop=byArtist]').text() ||
				$('.detail-artist a').text() ||
				null;
	if (artist === null) {
		artist = $('.waypoint-artist-title').text().substr(3);
	}
	return cleanText(artist);
}

function getTrack() {
	var track = $('.track_info .title').first().text() ||
				$('.trackTitle').first().text() ||
				$('.waypoint-item-title').children().remove().end().text() ||
				$('.track_info .title') ||
				null;
	return cleanText(track);
}

function artistIsVarious() {
	// album page: true if all tracks contain a hyphen or vertical bar (pipe symbol)
	// example of pipe usage: http://tigersmilkrecords.bandcamp.com/album/peru-maravilloso-vintage-latin-tropical-cumbia
	if ($('meta[property="og:type"]').attr('content') === 'album') {
		var allDashed = true;
		$('.track_list span[itemprop="name"]').each(function () {
			if (!/\||-/.test($(this).text())) {
				allDashed = false;
				return false;
			}
		});
		return allDashed;
	}
	// discover & song pages: true if artist name is 'Various' or 'Various Artists'
	// and track contains a hyphen or vertical bar.
	// Also takes into account misspelling of various as varios
	//    http://krefeld8ung.bandcamp.com/album/krefeld-8ung-vol-1
	return (/^Variou?s(\sArtists)?$/.test(getArtist()) && /\||-/.test(getTrack()));
}

/* @returns {{artist, track}} */
Connector.getArtistTrack = function () {
	var artist = getArtist(),
		track = getTrack(),
		separatorIndex;
	if (artistIsVarious()) {
		separatorIndex = Math.max(track.indexOf('-'), track.indexOf('|'));
		artist = cleanText(track.substring(0, separatorIndex));
		track = cleanText(track.substring(separatorIndex + 1));
	}
	return {
		artist: artist,
		track: track
	};
};

Connector.getAlbum = function () {
	var album = $('.detail_item_link').text() ||
				$('h2.trackTitle').text() ||
				$('[itemprop="inAlbum"] [itemprop="name"]').text() ||
				null;
	return cleanText(album);
};

Connector.playButtonSelector = 'div.playbutton:not(.playing)';

Connector.getTrackArt = function() {
	return $('#tralbumArt > a > img').attr('src') ||
	$('#detail_gallery_container img').attr('src') ||
	$('.discover-detail-inner img').attr('src');
};

Connector.getCurrentTime = function () {
	return Math.round($('audio')[0].currentTime);
};

Connector.getDuration = function () {
	return Math.round($('audio')[0].duration);
};

/** Returns a unique identifier of current track.
 *  @returns {String|null} */
Connector.getUniqueID = function () {
	var match = /&id=(\d+)&/.exec($('audio').first().attr('src'));
	if (match) {
		return match[1];
	}
	return null;
};
<commit_msg>Correct fix<commit_after>'use strict';

/* global Connector */

/** note: the discover page doesn't display the track artist for compilation albums.  This connector
    currently passes 'Various Artist' (or other variant) as the artist name so tracks on albums with
    various artists played on the discover page will most likely not be recognized.*/

// wire audio element to fire state changes
$('audio').bind('playing pause timeupdate', Connector.onStateChanged);

/**
 * remove zero width characters & trim
 * @param  {string} text to clean up
 * @return {string} cleaned up text
 */
function cleanText(input) {
	if (input === null) {
		return input;
	}
	return input.replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
}

function getArtist() {
	var artist = $('.detail_item_link_2').text() ||
				$('span[itemprop=byArtist]').text() ||
				$('.detail-artist a').text() ||
				null;
	if (artist === null) {
		artist = $('.waypoint-artist-title').text().substr(3);
	}
	return cleanText(artist);
}

function getTrack() {
	var track = $('.track_info .title').first().text() ||
				$('.trackTitle').first().text() ||
				$('.collection-item-container.playing').find('.fav-track-static').first().text() ||
				$('.waypoint-item-title').text() ||
				$('.track_info .title') ||
				null;
	return cleanText(track);
}

function artistIsVarious() {
	// album page: true if all tracks contain a hyphen or vertical bar (pipe symbol)
	// example of pipe usage: http://tigersmilkrecords.bandcamp.com/album/peru-maravilloso-vintage-latin-tropical-cumbia
	if ($('meta[property="og:type"]').attr('content') === 'album') {
		var allDashed = true;
		$('.track_list span[itemprop="name"]').each(function () {
			if (!/\||-/.test($(this).text())) {
				allDashed = false;
				return false;
			}
		});
		return allDashed;
	}
	// discover & song pages: true if artist name is 'Various' or 'Various Artists'
	// and track contains a hyphen or vertical bar.
	// Also takes into account misspelling of various as varios
	//    http://krefeld8ung.bandcamp.com/album/krefeld-8ung-vol-1
	return (/^Variou?s(\sArtists)?$/.test(getArtist()) && /\||-/.test(getTrack()));
}

/* @returns {{artist, track}} */
Connector.getArtistTrack = function () {
	var artist = getArtist(),
		track = getTrack(),
		separatorIndex;
	if (artistIsVarious()) {
		separatorIndex = Math.max(track.indexOf('-'), track.indexOf('|'));
		artist = cleanText(track.substring(0, separatorIndex));
		track = cleanText(track.substring(separatorIndex + 1));
	}
	return {
		artist: artist,
		track: track
	};
};

Connector.getAlbum = function () {
	var album = $('.detail_item_link').text() ||
				$('h2.trackTitle').text() ||
				$('[itemprop="inAlbum"] [itemprop="name"]').text() ||
				null;
	return cleanText(album);
};

Connector.playButtonSelector = 'div.playbutton:not(.playing)';

Connector.getTrackArt = function() {
	return $('#tralbumArt > a > img').attr('src') ||
	$('#detail_gallery_container img').attr('src') ||
	$('.discover-detail-inner img').attr('src');
};

Connector.getCurrentTime = function () {
	return Math.round($('audio')[0].currentTime);
};

Connector.getDuration = function () {
	return Math.round($('audio')[0].duration);
};

/** Returns a unique identifier of current track.
 *  @returns {String|null} */
Connector.getUniqueID = function () {
	var match = /&id=(\d+)&/.exec($('audio').first().attr('src'));
	if (match) {
		return match[1];
	}
	return null;
};
<|endoftext|>


<commit_before>import systemTracking from 'tower/system-tracking/main';
import {describeModule} from '../describe-module';

describeModule(systemTracking.name)
    .testService('factScanDataService', function(test, restStub) {

        var service;

        test.withService(function(_service) {
            service = _service;
        });

        it('returns list of versions', function() {
            var version = [{}],
            host_id = 1,
            module = 'packages',
            start = moment('2015-05-05'),
            end = moment('2015-05-06'),
            result = {
                data: {
                    results: version
                }
            };

            var actual = service.getVersion(host_id, module, start, end);

            restStub.succeed(result);
            restStub.flush();

            return expect(actual).to.eventually.equal(version[0]);

        });

        it('returns list of facts', function() {
            var facts = [{}],
            version = {
                "module" : "package",
                "timestamp": '2015-05-07T14:57:37',
                "related" : {
                    "fact_view" : "/hosts/1/fact_versions/?module=packages&from=2015-05-05T00:00:00-04:00&to=2015-05-06T00:00:00-04:00"
                }
            },
            result = {
                data: {
                    fact: facts
                }
            };

            var actual = service.getFacts(version)
                            .then(function(response) {
                                return response.fact;
                            });

            restStub.succeedAt(version.related.fact_view, result);
            restStub.flush();

            return expect(actual).to.eventually.equal(facts);

        });
    });
<commit_msg>Fix tests<commit_after>import systemTracking from 'tower/system-tracking/main';
import {describeModule} from '../describe-module';
import moment from 'tower/shared/moment/moment';

describeModule(systemTracking.name)
    .testService('factScanDataService', function(test, restStub) {

        var service;

        test.withService(function(_service) {
            service = _service;
        });

        it('returns list of versions', function() {
            var version = [{}],
            host_id = 1,
            module = 'packages',
            start = moment('2015-05-05'),
            end = moment('2015-05-06'),
            result = {
                data: {
                    results: version
                }
            };

            var actual = service.getVersion(host_id, module, start, end);

            restStub.succeed(result);
            restStub.flush();

            return expect(actual).to.eventually.equal(version[0]);

        });

        it('returns list of facts', function() {
            var facts = [{}],
            version = {
                "module" : "package",
                "timestamp": '2015-05-07T14:57:37',
                "related" : {
                    "fact_view" : "/hosts/1/fact_versions/?module=packages&from=2015-05-05T00:00:00-04:00&to=2015-05-06T00:00:00-04:00"
                }
            },
            result = {
                data: {
                    fact: facts
                }
            };

            var actual = service.getFacts(version)
                            .then(function(response) {
                                return response.fact;
                            });

            restStub.succeedAt(version.related.fact_view, result);
            restStub.flush();

            return expect(actual).to.eventually.equal(facts);

        });
    });
<|endoftext|>


<commit_before>/**
 * Backbone-tastypie.js 0.2
 * (c) 2011 Paul Uithol
 *
 * Backbone-tastypie may be freely distributed under the MIT license.
 * Add or override Backbone.js functionality, for compatibility with django-tastypie.
 * Depends on Backbone (and thus on Underscore as well): https://github.com/documentcloud/backbone.
 */
( function( root, factory ) {
	// Set up Backbone-relational for the environment. Start with AMD.
	if ( typeof define === 'function' && define.amd ) {
		define( [ 'exports', 'backbone', 'underscore' ], factory );
	}
	// Next for Node.js or CommonJS.
	else if ( typeof exports !== 'undefined' ) {
		factory( exports, require( 'backbone' ), require( 'underscore' ) );
	}
	// Finally, as a browser global. Use `root` here as it references `window`.
	else {
		factory( root, root.Backbone, root._ );
	}
}( this, function( exports, Backbone, _ ) {
	"use strict";

	Backbone.Tastypie = {
		doGetOnEmptyPostResponse: true,
		doGetOnEmptyPutResponse: false,
		apiKey: {
			username: '',
			key: ''
		},
		csrfToken: ''
	};

	/**
	 * Override Backbone's sync function, to do a GET upon receiving a HTTP CREATED.
	 * This requires 2 requests to do a create, so you may want to use some other method in production.
	 * Modified from http://joshbohde.com/blog/backbonejs-and-django
	 */
	Backbone.oldSync = Backbone.sync;
	Backbone.sync = function( method, model, options ) {
		var headers = {};

		if ( Backbone.Tastypie.apiKey && Backbone.Tastypie.apiKey.username ) {
			headers[ 'Authorization' ] = 'ApiKey ' + Backbone.Tastypie.apiKey.username + ':' + Backbone.Tastypie.apiKey.key;
		}

		if ( Backbone.Tastypie.csrfToken ) {
			headers[ 'X-CSRFToken' ] = Backbone.Tastypie.csrfToken;
		}

		// Keep `headers` for a potential second request
		headers = _.extend( headers, options.headers );
		options.headers = headers;

		if ( ( method === 'create' && Backbone.Tastypie.doGetOnEmptyPostResponse ) ||
			( method === 'update' && Backbone.Tastypie.doGetOnEmptyPutResponse ) ) {
			var dfd = new $.Deferred();

			// Set up 'success' handling
			var success = options.success;
			dfd.done( function( resp, textStatus, xhr ) {
				_.isFunction( success ) && success( resp );
			});

			options.success = function( resp, textStatus, xhr ) {
				// If create is successful but doesn't return a response, fire an extra GET.
				// Otherwise, resolve the deferred (which triggers the original 'success' callbacks).
				if ( !resp && ( xhr.status === 201 || xhr.status === 202 || xhr.status === 204 ) ) { // 201 CREATED, 202 ACCEPTED or 204 NO CONTENT; response null or empty.
					var location = xhr.getResponseHeader( 'Location' ) || model.url();
					return Backbone.ajax({
						url: location,
						headers: headers,
						success: dfd.resolve,
						error: dfd.reject
					});
				}
				else {
					return dfd.resolveWith( options.context || options, [ resp, textStatus, xhr ] );
				}
			};

			// Set up 'error' handling
			var error = options.error;
			dfd.fail( function( xhr, textStatus, errorThrown ) {
				_.isFunction( error ) && error( xhr.responseText );
			});

			options.error = function( xhr, textStatus, errorText ) {
				dfd.rejectWith( options.context || options, [ xhr, textStatus, xhr.responseText ] );
			};

			// Create the request, and make it accessibly by assigning it to the 'request' property on the deferred
			dfd.request = Backbone.oldSync( method, model, options );
			return dfd;
		}

		return Backbone.oldSync( method, model, options );
	};

	Backbone.Model.prototype.idAttribute = 'resource_uri';

	Backbone.Model.prototype.url = function() {
		// Use the 'resource_uri' if possible
		var url = this.get( 'resource_uri' );

		// If there's no idAttribute, use the 'urlRoot'. Fallback to try to have the collection construct a url.
		// Explicitly add the 'id' attribute if the model has one.
		if ( !url ) {
			url = _.result( this, 'urlRoot' ) || ( this.collection && _.result( this.collection, 'url' ) );

			if ( url && this.has( 'id' ) ) {
				url = addSlash( url ) + this.get( 'id' );
			}
		}

		url = url && addSlash( url );

		return url || null;
	};

	/**
	 * Return the first entry in 'data.objects' if it exists and is an array, or else just plain 'data'.
	 */
	Backbone.Model.prototype.parse = function( data ) {
		return data && data.objects && ( _.isArray( data.objects ) ? data.objects[ 0 ] : data.objects ) || data;
	};

	/**
	 * Return 'data.objects' if it exists.
	 * If present, the 'data.meta' object is assigned to the 'collection.meta' var.
	 */
	Backbone.Collection.prototype.parse = function( data ) {
		if ( data && data.meta ) {
			this.meta = data.meta;
		}

		return data && data.objects || data;
	};

	Backbone.Collection.prototype.url = function( models ) {
		var url = _.result( this, 'urlRoot' );
		// If the collection doesn't specify an url, try to obtain one from a model in the collection
		if ( !url ) {
			var model = models && models.length && models[ 0 ];
			url = model && _.result( model, 'urlRoot' );
		}
		url = url && addSlash( url );

		// Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
		// (set to 'resource_uri') contains the model's id.
		if ( models && models.length ) {
			var ids = _.map( models, function( model ) {
				var parts = _.compact( model.url().split( '/' ) );
				return parts[ parts.length - 1 ];
			});
			url += 'set/' + ids.join( ';' ) + '/';
		}

		return url || null;
	};

	var addSlash = function( str ) {
		return str + ( ( str.length > 0 && str.charAt( str.length - 1 ) === '/' ) ? '' : '/' );
	};
}));
<commit_msg>Call it '0.2.0' in the js itself as well (as opposed to '0.2')<commit_after>/**
 * Backbone-tastypie.js 0.2.0
 * (c) 2011 Paul Uithol
 *
 * Backbone-tastypie may be freely distributed under the MIT license.
 * Add or override Backbone.js functionality, for compatibility with django-tastypie.
 * Depends on Backbone (and thus on Underscore as well): https://github.com/documentcloud/backbone.
 */
( function( root, factory ) {
	// Set up Backbone-relational for the environment. Start with AMD.
	if ( typeof define === 'function' && define.amd ) {
		define( [ 'exports', 'backbone', 'underscore' ], factory );
	}
	// Next for Node.js or CommonJS.
	else if ( typeof exports !== 'undefined' ) {
		factory( exports, require( 'backbone' ), require( 'underscore' ) );
	}
	// Finally, as a browser global. Use `root` here as it references `window`.
	else {
		factory( root, root.Backbone, root._ );
	}
}( this, function( exports, Backbone, _ ) {
	"use strict";

	Backbone.Tastypie = {
		doGetOnEmptyPostResponse: true,
		doGetOnEmptyPutResponse: false,
		apiKey: {
			username: '',
			key: ''
		},
		csrfToken: ''
	};

	/**
	 * Override Backbone's sync function, to do a GET upon receiving a HTTP CREATED.
	 * This requires 2 requests to do a create, so you may want to use some other method in production.
	 * Modified from http://joshbohde.com/blog/backbonejs-and-django
	 */
	Backbone.oldSync = Backbone.sync;
	Backbone.sync = function( method, model, options ) {
		var headers = {};

		if ( Backbone.Tastypie.apiKey && Backbone.Tastypie.apiKey.username ) {
			headers[ 'Authorization' ] = 'ApiKey ' + Backbone.Tastypie.apiKey.username + ':' + Backbone.Tastypie.apiKey.key;
		}

		if ( Backbone.Tastypie.csrfToken ) {
			headers[ 'X-CSRFToken' ] = Backbone.Tastypie.csrfToken;
		}

		// Keep `headers` for a potential second request
		headers = _.extend( headers, options.headers );
		options.headers = headers;

		if ( ( method === 'create' && Backbone.Tastypie.doGetOnEmptyPostResponse ) ||
			( method === 'update' && Backbone.Tastypie.doGetOnEmptyPutResponse ) ) {
			var dfd = new $.Deferred();

			// Set up 'success' handling
			var success = options.success;
			dfd.done( function( resp, textStatus, xhr ) {
				_.isFunction( success ) && success( resp );
			});

			options.success = function( resp, textStatus, xhr ) {
				// If create is successful but doesn't return a response, fire an extra GET.
				// Otherwise, resolve the deferred (which triggers the original 'success' callbacks).
				if ( !resp && ( xhr.status === 201 || xhr.status === 202 || xhr.status === 204 ) ) { // 201 CREATED, 202 ACCEPTED or 204 NO CONTENT; response null or empty.
					var location = xhr.getResponseHeader( 'Location' ) || model.url();
					return Backbone.ajax({
						url: location,
						headers: headers,
						success: dfd.resolve,
						error: dfd.reject
					});
				}
				else {
					return dfd.resolveWith( options.context || options, [ resp, textStatus, xhr ] );
				}
			};

			// Set up 'error' handling
			var error = options.error;
			dfd.fail( function( xhr, textStatus, errorThrown ) {
				_.isFunction( error ) && error( xhr.responseText );
			});

			options.error = function( xhr, textStatus, errorText ) {
				dfd.rejectWith( options.context || options, [ xhr, textStatus, xhr.responseText ] );
			};

			// Create the request, and make it accessibly by assigning it to the 'request' property on the deferred
			dfd.request = Backbone.oldSync( method, model, options );
			return dfd;
		}

		return Backbone.oldSync( method, model, options );
	};

	Backbone.Model.prototype.idAttribute = 'resource_uri';

	Backbone.Model.prototype.url = function() {
		// Use the 'resource_uri' if possible
		var url = this.get( 'resource_uri' );

		// If there's no idAttribute, use the 'urlRoot'. Fallback to try to have the collection construct a url.
		// Explicitly add the 'id' attribute if the model has one.
		if ( !url ) {
			url = _.result( this, 'urlRoot' ) || ( this.collection && _.result( this.collection, 'url' ) );

			if ( url && this.has( 'id' ) ) {
				url = addSlash( url ) + this.get( 'id' );
			}
		}

		url = url && addSlash( url );

		return url || null;
	};

	/**
	 * Return the first entry in 'data.objects' if it exists and is an array, or else just plain 'data'.
	 */
	Backbone.Model.prototype.parse = function( data ) {
		return data && data.objects && ( _.isArray( data.objects ) ? data.objects[ 0 ] : data.objects ) || data;
	};

	/**
	 * Return 'data.objects' if it exists.
	 * If present, the 'data.meta' object is assigned to the 'collection.meta' var.
	 */
	Backbone.Collection.prototype.parse = function( data ) {
		if ( data && data.meta ) {
			this.meta = data.meta;
		}

		return data && data.objects || data;
	};

	Backbone.Collection.prototype.url = function( models ) {
		var url = _.result( this, 'urlRoot' );
		// If the collection doesn't specify an url, try to obtain one from a model in the collection
		if ( !url ) {
			var model = models && models.length && models[ 0 ];
			url = model && _.result( model, 'urlRoot' );
		}
		url = url && addSlash( url );

		// Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
		// (set to 'resource_uri') contains the model's id.
		if ( models && models.length ) {
			var ids = _.map( models, function( model ) {
				var parts = _.compact( model.url().split( '/' ) );
				return parts[ parts.length - 1 ];
			});
			url += 'set/' + ids.join( ';' ) + '/';
		}

		return url || null;
	};

	var addSlash = function( str ) {
		return str + ( ( str.length > 0 && str.charAt( str.length - 1 ) === '/' ) ? '' : '/' );
	};
}));
<|endoftext|>


<commit_before>exports.commands = {
    roomfounder: function (target, room, user) {
        if (!room.chatRoomData) {
            return this.sendReply("/roomfounder - This room isn\'t designed for per-room moderation to be added.");
        }
        target = this.splitTarget(target, true);
        var targetUser = this.targetUser;
        if (!targetUser) return this.sendReply("User '" + this.targetUsername + "' is not online.");
        if (!this.can('makeroom')) return false;
        if (!room.auth) room.auth = room.chatRoomData.auth = {};
        if (!room.leagueauth) room.leagueauth = room.chatRoomData.leagueauth = {};
        var name = targetUser.name;
        room.auth[targetUser.userid] = '#';
        room.founder = targetUser.userid;
        this.addModCommand(name + ' was appointed to Room Founder by ' + user.name + '.');
        room.onUpdateIdentity(targetUser);
        room.chatRoomData.founder = room.founder;
        Rooms.global.writeChatRoomData();
    },

    roomdefounder: 'deroomfounder',
    deroomfounder: function (target, room, user) {
        if (!room.auth) {
            return this.sendReply("/roomdeowner - This room isn't designed for per-room moderation");
        }
        target = this.splitTarget(target, true);
        var targetUser = this.targetUser;
        var name = this.targetUsername;
        var userid = toId(name);
        if (!userid || userid === '') return this.sendReply("User '" + name + "' does not exist.");

        if (room.auth[userid] !== '#') return this.sendReply("User '" + name + "' is not a room founder.");
        if (!this.can('makeroom', null, room)) return false;

        delete room.auth[userid];
        delete room.founder;
        this.sendReply("(" + name + " is no longer Room Founder.)");
        if (targetUser) targetUser.updateIdentity();
        if (room.chatRoomData) {
            Rooms.global.writeChatRoomData();
        }
	},

	roomowner: function (target, room, user) {
		if (!room.chatRoomData) {
			return this.sendReply("/roomowner - This room isn't designed for per-room moderation to be added");
		}
		target = this.splitTarget(target, true);
		var targetUser = this.targetUser;

		if (!targetUser) return this.sendReply("User '" + this.targetUsername + "' is not online.");

		if (!room.founder) return this.sendReply('The room needs a room founder before it can have a room owner.');
		if (room.founder !== user.userid && !this.can('makeroom')) return this.sendReply('/roomowner - Access denied.');

		if (!room.auth) room.auth = room.chatRoomData.auth = {};

		var name = targetUser.name;

		room.auth[targetUser.userid] = '#';
		this.addModCommand("" + name + " was appointed Room Owner by " + user.name + ".");
		room.onUpdateIdentity(targetUser);
		Rooms.global.writeChatRoomData();
	},
	roomownerhelp: ["/roomowner [username] - Appoints [username] as a room owner. Removes official status. Requires: ~"],

	roomdeowner: 'deroomowner',
	deroomowner: function (target, room, user) {
		if (!room.auth) {
			return this.sendReply("/roomdeowner - This room isn't designed for per-room moderation");
		}
		target = this.splitTarget(target, true);
		var targetUser = this.targetUser;
		var name = this.targetUsername;
		var userid = toId(name);
		if (!userid || userid === '') return this.sendReply("User '" + name + "' does not exist.");

		if (room.auth[userid] !== '#') return this.sendReply("User '"+name+"' is not a room owner.");
		if (!room.founder || user.userid !== room.founder && !this.can('makeroom', null, room)) return false;

		delete room.auth[userid];
		this.sendReply("(" + name + " is no longer Room Owner.)");
		if (targetUser) targetUser.updateIdentity();
		if (room.chatRoomData) {
			Rooms.global.writeChatRoomData();
		}
	},

	roomleader: function (target, room, user) {
		if (!room.chatRoomData) {
			return this.sendReply("/roomowner - This room isn't designed for per-room moderation to be added");
		}
		target = this.splitTarget(target, true);
		var targetUser = this.targetUser;

		if (!targetUser) return this.sendReply("User '" + this.targetUsername + "' is not online.");

		if (!room.founder) return this.sendReply('The room needs a room founder before it can have a room owner.');
		if (room.founder !== user.userid && !this.can('makeroom')) return this.sendReply('/roomowner - Access denied.');

		if (!room.auth) room.auth = room.chatRoomData.auth = {};

		var name = targetUser.name;

		room.auth[targetUser.userid] = '&';
		this.addModCommand("" + name + " was appointed Room Leader by " + user.name + ".");
		room.onUpdateIdentity(targetUser);
		Rooms.global.writeChatRoomData();
	},

	roomdeleader: 'deroomowner',
	deroomleader: function (target, room, user) {
		if (!room.auth) {
			return this.sendReply("/roomdeowner - This room isn't designed for per-room moderation");
		}
		target = this.splitTarget(target, true);
		var targetUser = this.targetUser;
		var name = this.targetUsername;
		var userid = toId(name);
		if (!userid || userid === '') return this.sendReply("User '" + name + "' does not exist.");

		if (room.auth[userid] !== '&') return this.sendReply("User '"+name+"' is not a room leader.");
		if (!room.founder || user.userid !== room.founder && !this.can('makeroom', null, room)) return false;

		delete room.auth[userid];
		this.sendReply("(" + name + " is no longer Room Leader.)");
		if (targetUser) targetUser.updateIdentity();
		if (room.chatRoomData) {
			Rooms.global.writeChatRoomData();
		}
        },

	leagueroom: function (target, room, user) {
		if (!this.can('makeroom')) return;
		if (!room.chatRoomData) {
			return this.sendReply('/leagueroom - This room can\'t be marked as a league');
		}
		if (target === 'off') {
			delete room.isLeague;
			this.addModCommand(user.name+' has made this chat room a normal room.');
			delete room.chatRoomData.isLeague;
			Rooms.global.writeChatRoomData();
		} else {
			room.isLeague = true;
			this.addModCommand(user.name+' made this room a league room.');
			room.chatRoomData.isLeague = true;
			Rooms.global.writeChatRoomData();
		}

	},

	closeleague: 'openleague',
	openleague: function (target, room, user, connection, cmd) {
		if (!room.isLeague) return this.sendReply("This is not a league room, if it is, get a Leader or Admin to set the room as a league room.");
		if (!this.can('roommod', null, room)) return false;
		if (!room.chatRoomData) {
			return this.sendReply("This room cannot have a league toggle option.");
		}
		if (cmd === 'closeleague') {
			if (!room.isOpen) return this.sendReply('The league is already marked as closed.');
			delete room.isOpen;
			delete room.chatRoomData.isOpen;
			Rooms.global.writeChatRoomData();
			return this.sendReply('This league has now been marked as closed.');
		}
		else {
			if (room.isOpen) return this.sendReply('The league is already marked as open.');
			room.isOpen = true;
			room.chatRoomData.isOpen = true;
			Rooms.global.writeChatRoomData();
			return this.sendReply('This league has now been marked as open.');
		}
	},

	leaguestatus: function (target, room, user) {
		if (!room.isLeague) return this.sendReply("This is not a league room, if it is, get a Leader or Admin to set the room as a league room.");
		if (!this.canBroadcast()) return;
		if (room.isOpen) {
			return this.sendReplyBox(room.title+' is open to challengers.');
		}
		else if (!room.isOpen) {
			return this.sendReplyBox(room.title+' is closed to challengers.');
		}
		else return this.sendReply('This league does not have a status set.');
	},

	roomstatus: function (target, room, user) {
		if (!room.chatRoomData) return false;
		if (!this.canBroadcast()) return false;
		if (room.isPublic && !room.isOfficial) {
			return this.sendReplyBox(room.title + ' is a public room.');
		} else if (!room.isPublic && !room.isOfficial) {
			return this.sendReplyBox(room.title + ' is not a public room.');
		}
		if (room.isOfficial && room.isPublic) {
			return this.sendReplyBox(room.title + ' is an official room.');
		}
},
	randp: function (target, room, user) {
		var fs = require('fs');
		var fileName = "pokedex.js";
		if (!this.canBroadcast()) return;
		var shinyPoke = '';
		var x = '';
		if (/shiny/i.test(target)) {
			var shinyPoke = '-shiny';
		}
		var kanto = false; var johto = false; var hoenn = false; var sinnoh = false; var kalos = false; var unova = false;
		if (/kanto/i.test(target) || /gen 1/i.test(target)) {
			var kalos = true;
			var x = Math.floor(Math.random() * (174 - 1)) + 1;
		} else if (/johto/i.test(target) || /gen 2/i.test(target)) {
			var johto = true;
			var x = Math.floor(Math.random() * (281 - 173)) + 173;
		} else if (/hoenn/i.test(target) || /gen 3/i.test(target)) {
			var hoenn = true;
			var x = Math.floor(Math.random() * (444 - 280)) + 280;
		} else if (/sinnoh/i.test(target) || /gen 4/i.test(target)) {
			var sinnoh = true;
			var x = Math.floor(Math.random() * (584 - 443)) + 443;
		} else if (/kalos/i.test(target) || /gen 5/i.test(target)) {
			var kalos = true;
			var x = Math.floor(Math.random() * (755 - 583)) + 583;
		} else if (/unova/i.test(target) || /gen 6/i.test(target)) {
			var unova = true;
			var x = Math.floor(Math.random() * (834 - 752)) + 752;
		}
		if (kanto === false && johto === false && hoenn === false && sinnoh === false && kalos === false && unova === false) {
			var x = Math.floor(Math.random() * (856 - 1)) + 1;
		}
		var randP = '';
		var pokeNum = parseInt(x);
		var pokedex = fs.readFileSync('./data/pokedex.js').toString().split("\n");
		var pokemon = (pokedex[x]);
		var speciesIndex1 = pokemon.indexOf('species:"') + 9; var speciesIndex2 = pokemon.indexOf('",', speciesIndex1);
		var pokeName = pokemon.slice(speciesIndex1, speciesIndex2);
		var type1Index1 = pokemon.indexOf(',types:["') + 9; var type1Index2 = pokemon.indexOf('"],', type1Index1);
		var pokeType2 = '';
		if (/,/.test(pokemon.slice(type1Index1, type1Index2))) {
			var type1Index2 = pokemon.indexOf('","', type1Index1);
			var type2Index1 = pokemon.indexOf('","', type1Index1) + 3; var type2Index2 = pokemon.indexOf('"],', type2Index1);
			var pokeType2 = '';
		}
		var pokeType1 = '';
		var ability1Index1 = pokemon.indexOf(',abilities:{0:"') + 15; var ability1Index2 = pokemon.indexOf('"},h', ability1Index1);
		var pokeAbility2 = '';
		var pokeAbility3 = '';
		if (/",/.test(pokemon.slice(ability1Index1, ability1Index2))) {
			if (/",H:"/.test(pokemon.slice(ability1Index1, ability1Index2))) {
				var ability1Index2 = pokemon.indexOf('",H:"', ability1Index1);
				var ability3Index1 = pokemon.indexOf('",H:"', ability1Index1) + 5; var ability3Index2 = pokemon.indexOf('"', ability3Index1);
				var pokeAbility3 = ', ' + pokemon.slice(ability3Index1, ability3Index2);
			}
			if (/",1:"/.test(pokemon.slice(ability1Index1, ability1Index2))) {
				var ability1Index2 = pokemon.indexOf('",1:"', ability1Index1);
				var ability2Index1 = pokemon.indexOf('",1:"', ability1Index1) + 5; var ability2Index2 = pokemon.indexOf('"', ability2Index1);
				var pokeAbility2 = ', ' + pokemon.slice(ability2Index1, ability2Index2);
			}
		}
		var ability1Index2 = pokemon.indexOf('"', ability1Index1);
		var pokeAbility1 = pokemon.slice(ability1Index1, ability1Index2);
		var hpIndex1 = pokemon.indexOf('hp:') + 3; var hpIndex2 = pokemon.indexOf(',', hpIndex1);
		var pokeHp = parseInt(pokemon.slice(hpIndex1, hpIndex2));
		var atkIndex1 = pokemon.indexOf('atk:') + 4; var atkIndex2 = pokemon.indexOf(',', atkIndex1);
		var pokeAtk = parseInt(pokemon.slice(atkIndex1, atkIndex2));
		var defIndex1 = pokemon.indexOf('def:') + 4; var defIndex2 = pokemon.indexOf(',', defIndex1);
		var pokeDef = parseInt(pokemon.slice(defIndex1, defIndex2));
		var spaIndex1 = pokemon.indexOf('spa:') + 4; var spaIndex2 = pokemon.indexOf(',', spaIndex1);
		var pokeSpa = parseInt(pokemon.slice(spaIndex1, spaIndex2));
		var spdIndex1 = pokemon.indexOf('spd:') + 4; var spdIndex2 = pokemon.indexOf(',', spdIndex1);
		var pokeSpd = parseInt(pokemon.slice(spdIndex1, spdIndex2));
		var speIndex1 = pokemon.indexOf('spe:') + 4; var speIndex2 = pokemon.indexOf('}', speIndex1);
		var pokeSpe = parseInt(pokemon.slice(speIndex1, speIndex2));
		var pokeBst = pokeHp + pokeAtk + pokeDef + pokeSpa + pokeSpd + pokeSpe;
		var pokeStats = 'HP ' + pokeHp + ' / Atk ' + pokeAtk + ' / Def ' + pokeDef + ' / SpA ' + pokeSpa + ' / SpD ' + pokeSpd + ' / Spe ' + pokeSpe + ' / BST ' + pokeBst;
		var colorIndex1 = pokemon.indexOf(',color:"') + 8; var colorIndex2 = pokemon.indexOf('",', colorIndex1);
		var pokeColor = pokemon.slice(colorIndex1, colorIndex2);
		var egg1Index1 = pokemon.indexOf(',eggGroups:["') + 13; var egg1Index2 = pokemon.indexOf('"]', egg1Index1);
		var pokeEgg2 = "";
		if (/,/.test(pokemon.slice(egg1Index1, egg1Index2))) {
			var egg1Index2 = pokemon.indexOf('","', egg1Index1);
			var egg2Index1 = pokemon.indexOf('","', egg1Index1) + 3; var egg2Index2 = pokemon.indexOf('"]', egg2Index1);
			var pokeEgg2 = ", " + pokemon.slice(egg2Index1, egg2Index2);
		}
		var pokeEgg1 = pokemon.slice(egg1Index1, egg1Index2);
		if (pokeName === "Ho-Oh" || pokeName === "Nidoran-F" || pokeName === "Nidoran-M" || pokeName === "Farfetch'd" || pokeName === "Porygon-Z") {
			randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: ' + pokeAbility1 + pokeAbility2 + pokeAbility3 + '
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
		} else if (pokeName === "Basculin-Blue-Striped") {
			randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: ' + pokeAbility1 + pokeAbility2 + pokeAbility3 + '
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
		} else if (pokeName === "Pichu-Spiky-eared") {
			randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: ' + pokeAbility1 + pokeAbility2 + pokeAbility3 + '
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
		} else if (pokeName === "Floette-Eternal-Flower") {
			randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: ' + pokeAbility1 + pokeAbility2 + pokeAbility3 + '
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
		} else if (pokeName === "Missingno.") {
			var y = Math.floor(Math.random() * (6 - 1)) + 1;
			switch (y) {
			case 1:
				randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: None
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
				break;
			case 2:
				randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: None
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
				break;
			case 3:
				randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: None
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
				break;
			case 4:
				randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: None
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
				break;
			case 5:
				randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: None
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
				break;
			default:
				break;
			}
		} else if (pokeName === "Pikachu-Cosplay") {
			var z = Math.floor(Math.random() * (6 - 1)) + 1;
			switch (z) {
			case 1:
				randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: ' + pokeAbility1 + pokeAbility2 + pokeAbility3 + '
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
				break;
			case 2:
				randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: ' + pokeAbility1 + pokeAbility2 + pokeAbility3 + '
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
				break;
			case 3:
				randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: ' + pokeAbility1 + pokeAbility2 + pokeAbility3 + '
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
				break;
			case 4:
				randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: ' + pokeAbility1 + pokeAbility2 + pokeAbility3 + '
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
				break;
			case 5:
				randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: ' + pokeAbility1 + pokeAbility2 + pokeAbility3 + '
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
				break;
			default:
				break;
			}
		} else {
			randP = '

	Name: ' + pokeName + '
Type(s): ' + pokeType1 + ' ' + pokeType2 + '
Ability: ' + pokeAbility1 + pokeAbility2 + pokeAbility3 + '
Stats: ' + pokeStats + '
Color: ' + pokeColor + '
Egg Group(s): ' + pokeEgg1 + pokeEgg2 + '

';
		}
		this.sendReplyBox(randP);
	}
	};
<commit_msg>Delete roomauth.js<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';

class Image extends Component {
  // Set pluginOptions
  static pluginOptions = {
    // Handle focused style manually
    customFocusedStyle: true,
    // Handle alignment style manually
    customAlignmentStyle: true,
    // Handle upload progress style manually
    customUploadProgress: true,
    // Handle dnd onDragStart/draggable manually
    customHandleDnd: true
  }

  renderProgress = (progress, theme) => progress >= 0
    ? <div className={ theme.imageLoader } style={{ width: `${100 - progress}%` }} />
    : null;

  render() {
    const { alignment, onDragStart, draggable, theme, focusedStyle, isFocused,
      progress, src, url } = this.props;

    // Compose figure classNames
    const className = `${theme.imageWrapper} ${theme[alignment || 'center']}`;
    // Compose image classNames
    const imageClassName = theme.image + (isFocused ? ` ${focusedStyle.focused}` : '');

    return (

        {this.renderProgress(progress, theme)}

    );
  }
}

export default Image;
<commit_msg>Refactor image component<commit_after>import React, { Component } from 'react';

class Image extends Component {
  // Set pluginOptions
  static pluginOptions = {
    // Handle focused style manually
    customFocusedStyle: true,
    // Handle alignment style manually
    customAlignmentStyle: true,
    // Handle upload progress style manually
    customUploadProgress: true,
    // Handle dnd onDragStart/draggable manually
    customHandleDnd: true
  }

  renderProgress = (progress, theme) => progress >= 0
    ? <div className={ theme.imageLoader } style={{ width: `${100 - progress}%` }} />
    : null;

  render() {
    const { alignment, onDragStart, draggable, theme, focusedStyle, isFocused,
      progress, src, url } = this.props;

    // Compose figure classNames
    const className = `${theme.imageWrapper} ${theme[alignment || 'center']}`;
    // Compose image classNames
    const imageClassName = theme.image + (isFocused ? ` ${focusedStyle.focused}` : '');

    return (

        {this.renderProgress(progress, theme)}

    );
  }
}

export default Image;
<|endoftext|>


<commit_before>dojo.require("doh.runner");
dojo.require("<%= full_name%>");

dojo.addOnLoad(function () {
	doh.register("<%= full_name%>", [
	function test1(t) {
		t.t(false, 'not implemented');
	},
	function asyncTest(t) {
		var d = new doh.Deferred();
		t.t(false, 'not implemented');
		//d.callback(true);
		return d;
	}]);
});
<commit_msg>add doh run<commit_after>dojo.require("doh.runner");
//dojo.require("dojo.robot");
dojo.require("<%= full_name%>");

dojo.addOnLoad(function () {
	doh.register("<%= full_name%>", [
	function test1(t) {
		t.t(false, 'not implemented');
	},
	function asyncTest(t) {
		var d = new doh.Deferred();
		t.t(false, 'not implemented');
		//d.callback(true);
		return d;
	}]);
	doh.run();
});
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2017 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */
module.exports = {
    writeFiles
};

function writeFiles() {
    return {
        writeDockerCompose() {
            this.template('_docker-compose.yml', 'docker-compose.yml');
            this.template('_README-DOCKER-COMPOSE.md', 'README-DOCKER-COMPOSE.md');
        },

        writeRegistryFiles() {
            if (this.serviceDiscoveryType === 'eureka') {
                this.template('_jhipster-registry.yml', 'jhipster-registry.yml');
            }
            if (this.serviceDiscoveryType) {
                this.template('central-server-config/_application.yml', 'central-server-config/application.yml');
            }
            if (this.gatewayNb === 0 && this.microserviceNb === 0) return;
            if (this.serviceDiscoveryType === 'consul') {
                this.template('_consul.yml', 'consul.yml');
            }
        },

        writeTraefikFiles() {
            if (this.gatewayType !== 'traefik') return;
            this.template('_traefik.yml', 'traefik.yml');
            this.template('traefik/_traefik.toml', 'traefik/traefik.toml');
        },

        writeKafkaFiles() {
            if (!this.useKafka) return;

            this.template('_kafka.yml', 'kafka.yml');
        },

        writeKeycloakFiles() {
            if (this.authenticationType !== 'oauth2') return;
            this.template('_keycloak.yml', 'keycloak.yml');
            this.template('realm-config/_jhipster-realm.json', 'realm-config/jhipster-realm.json');
            this.template('realm-config/_jhipster-users-0.json', 'realm-config/_jhipster-users-0.json');
        },

        writeElkFiles() {
            if (this.monitoring !== 'elk') return;

            this.template('_jhipster-console.yml', 'jhipster-console.yml');
            this.template('log-conf/_logstash.conf', 'log-conf/logstash.conf');
            this.template('log-data/_.gitignore', 'log-data/.gitignore');
        },

        writePrometheusFiles() {
            if (this.monitoring !== 'prometheus') return;

            // Generate a list of target apps to monitor for the prometheus config
            const appsToMonitor = [];
            for (let i = 0; i < this.appConfigs.length; i++) {
                appsToMonitor.push(`             - ${this.appConfigs[i].baseName}-app:${this.appConfigs[i].serverPort}`);
            }

            // Format the application target list as a YAML array
            this.appsToMonitorList = appsToMonitor.join('\n').replace(/'/g, '');

            this.template('_prometheus.yml', 'prometheus.yml');
            this.template('prometheus-conf/_prometheus.yml', 'prometheus-conf/prometheus.yml');
            this.template('prometheus-conf/_alert.rules', 'prometheus-conf/alert.rules');
            this.template('alertmanager-conf/_config.yml', 'alertmanager-conf/config.yml');
        }
    };
}
<commit_msg>Correct file name<commit_after>/**
 * Copyright 2013-2017 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */
module.exports = {
    writeFiles
};

function writeFiles() {
    return {
        writeDockerCompose() {
            this.template('_docker-compose.yml', 'docker-compose.yml');
            this.template('_README-DOCKER-COMPOSE.md', 'README-DOCKER-COMPOSE.md');
        },

        writeRegistryFiles() {
            if (this.serviceDiscoveryType === 'eureka') {
                this.template('_jhipster-registry.yml', 'jhipster-registry.yml');
            }
            if (this.serviceDiscoveryType) {
                this.template('central-server-config/_application.yml', 'central-server-config/application.yml');
            }
            if (this.gatewayNb === 0 && this.microserviceNb === 0) return;
            if (this.serviceDiscoveryType === 'consul') {
                this.template('_consul.yml', 'consul.yml');
            }
        },

        writeTraefikFiles() {
            if (this.gatewayType !== 'traefik') return;
            this.template('_traefik.yml', 'traefik.yml');
            this.template('traefik/_traefik.toml', 'traefik/traefik.toml');
        },

        writeKafkaFiles() {
            if (!this.useKafka) return;

            this.template('_kafka.yml', 'kafka.yml');
        },

        writeKeycloakFiles() {
            if (this.authenticationType !== 'oauth2') return;
            this.template('_keycloak.yml', 'keycloak.yml');
            this.template('realm-config/_jhipster-realm.json', 'realm-config/jhipster-realm.json');
            this.template('realm-config/_jhipster-users-0.json', 'realm-config/jhipster-users-0.json');
        },

        writeElkFiles() {
            if (this.monitoring !== 'elk') return;

            this.template('_jhipster-console.yml', 'jhipster-console.yml');
            this.template('log-conf/_logstash.conf', 'log-conf/logstash.conf');
            this.template('log-data/_.gitignore', 'log-data/.gitignore');
        },

        writePrometheusFiles() {
            if (this.monitoring !== 'prometheus') return;

            // Generate a list of target apps to monitor for the prometheus config
            const appsToMonitor = [];
            for (let i = 0; i < this.appConfigs.length; i++) {
                appsToMonitor.push(`             - ${this.appConfigs[i].baseName}-app:${this.appConfigs[i].serverPort}`);
            }

            // Format the application target list as a YAML array
            this.appsToMonitorList = appsToMonitor.join('\n').replace(/'/g, '');

            this.template('_prometheus.yml', 'prometheus.yml');
            this.template('prometheus-conf/_prometheus.yml', 'prometheus-conf/prometheus.yml');
            this.template('prometheus-conf/_alert.rules', 'prometheus-conf/alert.rules');
            this.template('alertmanager-conf/_config.yml', 'alertmanager-conf/config.yml');
        }
    };
}
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2017 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */
module.exports = {
    writeFiles
};

function writeFiles() {
    return {
        writeDockerCompose() {
            this.template('_docker-compose.yml', 'docker-compose.yml');
            this.template('_README-DOCKER-COMPOSE.md', 'README-DOCKER-COMPOSE.md');
        },

        writeRegistryFiles() {
            if (this.serviceDiscoveryType === 'eureka') {
                this.template('_jhipster-registry.yml', 'jhipster-registry.yml');
            }
            if (this.serviceDiscoveryType) {
                this.template('central-server-config/_application.yml', 'central-server-config/application.yml');
            }
            if (this.gatewayNb === 0 && this.microserviceNb === 0) return;
            if (this.serviceDiscoveryType === 'consul') {
                this.template('_consul.yml', 'consul.yml');
            }
        },

        writeTraefikFiles() {
            if (this.gatewayType !== 'traefik') return;
            this.template('_traefik.yml', 'traefik.yml');
            this.template('traefik/_traefik.toml', 'traefik/traefik.toml');
        },

        writeKafkaFiles() {
            if (!this.useKafka) return;

            this.template('_kafka.yml', 'kafka.yml');
        },

        writeKeycloakFiles() {
            if (this.authenticationType !== 'oauth2') return;
            this.template('_keycloak.yml', 'keycloak.yml');
            this.template('_realm-config/_jhipster-realm.yml', 'realm-config/jhipster-realm.yml');
            this.template('_realm-config/_jhipster-users-0.yml', 'realm-config/_jhipster-users-0.yml');
        },

        writeElkFiles() {
            if (this.monitoring !== 'elk') return;

            this.template('_jhipster-console.yml', 'jhipster-console.yml');
            this.template('log-conf/_logstash.conf', 'log-conf/logstash.conf');
            this.template('log-data/_.gitignore', 'log-data/.gitignore');
        },

        writePrometheusFiles() {
            if (this.monitoring !== 'prometheus') return;

            // Generate a list of target apps to monitor for the prometheus config
            const appsToMonitor = [];
            for (let i = 0; i < this.appConfigs.length; i++) {
                appsToMonitor.push(`             - ${this.appConfigs[i].baseName}-app:${this.appConfigs[i].serverPort}`);
            }

            // Format the application target list as a YAML array
            this.appsToMonitorList = appsToMonitor.join('\n').replace(/'/g, '');

            this.template('_prometheus.yml', 'prometheus.yml');
            this.template('prometheus-conf/_prometheus.yml', 'prometheus-conf/prometheus.yml');
            this.template('prometheus-conf/_alert.rules', 'prometheus-conf/alert.rules');
            this.template('alertmanager-conf/_config.yml', 'alertmanager-conf/config.yml');
        }
    };
}
<commit_msg>Fix file path errors<commit_after>/**
 * Copyright 2013-2017 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */
module.exports = {
    writeFiles
};

function writeFiles() {
    return {
        writeDockerCompose() {
            this.template('_docker-compose.yml', 'docker-compose.yml');
            this.template('_README-DOCKER-COMPOSE.md', 'README-DOCKER-COMPOSE.md');
        },

        writeRegistryFiles() {
            if (this.serviceDiscoveryType === 'eureka') {
                this.template('_jhipster-registry.yml', 'jhipster-registry.yml');
            }
            if (this.serviceDiscoveryType) {
                this.template('central-server-config/_application.yml', 'central-server-config/application.yml');
            }
            if (this.gatewayNb === 0 && this.microserviceNb === 0) return;
            if (this.serviceDiscoveryType === 'consul') {
                this.template('_consul.yml', 'consul.yml');
            }
        },

        writeTraefikFiles() {
            if (this.gatewayType !== 'traefik') return;
            this.template('_traefik.yml', 'traefik.yml');
            this.template('traefik/_traefik.toml', 'traefik/traefik.toml');
        },

        writeKafkaFiles() {
            if (!this.useKafka) return;

            this.template('_kafka.yml', 'kafka.yml');
        },

        writeKeycloakFiles() {
            if (this.authenticationType !== 'oauth2') return;
            this.template('_keycloak.yml', 'keycloak.yml');
            this.template('realm-config/_jhipster-realm.json', 'realm-config/jhipster-realm.json');
            this.template('realm-config/_jhipster-users-0.json', 'realm-config/_jhipster-users-0.json');
        },

        writeElkFiles() {
            if (this.monitoring !== 'elk') return;

            this.template('_jhipster-console.yml', 'jhipster-console.yml');
            this.template('log-conf/_logstash.conf', 'log-conf/logstash.conf');
            this.template('log-data/_.gitignore', 'log-data/.gitignore');
        },

        writePrometheusFiles() {
            if (this.monitoring !== 'prometheus') return;

            // Generate a list of target apps to monitor for the prometheus config
            const appsToMonitor = [];
            for (let i = 0; i < this.appConfigs.length; i++) {
                appsToMonitor.push(`             - ${this.appConfigs[i].baseName}-app:${this.appConfigs[i].serverPort}`);
            }

            // Format the application target list as a YAML array
            this.appsToMonitorList = appsToMonitor.join('\n').replace(/'/g, '');

            this.template('_prometheus.yml', 'prometheus.yml');
            this.template('prometheus-conf/_prometheus.yml', 'prometheus-conf/prometheus.yml');
            this.template('prometheus-conf/_alert.rules', 'prometheus-conf/alert.rules');
            this.template('alertmanager-conf/_config.yml', 'alertmanager-conf/config.yml');
        }
    };
}
<|endoftext|>