<commit_before>/**
 * WordPress dependencies
 */
import {
	ContrastChecker,
	FontSizePicker,
	InspectorControls,
	PanelColorSettings,
	withColors,
	withFontSizes,
} from '@wordpress/block-editor';
import { getBlockType } from '@wordpress/blocks';
import { withDispatch, withSelect } from '@wordpress/data';
import { Fragment } from '@wordpress/element';
import { compose, createHigherOrderComponent } from '@wordpress/compose';
import { PanelBody, RangeControl, SelectControl, ToggleControl, withFallbackStyles } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import { StoryBlockMover, FontFamilyPicker, ResizableBox, AnimationControls, RotatableBox } from './';
import { ALLOWED_CHILD_BLOCKS, ALLOWED_MOVABLE_BLOCKS, BLOCKS_WITH_TEXT_SETTINGS } from '../constants';
import { maybeEnqueueFontStyle } from '../helpers';

const { getComputedStyle } = window;

const applyFallbackStyles = withFallbackStyles( ( node, ownProps ) => {
	const { textColor, backgroundColor, fontSize, customFontSize } = ownProps;
	const editableNode = node.querySelector( '[contenteditable="true"]' );
	const computedStyles = editableNode ? getComputedStyle( editableNode ) : null;

	return {
		fallbackBackgroundColor: backgroundColor || ! computedStyles ? undefined : computedStyles.backgroundColor,
		fallbackTextColor: textColor || ! computedStyles ? undefined : computedStyles.color,
		fallbackFontSize: fontSize || customFontSize || ! computedStyles ? undefined : parseInt( computedStyles.fontSize ) || undefined,
	};
} );

const applyWithSelect = withSelect( ( select, props ) => {
	const { getSelectedBlockClientId, getBlockRootClientId, getBlock } = select( 'core/block-editor' );
	const { getAnimatedBlocks, isValidAnimationPredecessor } = select( 'amp/story' );

	const currentBlock = getSelectedBlockClientId();
	const page = getBlockRootClientId( currentBlock );

	const animatedBlocks = getAnimatedBlocks()[ page ] || [];
	const animationOrderEntry = animatedBlocks.find( ( { id } ) => id === props.clientId );

	return {
		parentBlock: getBlock( getBlockRootClientId( props.clientId ) ),
		// Use parent's clientId instead of anchor attribute.
		// The attribute will be updated via subscribers.
		animationAfter: animationOrderEntry ? animationOrderEntry.parent : undefined,
		getAnimatedBlocks() {
			return ( getAnimatedBlocks()[ page ] || [] )
				.filter( ( { id } ) => id !== currentBlock )
				.filter( ( { id } ) => {
					const block = getBlock( id );

					return block && block.attributes.ampAnimationType && isValidAnimationPredecessor( page, currentBlock, id );
				} )
				.map( ( { id } ) => {
					const block = getBlock( id );
					return {
						value: id,
						label: block.name,
						block,
						blockType: getBlockType( block.name ),
					};
				} );
		},
	};
} );

const applyWithDispatch = withDispatch( ( dispatch, { toggleSelection }, { select } ) => {
	const {
		getSelectedBlockClientId,
		getBlockRootClientId,
	} = select( 'core/block-editor' );
	const { clearSelectedBlock } = dispatch( 'core/block-editor' );

	const item = getSelectedBlockClientId();
	const page = getBlockRootClientId( item );

	const {
		addAnimation,
		changeAnimationType,
		changeAnimationDuration,
		changeAnimationDelay,
	} = dispatch( 'amp/story' );

	return {
		onAnimationTypeChange( type ) {
			changeAnimationType( page, item, type );
		},
		onAnimationOrderChange( predecessor ) {
			addAnimation( page, item, predecessor );
		},
		onAnimationDurationChange( value ) {
			changeAnimationDuration( page, item, value );
		},
		onAnimationDelayChange( value ) {
			changeAnimationDelay( page, item, value );
		},
		startBlockRotation: () => toggleSelection( false ),
		stopBlockRotation: () => {
			toggleSelection( true );

			clearSelectedBlock();
			document.activeElement.blur();
		},
	};
} );

const enhance = compose(
	withColors( 'backgroundColor', { textColor: 'color' } ),
	withFontSizes( 'fontSize' ),
	applyFallbackStyles,
	applyWithSelect,
	applyWithDispatch,
);

export default createHigherOrderComponent(
	( BlockEdit ) => {
		return enhance( ( props ) => {
			const {
				clientId,
				name,
				attributes,
				isSelected,
				toggleSelection,
				fontSize,
				setFontSize,
				setAttributes,
				backgroundColor,
				setBackgroundColor,
				textColor,
				setTextColor,
				fallbackBackgroundColor,
				fallbackTextColor,
				onAnimationTypeChange,
				onAnimationOrderChange,
				onAnimationDurationChange,
				onAnimationDelayChange,
				getAnimatedBlocks,
				animationAfter,
				startBlockRotation,
				stopBlockRotation,
			} = props;

			const isChildBlock = ALLOWED_CHILD_BLOCKS.includes( name );

			if ( ! isChildBlock ) {
				return <BlockEdit { ...props } />;
			}

			const isImageBlock = 'core/image' === name;
			const isTextBlock = 'amp/amp-story-text' === name;
			const needsTextSettings = BLOCKS_WITH_TEXT_SETTINGS.includes( name );
			const isMovableBlock = ALLOWED_MOVABLE_BLOCKS.includes( name );

			const {
				ampFontFamily,
				ampFitText,
				height,
				width,
				opacity,
				type: textBlockTextType,
				ampShowImageCaption,
				ampAnimationType,
				ampAnimationDuration,
				ampAnimationDelay,
				rotationAngle,
			} = attributes;

			// If we have an image with pre-set caption we should remove it.
			if ( isImageBlock && ! ampShowImageCaption && attributes.caption && 0 !== attributes.caption.length ) {
				setAttributes( { caption: '' } );
			}

			const minTextHeight = 20;
			const minTextWidth = 30;

			return (
				<Fragment>
					{ isMovableBlock && (
						<StoryBlockMover
							clientId={ props.clientId }
							blockElementId={ `block-${ props.clientId }` }
							isDraggable={ ! props.isPartOfMultiSelection && isSelected }
						/>
					) }
					{ ! isMovableBlock && ( <BlockEdit { ...props } /> ) }
					{ isImageBlock && (
						<RotatableBox
							blockElementId={ `block-${ clientId }` }
							initialAngle={ rotationAngle }
							className="amp-story-editor__rotate-container"
							angle={ isSelected ? 0 : rotationAngle }
							onRotateStart={ () => {
								startBlockRotation();
							} }
							onRotateStop={ ( event, angle ) => {
								setAttributes( {
									rotationAngle: angle,
								} );

								stopBlockRotation();
							} }
						>
							<BlockEdit { ...props } />
						</RotatableBox>
					) }
					{ isMovableBlock && ! isImageBlock && (
						<ResizableBox
							isSelected={ isSelected }
							width={ width }
							height={ height }
							minHeight={ minTextHeight }
							minWidth={ minTextWidth }
							onResizeStop={ ( value ) => {
								setAttributes( value );
								toggleSelection( true );
							} }
							onResizeStart={ () => {
								toggleSelection( false );
							} }
						>
							<RotatableBox
								blockElementId={ `block-${ clientId }` }
								initialAngle={ rotationAngle }
								className="amp-story-editor__rotate-container"
								angle={ isSelected ? 0 : rotationAngle }
								onRotateStart={ () => {
									startBlockRotation();
								} }
								onRotateStop={ ( event, angle ) => {
									setAttributes( {
										rotationAngle: angle,
									} );

									stopBlockRotation();
								} }
							>
								<BlockEdit { ...props } />
							</RotatableBox>
						</ResizableBox>
					) }
					{ needsTextSettings && (
						<InspectorControls>
							<PanelBody title={ __( 'Text Settings', 'amp' ) }>
								<FontFamilyPicker
									value={ ampFontFamily }
									onChange={ ( value ) => {
										maybeEnqueueFontStyle( value );
										setAttributes( { ampFontFamily: value } );
									} }
								/>
								{ ! ampFitText && (
									<FontSizePicker
										value={ fontSize.size }
										onChange={ setFontSize }
									/>
								) }
								{ isTextBlock && (
									<ToggleControl
										label={ __( 'Automatically fit text to container', 'amp' ) }
										checked={ ampFitText }
										onChange={ () => ( setAttributes( { ampFitText: ! ampFitText } ) ) }
									/>
								) }
								{ isTextBlock && (
									<SelectControl
										label={ __( 'Select text type', 'amp' ) }
										value={ textBlockTextType }
										onChange={ ( selected ) => setAttributes( { type: selected } ) }
										options={ [
											{ value: 'auto', label: __( 'Automatic', 'amp' ) },
											{ value: 'p', label: __( 'Paragraph', 'amp' ) },
											{ value: 'h1', label: __( 'Heading 1', 'amp' ) },
											{ value: 'h2', label: __( 'Heading 2', 'amp' ) },
										] }
									/>
								) }
							</PanelBody>
							<PanelColorSettings
								title={ __( 'Color Settings', 'amp' ) }
								initialOpen={ false }
								colorSettings={ [
									{
										value: backgroundColor.color,
										onChange: setBackgroundColor,
										label: __( 'Background Color', 'amp' ),
									},
									{
										value: textColor.color,
										onChange: setTextColor,
										label: __( 'Text Color', 'amp' ),
									},
								] }
							>
								<ContrastChecker
									{ ...{
										textColor: textColor.color,
										backgroundColor: backgroundColor.color,
										fallbackTextColor,
										fallbackBackgroundColor,
										fontSize: fontSize.size,
									} }
								/>
								<RangeControl
									label={ __( 'Background Opacity', 'amp' ) }
									value={ opacity }
									onChange={ ( value ) => setAttributes( { opacity: value } ) }
									min={ 5 }
									max={ 100 }
									step={ 5 }
								/>
							</PanelColorSettings>
							<PanelBody
								title={ __( 'Animation', 'amp' ) }
							>
								<AnimationControls
									animatedBlocks={ getAnimatedBlocks }
									animationType={ ampAnimationType }
									animationDuration={ ampAnimationDuration ? parseInt( ampAnimationDuration ) : '' }
									animationDelay={ ampAnimationDelay ? parseInt( ampAnimationDelay ) : '' }
									animationAfter={ animationAfter }
									onAnimationTypeChange={ onAnimationTypeChange }
									onAnimationDurationChange={ onAnimationDurationChange }
									onAnimationDelayChange={ onAnimationDelayChange }
									onAnimationAfterChange={ onAnimationOrderChange }
								/>
							</PanelBody>
						</InspectorControls>
					) }
					{ isMovableBlock && (
						<InspectorControls>
							<PanelBody
								title={ __( 'Animation', 'amp' ) }
							>
								<AnimationControls
									animatedBlocks={ getAnimatedBlocks }
									animationType={ ampAnimationType }
									animationDuration={ ampAnimationDuration ? parseInt( ampAnimationDuration ) : '' }
									animationDelay={ ampAnimationDelay ? parseInt( ampAnimationDelay ) : '' }
									animationAfter={ animationAfter }
									onAnimationTypeChange={ onAnimationTypeChange }
									onAnimationDurationChange={ onAnimationDurationChange }
									onAnimationDelayChange={ onAnimationDelayChange }
									onAnimationAfterChange={ onAnimationOrderChange }
								/>
							</PanelBody>
						</InspectorControls>
					) }
					{ isImageBlock && (
						<InspectorControls>
							<PanelBody
								title={ __( 'Story Settings', 'amp' ) }
							>
								<ToggleControl
									key="position"
									label={ __( 'Show or hide the caption', 'amp' ) }
									checked={ ampShowImageCaption }
									onChange={
										function() {
											props.setAttributes( { ampShowImageCaption: ! attributes.ampShowImageCaption } );
											if ( ! attributes.ampShowImageCaption ) {
												props.setAttributes( { caption: '' } );
											}
										}
									}
									help={ __( 'Toggle on to show image caption. If you turn this off the current caption text will be deleted.', 'amp' ) }
								/>
							</PanelBody>
						</InspectorControls>
					) }
				</Fragment>
			);
		} );
	},
	'withAmpStorySettings'
);
<commit_msg>Remove duplicate animation controls.<commit_after>/**
 * WordPress dependencies
 */
import {
	ContrastChecker,
	FontSizePicker,
	InspectorControls,
	PanelColorSettings,
	withColors,
	withFontSizes,
} from '@wordpress/block-editor';
import { getBlockType } from '@wordpress/blocks';
import { withDispatch, withSelect } from '@wordpress/data';
import { Fragment } from '@wordpress/element';
import { compose, createHigherOrderComponent } from '@wordpress/compose';
import { PanelBody, RangeControl, SelectControl, ToggleControl, withFallbackStyles } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import { StoryBlockMover, FontFamilyPicker, ResizableBox, AnimationControls, RotatableBox } from './';
import { ALLOWED_CHILD_BLOCKS, ALLOWED_MOVABLE_BLOCKS, BLOCKS_WITH_TEXT_SETTINGS } from '../constants';
import { maybeEnqueueFontStyle } from '../helpers';

const { getComputedStyle } = window;

const applyFallbackStyles = withFallbackStyles( ( node, ownProps ) => {
	const { textColor, backgroundColor, fontSize, customFontSize } = ownProps;
	const editableNode = node.querySelector( '[contenteditable="true"]' );
	const computedStyles = editableNode ? getComputedStyle( editableNode ) : null;

	return {
		fallbackBackgroundColor: backgroundColor || ! computedStyles ? undefined : computedStyles.backgroundColor,
		fallbackTextColor: textColor || ! computedStyles ? undefined : computedStyles.color,
		fallbackFontSize: fontSize || customFontSize || ! computedStyles ? undefined : parseInt( computedStyles.fontSize ) || undefined,
	};
} );

const applyWithSelect = withSelect( ( select, props ) => {
	const { getSelectedBlockClientId, getBlockRootClientId, getBlock } = select( 'core/block-editor' );
	const { getAnimatedBlocks, isValidAnimationPredecessor } = select( 'amp/story' );

	const currentBlock = getSelectedBlockClientId();
	const page = getBlockRootClientId( currentBlock );

	const animatedBlocks = getAnimatedBlocks()[ page ] || [];
	const animationOrderEntry = animatedBlocks.find( ( { id } ) => id === props.clientId );

	return {
		parentBlock: getBlock( getBlockRootClientId( props.clientId ) ),
		// Use parent's clientId instead of anchor attribute.
		// The attribute will be updated via subscribers.
		animationAfter: animationOrderEntry ? animationOrderEntry.parent : undefined,
		getAnimatedBlocks() {
			return ( getAnimatedBlocks()[ page ] || [] )
				.filter( ( { id } ) => id !== currentBlock )
				.filter( ( { id } ) => {
					const block = getBlock( id );

					return block && block.attributes.ampAnimationType && isValidAnimationPredecessor( page, currentBlock, id );
				} )
				.map( ( { id } ) => {
					const block = getBlock( id );
					return {
						value: id,
						label: block.name,
						block,
						blockType: getBlockType( block.name ),
					};
				} );
		},
	};
} );

const applyWithDispatch = withDispatch( ( dispatch, { toggleSelection }, { select } ) => {
	const {
		getSelectedBlockClientId,
		getBlockRootClientId,
	} = select( 'core/block-editor' );
	const { clearSelectedBlock } = dispatch( 'core/block-editor' );

	const item = getSelectedBlockClientId();
	const page = getBlockRootClientId( item );

	const {
		addAnimation,
		changeAnimationType,
		changeAnimationDuration,
		changeAnimationDelay,
	} = dispatch( 'amp/story' );

	return {
		onAnimationTypeChange( type ) {
			changeAnimationType( page, item, type );
		},
		onAnimationOrderChange( predecessor ) {
			addAnimation( page, item, predecessor );
		},
		onAnimationDurationChange( value ) {
			changeAnimationDuration( page, item, value );
		},
		onAnimationDelayChange( value ) {
			changeAnimationDelay( page, item, value );
		},
		startBlockRotation: () => toggleSelection( false ),
		stopBlockRotation: () => {
			toggleSelection( true );

			clearSelectedBlock();
			document.activeElement.blur();
		},
	};
} );

const enhance = compose(
	withColors( 'backgroundColor', { textColor: 'color' } ),
	withFontSizes( 'fontSize' ),
	applyFallbackStyles,
	applyWithSelect,
	applyWithDispatch,
);

export default createHigherOrderComponent(
	( BlockEdit ) => {
		return enhance( ( props ) => {
			const {
				clientId,
				name,
				attributes,
				isSelected,
				toggleSelection,
				fontSize,
				setFontSize,
				setAttributes,
				backgroundColor,
				setBackgroundColor,
				textColor,
				setTextColor,
				fallbackBackgroundColor,
				fallbackTextColor,
				onAnimationTypeChange,
				onAnimationOrderChange,
				onAnimationDurationChange,
				onAnimationDelayChange,
				getAnimatedBlocks,
				animationAfter,
				startBlockRotation,
				stopBlockRotation,
			} = props;

			const isChildBlock = ALLOWED_CHILD_BLOCKS.includes( name );

			if ( ! isChildBlock ) {
				return <BlockEdit { ...props } />;
			}

			const isImageBlock = 'core/image' === name;
			const isTextBlock = 'amp/amp-story-text' === name;
			const needsTextSettings = BLOCKS_WITH_TEXT_SETTINGS.includes( name );
			const isMovableBlock = ALLOWED_MOVABLE_BLOCKS.includes( name );

			const {
				ampFontFamily,
				ampFitText,
				height,
				width,
				opacity,
				type: textBlockTextType,
				ampShowImageCaption,
				ampAnimationType,
				ampAnimationDuration,
				ampAnimationDelay,
				rotationAngle,
			} = attributes;

			// If we have an image with pre-set caption we should remove it.
			if ( isImageBlock && ! ampShowImageCaption && attributes.caption && 0 !== attributes.caption.length ) {
				setAttributes( { caption: '' } );
			}

			const minTextHeight = 20;
			const minTextWidth = 30;

			return (
				<Fragment>
					{ isMovableBlock && (
						<StoryBlockMover
							clientId={ props.clientId }
							blockElementId={ `block-${ props.clientId }` }
							isDraggable={ ! props.isPartOfMultiSelection && isSelected }
						/>
					) }
					{ ! isMovableBlock && ( <BlockEdit { ...props } /> ) }
					{ isImageBlock && (
						<RotatableBox
							blockElementId={ `block-${ clientId }` }
							initialAngle={ rotationAngle }
							className="amp-story-editor__rotate-container"
							angle={ isSelected ? 0 : rotationAngle }
							onRotateStart={ () => {
								startBlockRotation();
							} }
							onRotateStop={ ( event, angle ) => {
								setAttributes( {
									rotationAngle: angle,
								} );

								stopBlockRotation();
							} }
						>
							<BlockEdit { ...props } />
						</RotatableBox>
					) }
					{ isMovableBlock && ! isImageBlock && (
						<ResizableBox
							isSelected={ isSelected }
							width={ width }
							height={ height }
							minHeight={ minTextHeight }
							minWidth={ minTextWidth }
							onResizeStop={ ( value ) => {
								setAttributes( value );
								toggleSelection( true );
							} }
							onResizeStart={ () => {
								toggleSelection( false );
							} }
						>
							<RotatableBox
								blockElementId={ `block-${ clientId }` }
								initialAngle={ rotationAngle }
								className="amp-story-editor__rotate-container"
								angle={ isSelected ? 0 : rotationAngle }
								onRotateStart={ () => {
									startBlockRotation();
								} }
								onRotateStop={ ( event, angle ) => {
									setAttributes( {
										rotationAngle: angle,
									} );

									stopBlockRotation();
								} }
							>
								<BlockEdit { ...props } />
							</RotatableBox>
						</ResizableBox>
					) }
					{ needsTextSettings && (
						<InspectorControls>
							<PanelBody title={ __( 'Text Settings', 'amp' ) }>
								<FontFamilyPicker
									value={ ampFontFamily }
									onChange={ ( value ) => {
										maybeEnqueueFontStyle( value );
										setAttributes( { ampFontFamily: value } );
									} }
								/>
								{ ! ampFitText && (
									<FontSizePicker
										value={ fontSize.size }
										onChange={ setFontSize }
									/>
								) }
								{ isTextBlock && (
									<ToggleControl
										label={ __( 'Automatically fit text to container', 'amp' ) }
										checked={ ampFitText }
										onChange={ () => ( setAttributes( { ampFitText: ! ampFitText } ) ) }
									/>
								) }
								{ isTextBlock && (
									<SelectControl
										label={ __( 'Select text type', 'amp' ) }
										value={ textBlockTextType }
										onChange={ ( selected ) => setAttributes( { type: selected } ) }
										options={ [
											{ value: 'auto', label: __( 'Automatic', 'amp' ) },
											{ value: 'p', label: __( 'Paragraph', 'amp' ) },
											{ value: 'h1', label: __( 'Heading 1', 'amp' ) },
											{ value: 'h2', label: __( 'Heading 2', 'amp' ) },
										] }
									/>
								) }
							</PanelBody>
							<PanelColorSettings
								title={ __( 'Color Settings', 'amp' ) }
								initialOpen={ false }
								colorSettings={ [
									{
										value: backgroundColor.color,
										onChange: setBackgroundColor,
										label: __( 'Background Color', 'amp' ),
									},
									{
										value: textColor.color,
										onChange: setTextColor,
										label: __( 'Text Color', 'amp' ),
									},
								] }
							>
								<ContrastChecker
									{ ...{
										textColor: textColor.color,
										backgroundColor: backgroundColor.color,
										fallbackTextColor,
										fallbackBackgroundColor,
										fontSize: fontSize.size,
									} }
								/>
								<RangeControl
									label={ __( 'Background Opacity', 'amp' ) }
									value={ opacity }
									onChange={ ( value ) => setAttributes( { opacity: value } ) }
									min={ 5 }
									max={ 100 }
									step={ 5 }
								/>
							</PanelColorSettings>
						</InspectorControls>
					) }
					{ isMovableBlock && (
						<InspectorControls>
							<PanelBody
								title={ __( 'Animation', 'amp' ) }
							>
								<AnimationControls
									animatedBlocks={ getAnimatedBlocks }
									animationType={ ampAnimationType }
									animationDuration={ ampAnimationDuration ? parseInt( ampAnimationDuration ) : '' }
									animationDelay={ ampAnimationDelay ? parseInt( ampAnimationDelay ) : '' }
									animationAfter={ animationAfter }
									onAnimationTypeChange={ onAnimationTypeChange }
									onAnimationDurationChange={ onAnimationDurationChange }
									onAnimationDelayChange={ onAnimationDelayChange }
									onAnimationAfterChange={ onAnimationOrderChange }
								/>
							</PanelBody>
						</InspectorControls>
					) }
					{ isImageBlock && (
						<InspectorControls>
							<PanelBody
								title={ __( 'Story Settings', 'amp' ) }
							>
								<ToggleControl
									key="position"
									label={ __( 'Show or hide the caption', 'amp' ) }
									checked={ ampShowImageCaption }
									onChange={
										function() {
											props.setAttributes( { ampShowImageCaption: ! attributes.ampShowImageCaption } );
											if ( ! attributes.ampShowImageCaption ) {
												props.setAttributes( { caption: '' } );
											}
										}
									}
									help={ __( 'Toggle on to show image caption. If you turn this off the current caption text will be deleted.', 'amp' ) }
								/>
							</PanelBody>
						</InspectorControls>
					) }
				</Fragment>
			);
		} );
	},
	'withAmpStorySettings'
);
<|endoftext|>


<commit_before>/**
 * Created by Tom on 7/29/2017.
 */
exports.run = (client, guild) => {
    const moment = require('moment');
    const snekfetch = require('snekfetch');
    const config = require("../config.json");
    const dblkey = config.dblkey;
    const dbotskey = config.dbotskey;
    snekfetch.post(`https://discordbots.org/api/bots/334186716770598912/stats`)
        .set('Authorization', dblkey)
        .send({server_count: client.guilds.size})
        .then(r => console.log(r.status + ' for dbl guild count of ' + client.guilds.size))
        .catch(e => console.warn('wew tf happened here ' + e + ' for dbl post guild count of ' + client.guilds.size));
    snekfetch.post(`https://bots.discord.pw/api/bots/334186716770598912/stats`)
        .set('Authorization', dbotskey)
        .send({server_count: client.guilds.size})
        .then(r => console.log('status : ' + r.status + ' for dbots guild count of ' + client.guilds.size))
        .catch(e => console.warn('wew tf happened here ' + e + ' for dbots post guild count of ' + client.guilds.size));
    client.user.setGame(`With Nekos \\o/`);

    guild.defaultChannel.createInvite({
        maxAge: 0
    }).then(inv =>

        client.channels.get("334471388289302539").send({
            embed: {

                color: 8190976,
                title: "i joined a guild \\o/",
                thumbnail: {url: guild.iconURL},
                fields: [{
                    name: "Guild",
                    value: guild.name
                },
                    {
                        name: "Owner",
                        value: guild.owner.displayName
                    }, {
                        name: "Users",
                        value: guild.memberCount
                    },
                    {
                        name: "Bots",
                        value: guild.members.filter(member => member.user.bot).size
                    },
                    {
                        name: "invite",
                        value: inv.url
                    },
                    {
                        name: "Guild id",
                        value: guild.id
                    },
                    {
                        name: "Created At",
                        value: moment(guild.createdAt).format('LLLL')
                    },
                    {
                        name: "Total guilds",
                        value: client.guilds.size
                    }
                ],
                timestamp: new Date(),
            }
        })).catch(client.channels.get("334471388289302539").send({
        embed: {

            color: 8190976,
            title: "i joined a guild \\o/",
            thumbnail: {url: guild.iconURL},
            fields: [{
                name: "Guild",
                value: guild.name
            },
                {
                    name: "Owner",
                    value: guild.owner.displayName
                }, {
                    name: "Users",
                    value: guild.memberCount
                },
                {
                    name: "Bots",
                    value: guild.members.filter(member => member.user.bot).size
                },
                {
                    name: "invite",
                    value: "no perms"
                },
                {
                    name: "Guild id",
                    value: guild.id
                },
                {
                    name: "Created At",
                    value: moment(guild.createdAt).format('LLLL')
                },
                {
                    name: "Total guilds",
                    value: client.guilds.size
                }
            ],
            timestamp: new Date(),
        }
    }));

    console.log(`joined ${guild.name}.`);
};<commit_msg>Catches too much. Needs to just catch error<commit_after>/**
 * Created by Tom on 7/29/2017.
 */
exports.run = (client, guild) => {
    const moment = require('moment');
    const snekfetch = require('snekfetch');
    const config = require("../config.json");
    const dblkey = config.dblkey;
    const dbotskey = config.dbotskey;
    snekfetch.post(`https://discordbots.org/api/bots/334186716770598912/stats`)
        .set('Authorization', dblkey)
        .send({server_count: client.guilds.size})
        .then(r => console.log(r.status + ' for dbl guild count of ' + client.guilds.size))
        .catch(e => console.warn('wew tf happened here ' + e + ' for dbl post guild count of ' + client.guilds.size));
    snekfetch.post(`https://bots.discord.pw/api/bots/334186716770598912/stats`)
        .set('Authorization', dbotskey)
        .send({server_count: client.guilds.size})
        .then(r => console.log('status : ' + r.status + ' for dbots guild count of ' + client.guilds.size))
        .catch(e => console.warn('wew tf happened here ' + e + ' for dbots post guild count of ' + client.guilds.size));
    client.user.setGame(`With Nekos \\o/`);

    guild.defaultChannel.createInvite({
        maxAge: 0
    }).then(inv =>

        client.channels.get("334471388289302539").send({
            embed: {

                color: 8190976,
                title: "i joined a guild \\o/",
                thumbnail: {url: guild.iconURL},
                fields: [{
                    name: "Guild",
                    value: guild.name
                },
                    {
                        name: "Owner",
                        value: guild.owner.displayName
                    }, {
                        name: "Users",
                        value: guild.memberCount
                    },
                    {
                        name: "Bots",
                        value: guild.members.filter(member => member.user.bot).size
                    },
                    {
                        name: "invite",
                        value: inv.url
                    },
                    {
                        name: "Guild id",
                        value: guild.id
                    },
                    {
                        name: "Created At",
                        value: moment(guild.createdAt).format('LLLL')
                    },
                    {
                        name: "Total guilds",
                        value: client.guilds.size
                    }
                ],
                timestamp: new Date(),
            }
        })).catch(err => { client.channels.get("334471388289302539").send({
        embed: {

            color: 8190976,
            title: "i joined a guild \\o/",
            thumbnail: {url: guild.iconURL},
            fields: [{
                name: "Guild",
                value: guild.name
            },
                {
                    name: "Owner",
                    value: guild.owner.displayName
                }, {
                    name: "Users",
                    value: guild.memberCount
                },
                {
                    name: "Bots",
                    value: guild.members.filter(member => member.user.bot).size
                },
                {
                    name: "invite",
                    value: "no perms"
                },
                {
                    name: "Guild id",
                    value: guild.id
                },
                {
                    name: "Created At",
                    value: moment(guild.createdAt).format('LLLL')
                },
                {
                    name: "Total guilds",
                    value: client.guilds.size
                }
            ],
            timestamp: new Date(),
        }
    })});

    console.log(`joined ${guild.name}.`);
};
<|endoftext|>


<commit_before>load('mongo-fulltext/_load.js');
var s = db.fulltext_index_creation;
s.drop();
var i = db.fulltext_index_creation__fulltext_index;
i.drop();

var fixture = [
    { "_id" : 1, "title" : "fish", "content" : "groupers like John Dory" },
    { "_id" : 2, "title" : "dogs", "content" : "whippets kick mongrels" },
    { "_id" : 3, "title" : "dogs & fish", "content" : "whippets kick groupers" }
]

mft.get('util').load_records_from_list(fixture, 'fulltext_index_creation');
db.eval("mftsearch = mft.get('search');");

var result ;
var conf = db.fulltext_config
conf.insert({'collection_name' : 'fulltext_index_creation', 'fields': {'title': 5, 'content': 1}});

// TODO: add index on collection name (should we have an _id attribute too?)
db.eval("mftsearch.mapReduceIndex('fulltext_index_creation');");

assert.eq(i.find().toArray(), [
  { "_id" : 1, "_extracted_terms" : [ "fish", "fish", "fish", "fish", "fish", "grouper", "like", "john", "dori"
  ] },
  { "_id" : 2,  "_extracted_terms" : [ "dog", "dog", "dog", "dog", "dog", "whippet", "kick", "mongrel" ] },
  { "_id" : 3,  "_extracted_terms" : [ "dog", "fish", "dog", "fish", "dog", "fish", "dog", "fish", "dog", "fish", "whippet", "kick", "grouper"
  ] }
])<commit_msg>remove spurious tests<commit_after><|endoftext|>


<commit_before>define([],
  function() {

    function typeOf(obj) {
      // summary:
      //   A better type then Object.toString() or typeof.
      // description:
      //      toType(undefined); //"undefined"
      //      toType(new); //"null"
      //      toType({a: 4}); //"object"
      //      toType([1, 2, 3]); //"array"
      //      (function() {console.log(toType(arguments))})(); //arguments
      //      toType(new ReferenceError); //"error"
      //      toType(new Date); //"date"
      //      toType(/a-z/); //"regexp"
      //      toType(Math); //"math"
      //      toType(JSON); //"json"
      //      toType(new Number(4)); //"number"
      //      toType(new String("abc")); //"string"
      //      toType(new Boolean(true)); //"boolean"

      /* based on
       http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
       */

      var result = Object.prototype.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
      // on some browsers, the main window returns as "global" (WebKit) or "window" (FF), but this is an object too
      if (result === "global" || result == "window") {
        result = "object";
      }
      return result; // return String
    }

    function getPrototypeChain(/*Object*/ obj) {
      // summary:
      //   Returns an array where result[i] is the prototype
      //   of result[i-1], with obj === result[0]. result[length]
      //   is thus Object.prototype.

      function recursive(acc, o) {
        if (!o) {
          return acc;
        }
        else {
          acc.push(o);
          return recursive(acc, Object.getPrototypeOf(o));
        }
      }

      return recursive([], obj);
    }

    function getAllKeys(/*Object*/ obj) {
      // summary:
      //   Returns an array containing the names of all given objects enumerable properties.
      //   Like keys, but for the entire prototype chain. The array starts with the properties
      //   of Object.prototype, and works down the chain.

      return getPrototypeChain(obj).reduceRight(
        function(acc, proto) {
          return acc.concat(Object.keys(proto));
        },
        []
      );
    }

    function isInt(/*Number*/ n) {
      // summary:
      //   True if n is an integer.
      //   n must be a number.

      return n % 1 === 0;
    }

    function nub(/*Array*/ array, /*Boolean?*/ removeNull) {
      // summary:
      //   Returns an array that has all the elements of `array`, in order, but with later duplicates removed.
      //   If `removeNull` is given and thruthy, nulls and undefineds are removed too.

      if (!array) {
        return array;
      }
      var result = array.reduce(
        function(acc, el) {
          if ((!removeNull || el) && acc.indexOf(el) < 0) {
            acc.push(el);
          }
          return acc;
        },
        []
      );
      return result;
    }

    function substitute(/*String*/ str, /*Object*/ context) {
      // summary:
      //  All occurrences of "${...}$" in `str` are replaced by the result of the
      //  execution of what is between the curly brackets as JavaScript, with `context`
      //  as `this`.

      //   Like dojo/string.substitute, but evals full code.
      //   No formatting (yet).
      return str.replace( // return String
        /\$\{(.+?)\}\$/gm,
        function(match, pattern) {
          var value;
          try {
            var executor = new Function("return (" + pattern + ");");
            value = executor.call(context);
          }
          catch (err) {
            logger.error("Executing pattern substitution of ${" + pattern + "}$ in '" + str + "' with context " + context, err);
            return "?? ${" + pattern  + "}$ -- " + (err.message || err) + " ??";
          }
          return value ? value.toString() : "?" + pattern  + "?";
        }
      );
    }

    function sortComparable(/*Object*/ c1, /*Object*/ c2) {
      // summary:
      //   A sort function for objects that have a compare function.
      //   undefined < null < the compare function of the objects

      return c1 === undefined ? (
               c2 === undefined ? 0 : -1
             )
             : (
               c1 === null ? (
                 c2 === undefined ?
                   +1 :
                   c2 === null ? 0 : -1
               )
               : (
                 !c2 ? +1 : c1.compare(c2)
               )
             );
    }

    function string2CharCode(str) {
      // summary:
      //   Transform a string into an array of CharCodes.

      return str.split("").map(function(c) {return c.charCodeAt(0);});
    }

    function charCode2String(charCodes) {
      // summary:
      //   Transform an array of CharCodes into a String.

      return charCodes.map(function(charCode) {return String.fromCharCode(charCode);}).join("");
    }

    var js = {
      // summary:
      //   Methods to aid with the JavaScript language.
      typeOf: typeOf,
      getPrototypeChain: getPrototypeChain,
      getAllKeys: getAllKeys,
      isInt: isInt,
      nub: nub,
      substitute: substitute,
      sortComparable: sortComparable,
      string2CharCode: string2CharCode,
      charCode2String: charCode2String
    };

    return js;
  }
);
<commit_msg>working alias for ppwcode-util- in viewmodel<commit_after>define([],
  function() {

    function typeOf(obj) {
      // summary:
      //   A better type then Object.toString() or typeof.
      // description:
      //      toType(undefined); //"undefined"
      //      toType(new); //"null"
      //      toType({a: 4}); //"object"
      //      toType([1, 2, 3]); //"array"
      //      (function() {console.log(toType(arguments))})(); //arguments
      //      toType(new ReferenceError); //"error"
      //      toType(new Date); //"date"
      //      toType(/a-z/); //"regexp"
      //      toType(Math); //"math"
      //      toType(JSON); //"json"
      //      toType(new Number(4)); //"number"
      //      toType(new String("abc")); //"string"
      //      toType(new Boolean(true)); //"boolean"

      /* based on
       http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
       */

      var result = Object.prototype.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
      // on some browsers, the main window returns as "global" (WebKit) or "window" (FF), but this is an object too
      if (result === "global" || result == "window") {
        result = "object";
      }
      return result; // return String
    }

    function getPrototypeChain(/*Object*/ obj) {
      // summary:
      //   Returns an array where result[i] is the prototype
      //   of result[i-1], with obj === result[0]. result[length]
      //   is thus Object.prototype.

      function recursive(acc, o) {
        if (!o) {
          return acc;
        }
        else {
          acc.push(o);
          return recursive(acc, Object.getPrototypeOf(o));
        }
      }

      return recursive([], obj);
    }

    function getAllKeys(/*Object*/ obj) {
      // summary:
      //   Returns an array containing the names of all given objects enumerable properties.
      //   Like keys, but for the entire prototype chain. The array starts with the properties
      //   of Object.prototype, and works down the chain.

      return getPrototypeChain(obj).reduceRight(
        function(acc, proto) {
          return acc.concat(Object.keys(proto));
        },
        []
      );
    }

    function isInt(/*Number*/ n) {
      // summary:
      //   True if n is an integer.
      //   n must be a number.

      return n % 1 === 0;
    }

    function nub(/*Array*/ array, /*Boolean?*/ removeNull) {
      // summary:
      //   Returns an array that has all the elements of `array`, in order, but with later duplicates removed.
      //   If `removeNull` is given and thruthy, nulls and undefineds are removed too.

      if (!array) {
        return array;
      }
      var result = array.reduce(
        function(acc, el) {
          if ((!removeNull || el) && acc.indexOf(el) < 0) {
            acc.push(el);
          }
          return acc;
        },
        []
      );
      return result;
    }

    function substitute(/*String*/ str, /*Object*/ context) {
      // summary:
      //  All occurrences of "${...}$" in `str` are replaced by the result of the
      //  execution of what is between the curly brackets as JavaScript, with `context`
      //  as `this`.

      //   Like dojo/string.substitute, but evals full code.
      //   No formatting (yet).
      return str.replace( // return String
        /\$\{(.+?)\}\$/gm,
        function(match, pattern) {
          var value;
          try {
            var executor = new Function("return (" + pattern + ");");
            value = executor.call(context);
          }
          catch (err) {
            logger.error("Executing pattern substitution of ${" + pattern + "}$ in '" + str + "' with context " + context, err);
            return "?? ${" + pattern  + "}$ -- " + (err.message || err) + " ??";
          }
          return value ? value.toString() : "?" + pattern  + "?";
        }
      );
    }

    function sortComparable(/*Object*/ c1, /*Object*/ c2) {
      // summary:
      //   A sort function for objects that have a compare function.
      //   undefined < null < the compare function of the objects

      return c1 === undefined ? (
               c2 === undefined ? 0 : -1
             )
             : (
               c1 === null ? (
                 c2 === undefined ?
                   +1 :
                   c2 === null ? 0 : -1
               )
               : (
                 !c2 ? +1 : c1.compare(c2)
               )
             );
    }

    function string2CharCode(str) {
      // summary:
      //   Transform a string into an array of CharCodes.

      return str.split("").map(function(c) {return c.charCodeAt(0);});
    }

    function charCode2String(charCodes) {
      // summary:
      //   Transform an array of CharCodes into a String.

      return charCodes.map(function(charCode) {return String.fromCharCode(charCode);}).join("");
    }

    var MAX_INT = 9007199254740992;
    var MIN_INT = -9007199254740992;

    // From https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random
    // Returns a random integer between min and max
    // Using Math.round() will give you a non-uniform distribution!
    function randomInt(min, max) {
      if (!max) {
        max = MAX_INT;
      }
      if (!min) {
        min = MIN_INT;
      }
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function randomInts(min, max, nr) {
      var result = [];
      var r = undefined;
      for (var i = 0; i < nr; i++) {
        while (!r || result.some(function(earlierR) {//noinspection JSReferencingMutableVariableFromClosure
          return r === earlierR;})) {
          r = randomInt(min, max);
        }
        result[i] = r;
        r = undefined;
      }
      return result;
    }

    var js = {
      // summary:
      //   Methods to aid with the JavaScript language.
      typeOf: typeOf,
      getPrototypeChain: getPrototypeChain,
      getAllKeys: getAllKeys,
      isInt: isInt,
      nub: nub,
      substitute: substitute,
      sortComparable: sortComparable,
      string2CharCode: string2CharCode,
      charCode2String: charCode2String,
      MAX_INT: MAX_INT,
      MIN_INT: MIN_INT,
      randomInt: randomInt,
      randomInts: randomInts
    };

    return js;
  }
);
<|endoftext|>


<commit_before>(function(){

"use strict";

nv.dev = false;

var tooltipShow = nv.tooltip.show;
nv.tooltip.show = function(pos, content, gravity, dist, parentContainer, classes) {
	var body = parentContainer;
	if (body && !$("body").is(body)) {
		var diff = $(body).offset();
		pos[0] += diff.left;
		pos[1] += diff.top + 12;
		body = $("body")[0];
	}
	tooltipShow(pos, content, gravity, dist, body, classes);
};

var ui = angular.module('axelor.ui');

this.ChartCtrl = ChartCtrl;

ChartCtrl.$inject = ['$scope', '$element', '$http'];
function ChartCtrl($scope, $element, $http) {

	var views = $scope._views;
	var view = $scope.view = views['chart'];

	function refresh() {
		return $http.get('ws/meta/chart/' + view.name).then(function(response) {
			var res = response.data;
			$scope.render(res.data);
		});
	}

	refresh();

	$scope.onRefresh = function() {
		refresh();
	};

	$scope.render = function(data) {

	};
};

function $eval(scope, expr, locals) {
	var root = scope.$root || scope;
	var context = _.extend({
		"$moment": moment,
		"$number": function(v) { return +v; }
	}, locals);
	return root.$eval(expr, context);
}

function $conv(value) {
	if (!value) return 0;
	if (_.isNumber(value)) return value;
	if (/(-)?\d+(\.\d+)?/.test(value)) {
		return +value;
	}
	return value;
}

function PlusData(scope, data, type) {
	var result = [];
	_.each(data.series, function(series) {
		if (series.type !== type) return;
		var key = series.key;
		var expr = series.expr;
		_.chain(data.data).groupBy(data.xAxis).each(function(group, name) {
			var value = 0;
			_.each(group, function(item) {
				value += $conv(expr ? $eval(scope, expr, item) : item[key]);
			});
			result.push({x: name, y: value});
		});
	});
	return result;
}

function PlotData(scope, data, type) {
	var chart_data = [];
	var points = _.chain(data.data).pluck(data.xAxis).unique().value();
	_.each(data.series, function(series) {
		if (series.type !== type) return;
		var key = series.key;
		var expr = series.expr;
		_.chain(data.data).groupBy(key).each(function(group, name) {
			var my = [];
			var values = _.map(group, function(item) {
				var x = $conv(item[data.xAxis]) || 0;
				var y = $conv(expr ? $eval(scope, expr, item) : name);
				my.push(x);
				return { x: x, y: y };
			});

			var missing = _.difference(points, my);
			if (points.length === missing.length) return;

			_.each(missing, function(x) {
				values.push({ x: x, y: 0 });
			});

			values = _.sortBy(values, "x");

			chart_data.push({
				key: name,
				type: type,
				values: values
			});
		});
	});
	return chart_data;
}

function PieChart(scope, element, data) {

	var chart_data = PlusData(scope, data, "pie");

	var chart = nv.models.pieChart()
		.showLabels(false)
		.x(function(d) { return d.x; })
	    .y(function(d) { return d.y; })
	    .values(function(d) { return d; })
	    .color(d3.scale.category10().range());

	d3.select(element[0])
	  .datum([chart_data])
	  .transition().duration(1200).call(chart);

	return chart;
}

function BarChart(scope, element, data) {

	var chart_data = PlotData(scope, data, "bar");
	var chart = nv.models.multiBarChart()
		.reduceXTicks(false)
		.barColor(d3.scale.category20().range());

	chart.multibar.hideable(true);

	d3.select(element[0])
	  .datum(chart_data)
	  .transition().duration(500).call(chart);

	return chart;
}

function LineChart(scope, element, data) {

	var chart_data = PlotData(scope, data, "line");
	var chart = nv.models.lineChart()
		.color(d3.scale.category10().range());

	d3.select(element[0])
	  .datum(chart_data)
	  .transition().duration(500).call(chart);

	return chart;
}

function AreaChart(scope, element, data) {

	var chart_data = PlotData(scope, data, "area");
	var chart = nv.models.stackedAreaChart()
		.color(d3.scale.category10().range());

	d3.select(element[0])
	  .datum(chart_data)
	  .transition().duration(500).call(chart);

	return chart;
}

function Chart(scope, element, data) {

	var type = null;

	for(var i = 0 ; i < data.series.length ; i++) {
		type = data.series[i].type;
		if (type === "pie") {
			break;
		}
	}

	if (type === "pie" && data.series.length > 1) {
		return;
	}

	if (data.series.length > 1) {
		type = "multi";
	}

	nv.addGraph(function generate() {

		var chart = null;

		if (type === "pie") {
			chart = PieChart(scope, element, data);
		}
		if (type === "bar") {
			chart = BarChart(scope, element, data);
		}
		if (type === "line") {
			chart = LineChart(scope, element, data);
		}
		if (type === "area") {
			chart = AreaChart(scope, element, data);
		}

		if (chart == null) {
			return;
		}

		var tickFormats = {
			"month" : function(d) {
				return moment([2000, d, 1]).format("MMM");
			},
			"year" : function(d) {
				return moment([2000, d, 1]).format("YYYY");
			},
			"number": d3.format(',f'),
			"decimal": d3.format(',.1f')
		};

		var tickFormat = tickFormats[data.xType];
		if (chart.xAxis && tickFormat) {
			chart.xAxis
				.rotateLabels(-45)
				.tickFormat(tickFormat);
		}

		var lastWidth = 0;
		var lastHeight = 0;

		function adjust() {

			if (element.is(":hidden")) {
				return;
			}

			var w = element.width(),
				h = element.height();

			if (w === lastWidth && h === lastHeight) {
				return;
			}

			lastWidth = w;
			lastHeight = h;

			chart.update();
		}

		element.on('adjustSize', _.debounce(adjust, 100));
		setTimeout(chart.update);

		return chart;
	});
}

var directiveFn = function(){
	return {
		controller: ChartCtrl,
		link: function(scope, element, attrs) {
			var elem = element.children('svg');

			scope.render = function(data) {
				Chart(scope, elem, data);
			};
		},
		replace: true,
		template:
		'
'+
			'<svg></svg>'+
		'
'
	};
};

ui.directive('uiViewChart', directiveFn);
ui.directive('uiPortletChart', directiveFn);

}).call(this);
<commit_msg>Implemented horizontal bar chart and fixed some issues.<commit_after>(function(){

"use strict";

nv.dev = false;

var tooltipShow = nv.tooltip.show;
nv.tooltip.show = function(pos, content, gravity, dist, parentContainer, classes) {
	var body = parentContainer;
	if (body && !$("body").is(body)) {
		var diff = $(body).offset();
		pos[0] += diff.left;
		pos[1] += diff.top;
		body = $("body")[0];
	}
	tooltipShow(pos, content, gravity, dist, body, classes);
};

var ui = angular.module('axelor.ui');

this.ChartCtrl = ChartCtrl;

ChartCtrl.$inject = ['$scope', '$element', '$http'];
function ChartCtrl($scope, $element, $http) {

	var views = $scope._views;
	var view = $scope.view = views['chart'];

	function refresh() {
		return $http.get('ws/meta/chart/' + view.name).then(function(response) {
			var res = response.data;
			$scope.render(res.data);
		});
	}

	refresh();

	$scope.onRefresh = function() {
		refresh();
	};

	$scope.render = function(data) {

	};
};

function $eval(scope, expr, locals) {
	var root = scope.$root || scope;
	var context = _.extend({
		"$moment": moment,
		"$number": function(v) { return +v; }
	}, locals);
	return root.$eval(expr, context);
}

function $conv(value) {
	if (!value) return 0;
	if (_.isNumber(value)) return value;
	if (/(-)?\d+(\.\d+)?/.test(value)) {
		return +value;
	}
	return value;
}

function PlusData(scope, data, type) {
	var result = [];
	_.each(data.series, function(series) {
		if (series.type !== type) return;
		var key = series.key;
		var expr = series.expr;
		_.chain(data.data).groupBy(data.xAxis).each(function(group, name) {
			var value = 0;
			_.each(group, function(item) {
				value += $conv(expr ? $eval(scope, expr, item) : item[key]);
			});
			result.push({x: name, y: value});
		});
	});
	return result;
}

function PlotData(scope, data, type) {
	var chart_data = [];
	var points = _.chain(data.data).pluck(data.xAxis).unique().value();
	_.each(data.series, function(series) {
		if (series.type !== type) return;
		var key = series.key;
		var expr = series.expr;
		_.chain(data.data).groupBy(key).each(function(group, name) {
			var my = [];
			var values = _.map(group, function(item) {
				var x = $conv(item[data.xAxis]) || 0;
				var y = $conv(expr ? $eval(scope, expr, item) : name);
				my.push(x);
				return { x: x, y: y };
			});

			var missing = _.difference(points, my);
			if (points.length === missing.length) return;

			_.each(missing, function(x) {
				values.push({ x: x, y: 0 });
			});

			values = _.sortBy(values, "x");

			chart_data.push({
				key: name,
				type: type,
				values: values
			});
		});
	});
	return chart_data;
}

function PieChart(scope, element, data) {

	var chart_data = PlusData(scope, data, "pie");

	var chart = nv.models.pieChart()
		.showLabels(false)
		.x(function(d) { return d.x; })
	    .y(function(d) { return d.y; })
	    .values(function(d) { return d; })
	    .color(d3.scale.category10().range());

	d3.select(element[0])
	  .datum([chart_data])
	  .transition().duration(1200).call(chart);

	return chart;
}

function BarChart(scope, element, data) {

	var chart_data = PlotData(scope, data, "bar");
	var chart = nv.models.multiBarChart()
		.reduceXTicks(false)
		.color(d3.scale.category10().range());

	chart.multibar.hideable(true);

	d3.select(element[0])
	  .datum(chart_data)
	  .transition().duration(500).call(chart);

	return chart;
}

function HBarChart(scope, element, data) {

	var chart_data = PlotData(scope, data, "hbar");
	var chart = nv.models.multiBarHorizontalChart()
		.color(d3.scale.category10().range());

	d3.select(element[0])
	  .datum(chart_data)
	  .transition().duration(500).call(chart);

	return chart;
}

function LineChart(scope, element, data) {

	var chart_data = PlotData(scope, data, "line");
	var chart = nv.models.lineChart()
		.color(d3.scale.category10().range());

	d3.select(element[0])
	  .datum(chart_data)
	  .transition().duration(500).call(chart);

	return chart;
}

function AreaChart(scope, element, data) {

	var chart_data = PlotData(scope, data, "area");
	var chart = nv.models.stackedAreaChart()
		.color(d3.scale.category10().range());

	d3.select(element[0])
	  .datum(chart_data)
	  .transition().duration(500).call(chart);

	return chart;
}

function Chart(scope, element, data) {

	var type = null;

	for(var i = 0 ; i < data.series.length ; i++) {
		type = data.series[i].type;
		if (type === "pie") {
			break;
		}
	}

	if (type === "pie" && data.series.length > 1) {
		return;
	}

	if (data.series.length > 1) {
		type = "multi";
	}

	nv.addGraph(function generate() {

		var chart = null;

		element.off('adjustSize').empty();

		if (type === "pie") {
			chart = PieChart(scope, element, data);
		}
		if (type === "bar") {
			chart = BarChart(scope, element, data);
		}
		if (type === "hbar") {
			chart = HBarChart(scope, element, data);
		}
		if (type === "line") {
			chart = LineChart(scope, element, data);
		}
		if (type === "area") {
			chart = AreaChart(scope, element, data);
		}

		if (chart == null) {
			return;
		}

		var tickFormats = {
			"month" : function(d) {
				return moment([2000, d, 1]).format("MMM");
			},
			"year" : function(d) {
				return moment([2000, d, 1]).format("YYYY");
			},
			"number": d3.format(',f'),
			"decimal": d3.format(',.1f')
		};

		var tickFormat = tickFormats[data.xType];
		if (chart.xAxis && tickFormat) {
			chart.xAxis
				.rotateLabels(-45)
				.tickFormat(tickFormat);
		}

		var lastWidth = 0;
		var lastHeight = 0;

		function adjust() {

			if (element.is(":hidden")) {
				return;
			}

			var w = element.width(),
				h = element.height();

			if (w === lastWidth && h === lastHeight) {
				return;
			}

			lastWidth = w;
			lastHeight = h;

			chart.update();
		}

		element.on('adjustSize', _.debounce(adjust, 100));
		setTimeout(chart.update);

		return chart;
	});
}

var directiveFn = function(){
	return {
		controller: ChartCtrl,
		link: function(scope, element, attrs) {
			var elem = element.children('svg');
			scope.render = function(data) {
				Chart(scope, elem, data);
			};
		},
		replace: true,
		template:
		'
'+
			'<svg></svg>'+
		'
'
	};
};

ui.directive('uiViewChart', directiveFn);
ui.directive('uiPortletChart', directiveFn);

}).call(this);
<|endoftext|>


<commit_before>/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2005-2017 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
(function () {

"use strict";

var ui = angular.module("axelor.ui");

EditorCtrl.$inject = ['$scope', '$element', 'DataSource', 'ViewService', '$q'];

function EditorCtrl($scope, $element, DataSource, ViewService, $q) {

	var parent = $scope.$parent;

	$scope._viewParams = parent._viewParams;
	$scope.editorCanSave = parent.editorCanSave;
	$scope.editorCanReload = parent.editorCanReload;

	ui.ViewCtrl.call(this, $scope, DataSource, ViewService);
	ui.FormViewCtrl.call(this, $scope, $element);

	var closeCallback = null;
	var originalEdit = $scope.edit;
	var originalShow = $scope.show;

	var recordVersion = -1;
	var canClose = false;
	var isClosed = true;

	$scope.show = function(record, callback) {
		originalShow();
		if (_.isFunction(record)) {
			callback = record;
			record = null;
		}
		closeCallback = callback;
		isClosed = false;
		recordVersion = record ? record.version : -1;
		if (recordVersion === undefined && record) {
			recordVersion = record.$version;
		}
		this.edit(record);
	};

	function doEdit(record, fireOnLoad) {
		if (record && record.id > 0 && (!_.isNumber(record.version) || !record.$fetched)) {
			$scope.doRead(record.id).success(function(rec) {
				if (record.$dirty) {
					rec = _.extend({}, rec, record);
				}
				originalEdit(rec, fireOnLoad);
			});
		} else {
			originalEdit(record, fireOnLoad);
		}
		canClose = false;
	}

	var parentCanEditTarget = null;

	$scope.canEditTarget =  function () {
		if (parentCanEditTarget === null) {
			var parent = $scope.$parent;
			var func = parent.canEditTarget;
			while (parent && func === $scope.canEditTarget) {
				parent = parent.$parent;
				func = parent.canEditTarget;
			}
			parentCanEditTarget = func || angular.noop;
		}
		return parentCanEditTarget() !== false;
	};

	var isEditable = $scope.isEditable;
	$scope.isEditable = function () {
		var id = ($scope.record || {}).id;
		var perm = id > 0 ? 'write' : 'create';
		return $scope.hasPermission(perm)
			&& $scope.canEditTarget()
			&& isEditable.call($scope);
	};

	var canEdit = $scope.canEdit;
	$scope.canEdit = function() {
		return $scope.canEditTarget() && canEdit.call($scope);
	};

	$scope.edit = function(record, fireOnLoad) {
		if (isClosed) return;
		$scope._viewPromise.then(function(){
			doEdit(record, fireOnLoad);
			$scope.setEditable(!$scope.$parent.$$readonly);
		});
	};

	function isChanged() {
		if ($scope.isDirty()) return true;
		var record = $scope.record || {};
		var version = record.version;
		return recordVersion !== version || record.$forceDirty;
	}

	function canOK() {
		if (isClosed) return false;
		return isChanged();
	}

	function onOK() {

		var record = $scope.record;

		function close(value, forceSelect) {
			if (value && (forceSelect || canOK())) {
				value.$fetched = true;
				value.selected = true;
				$scope.$parent.select(value);
			}
			canClose = true;
			$element.dialog('close');
			if ($scope.editorCanReload) {
				$scope.$parent.parentReload();
			}
			if (closeCallback && value) {
				closeCallback(value);
			}
			closeCallback = null;
			isClosed = true;
		}

		var event = $scope.$broadcast('on:before-save', record);
		if (event.defaultPrevented) {
			if (event.error) {
				axelor.dialogs.error(event.error);
			}
			return;
 		}

		// wait for onChange actions
		$scope.waitForActions(function() {
			if ($scope.editorCanSave && isChanged()) {
				if (record.id < 0)
					record.id = null;
				return $scope.onSave({force: true}).then(function(record, page) {
					// wait for onSave actions
					$scope.waitForActions(function(){
						close(record, true);
					});
				});
			}
			if ($scope.isValid()) {
				close(record);
			}
		}, 100);
	}

	$scope.onOK = function() {
		$scope.$timeout(onOK, 10);
	};

	$scope.onBeforeClose = function(event, ui) {

		if (canClose || !$scope.isDirty()) {
			$scope.$evalAsync(function () {
				$scope.edit(null, false);
			});
			return true;
		}

		event.preventDefault();

		$scope.confirmDirty(function(){
			canClose = true;
			$element.dialog('close');
		});
	};

	$scope.onHotKey = function (e, action) {

		if (action === "save") {
			$(e.target).blur().focus();
			$scope.onOK();
		}

		$scope.applyLater();

		return false;
	};
}

SelectorCtrl.$inject = ['$scope', '$element', 'DataSource', 'ViewService'];
function SelectorCtrl($scope, $element, DataSource, ViewService) {

	var parent = $scope.$parent;

	$scope._viewParams = parent._viewParams;
	$scope.getDomain = parent.getDomain;

	ui.ViewCtrl.call(this, $scope, DataSource, ViewService);
	ui.GridViewCtrl.call(this, $scope, $element);

	var searchLimit = (parent.field||{}).searchLimit || 0;
	if (searchLimit > 0) {
		$scope._dataSource._page.limit = searchLimit;
	}

	function doFilter() {
		$scope.filter($scope.getDomain());
	}

	var initialized = false;
	var origShow = $scope.show;
	$scope.show = function() {
		origShow();
		if (initialized) {
			doFilter();
		}
	};

	var _getContext = $scope.getContext;
	$scope.getContext = function() {
		// selector popup should return parent's context
		if ($scope.$parent && $scope.$parent.getContext) {
			return $scope.$parent.getContext();
		}
		return _getContext();
	};

	$scope.onItemClick = function(e, args) {
		$scope.applyLater($scope.onOK);
	};

	var origOnShow = $scope.onShow;
	$scope.onShow = function(viewPromise) {

		viewPromise.then(function(){
			$element.dialog('open');
			initialized = true;
			origOnShow(viewPromise);
		});
	};

	$scope.onOK = function() {

		var selection = _.map($scope.selection, function(index){
			return $scope.dataView.getItem(index);
		});

		if (!_.isEmpty(selection)) {
			$scope.applyLater(function () {
				$scope.$parent.select(selection);
				$scope.selection = [];
			});
		}

		$element.dialog('close');
	};

	$scope.onCreate = function () {
		$element.dialog('close');
		$scope.$parent.onNew();
	};

	$scope.canNew = function () {
		return $scope.hasPermission('create') && $scope.$parent.canNew();
	};
}

ui.directive('uiDialogSize', function() {

	return function (scope, element, attrs) {

		// use only with dialogs
		if (attrs.uiDialog === undefined && !element.hasClass('ui-dialog-content')) {
			return;
		}

		var addMaximizeButton = _.once(function () {
			var elemDialog = element.parent();
			var elemTitle = elemDialog.find('.ui-dialog-title');
			$('').click(function (e) {
				$(this).children('i').toggleClass('fa-expand fa-compress');
				elemDialog.toggleClass('maximized');
				axelor.$adjustSize();
				return false;
			}).insertAfter(elemTitle);

			// remove maximized state on close
			element.on('dialogclose', function(e, ui) {
				elemTitle.parent().find('i.fa-compress').toggleClass('fa-expand fa-compress');
				elemDialog.removeClass('maximized');
			});
		});

		function doShow() {

			addMaximizeButton();

			//XXX: ui-dialog issue
			element.find('.slick-headerrow-column,.slickgrid,[ui-embedded-editor]').zIndex(element.zIndex());
			element.find('.record-toolbar .btn').zIndex(element.zIndex()+1);

			setTimeout(function () {
				element.dialog('open');
				// focus first element
				if (!axelor.device.mobile) {
					element.find('.slick-headerrow-column input[type="text"]:first,.form-item-container > input[type="text"]:first').focus();
				}
			});
		}

		// a flag used by evalScope to detect popup (see form.base.js)
		scope._isPopup = true;
		scope._doShow = function(viewPromise) {
			if (viewPromise && viewPromise.then) {
				viewPromise.then(doShow);
			} else {
				doShow();
			}
		};

		scope._setTitle = function (title) {
			if (title) {
				element.closest('.ui-dialog').find('.ui-dialog-title').text(title);
			}
		};

		scope.adjustSize = function() {
		};
	};
});

ui.directive('uiEditorPopup', function() {

	return {
		restrict: 'EA',
		controller: EditorCtrl,
		scope: {},
		link: function(scope, element, attrs) {

			scope.onShow = function(viewPromise) {
				scope._doShow(viewPromise);
			};

			scope.$watch('schema.title', function (title) {
				scope._setTitle(title);
			});

			element.scroll(function (e) {
				$.event.trigger('adjustScroll');
			});

			var onNewHandler = scope.onNewHandler;
			scope.onNewHandler = function (event) {
				if (element.dialog('isOpen')) {
					return onNewHandler.apply(scope, arguments);
				}
			};

			scope.isPopupOpen = true;
			setTimeout(function () {
				var isOpen = false;
				element.on('dialogclose', function (e) {
					isOpen = false;
					scope.waitForActions(function () {
						scope.isPopupOpen = isOpen;
					}, 2000); // delay couple of seconds to that popup can cleanup
				});
				element.on('dialogopen', function (e) {
					scope.isPopupOpen = isOpen = true;
					scope.applyLater();
				});
			});
		},
		replace: true,
		template:
		'
'+
		    '

'+
		'
'
	};
});

ui.directive('uiSelectorPopup', function(){

	return {
		restrict: 'EA',
		controller: SelectorCtrl,
		scope: {
			selectMode: "@"
		},
		link: function(scope, element, attrs) {

			var onShow = scope.onShow;
			scope.onShow = function (viewPromise) {
				if (scope.clearFilters) {
					scope.clearFilters();
					scope.selection = [];
				}
				onShow(viewPromise);
				scope._doShow(viewPromise);
			};

			scope.$watch('schema.title', function(title){
				scope._setTitle(title);
			});

			var btnOK = null;

			function buttonState(count) {
				if (btnOK === null) {
					btnOK = element.siblings('.ui-dialog-buttonpane').find('.btn:last');
				}
				return btnOK.attr('disabled', !count || count <= 0);
			}

			scope.$watch('selection.length', buttonState);

			setTimeout(function(){
				var footer = element.closest('.ui-dialog').find('.ui-dialog-buttonpane'),
					header = element.closest('.ui-dialog').find('.ui-dialog-titlebar'),
					pager = element.find('.record-pager'),
					buttons = element.find('.ui-dialog-buttonset-left');
				header.find('.ui-dialog-title').after(pager);
				footer.prepend(buttons);
				footer.find('.button-ok').html(_t("Select"));
			});
		},
		replace: true,
		template:
		'
'+
		    '

'+
		    '

'+
		    '
'+
		    	'<button class="btn" ng-click="onCreate()" x-translate>Create</button>'+
		    '
'+
		'
'
	};
});

})();
<commit_msg>Fix popup focus issue<commit_after>/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2005-2017 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
(function () {

"use strict";

var ui = angular.module("axelor.ui");

EditorCtrl.$inject = ['$scope', '$element', 'DataSource', 'ViewService', '$q'];

function EditorCtrl($scope, $element, DataSource, ViewService, $q) {

	var parent = $scope.$parent;

	$scope._viewParams = parent._viewParams;
	$scope.editorCanSave = parent.editorCanSave;
	$scope.editorCanReload = parent.editorCanReload;

	ui.ViewCtrl.call(this, $scope, DataSource, ViewService);
	ui.FormViewCtrl.call(this, $scope, $element);

	var closeCallback = null;
	var originalEdit = $scope.edit;
	var originalShow = $scope.show;

	var recordVersion = -1;
	var canClose = false;
	var isClosed = true;

	$scope.show = function(record, callback) {
		originalShow();
		if (_.isFunction(record)) {
			callback = record;
			record = null;
		}
		closeCallback = callback;
		isClosed = false;
		recordVersion = record ? record.version : -1;
		if (recordVersion === undefined && record) {
			recordVersion = record.$version;
		}
		this.edit(record);
	};

	function doEdit(record, fireOnLoad) {
		if (record && record.id > 0 && (!_.isNumber(record.version) || !record.$fetched)) {
			$scope.doRead(record.id).success(function(rec) {
				if (record.$dirty) {
					rec = _.extend({}, rec, record);
				}
				originalEdit(rec, fireOnLoad);
			});
		} else {
			originalEdit(record, fireOnLoad);
		}
		canClose = false;
	}

	var parentCanEditTarget = null;

	$scope.canEditTarget =  function () {
		if (parentCanEditTarget === null) {
			var parent = $scope.$parent;
			var func = parent.canEditTarget;
			while (parent && func === $scope.canEditTarget) {
				parent = parent.$parent;
				func = parent.canEditTarget;
			}
			parentCanEditTarget = func || angular.noop;
		}
		return parentCanEditTarget() !== false;
	};

	var isEditable = $scope.isEditable;
	$scope.isEditable = function () {
		var id = ($scope.record || {}).id;
		var perm = id > 0 ? 'write' : 'create';
		return $scope.hasPermission(perm)
			&& $scope.canEditTarget()
			&& isEditable.call($scope);
	};

	var canEdit = $scope.canEdit;
	$scope.canEdit = function() {
		return $scope.canEditTarget() && canEdit.call($scope);
	};

	$scope.edit = function(record, fireOnLoad) {
		if (isClosed) return;
		$scope._viewPromise.then(function(){
			doEdit(record, fireOnLoad);
			$scope.setEditable(!$scope.$parent.$$readonly);
		});
	};

	function isChanged() {
		if ($scope.isDirty()) return true;
		var record = $scope.record || {};
		var version = record.version;
		return recordVersion !== version || record.$forceDirty;
	}

	function canOK() {
		if (isClosed) return false;
		return isChanged();
	}

	function onOK() {

		var record = $scope.record;

		function close(value, forceSelect) {
			if (value && (forceSelect || canOK())) {
				value.$fetched = true;
				value.selected = true;
				$scope.$parent.select(value);
			}
			canClose = true;
			$element.dialog('close');
			if ($scope.editorCanReload) {
				$scope.$parent.parentReload();
			}
			if (closeCallback && value) {
				closeCallback(value);
			}
			closeCallback = null;
			isClosed = true;
		}

		var event = $scope.$broadcast('on:before-save', record);
		if (event.defaultPrevented) {
			if (event.error) {
				axelor.dialogs.error(event.error);
			}
			return;
 		}

		// wait for onChange actions
		$scope.waitForActions(function() {
			if ($scope.editorCanSave && isChanged()) {
				if (record.id < 0)
					record.id = null;
				return $scope.onSave({force: true}).then(function(record, page) {
					// wait for onSave actions
					$scope.waitForActions(function(){
						close(record, true);
					});
				});
			}
			if ($scope.isValid()) {
				close(record);
			}
		}, 100);
	}

	$scope.onOK = function() {
		$scope.$timeout(onOK, 10);
	};

	$scope.onBeforeClose = function(event, ui) {

		if (canClose || !$scope.isDirty()) {
			$scope.$evalAsync(function () {
				$scope.edit(null, false);
			});
			return true;
		}

		event.preventDefault();

		$scope.confirmDirty(function(){
			canClose = true;
			$element.dialog('close');
		});
	};

	$scope.onHotKey = function (e, action) {

		if (action === "save") {
			$(e.target).blur().focus();
			$scope.onOK();
		}

		$scope.applyLater();

		return false;
	};
}

SelectorCtrl.$inject = ['$scope', '$element', 'DataSource', 'ViewService'];
function SelectorCtrl($scope, $element, DataSource, ViewService) {

	var parent = $scope.$parent;

	$scope._viewParams = parent._viewParams;
	$scope.getDomain = parent.getDomain;

	ui.ViewCtrl.call(this, $scope, DataSource, ViewService);
	ui.GridViewCtrl.call(this, $scope, $element);

	var searchLimit = (parent.field||{}).searchLimit || 0;
	if (searchLimit > 0) {
		$scope._dataSource._page.limit = searchLimit;
	}

	function doFilter() {
		$scope.filter($scope.getDomain());
	}

	var initialized = false;
	var origShow = $scope.show;
	$scope.show = function() {
		origShow();
		if (initialized) {
			doFilter();
		}
	};

	var _getContext = $scope.getContext;
	$scope.getContext = function() {
		// selector popup should return parent's context
		if ($scope.$parent && $scope.$parent.getContext) {
			return $scope.$parent.getContext();
		}
		return _getContext();
	};

	$scope.onItemClick = function(e, args) {
		$scope.applyLater($scope.onOK);
	};

	var origOnShow = $scope.onShow;
	$scope.onShow = function(viewPromise) {

		viewPromise.then(function(){
			$element.dialog('open');
			initialized = true;
			origOnShow(viewPromise);
		});
	};

	$scope.onOK = function() {

		var selection = _.map($scope.selection, function(index){
			return $scope.dataView.getItem(index);
		});

		if (!_.isEmpty(selection)) {
			$scope.applyLater(function () {
				$scope.$parent.select(selection);
				$scope.selection = [];
			});
		}

		$element.dialog('close');
	};

	$scope.onCreate = function () {
		$element.dialog('close');
		$scope.$parent.onNew();
	};

	$scope.canNew = function () {
		return $scope.hasPermission('create') && $scope.$parent.canNew();
	};
}

ui.directive('uiDialogSize', function() {

	return function (scope, element, attrs) {

		// use only with dialogs
		if (attrs.uiDialog === undefined && !element.hasClass('ui-dialog-content')) {
			return;
		}

		var addMaximizeButton = _.once(function () {
			var elemDialog = element.parent();
			var elemTitle = elemDialog.find('.ui-dialog-title');
			$('').click(function (e) {
				$(this).children('i').toggleClass('fa-expand fa-compress');
				elemDialog.toggleClass('maximized');
				axelor.$adjustSize();
				return false;
			}).insertAfter(elemTitle);

			// remove maximized state on close
			element.on('dialogclose', function(e, ui) {
				elemTitle.parent().find('i.fa-compress').toggleClass('fa-expand fa-compress');
				elemDialog.removeClass('maximized');
			});
		});

		function setFocus() {
			var focusElem = element.find('input:tabbable');
			if (focusElem.size() == 0) {
				focusElem = element.parent().find('.ui-dialog-buttonset').find(':tabbable');
			}
			if (focusElem[0]) {
				focusElem[0].focus();
			}
		}

		function doShow() {

			addMaximizeButton();

			//XXX: ui-dialog issue
			element.find('.slick-headerrow-column,.slickgrid,[ui-embedded-editor]').zIndex(element.zIndex());
			element.find('.record-toolbar .btn').zIndex(element.zIndex()+1);

			setTimeout(function () {
				element.dialog('open');
				element.scrollTop(0);
				// focus first element
				if (!axelor.device.mobile) {
					setTimeout(setFocus);
				}
			});
		}

		// a flag used by evalScope to detect popup (see form.base.js)
		scope._isPopup = true;
		scope._doShow = function(viewPromise) {
			if (viewPromise && viewPromise.then) {
				viewPromise.then(doShow);
			} else {
				doShow();
			}
		};

		scope._setTitle = function (title) {
			if (title) {
				element.closest('.ui-dialog').find('.ui-dialog-title').text(title);
			}
		};

		scope.adjustSize = function() {
		};
	};
});

ui.directive('uiEditorPopup', function() {

	return {
		restrict: 'EA',
		controller: EditorCtrl,
		scope: {},
		link: function(scope, element, attrs) {

			scope.onShow = function(viewPromise) {
				scope._doShow(viewPromise);
			};

			scope.$watch('schema.title', function (title) {
				scope._setTitle(title);
			});

			element.scroll(function (e) {
				$.event.trigger('adjustScroll');
			});

			var onNewHandler = scope.onNewHandler;
			scope.onNewHandler = function (event) {
				if (element.dialog('isOpen')) {
					return onNewHandler.apply(scope, arguments);
				}
			};

			scope.isPopupOpen = true;
			setTimeout(function () {
				var isOpen = false;
				element.on('dialogclose', function (e) {
					isOpen = false;
					scope.waitForActions(function () {
						scope.isPopupOpen = isOpen;
					}, 2000); // delay couple of seconds to that popup can cleanup
				});
				element.on('dialogopen', function (e) {
					scope.isPopupOpen = isOpen = true;
					scope.applyLater();
				});
			});
		},
		replace: true,
		template:
		'
'+
		    '

'+
		'
'
	};
});

ui.directive('uiSelectorPopup', function(){

	return {
		restrict: 'EA',
		controller: SelectorCtrl,
		scope: {
			selectMode: "@"
		},
		link: function(scope, element, attrs) {

			var onShow = scope.onShow;
			scope.onShow = function (viewPromise) {
				if (scope.clearFilters) {
					scope.clearFilters();
					scope.selection = [];
				}
				onShow(viewPromise);
				scope._doShow(viewPromise);
			};

			scope.$watch('schema.title', function(title){
				scope._setTitle(title);
			});

			var btnOK = null;

			function buttonState(count) {
				if (btnOK === null) {
					btnOK = element.siblings('.ui-dialog-buttonpane').find('.btn:last');
				}
				return btnOK.attr('disabled', !count || count <= 0);
			}

			scope.$watch('selection.length', buttonState);

			setTimeout(function(){
				var footer = element.closest('.ui-dialog').find('.ui-dialog-buttonpane'),
					header = element.closest('.ui-dialog').find('.ui-dialog-titlebar'),
					pager = element.find('.record-pager'),
					buttons = element.find('.ui-dialog-buttonset-left');
				header.find('.ui-dialog-title').after(pager);
				footer.prepend(buttons);
				footer.find('.button-ok').html(_t("Select"));
			});
		},
		replace: true,
		template:
		'
'+
		    '

'+
		    '

'+
		    '
'+
		    	'<button class="btn" ng-click="onCreate()" x-translate>Create</button>'+
		    '
'+
		'
'
	};
});

})();
<|endoftext|>


<commit_before>import Project from '../models/project.model';
import User from '../models/user.model';
import APIError from '../helpers/APIError';

function load(req, res, next, id) {
    Project.get(id)
    .then((project) => {
        req.project = project;
        return next();
    })
    .catch(e => next(e));
}

function get(req, res) {
    return res.json(req.project);
}

async function create(req, res, next) {
    const project = new Project({
        approvers: req.body.approvers,
        name: req.body.name,
        description: req.body.description,
    });

    project.save()
        .then(savedProject => res.json(savedProject))
        .catch(e => next(e));
}

function update(req, res, next) {
    const project = req.project;
    project.approvers = req.body.approvers;
    project.name = req.body.name;
    project.description = req.body.description;

    project.save()
    .then(savedProject => res.json(savedProject))
    .catch(e => next(e));
}

function list(req, res, next) {
    const { limit = 50, skip = 0 } = req.query;
    Project.list({ limit, skip })
    .then(projects => res.json(projects))
    .catch(e => next(e));
}

function remove(req, res, next) {
    const project = req.project;
    project.remove()
    .then(deletedProject => res.json(deletedProject))
    .catch(e => next(e));
}

function getUsers(req, res, next) {
    const { projectId } = req.params;
    User.find({projectId})
    .then(users => res.json(users))
    .catch(e => next(e));
}

async function getApprovers(req, res, next) {
    const { projectId } = req.params;
    const { approvers } = await Project.findOne({ _id: projectId });
    const users = Promise.all(approvers.map(async (approver) => {
        let user = await User.findOne({ _id: approver });
        const noPasswodUser = user.toObject();
        delete noPasswodUser.password;

        return noPasswodUser;
    }));

    users
        .then(result => res.json(result))
        .catch(e => next(e));
}

export default { load, get, create, update, list, remove, getUsers, getApprovers };
<commit_msg>removed unused import<commit_after>import Project from '../models/project.model';
import User from '../models/user.model';

function load(req, res, next, id) {
    Project.get(id)
    .then((project) => {
        req.project = project;
        return next();
    })
    .catch(e => next(e));
}

function get(req, res) {
    return res.json(req.project);
}

async function create(req, res, next) {
    const project = new Project({
        approvers: req.body.approvers,
        name: req.body.name,
        description: req.body.description,
    });

    project.save()
        .then(savedProject => res.json(savedProject))
        .catch(e => next(e));
}

function update(req, res, next) {
    const project = req.project;
    project.approvers = req.body.approvers;
    project.name = req.body.name;
    project.description = req.body.description;

    project.save()
    .then(savedProject => res.json(savedProject))
    .catch(e => next(e));
}

function list(req, res, next) {
    const { limit = 50, skip = 0 } = req.query;
    Project.list({ limit, skip })
    .then(projects => res.json(projects))
    .catch(e => next(e));
}

function remove(req, res, next) {
    const project = req.project;
    project.remove()
    .then(deletedProject => res.json(deletedProject))
    .catch(e => next(e));
}

function getUsers(req, res, next) {
    const { projectId } = req.params;
    User.find({projectId})
    .then(users => res.json(users))
    .catch(e => next(e));
}

async function getApprovers(req, res, next) {
    const { projectId } = req.params;
    const { approvers } = await Project.findOne({ _id: projectId });
    const users = Promise.all(approvers.map(async (approver) => {
        let user = await User.findOne({ _id: approver });
        const noPasswodUser = user.toObject();
        delete noPasswodUser.password;

        return noPasswodUser;
    }));

    users
        .then(result => res.json(result))
        .catch(e => next(e));
}

export default { load, get, create, update, list, remove, getUsers, getApprovers };
<|endoftext|>


<commit_before>// Copyright (c) 2011 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.

/**
 * TestFixture for OptionsPage WebUI testing.
 * @extends {testing.Test}
 * @constructor
 */
function OptionsWebUITest() {}

OptionsWebUITest.prototype = {
  __proto__: testing.Test.prototype,

  /**
   * Browse to the options page & call our preLoad().
   */
  browsePreload: 'chrome://settings',

  /**
   * Register a mock handler to ensure expectations are met and options pages
   * behave correctly.
   */
  preLoad: function() {
    this.makeAndRegisterMockHandler(
        ['coreOptionsInitialize',
         'fetchPrefs',
         'observePrefs',
         'setBooleanPref',
         'setIntegerPref',
         'setDoublePref',
         'setStringPref',
         'setObjectPref',
         'clearPref',
         'coreOptionsUserMetricsAction',
         // TODO(scr): Handle this new message:
         // getInstantFieldTrialStatus: function() {},
        ]);

    // Register stubs for methods expected to be called before our tests run.
    // Specific expectations can be made in the tests themselves.
    this.mockHandler.stubs().fetchPrefs(ANYTHING);
    this.mockHandler.stubs().observePrefs(ANYTHING);
    this.mockHandler.stubs().coreOptionsInitialize();
  },
};

// Crashes on Mac only. See http://crbug.com/79181
GEN('#if defined(OS_MACOSX)');
GEN('#define MAYBE_testSetBooleanPrefTriggers ' +
    'DISABLED_testSetBooleanPrefTriggers');
GEN('#else');
GEN('#define MAYBE_testSetBooleanPrefTriggers testSetBooleanPrefTriggers');
GEN('#endif  // defined(OS_MACOSX)');

TEST_F('OptionsWebUITest', 'MAYBE_testSetBooleanPrefTriggers', function() {
  // TODO(dtseng): make generic to click all buttons.
  var showHomeButton = $('toolbarShowHomeButton');
  var trueListValue = [
    'browser.show_home_button',
    true,
    'Options_Homepage_HomeButton',
  ];
  // Note: this expectation is checked in testing::Test::tearDown.
  this.mockHandler.expects(once()).setBooleanPref(trueListValue);

  // Cause the handler to be called.
  showHomeButton.click();
  showHomeButton.blur();
});

// Not meant to run on ChromeOS at this time.
// Not finishing in windows. http://crbug.com/81723
GEN('#if defined(OS_CHROMEOS) || defined(OS_MACOSX) || defined(OS_WIN)');
GEN('#define MAYBE_testRefreshStaysOnCurrentPage \\');
GEN('    DISABLED_testRefreshStaysOnCurrentPage');
GEN('#else');
GEN('#define MAYBE_testRefreshStaysOnCurrentPage ' +
    'testRefreshStaysOnCurrentPage');
GEN('#endif');

TEST_F('OptionsWebUITest', 'MAYBE_testRefreshStaysOnCurrentPage', function() {
  var item = $('advancedPageNav');
  item.onclick();
  window.location.reload();
  var pageInstance = AdvancedOptions.getInstance();
  var topPage = OptionsPage.getTopmostVisiblePage();
  var expectedTitle = pageInstance.title;
  var actualTitle = document.title;
  assertEquals("chrome://settings/advanced", document.location.href);
  assertEquals(expectedTitle, actualTitle);
  assertEquals(pageInstance, topPage);
});
<commit_msg>Disable testRefreshStaysOnCurrentPage, which is timing out on all platforms.<commit_after>// Copyright (c) 2012 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.

/**
 * TestFixture for OptionsPage WebUI testing.
 * @extends {testing.Test}
 * @constructor
 */
function OptionsWebUITest() {}

OptionsWebUITest.prototype = {
  __proto__: testing.Test.prototype,

  /**
   * Browse to the options page & call our preLoad().
   */
  browsePreload: 'chrome://settings',

  /**
   * Register a mock handler to ensure expectations are met and options pages
   * behave correctly.
   */
  preLoad: function() {
    this.makeAndRegisterMockHandler(
        ['coreOptionsInitialize',
         'fetchPrefs',
         'observePrefs',
         'setBooleanPref',
         'setIntegerPref',
         'setDoublePref',
         'setStringPref',
         'setObjectPref',
         'clearPref',
         'coreOptionsUserMetricsAction',
         // TODO(scr): Handle this new message:
         // getInstantFieldTrialStatus: function() {},
        ]);

    // Register stubs for methods expected to be called before our tests run.
    // Specific expectations can be made in the tests themselves.
    this.mockHandler.stubs().fetchPrefs(ANYTHING);
    this.mockHandler.stubs().observePrefs(ANYTHING);
    this.mockHandler.stubs().coreOptionsInitialize();
  },
};

// Crashes on Mac only. See http://crbug.com/79181
GEN('#if defined(OS_MACOSX)');
GEN('#define MAYBE_testSetBooleanPrefTriggers ' +
    'DISABLED_testSetBooleanPrefTriggers');
GEN('#else');
GEN('#define MAYBE_testSetBooleanPrefTriggers testSetBooleanPrefTriggers');
GEN('#endif  // defined(OS_MACOSX)');

TEST_F('OptionsWebUITest', 'MAYBE_testSetBooleanPrefTriggers', function() {
  // TODO(dtseng): make generic to click all buttons.
  var showHomeButton = $('toolbarShowHomeButton');
  var trueListValue = [
    'browser.show_home_button',
    true,
    'Options_Homepage_HomeButton',
  ];
  // Note: this expectation is checked in testing::Test::tearDown.
  this.mockHandler.expects(once()).setBooleanPref(trueListValue);

  // Cause the handler to be called.
  showHomeButton.click();
  showHomeButton.blur();
});

// Not meant to run on ChromeOS at this time.
// Not finishing in windows, mac, linux, and WebKit bots. http://crbug.com/81723
TEST_F('OptionsWebUITest', 'DISABLED_testRefreshStaysOnCurrentPage',
       function() {
  var item = $('advancedPageNav');
  item.onclick();
  window.location.reload();
  var pageInstance = AdvancedOptions.getInstance();
  var topPage = OptionsPage.getTopmostVisiblePage();
  var expectedTitle = pageInstance.title;
  var actualTitle = document.title;
  assertEquals("chrome://settings/advanced", document.location.href);
  assertEquals(expectedTitle, actualTitle);
  assertEquals(pageInstance, topPage);
});
<|endoftext|>


<commit_before>// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage

module.exports = {
  'default e2e tests': function (browser) {
    // automatically uses dev Server port from /config.index.js
    // default: http://localhost:8080
    // see nightwatch.conf.js
    const devServer = browser.globals.devServerURL

    browser
      .url(devServer)
      .waitForElementVisible('#app', 5000)
      .assert.elementPresent('.hello')
      .assert.containsText('h1', 'Welcome to Your Vue.js App')
      .assert.elementCount('img', 1)
      .end()
  }
}
<commit_msg>add single e2e test<commit_after>// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage

module.exports = {
  'default e2e tests': function (browser) {
    // automatically uses dev Server port from /config.index.js
    // default: http://localhost:8080
    // see nightwatch.conf.js
    const devServer = browser.globals.devServerURL

    browser
      .url(devServer)
      .waitForElementVisible('#app', 5000)
      .assert.elementPresent('#salaryValue')
      .assert.elementCount('img', 1)
      .end()
  }
}
<|endoftext|>


<commit_before>const Submission = require('../models/Submission');
const moment = require('moment');

/**
 * GET /submissions
 */
exports.getSubmissions = (req, res) => {
  const page = parseInt(req.query && req.query.page) || 0;
  Submission
  .find()
  .sort({ _id: -1 })
  .populate('user')
  .populate('language')
  .skip(500 * page)
  .limit(500)
  .exec((err, submissions) => {
    res.render('submissions', {
      title: 'Submissions',
      submissions,
      moment,
    });
  });
};

/**
 * GET /submissions/:submission
 */
exports.getSubmission = (req, res) => {
  const _id = req.params.submission;

  Submission
  .findOne({ _id })
  .populate('user')
  .populate('language')
  .exec()
  .then((submission) => {
    if (submission === null) {
      return res.sendStatus(404);
    }

    res.render('submission', {
      title: 'Submission',
      submission,
      selfTeam: req.user && typeof req.user.team === 'number' && req.user.team === submission.user.team,
    });
  });
};
<commit_msg>Add author and status parameter<commit_after>const Submission = require('../models/Submission');
const User = require('../models/User');
const moment = require('moment');
const Promise = require('bluebird');

/**
 * GET /submissions
 */
exports.getSubmissions = (req, res) => {
  Promise.try(() => {
    if (req.query.author) {
      return User.findOne({ email: `${req.query.author}@twitter.com` });
    }

    return null;
  }).then((author) => {
    const page = parseInt(req.query && req.query.page) || 0;
    const query = {};

    if (author) {
      query.user = author._id;
    }

    if (req.query.status) {
      query.status = req.query.status;
    }

    return Submission.find(query)
    .sort({ _id: -1 })
    .populate('user')
    .populate('language')
    .skip(500 * page)
    .limit(500)
    .exec();
  }).then((submissions) => {
    res.render('submissions', {
      title: 'Submissions',
      submissions,
      moment,
    });
  });
};

/**
 * GET /submissions/:submission
 */
exports.getSubmission = (req, res) => {
  const _id = req.params.submission;

  Submission
  .findOne({ _id })
  .populate('user')
  .populate('language')
  .exec()
  .then((submission) => {
    if (submission === null) {
      return res.sendStatus(404);
    }

    res.render('submission', {
      title: 'Submission',
      submission,
      selfTeam: req.user && typeof req.user.team === 'number' && req.user.team === submission.user.team,
    });
  });
};
<|endoftext|>