<commit_before>const config = require('../config/config.json').PREFIX;

let channelsArr = [];
exports.run = async (client, guild) => {
    let Id = guild.channels.get(guild.channels.filter(i => i.type === 'text').map(i => i)[0].id);
    let p = guild.channels.filter(o => o.type === 'text').map(o => o);
    Id.send(`Hey :wave:, Thank you very much for adding me to \`${guild.name}\` to get access to the command list do \`${config}help\``);

    /**
     * Check if there's a channel with the name of may-log
     * @type {Array}
     */
    for (let i = 0; i < p.length; i++) {
        channelsArr.push(p[i].name);
    }

    /**
     * Create a channel for may to print out punishments
     * @returns {Error}
     * @returns {Promise}
     */
    if (!channelsArr.includes('may-log')) {
        channelsArr.shift();
        guild.createChannel('may-log', 'text').then(channel => channel.overwritePermissions(guild.id, {
            SEND_MESSAGES: false
        }))
            .catch(e => {
                logger.error(e);
            });
    }

    /*
  * Check if may-muted is already exists.
  */
    let checkIfMayMutedExists = guild.roles.filter(o => o.name === 'may-muted').map(o => o);
    /**
     * Create muted role
     * @param {Object} data
     * @param {String} name
     * @param {String} color
     * @param {Array} permissions
     * @param {String} reason
     * @returns {Error}
     * @returns {Promise}
     */
    if (checkIfMayMutedExists.length < 1) {
        guild.createRole({
            name: 'may-muted',
            permissions: ['USE_VAD', 'ADD_REACTIONS', 'READ_MESSAGE_HISTORY', 'CREATE_INSTANT_INVITE', 'READ_MESSAGES'],
            reason: 'we needed a role for muted'
        })
            .then(role => logger.info(`Created role ${role.name}`))
            .catch(e => {
                logger.error(e);
            });
    } else {
        logger.log('The role is already exists.');
    }

    /*
    Loop through all the channels and block muted people to talk there
  */
    setTimeout(() => {
        guild.channels.filter(textchannel => textchannel.type === 'text').forEach(cnl => {
            cnl.overwritePermissions(guild.roles.find('name', 'may-muted').id, {
                SEND_MESSAGES: false
            })
                .catch(e => logger.error(e));
        });
    }, 2000);

    //TODO: create document with the name of the guildID to hold all the data for the specific guild.
    r.table('guilds').filter({guildID : guild.id}).run().then(async as => {
      if (!as[0]) {
        r.table('guilds').insert({
          guildID : guild.id,
          ownerID : guild.owner.user.id,
        }).then(() => logger.info('Created document for ' + guild.name)).catch(console.error)
      } else {
        logger.info('Looks like the guild: ' + guild.name + ' Added me again :D')
      }
    });

    r.table('livestreams').filter({guildID : guild.id}).run().then(async as => {
        if (!as[0]) {
            r.table('livestreams').insert({
                [guild.id]: {
                    streams: false
                }
            }).then(() => logger.info('Created document for ' + guild.name)).catch(console.error)
        } else {
            logger.info('Looks like the guild: ' + guild.name + ' Added me again :D')
        }
    })

};
<commit_msg>livestreams<commit_after>const config = require('../config/config.json').PREFIX;

let channelsArr = [];
exports.run = async (client, guild) => {
    let Id = guild.channels.get(guild.channels.filter(i => i.type === 'text').map(i => i)[0].id);
    let p = guild.channels.filter(o => o.type === 'text').map(o => o);
    Id.send(`Hey :wave:, Thank you very much for adding me to \`${guild.name}\` to get access to the command list do \`${config}help\``);

    /**
     * Check if there's a channel with the name of may-log
     * @type {Array}
     */
    for (let i = 0; i < p.length; i++) {
        channelsArr.push(p[i].name);
    }

    /**
     * Create a channel for may to print out punishments
     * @returns {Error}
     * @returns {Promise}
     */
    if (!channelsArr.includes('may-log')) {
        channelsArr.shift();
        guild.createChannel('may-log', 'text').then(channel => channel.overwritePermissions(guild.id, {
            SEND_MESSAGES: false
        }))
            .catch(e => {
                logger.error(e);
            });
    }

    /*
  * Check if may-muted is already exists.
  */
    let checkIfMayMutedExists = guild.roles.filter(o => o.name === 'may-muted').map(o => o);
    /**
     * Create muted role
     * @param {Object} data
     * @param {String} name
     * @param {String} color
     * @param {Array} permissions
     * @param {String} reason
     * @returns {Error}
     * @returns {Promise}
     */
    if (checkIfMayMutedExists.length < 1) {
        guild.createRole({
            name: 'may-muted',
            permissions: ['USE_VAD', 'ADD_REACTIONS', 'READ_MESSAGE_HISTORY', 'CREATE_INSTANT_INVITE', 'READ_MESSAGES'],
            reason: 'we needed a role for muted'
        })
            .then(role => logger.info(`Created role ${role.name}`))
            .catch(e => {
                logger.error(e);
            });
    } else {
        logger.log('The role is already exists.');
    }

    /*
    Loop through all the channels and block muted people to talk there
  */
    setTimeout(() => {
        guild.channels.filter(textchannel => textchannel.type === 'text').forEach(cnl => {
            cnl.overwritePermissions(guild.roles.find('name', 'may-muted').id, {
                SEND_MESSAGES: false
            })
                .catch(e => logger.error(e));
        });
    }, 2000);

    //TODO: create document with the name of the guildID to hold all the data for the specific guild.
    r.table('guilds').filter({guildID : guild.id}).run().then(async as => {
      if (!as[0]) {
        r.table('guilds').insert({
          guildID : guild.id,
          ownerID : guild.owner.user.id,
        }).then(() => logger.info('Created document for ' + guild.name)).catch(console.error)
      } else {
        logger.info('Looks like the guild: ' + guild.name + ' Added me again :D')
      }
    });

    r.table('livestreams').filter({guildID : guild.id}).run().then(async as => {
        if (!as[0]) {
            r.table('livestreams').insert({
                [guild.id]: {
                    streams: false,
                    channelID: null
                }
            }).then(() => logger.info('Created document for ' + guild.name)).catch(console.error)
        } else {
            logger.info('Looks like the guild: ' + guild.name + ' Added me again :D')
        }
    })

};
<|endoftext|>


<commit_before>// pour ne pas polluer le scope global, nous encapsulons le code dans une fonction autoappelante
(function() {
    // create an new instance of a pixi stage
	var stage = new PIXI.Stage(0x000000);

    //we store global data in S.Config
	S.Config = {
        width : Math.min(600, window.innerWidth),
        height : Math.min(400, window.innerHeight)
    };

	// create a renderer instance
	var renderer = PIXI.autoDetectRenderer(S.Config.width, S.Config.height);
    //append the view in the body
    document.body.appendChild(renderer.view);

    //here we just doing some tests for now
    //our main ship
	var ship = null;

    // load all needed assets
    var loader = new PIXI.AssetLoader(['img/ship.json']);
    loader.onComplete = onAssetsLoaded;
	loader.load();

    function onAssetsLoaded() {

        // create ship object
        ship = new S.Ship;

        //and addChild it in the stage
        stage.addChild(ship);

        requestAnimFrame( animate );

    }

    //function called each frame to render the game
	function animate() {
	    requestAnimFrame( animate );

	    // render the stage
	    renderer.render(stage);
	}

})();<commit_msg>English to french<commit_after>// pour ne pas polluer le scope global, nous encapsulons le code dans une fonction autoappelante
(function() {
    // on crée une nouvelle Scene (Stage) PIXI
	var stage = new PIXI.Stage(0x000000);

    //On crée un objet global S.Config pour y stocker différentes informations générale
	S.Config = {
        width : Math.min(600, window.innerWidth),
        height : Math.min(400, window.innerHeight)
    };

	// on crée un renderer PICI
	var renderer = PIXI.autoDetectRenderer(S.Config.width, S.Config.height);
    //on ajoute la view du renderer dans le DOM
    document.body.appendChild(renderer.view);

    //Notre vaisseau principal
	var ship = null;

    // On charge les assets (images / sprite (json) )  nécéssaire
    var loader = new PIXI.AssetLoader(['img/ship.json']);
    loader.onComplete = onAssetsLoaded;
	loader.load();

    function onAssetsLoaded() {

        // On crée une nouvelle instance de vaisseau
        ship = new S.Ship;

        //et on ajoute notre vaisseau dans la scene
        stage.addChild(ship);

        //boucle d'animation
        requestAnimFrame( animate );

    }

    //function appelée a chaque frame pour rendre notre jeu
	function animate() {
	    requestAnimFrame( animate );

	    // rendu de la scene
	    renderer.render(stage);
	}

})();
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
import Manager from '../Manager';
import {closest, events, vendorPrefix} from '../utils';
import invariant from 'invariant';

// Export Higher Order Sortable Container Component
export default function SortableContainer(WrappedComponent, config = {withRef: false}) {
	return class extends Component {
		constructor() {
			super();
			this.manager = new Manager();
			this.events = {
				start: this.handleStart,
				move: this.cancel,
				end: this.cancel
			};
		}
		static displayName = (WrappedComponent.displayName) ? `SortableList(${WrappedComponent.displayName})` : 'SortableList';
        static WrappedComponent = WrappedComponent;
		static defaultProps = {
			axis: 'y',
			transitionDuration: 300,
			pressDelay: 0,
			useWindowAsScrollContainer: false,
			hideSortableGhost: true,
			contentWindow: window,
			lockToContainerEdges: false
		};
		static propTypes = {
			axis: PropTypes.string,
			lockAxis: PropTypes.string,
			helperClass: PropTypes.string,
			transitionDuration: PropTypes.number,
			contentWindow: PropTypes.any,
			onSortStart: PropTypes.func,
			onSortMove: PropTypes.func,
			onSortEnd: PropTypes.func,
			pressDelay: PropTypes.number,
			useDragHandle: PropTypes.bool,
			useWindowAsScrollContainer: PropTypes.bool,
			hideSortableGhost: PropTypes.bool,
			lockToContainerEdges: PropTypes.bool
		};
		static childContextTypes = {
			manager: PropTypes.object.isRequired
		};
		state = {};
		getChildContext() {
			return {
				manager: this.manager
			};
		}
		componentDidMount() {
			let {contentWindow} = this.props;

			this.container = ReactDOM.findDOMNode(this);
			this.document = this.container.ownerDocument || document;
			this.scrollContainer = (this.props.useWindowAsScrollContainer) ? this.document.body : this.container;
			this.contentWindow = (typeof contentWindow == 'function') ? contentWindow() : contentWindow;

			for (let key in this.events) {
				events[key].forEach(eventName => this.container.addEventListener(eventName, this.events[key], false));
			}
		}
		componentWillUnmount() {
			for (let key in this.events) {
				events[key].forEach(eventName => this.container.removeEventListener(eventName, this.events[key]));
			}
		}
		handleStart = (e) => {
			let node = closest(e.target, (el) => el.sortableInfo != null);

			if (node && !this.state.sorting && node.sortableInfo) {
				let {useDragHandle} = this.props;
				let {index, collection} = node.sortableInfo;

				if (useDragHandle && !closest(e.target, (el) => el.sortableHandle != null)) return;

				this.manager.active = {index, collection};
				this.pressTimer = setTimeout(() => this.handlePress(e), this.props.pressDelay);
			}
		};
		cancel = (e) => {
			if (!this.state.sorting) {
				clearTimeout(this.pressTimer);
				this.manager.active = null;
			}
		};
		handlePress = (e) => {
			let active = this.manager.getActive();

			if (active) {
				let {axis, onSortStart, helperClass, hideSortableGhost, useWindowAsScrollContainer} = this.props;
				let {node, collection} = active;
				let index = node.sortableInfo.index;

				let containerBoundingRect = this.container.getBoundingClientRect();

				this.node = node;
				this.width = node.offsetWidth;
				this.height = node.offsetHeight;
				this.dimension = (axis == 'x') ? this.width : this.height;
				this.boundingClientRect = node.getBoundingClientRect();
				this.index = index;
				this.newIndex = index;

				let edge = this.edge = (axis == 'x') ? 'Left' : 'Top';
				this.offsetEdge = this.getEdgeOffset(edge, node);
				this.initialOffset = this.getOffset(e);
				this.initialScroll = this.scrollContainer[`scroll${edge}`];

				this.helper = this.document.body.appendChild(node.cloneNode(true));
				this.helper.style.position = 'fixed';
				this.helper.style.top = `${this.boundingClientRect.top}px`;
				this.helper.style.left = `${this.boundingClientRect.left}px`;
				this.helper.style.width = `${this.width}px`;

				if (hideSortableGhost) {
					node.style.visibility = 'hidden';
				}

				if (axis == 'x') {
					this.minTranslate = ((useWindowAsScrollContainer) ? 0 : containerBoundingRect.left) - this.boundingClientRect.left - this.width/2;
					this.maxTranslate = ((useWindowAsScrollContainer) ? this.contentWindow.innerWidth : containerBoundingRect.left + containerBoundingRect.width) - this.boundingClientRect.left - this.width/2;
				} else {
					this.minTranslate = ((useWindowAsScrollContainer) ? 0 : containerBoundingRect.top) - this.boundingClientRect.top - this.height/2;
					this.maxTranslate = ((useWindowAsScrollContainer) ? this.contentWindow.innerHeight : containerBoundingRect.top + containerBoundingRect.height) - this.boundingClientRect.top - this.height/2;
				}

				if (helperClass) {
					this.helper.classList.add(helperClass.split(' '));
				}

				this.listenerNode = (e.touches) ? node : this.contentWindow;
				events.move.forEach(eventName => this.listenerNode.addEventListener(eventName, this.handleSortMove, false));
				events.end.forEach(eventName => this.listenerNode.addEventListener(eventName, this.handleSortEnd, false));

				this.setState({
					sorting: true,
					sortingIndex: index
				});

				if (onSortStart) onSortStart({node, index, collection}, e);
			}
		}
		handleSortMove = (e) => {
			let {onSortMove} = this.props;
			e.preventDefault(); // Prevent scrolling on mobile

			this.updatePosition(e);
			this.animateNodes();
			this.autoscroll();

			if (onSortMove) onSortMove(e);
		}
		handleSortEnd = (e) => {
			let {hideSortableGhost, onSortEnd} = this.props;
			let {collection} = this.manager.active;

			// Remove the event listeners if the node is still in the DOM
			if (this.listenerNode) {
				events.move.forEach(eventName => this.listenerNode.removeEventListener(eventName, this.handleSortMove));
				events.end.forEach(eventName => this.listenerNode.removeEventListener(eventName, this.handleSortEnd));
			}

			// Remove the helper from the DOM
			this.helper.parentNode.removeChild(this.helper);

			if (hideSortableGhost && this.node) {
				this.node.style.visibility = '';
			}

			let nodes = this.manager.refs[collection];
			for (let i = 0, len = nodes.length; i < len; i++) {
				let node = nodes[i];
				let el = node.node;
				let index = el.sortableInfo.index;
				node.edgeOffset = null; // Clear the cached offsetTop / offsetLeft value

				// Remove the transforms / transitions
				el.style[`${vendorPrefix}Transform`] = '';
				el.style[`${vendorPrefix}TransitionDuration`] = '';
			}

			if (typeof onSortEnd == 'function') {
				onSortEnd({
					oldIndex: this.index,
					newIndex: this.newIndex,
					collection: collection
				}, e);
			}

			// Stop autoscroll
			clearInterval(this.autoscrollInterval);
			this.autoscrollInterval = null;

			// Update state
			this.manager.active = null;
			this.setState({
				sorting: false,
				sortingIndex: null
			});
		}
		getEdgeOffset(edge, node, offset = 0) {
			// Get the actual offsetTop / offsetLeft value, no matter how deep the node is nested
			if (node) {
				if (node.parentNode !== this.container) {
					return this.getEdgeOffset(edge, node.parentNode, offset + node[`offset${edge}`]);
				} else {
					return node[`offset${edge}`] + offset;
				}
			}
		}
		getOffset(e) {
			return {
				x: (e.touches) ? e.touches[0].clientX : e.clientX,
				y: (e.touches) ? e.touches[0].clientY : e.clientY
			}
		}
		updatePosition(e) {
			let {axis, lockAxis, lockToContainerEdges} = this.props;
			let offset = this.getOffset(e);
			let translate = {
				x: offset.x - this.initialOffset.x,
				y: offset.y - this.initialOffset.y
			};

			this.translate = translate[axis];

			if (lockToContainerEdges) {
				if (translate[axis] < this.minTranslate) {
					translate[axis] = this.minTranslate;
				} else if (translate[axis] > this.maxTranslate) {
					translate[axis] = this.maxTranslate;
				}
			}

			switch (lockAxis) {
				case 'x':
					translate.y = 0;
					break;
				case 'y':
					translate.x = 0;
					break;
			}

			this.helper.style[`${vendorPrefix}Transform`] = `translate3d(${translate.x}px,${translate.y}px, 0)`;
		}
		animateNodes() {
			let {axis, transitionDuration, hideSortableGhost} = this.props;
			let nodes = this.manager.getOrderedRefs();
			let deltaScroll = this.scrollContainer[`scroll${this.edge}`] - this.initialScroll;
			let sortingOffset = this.offsetEdge + this.translate + deltaScroll;
			this.newIndex = null;

			for (let i = 0, len = nodes.length; i < len; i++) {
				let {node, edgeOffset} = nodes[i];
				let index = node.sortableInfo.index;
				let dimension = (axis == 'x') ? node.offsetWidth : node.offsetHeight;
				let offset = (this.dimension > dimension) ? dimension / 2 : this.dimension / 2;
				let translate = 0;
				let translateX = 0;
				let translateY = 0;

				// If we haven't cached the node's offsetTop / offsetLeft value
				if (edgeOffset == null) {
					nodes[i].edgeOffset = edgeOffset = this.getEdgeOffset(this.edge, node);
				}

				// If the node is the one we're currently animating, skip it
				if (index === this.index) {
					if (hideSortableGhost) {
						node.style.visibility = 'hidden';
					}
					continue;
				}

				if (transitionDuration) {
					node.style[`${vendorPrefix}TransitionDuration`] = `${transitionDuration}ms`;
				}
				if (index > this.index && (sortingOffset + offset >= edgeOffset)) {
					translate = -this.dimension;
					this.newIndex = index;
				}
				else if (index < this.index && (sortingOffset <= edgeOffset + offset)) {
					translate = this.dimension;

					if (this.newIndex == null) {
						this.newIndex = index;
					}
				}

				if (axis == 'x') {
					translateX = translate;
				} else {
					translateY = translate;
				}

				node.style[`${vendorPrefix}Transform`] = `translate3d(${translateX}px,${translateY}px,0)`;
			}
			if (this.newIndex == null) {
				this.newIndex = this.index;
			}
		}
		autoscroll = () => {
			let translate = this.translate;
			let direction;
			let speed = 1;
			let acceleration = 10;

			if (translate >= this.maxTranslate - this.dimension/2) {
				direction = 1; // Scroll Down
				speed = acceleration * Math.abs((this.maxTranslate - this.dimension/2 - translate) / this.dimension);
			} else if (translate <= this.minTranslate + this.dimension/2) {
				direction = -1; // Scroll Up
				speed = acceleration * Math.abs((translate - this.dimension/2 - this.minTranslate) / this.dimension);
			}

			if (this.autoscrollInterval) {
				clearTimeout(this.autoscrollInterval);
				this.autoscrollInterval = null;
				this.isAutoScrolling = false;
			}

			if (direction) {
				this.autoscrollInterval = setInterval(() => {
					this.isAutoScrolling = true;
					let offset = 1 * speed * direction;
					this.scrollContainer[`scroll${this.edge}`] += offset;
					this.translate += offset;
					this.animateNodes();
				}, 5);
			}
		};
		getWrappedInstance() {
            invariant(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableContainer() call');
            return this.refs.wrappedInstance;
        }
        render() {
            const ref = (config.withRef) ? 'wrappedInstance' : null;

			return <WrappedComponent ref={ref} {...this.props} {...this.state} />;
		}
	}
}
<commit_msg>Fix helperClass<commit_after>import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
import Manager from '../Manager';
import {closest, events, vendorPrefix} from '../utils';
import invariant from 'invariant';

// Export Higher Order Sortable Container Component
export default function SortableContainer(WrappedComponent, config = {withRef: false}) {
	return class extends Component {
		constructor() {
			super();
			this.manager = new Manager();
			this.events = {
				start: this.handleStart,
				move: this.cancel,
				end: this.cancel
			};
		}
		static displayName = (WrappedComponent.displayName) ? `SortableList(${WrappedComponent.displayName})` : 'SortableList';
        static WrappedComponent = WrappedComponent;
		static defaultProps = {
			axis: 'y',
			transitionDuration: 300,
			pressDelay: 0,
			useWindowAsScrollContainer: false,
			hideSortableGhost: true,
			contentWindow: window,
			lockToContainerEdges: false
		};
		static propTypes = {
			axis: PropTypes.string,
			lockAxis: PropTypes.string,
			helperClass: PropTypes.string,
			transitionDuration: PropTypes.number,
			contentWindow: PropTypes.any,
			onSortStart: PropTypes.func,
			onSortMove: PropTypes.func,
			onSortEnd: PropTypes.func,
			pressDelay: PropTypes.number,
			useDragHandle: PropTypes.bool,
			useWindowAsScrollContainer: PropTypes.bool,
			hideSortableGhost: PropTypes.bool,
			lockToContainerEdges: PropTypes.bool
		};
		static childContextTypes = {
			manager: PropTypes.object.isRequired
		};
		state = {};
		getChildContext() {
			return {
				manager: this.manager
			};
		}
		componentDidMount() {
			let {contentWindow} = this.props;

			this.container = ReactDOM.findDOMNode(this);
			this.document = this.container.ownerDocument || document;
			this.scrollContainer = (this.props.useWindowAsScrollContainer) ? this.document.body : this.container;
			this.contentWindow = (typeof contentWindow == 'function') ? contentWindow() : contentWindow;

			for (let key in this.events) {
				events[key].forEach(eventName => this.container.addEventListener(eventName, this.events[key], false));
			}
		}
		componentWillUnmount() {
			for (let key in this.events) {
				events[key].forEach(eventName => this.container.removeEventListener(eventName, this.events[key]));
			}
		}
		handleStart = (e) => {
			let node = closest(e.target, (el) => el.sortableInfo != null);

			if (node && !this.state.sorting && node.sortableInfo) {
				let {useDragHandle} = this.props;
				let {index, collection} = node.sortableInfo;

				if (useDragHandle && !closest(e.target, (el) => el.sortableHandle != null)) return;

				this.manager.active = {index, collection};
				this.pressTimer = setTimeout(() => this.handlePress(e), this.props.pressDelay);
			}
		};
		cancel = (e) => {
			if (!this.state.sorting) {
				clearTimeout(this.pressTimer);
				this.manager.active = null;
			}
		};
		handlePress = (e) => {
			let active = this.manager.getActive();

			if (active) {
				let {axis, onSortStart, helperClass, hideSortableGhost, useWindowAsScrollContainer} = this.props;
				let {node, collection} = active;
				let index = node.sortableInfo.index;

				let containerBoundingRect = this.container.getBoundingClientRect();

				this.node = node;
				this.width = node.offsetWidth;
				this.height = node.offsetHeight;
				this.dimension = (axis == 'x') ? this.width : this.height;
				this.boundingClientRect = node.getBoundingClientRect();
				this.index = index;
				this.newIndex = index;

				let edge = this.edge = (axis == 'x') ? 'Left' : 'Top';
				this.offsetEdge = this.getEdgeOffset(edge, node);
				this.initialOffset = this.getOffset(e);
				this.initialScroll = this.scrollContainer[`scroll${edge}`];

				this.helper = this.document.body.appendChild(node.cloneNode(true));
				this.helper.style.position = 'fixed';
				this.helper.style.top = `${this.boundingClientRect.top}px`;
				this.helper.style.left = `${this.boundingClientRect.left}px`;
				this.helper.style.width = `${this.width}px`;

				if (hideSortableGhost) {
					node.style.visibility = 'hidden';
				}

				if (axis == 'x') {
					this.minTranslate = ((useWindowAsScrollContainer) ? 0 : containerBoundingRect.left) - this.boundingClientRect.left - this.width/2;
					this.maxTranslate = ((useWindowAsScrollContainer) ? this.contentWindow.innerWidth : containerBoundingRect.left + containerBoundingRect.width) - this.boundingClientRect.left - this.width/2;
				} else {
					this.minTranslate = ((useWindowAsScrollContainer) ? 0 : containerBoundingRect.top) - this.boundingClientRect.top - this.height/2;
					this.maxTranslate = ((useWindowAsScrollContainer) ? this.contentWindow.innerHeight : containerBoundingRect.top + containerBoundingRect.height) - this.boundingClientRect.top - this.height/2;
				}

				if (helperClass) {
					this.helper.classList.add(...(helperClass.split(' ')));
				}

				this.listenerNode = (e.touches) ? node : this.contentWindow;
				events.move.forEach(eventName => this.listenerNode.addEventListener(eventName, this.handleSortMove, false));
				events.end.forEach(eventName => this.listenerNode.addEventListener(eventName, this.handleSortEnd, false));

				this.setState({
					sorting: true,
					sortingIndex: index
				});

				if (onSortStart) onSortStart({node, index, collection}, e);
			}
		}
		handleSortMove = (e) => {
			let {onSortMove} = this.props;
			e.preventDefault(); // Prevent scrolling on mobile

			this.updatePosition(e);
			this.animateNodes();
			this.autoscroll();

			if (onSortMove) onSortMove(e);
		}
		handleSortEnd = (e) => {
			let {hideSortableGhost, onSortEnd} = this.props;
			let {collection} = this.manager.active;

			// Remove the event listeners if the node is still in the DOM
			if (this.listenerNode) {
				events.move.forEach(eventName => this.listenerNode.removeEventListener(eventName, this.handleSortMove));
				events.end.forEach(eventName => this.listenerNode.removeEventListener(eventName, this.handleSortEnd));
			}

			// Remove the helper from the DOM
			this.helper.parentNode.removeChild(this.helper);

			if (hideSortableGhost && this.node) {
				this.node.style.visibility = '';
			}

			let nodes = this.manager.refs[collection];
			for (let i = 0, len = nodes.length; i < len; i++) {
				let node = nodes[i];
				let el = node.node;
				let index = el.sortableInfo.index;
				node.edgeOffset = null; // Clear the cached offsetTop / offsetLeft value

				// Remove the transforms / transitions
				el.style[`${vendorPrefix}Transform`] = '';
				el.style[`${vendorPrefix}TransitionDuration`] = '';
			}

			if (typeof onSortEnd == 'function') {
				onSortEnd({
					oldIndex: this.index,
					newIndex: this.newIndex,
					collection: collection
				}, e);
			}

			// Stop autoscroll
			clearInterval(this.autoscrollInterval);
			this.autoscrollInterval = null;

			// Update state
			this.manager.active = null;
			this.setState({
				sorting: false,
				sortingIndex: null
			});
		}
		getEdgeOffset(edge, node, offset = 0) {
			// Get the actual offsetTop / offsetLeft value, no matter how deep the node is nested
			if (node) {
				if (node.parentNode !== this.container) {
					return this.getEdgeOffset(edge, node.parentNode, offset + node[`offset${edge}`]);
				} else {
					return node[`offset${edge}`] + offset;
				}
			}
		}
		getOffset(e) {
			return {
				x: (e.touches) ? e.touches[0].clientX : e.clientX,
				y: (e.touches) ? e.touches[0].clientY : e.clientY
			}
		}
		updatePosition(e) {
			let {axis, lockAxis, lockToContainerEdges} = this.props;
			let offset = this.getOffset(e);
			let translate = {
				x: offset.x - this.initialOffset.x,
				y: offset.y - this.initialOffset.y
			};

			this.translate = translate[axis];

			if (lockToContainerEdges) {
				if (translate[axis] < this.minTranslate) {
					translate[axis] = this.minTranslate;
				} else if (translate[axis] > this.maxTranslate) {
					translate[axis] = this.maxTranslate;
				}
			}

			switch (lockAxis) {
				case 'x':
					translate.y = 0;
					break;
				case 'y':
					translate.x = 0;
					break;
			}

			this.helper.style[`${vendorPrefix}Transform`] = `translate3d(${translate.x}px,${translate.y}px, 0)`;
		}
		animateNodes() {
			let {axis, transitionDuration, hideSortableGhost} = this.props;
			let nodes = this.manager.getOrderedRefs();
			let deltaScroll = this.scrollContainer[`scroll${this.edge}`] - this.initialScroll;
			let sortingOffset = this.offsetEdge + this.translate + deltaScroll;
			this.newIndex = null;

			for (let i = 0, len = nodes.length; i < len; i++) {
				let {node, edgeOffset} = nodes[i];
				let index = node.sortableInfo.index;
				let dimension = (axis == 'x') ? node.offsetWidth : node.offsetHeight;
				let offset = (this.dimension > dimension) ? dimension / 2 : this.dimension / 2;
				let translate = 0;
				let translateX = 0;
				let translateY = 0;

				// If we haven't cached the node's offsetTop / offsetLeft value
				if (edgeOffset == null) {
					nodes[i].edgeOffset = edgeOffset = this.getEdgeOffset(this.edge, node);
				}

				// If the node is the one we're currently animating, skip it
				if (index === this.index) {
					if (hideSortableGhost) {
						node.style.visibility = 'hidden';
					}
					continue;
				}

				if (transitionDuration) {
					node.style[`${vendorPrefix}TransitionDuration`] = `${transitionDuration}ms`;
				}
				if (index > this.index && (sortingOffset + offset >= edgeOffset)) {
					translate = -this.dimension;
					this.newIndex = index;
				}
				else if (index < this.index && (sortingOffset <= edgeOffset + offset)) {
					translate = this.dimension;

					if (this.newIndex == null) {
						this.newIndex = index;
					}
				}

				if (axis == 'x') {
					translateX = translate;
				} else {
					translateY = translate;
				}

				node.style[`${vendorPrefix}Transform`] = `translate3d(${translateX}px,${translateY}px,0)`;
			}
			if (this.newIndex == null) {
				this.newIndex = this.index;
			}
		}
		autoscroll = () => {
			let translate = this.translate;
			let direction;
			let speed = 1;
			let acceleration = 10;

			if (translate >= this.maxTranslate - this.dimension/2) {
				direction = 1; // Scroll Down
				speed = acceleration * Math.abs((this.maxTranslate - this.dimension/2 - translate) / this.dimension);
			} else if (translate <= this.minTranslate + this.dimension/2) {
				direction = -1; // Scroll Up
				speed = acceleration * Math.abs((translate - this.dimension/2 - this.minTranslate) / this.dimension);
			}

			if (this.autoscrollInterval) {
				clearTimeout(this.autoscrollInterval);
				this.autoscrollInterval = null;
				this.isAutoScrolling = false;
			}

			if (direction) {
				this.autoscrollInterval = setInterval(() => {
					this.isAutoScrolling = true;
					let offset = 1 * speed * direction;
					this.scrollContainer[`scroll${this.edge}`] += offset;
					this.translate += offset;
					this.animateNodes();
				}, 5);
			}
		};
		getWrappedInstance() {
            invariant(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableContainer() call');
            return this.refs.wrappedInstance;
        }
        render() {
            const ref = (config.withRef) ? 'wrappedInstance' : null;

			return <WrappedComponent ref={ref} {...this.props} {...this.state} />;
		}
	}
}
<|endoftext|>


<commit_before>/* global describe, it, expect */
import React from 'react';
import { shallow, mount } from 'enzyme';
import Dropdown from '../dropdown';
import Option from '../option';

describe('<Dropdown />', () => {
  let callbacks;

  const options = [
    {label: "Label Teste", value: "teste"},
    {label: "Label Teste 2", value: "teste 2"},
    {label: "Label Teste 3", value: "teste 3"}
  ];

  beforeEach(function () {
    callbacks = [];
  });

  afterEach(function () {
    callbacks.forEach(function (callback, index, array) {
      callback();
    });
  });

  const dispatchEvent = function (eventName, el) {
    let evt = document.createEvent('Event');
    evt.initEvent(eventName, true, true);
    el.dispatchEvent(evt);
  }

  it('should accept className', () => {
    const wrapper = shallow(<Dropdown options={options} className="foobar" />);
    expect(wrapper.hasClass('foobar')).toBe(true);
  });

  it('should have options', () => {
    const wrapper = mount(<Dropdown options={options} />);

    wrapper.simulate('click');
    const renderedOptions = wrapper.find(Option);
    expect(renderedOptions.length).toBe(3);
  });

  it('should accept options as Array of Strings', () => {
    const stringOptions = ['string 1', 'string 2'];
    const wrapper = shallow(<Dropdown options={stringOptions} />);
    const renderedOptions = wrapper.find(Option);

    expect(renderedOptions.length).toBe(2);
    expect(renderedOptions.first().prop('value')).toEqual(stringOptions[0]);
    expect(renderedOptions.last().prop('value')).toEqual(stringOptions[1]);
  });

  it('click should open dropdown', () => {
    const wrapper = mount(<Dropdown options={options} />);

    expect(wrapper.hasClass('bs-ui-dropdown--open')).toBe(false);

    wrapper.simulate('click');
    expect(wrapper.update().hasClass('bs-ui-dropdown--open')).toBe(true);
  });

  it('click out should close dropdown', (done) => {
    const wrapper = mount(<Dropdown options={options} />);

    expect(wrapper.hasClass('bs-ui-dropdown--open')).toBe(false);

    wrapper.simulate('click');
    expect(wrapper.update().hasClass('bs-ui-dropdown--open')).toBe(true);

    const expectCallback = function () {
      expect(wrapper.update().hasClass('bs-ui-dropdown--open')).toBe(false);
      done();
    };

    document.addEventListener('click', expectCallback, false);
    callbacks.push(function () {
      document.removeEventListener('click', expectCallback, false);
    });

    dispatchEvent('click', document.body);
  });

  it('click on option should close dropdown', () => {
    const wrapper = mount(<Dropdown options={options} />);
    wrapper.simulate('click');

    const option = wrapper.find(Option).first();
    option.simulate('click');
    expect(wrapper.update().hasClass('bs-ui-dropdown--open')).toBe(false);
  });

  it('click option should change selected option', () => {
    const wrapper = mount(<Dropdown options={options} />);
    wrapper.simulate('click');

    const option = wrapper.find(Option).first();
    option.simulate('click');

    const selectedOption = wrapper.find('.bs-ui-dropdown__item');
    expect(selectedOption.text()).toBe(options[0].label);
  });

  it('selected options must have a selected state', () => {
    const wrapper = mount(<Dropdown options={options} />);
    wrapper.simulate('click');

    const option = wrapper.find(Option).last();
    expect(option.props().selected).toBe(false);

    option.simulate('click');
    expect(option.prop('selected')).toBe(true);
  });

  it('should call onSelectOption callback whenever a option has been selected', (done) => {
    const onSelectOption = function (selectedOption) {
      expect(selectedOption).toEqual(options[options.length - 1]);
      done();
    };
    const wrapper = mount(<Dropdown options={options} onSelectOption={onSelectOption} />);
    const option = wrapper.find(Option).last();

    wrapper.simulate('click');
    option.simulate('click');
  });

  it('should call onOpen callback whenever the dropdown is opened', (done) => {
    const onOpen = function () {
      done();
    };
    const wrapper = mount(<Dropdown options={options} onOpen={onOpen} />);
    wrapper.simulate('click');
  });

  it('should call onClose callback whenever the dropdown is closed', (done) => {
    const onClose = function () {
      done();
    };
    const wrapper = mount(<Dropdown options={options} onClose={onClose} />);

    wrapper.simulate('click');
    dispatchEvent('click', document.body);
  });
});
<commit_msg>organize tests<commit_after>/* global describe, it, expect */
import React from 'react';
import { shallow, mount } from 'enzyme';
import Dropdown from '../dropdown';
import Option from '../option';

describe('<Dropdown />', () => {
  let callbacks;

  const options = [
    {label: "Label Teste", value: "teste"},
    {label: "Label Teste 2", value: "teste 2"},
    {label: "Label Teste 3", value: "teste 3"}
  ];

  beforeEach(function () {
    callbacks = [];
  });

  afterEach(function () {
    callbacks.forEach(function (callback, index, array) {
      callback();
    });
  });

  const dispatchEvent = function (eventName, el) {
    let evt = document.createEvent('Event');
    evt.initEvent(eventName, true, true);
    el.dispatchEvent(evt);
  }

  it('should accept className', () => {
    const wrapper = shallow(<Dropdown options={options} className="foobar" />);
    expect(wrapper.hasClass('foobar')).toBe(true);
  });

  it('should have options', () => {
    const wrapper = mount(<Dropdown options={options} />);

    wrapper.simulate('click');
    const renderedOptions = wrapper.find(Option);
    expect(renderedOptions.length).toBe(3);
  });

  it('should accept options as Array of Strings', () => {
    const stringOptions = ['string 1', 'string 2'];
    const wrapper = shallow(<Dropdown options={stringOptions} />);
    const renderedOptions = wrapper.find(Option);

    expect(renderedOptions.length).toBe(2);
    expect(renderedOptions.first().prop('value')).toEqual(stringOptions[0]);
    expect(renderedOptions.last().prop('value')).toEqual(stringOptions[1]);
  });

  it('should have options', () => {
    const wrapper = mount(<Dropdown options={options} />);

    wrapper.simulate('click');
    const renderedOptions = wrapper.find(Option);
    expect(renderedOptions.length).toBe(3);
  });

  describe('click', function () {
    it('should open dropdown', () => {
      const wrapper = mount(<Dropdown options={options} />);

      expect(wrapper.hasClass('bs-ui-dropdown--open')).toBe(false);

      wrapper.simulate('click');
      expect(wrapper.update().hasClass('bs-ui-dropdown--open')).toBe(true);
    });

    it('out should close dropdown', (done) => {
      const wrapper = mount(<Dropdown options={options} />);

      expect(wrapper.hasClass('bs-ui-dropdown--open')).toBe(false);

      wrapper.simulate('click');
      expect(wrapper.update().hasClass('bs-ui-dropdown--open')).toBe(true);

      const expectCallback = function () {
        expect(wrapper.update().hasClass('bs-ui-dropdown--open')).toBe(false);
        done();
      };

      document.addEventListener('click', expectCallback, false);
      callbacks.push(function () {
        document.removeEventListener('click', expectCallback, false);
      });

      dispatchEvent('click', document.body);
    });
  });

  describe('select option', function () {
    it('should close dropdown', () => {
      const wrapper = mount(<Dropdown options={options} />);
      wrapper.simulate('click');

      const option = wrapper.find(Option).first();
      option.simulate('click');
      expect(wrapper.update().hasClass('bs-ui-dropdown--open')).toBe(false);
    });

    it('should change selected option', () => {
      const wrapper = mount(<Dropdown options={options} />);
      wrapper.simulate('click');

      const option = wrapper.find(Option).first();
      option.simulate('click');

      const selectedOption = wrapper.find('.bs-ui-dropdown__item');
      expect(selectedOption.text()).toBe(options[0].label);
    });

    it('should set selected state to the selected option', () => {
      const wrapper = mount(<Dropdown options={options} />);
      wrapper.simulate('click');

      const option = wrapper.find(Option).last();
      expect(option.props().selected).toBe(false);

      option.simulate('click');
      expect(option.prop('selected')).toBe(true);
    });
  });

  describe('should call', function () {
    it('onSelectOption callback whenever a option has been selected', (done) => {
      const onSelectOption = function (selectedOption) {
        expect(selectedOption).toEqual(options[options.length - 1]);
        done();
      };
      const wrapper = mount(<Dropdown options={options} onSelectOption={onSelectOption} />);
      const option = wrapper.find(Option).last();

      wrapper.simulate('click');
      option.simulate('click');
    });

    it('onOpen callback whenever the dropdown is opened', (done) => {
      const onOpen = function () {
        done();
      };
      const wrapper = mount(<Dropdown options={options} onOpen={onOpen} />);
      wrapper.simulate('click');
    });

    it('onClose callback whenever the dropdown is closed', (done) => {
      const onClose = function () {
        done();
      };
      const wrapper = mount(<Dropdown options={options} onClose={onClose} />);

      wrapper.simulate('click');
      dispatchEvent('click', document.body);
    });
  });
});
<|endoftext|>


<commit_before>document.addEventListener( "DOMContentLoaded", function( e ) {

  require.config({
    baseUrl: "../../lib",
    paths: {
      "src": "../src",
      "base": "../src/base",
      "common": "../src/common",
      "core": "../src/core",
      "extensions": "../src/extensions"
    }
  });

  require(
    [ "core/gladius-core",
      "gladius-cubicvr" ],
    function( Gladius, cubicvrExtension ) {

      var engine = new Gladius();

      // Engine monitor setup
      function monitor( engine ) {
        debugger;
        engine.detach( monitor );
      }
      document.addEventListener( "keydown", function( event ) {
        var code = event.which || event.keyCode;
        if( code === 0x4D && event.ctrlKey && event.altKey ) {
          engine.attach( monitor );
        }
      });

      var cubicvrOptions = {
        renderer: {
          canvas: document.getElementById( "test-canvas" )
        }
      };
      engine.registerExtension( cubicvrExtension, cubicvrOptions );

      var resources = {};

      engine.get(
        [
          {
            type: engine["gladius-cubicvr"].Mesh,
            url: 'procedural-mesh.js',
            load: engine.loaders.procedural,
            onsuccess: function( mesh ) {
              resources.mesh = mesh;
            },
            onfailure: function( error ) {
            }
          },
          {
            type: engine["gladius-cubicvr"].MaterialDefinition,
            url: 'procedural-material.js',
            load: engine.loaders.procedural,
            onsuccess: function( material ) {
              resources.material = material;
            },
            onfailure: function( error ) {
            }
          }
        ],
        {
          oncomplete: game.bind( null, engine, resources )
        }
      );

  });

  function game( engine, resources ) {
    var space = new engine.simulation.Space();
    var cubicvr = engine.findExtension( "gladius-cubicvr" );

    var lightDefinition = new cubicvr.LightDefinition({
      intensity: 2,
      light_type: cubicvr.LightDefinition.LightTypes.POINT,
      method: cubicvr.LightDefinition.LightingMethods.DYNAMIC
    })

    space.add( new engine.simulation.Entity( "camera",
      [
        new engine.core.Transform( [0, 0, 0] ),
        new cubicvr.Camera()
      ]
    ));
    space.add( new engine.simulation.Entity( "light-center",
      [
        new engine.core.Transform( [0, 0, 5], [engine.math.TAU, engine.math.TAU, engine.math.TAU] )
      ]
    ));
    space.add( new engine.simulation.Entity( "light-marker",
      [
        new engine.core.Transform( [3, 0, 0], [0, 0, 0], [0.1, 0.1, 0.1] ),
        new cubicvr.Model( resources.mesh, resources.material )
      ]
    ));
    space.add( new engine.simulation.Entity( "light-source",
      [
        new engine.core.Transform( [3, 0, 0], [0, 0, 0], [1, 1, 1] ),
        new cubicvr.Light( lightDefinition )
      ]
    ));
    var parentCube = new engine.simulation.Entity( "cube",
      [
        new engine.core.Transform( [0, 0, 6], [0, -engine.math.TAU/8, engine.math.TAU/8] ),
        new cubicvr.Model( resources.mesh, resources.material )
      ]
    );
    space.add( parentCube );
    space.findNamed( "light-source" ).setParent( space.findNamed( "light-center" ) );
    space.findNamed( "light-marker" ).setParent( space.findNamed( "light-center" ) );

    var task = new engine.FunctionTask( function() {
      var cubeRotation = new engine.math.Vector3( space.findNamed( "cube" ).findComponent( "Transform" ).rotation );
      cubeRotation = engine.math.vector3.add( cubeRotation, [space.clock.delta * 0.003, space.clock.delta * 0.001, space.clock.delta * 0.0007] );
      space.findNamed( "cube" ).findComponent( "Transform" ).setRotation( cubeRotation );

      var lightRotation = new engine.math.Vector3( space.findNamed( "light-center" ).findComponent( "Transform" ).rotation );
      lightRotation = engine.math.vector3.add( lightRotation, [0, space.clock.delta * 0.001, 0] );
      space.findNamed( "light-center" ).findComponent( "Transform" ).setRotation( lightRotation );
    }, {
      tags: ["@update"]
    });
    task.start();

    engine.resume();
  }

});
<commit_msg>Fixed cube example that broke when we updated the cubicvr extension.<commit_after>document.addEventListener( "DOMContentLoaded", function( e ) {

  require.config({
    baseUrl: "../../lib",
    paths: {
      "src": "../src",
      "base": "../src/base",
      "common": "../src/common",
      "core": "../src/core",
      "extensions": "../src/extensions"
    }
  });

  require(
    [ "core/gladius-core",
      "gladius-cubicvr" ],
    function( Gladius, cubicvrExtension ) {

      var engine = new Gladius();

      // Engine monitor setup
      function monitor( engine ) {
        debugger;
        engine.detach( monitor );
      }
      document.addEventListener( "keydown", function( event ) {
        var code = event.which || event.keyCode;
        if( code === 0x4D && event.ctrlKey && event.altKey ) {
          engine.attach( monitor );
        }
      });

      var cubicvrOptions = {
        renderer: {
          canvas: document.getElementById( "test-canvas" )
        }
      };
      engine.registerExtension( cubicvrExtension, cubicvrOptions );

      var resources = {};

      engine.get(
        [
          {
            type: engine["gladius-cubicvr"].Mesh,
            url: 'procedural-mesh.js',
            load: engine.loaders.procedural,
            onsuccess: function( mesh ) {
              resources.mesh = mesh;
            },
            onfailure: function( error ) {
            }
          },
          {
            type: engine["gladius-cubicvr"].MaterialDefinition,
            url: 'procedural-material.js',
            load: engine.loaders.procedural,
            onsuccess: function( material ) {
              resources.material = material;
            },
            onfailure: function( error ) {
            }
          }
        ],
        {
          oncomplete: game.bind( null, engine, resources )
        }
      );

  });

  function game( engine, resources ) {
    var space = new engine.simulation.Space();
    var cubicvr = engine.findExtension( "gladius-cubicvr" );

    var lightDefinition = new cubicvr.LightDefinition({
      intensity: 2,
      light_type: cubicvr.LightDefinition.LightTypes.POINT,
      method: cubicvr.LightDefinition.LightingMethods.DYNAMIC
    })

    space.add( new engine.simulation.Entity( "camera",
      [
        new engine.core.Transform( [0, 0, 0] ),
        new cubicvr.Camera({
          targeted: true
        }),
        new cubicvr.Light()
      ]
    ));
    space.add( new engine.simulation.Entity( "light-center",
      [
        new engine.core.Transform( [0, 0, 5], [engine.math.TAU, engine.math.TAU, engine.math.TAU] )
      ]
    ));
    space.add( new engine.simulation.Entity( "light-marker",
      [
        new engine.core.Transform( [3, 0, 0], [0, 0, 0], [0.1, 0.1, 0.1] ),
        new cubicvr.Model( resources.mesh, resources.material )
      ]
    ));
    space.add( new engine.simulation.Entity( "light-source",
      [
        new engine.core.Transform( [3, 0, 0], [0, 0, 0], [1, 1, 1] ),
        new cubicvr.Light( lightDefinition )
      ]
    ));
    var parentCube = new engine.simulation.Entity( "cube",
      [
        new engine.core.Transform( [0, 0, 6], [0, -engine.math.TAU/8, engine.math.TAU/8] ),
        new cubicvr.Model( resources.mesh, resources.material )
      ]
    );
    space.add( parentCube );
    space.findNamed( "light-source" ).setParent( space.findNamed( "light-center" ) );
    space.findNamed( "light-marker" ).setParent( space.findNamed( "light-center" ) );

    var task = new engine.FunctionTask( function() {
      var cubeRotation = new engine.math.Vector3( space.findNamed( "cube" ).findComponent( "Transform" ).rotation );
      cubeRotation = engine.math.vector3.add( cubeRotation, [space.clock.delta * 0.003, space.clock.delta * 0.001, space.clock.delta * 0.0007] );
      space.findNamed( "cube" ).findComponent( "Transform" ).setRotation( cubeRotation );

      var lightRotation = new engine.math.Vector3( space.findNamed( "light-center" ).findComponent( "Transform" ).rotation );
      lightRotation = engine.math.vector3.add( lightRotation, [0, space.clock.delta * 0.001, 0] );
      space.findNamed( "light-center" ).findComponent( "Transform" ).setRotation( lightRotation );
    }, {
      tags: ["@update"]
    });
    task.start();

    engine.resume();
  }

});
<|endoftext|>


<commit_before>'use strict'

import * as CONSTANTS from '../constants/index'

import { MAX_ARTICLES_PER_FETCH, NUMBER_OF_FIRST_RESPONSE_PAGE, RETURN_DELAY_TIME } from '../constants/author-page'
import { arrayOf, normalize } from 'normalizr'

import { InternalServerError } from '../lib/custom-error'
import { article as articleSchema } from '../schemas/index'
import { camelizeKeys } from 'humps'
import fetch from 'isomorphic-fetch'
import get from 'lodash/get'
import omit from 'lodash/omit'
import { formatUrl } from '../utils/index'
import { urlParasToString } from '../utils/url-paras-to-string'

const _ = {
  get,
  omit
}

export function requestAuthorCollection(authorId) {
  return {
    type: CONSTANTS.FETCH_AUTHOR_COLLECTION_REQUEST,
    authorId
  }
}

export function failToReceiveAuthorCollection(authorId, error) {
  return {
    type: CONSTANTS.FETCH_AUTHOR_COLLECTION_FAILURE,
    authorId,
    error,
    failedAt: Date.now()
  }
}

export function receiveAuthorCollection({ authorId, items, responseContext }) {
  return {
    type: CONSTANTS.FETCH_AUTHOR_COLLECTION_SUCCESS,
    authorId,
    response: items, // responseObject.hit
    currentPage: _.get(responseContext, 'page'),
    totalPages: _.get(responseContext, 'nbPages'),
    totalResults: _.get(responseContext, 'nbHits'),
    receivedAt: Date.now()
  }
}

export function fetchAuthorCollection({ targetPage, authorId, returnDelay }) {
  return (dispatch, getState) => { // eslint-disable-line no-unused-vars
    const searchParas = {
      keywords: authorId,
      hitsPerPage: MAX_ARTICLES_PER_FETCH,
      page: targetPage
    }
    // Trans searchParas object to url parameters:
    let urlParasString = urlParasToString(searchParas)
    let url = formatUrl(`searchPosts?${urlParasString}`)
    dispatch(requestAuthorCollection(authorId))
    // Call our API server to fetch the data
    return fetch(url)
      .then((response) => {
        if (response.status >= 400) {
          throw new InternalServerError('Bad response from API, response:' + JSON.stringify(response))
        }
        return response.json()
      })
      .then(
        (responseObject) => {
          const responseItems = _.get(responseObject, 'hits', {})    // responseObject.hit
          const responseContext = _.omit(responseObject, 'hits', {}) // All the other things in responseObject except responseObject.hit
          const camelizedJson = camelizeKeys(responseItems)
          const items = normalize(camelizedJson, arrayOf(articleSchema))
          const returnParas = { authorId, items, responseContext }
          // delay for displaying loading spinner
          function delayDispatch() {
            return new Promise((resolve, reject)=> { // eslint-disable-line no-unused-vars
              setTimeout(() => {
                resolve()
              }, returnDelay)
            })
          }
          if (returnDelay > 0) {
            return delayDispatch().then(()=>{
              return dispatch(receiveAuthorCollection(returnParas))
            })
          }
          return dispatch(receiveAuthorCollection(returnParas))
        },
      (error) => dispatch(failToReceiveAuthorCollection(error))
    )
  }
}

export function fetchAuthorCollectionIfNeeded(authorId) {
  return (dispatch, getState) => {
    const currentState = getState()
    const articlesDataOfAnAuthor = _.get(currentState, [ 'articlesByAuthor', authorId ], null)
    // If state.articlesByAuthor[authorId] does not exist:
    if (articlesDataOfAnAuthor === null) {
      return dispatch(fetchAuthorCollection({
        authorId,
        targetPage: NUMBER_OF_FIRST_RESPONSE_PAGE,
        returnDelay: 0
      }))
    }
    //  If state.articlesByAuthor[authorId] exists:
    const { currentPage, isFetching, isFinish } = articlesDataOfAnAuthor
    if(!isFetching && !isFinish) {
      return dispatch(fetchAuthorCollection({
        authorId,
        targetPage: currentPage + 1,
        returnDelay: RETURN_DELAY_TIME
      }))
    }
  }
}
<commit_msg>Add default value of receiveAuthorCollection<commit_after>'use strict'

import * as CONSTANTS from '../constants/index'

import { MAX_ARTICLES_PER_FETCH, NUMBER_OF_FIRST_RESPONSE_PAGE, RETURN_DELAY_TIME } from '../constants/author-page'
import { arrayOf, normalize } from 'normalizr'

import { InternalServerError } from '../lib/custom-error'
import { article as articleSchema } from '../schemas/index'
import { camelizeKeys } from 'humps'
import fetch from 'isomorphic-fetch'
import get from 'lodash/get'
import omit from 'lodash/omit'
import { formatUrl } from '../utils/index'
import { urlParasToString } from '../utils/url-paras-to-string'

const _ = {
  get,
  omit
}

export function requestAuthorCollection(authorId) {
  return {
    type: CONSTANTS.FETCH_AUTHOR_COLLECTION_REQUEST,
    authorId
  }
}

export function failToReceiveAuthorCollection(authorId, error) {
  return {
    type: CONSTANTS.FETCH_AUTHOR_COLLECTION_FAILURE,
    authorId,
    error,
    failedAt: Date.now()
  }
}

export function receiveAuthorCollection({ authorId, items, responseContext }) {
  return {
    type: CONSTANTS.FETCH_AUTHOR_COLLECTION_SUCCESS,
    authorId,
    response: items, // responseObject.hit
    currentPage: _.get(responseContext, 'page', NUMBER_OF_FIRST_RESPONSE_PAGE - 1),
    totalPages: _.get(responseContext, 'nbPages', 0),
    totalResults: _.get(responseContext, 'nbHits', 0),
    receivedAt: Date.now()
  }
}

export function fetchAuthorCollection({ targetPage, authorId, returnDelay }) {
  return (dispatch, getState) => { // eslint-disable-line no-unused-vars
    const searchParas = {
      keywords: authorId,
      hitsPerPage: MAX_ARTICLES_PER_FETCH,
      page: targetPage
    }
    // Trans searchParas object to url parameters:
    let urlParasString = urlParasToString(searchParas)
    let url = formatUrl(`searchPosts?${urlParasString}`)
    dispatch(requestAuthorCollection(authorId))
    // Call our API server to fetch the data
    return fetch(url)
      .then((response) => {
        if (response.status >= 400) {
          throw new InternalServerError('Bad response from API, response:' + JSON.stringify(response))
        }
        return response.json()
      })
      .then(
        (responseObject) => {
          const responseItems = _.get(responseObject, 'hits', {})    // responseObject.hit
          const responseContext = _.omit(responseObject, 'hits', {}) // All the other things in responseObject except responseObject.hit
          const camelizedJson = camelizeKeys(responseItems)
          const items = normalize(camelizedJson, arrayOf(articleSchema))
          const returnParas = { authorId, items, responseContext }
          // delay for displaying loading spinner
          function delayDispatch() {
            return new Promise((resolve, reject)=> { // eslint-disable-line no-unused-vars
              setTimeout(() => {
                resolve()
              }, returnDelay)
            })
          }
          if (returnDelay > 0) {
            return delayDispatch().then(()=>{
              return dispatch(receiveAuthorCollection(returnParas))
            })
          }
          return dispatch(receiveAuthorCollection(returnParas))
        },
      (error) => dispatch(failToReceiveAuthorCollection(error))
    )
  }
}

export function fetchAuthorCollectionIfNeeded(authorId) {
  return (dispatch, getState) => {
    const currentState = getState()
    const articlesDataOfAnAuthor = _.get(currentState, [ 'articlesByAuthor', authorId ], null)
    // If state.articlesByAuthor[authorId] does not exist:
    if (articlesDataOfAnAuthor === null) {
      return dispatch(fetchAuthorCollection({
        authorId,
        targetPage: NUMBER_OF_FIRST_RESPONSE_PAGE,
        returnDelay: 0
      }))
    }
    //  If state.articlesByAuthor[authorId] exists:
    const { currentPage, isFetching, isFinish } = articlesDataOfAnAuthor
    if(!isFetching && !isFinish) {
      return dispatch(fetchAuthorCollection({
        authorId,
        targetPage: currentPage + 1,
        returnDelay: RETURN_DELAY_TIME
      }))
    }
  }
}
<|endoftext|>


<commit_before>/**
 * @author Slayvin / http://slayvin.net
 */

THREE.Mirror = function ( width, height, options ) {

	THREE.Mesh.call( this, new THREE.PlaneBufferGeometry( width, height ) );

	var scope = this;

	scope.name = 'mirror_' + scope.id;
	scope.matrixNeedsUpdate = true;

	options = options || {};

	var textureWidth = options.textureWidth !== undefined ? options.textureWidth : 512;
	var textureHeight = options.textureHeight !== undefined ? options.textureHeight : 512;

	var clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;
	var mirrorColor = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F );

	var mirrorPlane = new THREE.Plane();
	var normal = new THREE.Vector3();
	var mirrorWorldPosition = new THREE.Vector3();
	var cameraWorldPosition = new THREE.Vector3();
	var rotationMatrix = new THREE.Matrix4();
	var lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
	var clipPlane = new THREE.Vector4();

	var view = new THREE.Vector3();
	var target = new THREE.Vector3();
	var q = new THREE.Vector4();

	var textureMatrix = new THREE.Matrix4();

	var mirrorCamera = new THREE.PerspectiveCamera();

	var parameters = {
		minFilter: THREE.LinearFilter,
		magFilter: THREE.LinearFilter,
		format: THREE.RGBFormat,
		stencilBuffer: false
	};

	var renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight, parameters );

	if ( ! THREE.Math.isPowerOfTwo( textureWidth ) || ! THREE.Math.isPowerOfTwo( textureHeight ) ) {

		renderTarget.texture.generateMipmaps = false;

	}

	var mirrorShader = {

		uniforms: {
			mirrorColor: { value: new THREE.Color( 0x7F7F7F ) },
			mirrorSampler: { value: null },
			textureMatrix: { value: new THREE.Matrix4() }
		},

		vertexShader: [
			'uniform mat4 textureMatrix;',
			'varying vec4 mirrorCoord;',

			'void main() {',

			'	vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );',
			'	vec4 worldPosition = modelMatrix * vec4( position, 1.0 );',
			'	mirrorCoord = textureMatrix * worldPosition;',

			'	gl_Position = projectionMatrix * mvPosition;',

			'}'
		].join( '\n' ),

		fragmentShader: [
			'uniform vec3 mirrorColor;',
			'uniform sampler2D mirrorSampler;',
			'varying vec4 mirrorCoord;',

			'float blendOverlay(float base, float blend) {',
			'	return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );',
			'}',

			'void main() {',
			'	vec4 color = texture2DProj(mirrorSampler, mirrorCoord);',
			'	color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 1.0);',
			'	gl_FragColor = color;',
			'}'
		].join( '\n' )

	};

	var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );

	var material = new THREE.ShaderMaterial( {

		fragmentShader: mirrorShader.fragmentShader,
		vertexShader: mirrorShader.vertexShader,
		uniforms: mirrorUniforms

	} );

	material.uniforms.mirrorSampler.value = renderTarget.texture;
	material.uniforms.mirrorColor.value = mirrorColor;
	material.uniforms.textureMatrix.value = textureMatrix;

	scope.material = material;

	function updateTextureMatrix( camera ) {

		scope.updateMatrixWorld();

		mirrorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
		cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );

		rotationMatrix.extractRotation( scope.matrixWorld );

		normal.set( 0, 0, 1 );
		normal.applyMatrix4( rotationMatrix );

		view.subVectors( mirrorWorldPosition, cameraWorldPosition );
		view.reflect( normal ).negate();
		view.add( mirrorWorldPosition );

		rotationMatrix.extractRotation( camera.matrixWorld );

		lookAtPosition.set( 0, 0, - 1 );
		lookAtPosition.applyMatrix4( rotationMatrix );
		lookAtPosition.add( cameraWorldPosition );

		target.subVectors( mirrorWorldPosition, lookAtPosition );
		target.reflect( normal ).negate();
		target.add( mirrorWorldPosition );

		mirrorCamera.position.copy( view );
		mirrorCamera.up.set( 0, - 1, 0 );
		mirrorCamera.up.applyMatrix4( rotationMatrix );
		mirrorCamera.up.reflect( normal ).negate();
		mirrorCamera.lookAt( target );

		mirrorCamera.near = camera.near;
		mirrorCamera.far = camera.far;

		mirrorCamera.updateMatrixWorld();
		mirrorCamera.updateProjectionMatrix();

		// Update the texture matrix
		textureMatrix.set(
			0.5, 0.0, 0.0, 0.5,
			0.0, 0.5, 0.0, 0.5,
			0.0, 0.0, 0.5, 0.5,
			0.0, 0.0, 0.0, 1.0
		);
		textureMatrix.multiply( mirrorCamera.projectionMatrix );
		textureMatrix.multiply( mirrorCamera.matrixWorldInverse );

		// Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
		// Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
		mirrorPlane.setFromNormalAndCoplanarPoint( normal, mirrorWorldPosition );
		mirrorPlane.applyMatrix4( mirrorCamera.matrixWorldInverse );

		clipPlane.set( mirrorPlane.normal.x, mirrorPlane.normal.y, mirrorPlane.normal.z, mirrorPlane.constant );

		var projectionMatrix = mirrorCamera.projectionMatrix;

		q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
		q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
		q.z = - 1.0;
		q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];

		// Calculate the scaled plane vector
		clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) );

		// Replacing the third row of the projection matrix
		projectionMatrix.elements[ 2 ] = clipPlane.x;
		projectionMatrix.elements[ 6 ] = clipPlane.y;
		projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias;
		projectionMatrix.elements[ 14 ] = clipPlane.w;

	}

	scope.onBeforeRender = function ( renderer, scene, camera ) {

		updateTextureMatrix( camera );

		scope.visible = false;

		var currentRenderTarget = renderer.getRenderTarget();

		var currentVrEnabled = renderer.vr.enabled;
		var currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;

		renderer.vr.enabled = false; // Avoid camera modification and recursion
		renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows

		renderer.render( scene, mirrorCamera, renderTarget, true );

		renderer.vr.enabled = currentVrEnabled;
		renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;

		renderer.setRenderTarget( currentRenderTarget );

		scope.visible = true;

	};

};

THREE.Mirror.prototype = Object.create( THREE.Mesh.prototype );
<commit_msg>Mirror: Fixed VR support<commit_after>/**
 * @author Slayvin / http://slayvin.net
 */

THREE.Mirror = function ( width, height, options ) {

	THREE.Mesh.call( this, new THREE.PlaneBufferGeometry( width, height ) );

	var scope = this;

	scope.name = 'mirror_' + scope.id;
	scope.matrixNeedsUpdate = true;

	options = options || {};

	var viewport = new THREE.Vector4();

	var textureWidth = options.textureWidth !== undefined ? options.textureWidth : 512;
	var textureHeight = options.textureHeight !== undefined ? options.textureHeight : 512;

	var clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;
	var mirrorColor = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F );

	var mirrorPlane = new THREE.Plane();
	var normal = new THREE.Vector3();
	var mirrorWorldPosition = new THREE.Vector3();
	var cameraWorldPosition = new THREE.Vector3();
	var rotationMatrix = new THREE.Matrix4();
	var lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
	var clipPlane = new THREE.Vector4();

	var view = new THREE.Vector3();
	var target = new THREE.Vector3();
	var q = new THREE.Vector4();

	var textureMatrix = new THREE.Matrix4();

	var mirrorCamera = new THREE.PerspectiveCamera();

	var parameters = {
		minFilter: THREE.LinearFilter,
		magFilter: THREE.LinearFilter,
		format: THREE.RGBFormat,
		stencilBuffer: false
	};

	var renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight, parameters );

	if ( ! THREE.Math.isPowerOfTwo( textureWidth ) || ! THREE.Math.isPowerOfTwo( textureHeight ) ) {

		renderTarget.texture.generateMipmaps = false;

	}

	var mirrorShader = {

		uniforms: {
			mirrorColor: { value: new THREE.Color( 0x7F7F7F ) },
			mirrorSampler: { value: null },
			textureMatrix: { value: new THREE.Matrix4() }
		},

		vertexShader: [
			'uniform mat4 textureMatrix;',
			'varying vec4 mirrorCoord;',

			'void main() {',

			'	vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );',
			'	vec4 worldPosition = modelMatrix * vec4( position, 1.0 );',
			'	mirrorCoord = textureMatrix * worldPosition;',

			'	gl_Position = projectionMatrix * mvPosition;',

			'}'
		].join( '\n' ),

		fragmentShader: [
			'uniform vec3 mirrorColor;',
			'uniform sampler2D mirrorSampler;',
			'varying vec4 mirrorCoord;',

			'float blendOverlay(float base, float blend) {',
			'	return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );',
			'}',

			'void main() {',
			'	vec4 color = texture2DProj(mirrorSampler, mirrorCoord);',
			'	color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 1.0);',
			'	gl_FragColor = color;',
			'}'
		].join( '\n' )

	};

	var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );

	var material = new THREE.ShaderMaterial( {

		fragmentShader: mirrorShader.fragmentShader,
		vertexShader: mirrorShader.vertexShader,
		uniforms: mirrorUniforms

	} );

	material.uniforms.mirrorSampler.value = renderTarget.texture;
	material.uniforms.mirrorColor.value = mirrorColor;
	material.uniforms.textureMatrix.value = textureMatrix;

	scope.material = material;

	function updateTextureMatrix( camera ) {

		scope.updateMatrixWorld();

		mirrorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
		cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );

		rotationMatrix.extractRotation( scope.matrixWorld );

		normal.set( 0, 0, 1 );
		normal.applyMatrix4( rotationMatrix );

		view.subVectors( mirrorWorldPosition, cameraWorldPosition );
		view.reflect( normal ).negate();
		view.add( mirrorWorldPosition );

		rotationMatrix.extractRotation( camera.matrixWorld );

		lookAtPosition.set( 0, 0, - 1 );
		lookAtPosition.applyMatrix4( rotationMatrix );
		lookAtPosition.add( cameraWorldPosition );

		target.subVectors( mirrorWorldPosition, lookAtPosition );
		target.reflect( normal ).negate();
		target.add( mirrorWorldPosition );

		mirrorCamera.position.copy( view );
		mirrorCamera.up.set( 0, - 1, 0 );
		mirrorCamera.up.applyMatrix4( rotationMatrix );
		mirrorCamera.up.reflect( normal ).negate();
		mirrorCamera.lookAt( target );

		mirrorCamera.near = camera.near;
		mirrorCamera.far = camera.far;

		mirrorCamera.updateMatrixWorld();
		mirrorCamera.updateProjectionMatrix();

		// Update the texture matrix
		textureMatrix.set(
			0.5, 0.0, 0.0, 0.5,
			0.0, 0.5, 0.0, 0.5,
			0.0, 0.0, 0.5, 0.5,
			0.0, 0.0, 0.0, 1.0
		);
		textureMatrix.multiply( mirrorCamera.projectionMatrix );
		textureMatrix.multiply( mirrorCamera.matrixWorldInverse );

		// Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
		// Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
		mirrorPlane.setFromNormalAndCoplanarPoint( normal, mirrorWorldPosition );
		mirrorPlane.applyMatrix4( mirrorCamera.matrixWorldInverse );

		clipPlane.set( mirrorPlane.normal.x, mirrorPlane.normal.y, mirrorPlane.normal.z, mirrorPlane.constant );

		var projectionMatrix = mirrorCamera.projectionMatrix;

		q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
		q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
		q.z = - 1.0;
		q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];

		// Calculate the scaled plane vector
		clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) );

		// Replacing the third row of the projection matrix
		projectionMatrix.elements[ 2 ] = clipPlane.x;
		projectionMatrix.elements[ 6 ] = clipPlane.y;
		projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias;
		projectionMatrix.elements[ 14 ] = clipPlane.w;

	}

	scope.onBeforeRender = function ( renderer, scene, camera ) {

		updateTextureMatrix( camera );

		scope.visible = false;

		var currentRenderTarget = renderer.getRenderTarget();

		var currentVrEnabled = renderer.vr.enabled;
		var currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;

		renderer.vr.enabled = false; // Avoid camera modification and recursion
		renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows

		renderer.render( scene, mirrorCamera, renderTarget, true );

		renderer.vr.enabled = currentVrEnabled;
		renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;

		renderer.setRenderTarget( currentRenderTarget );

		// Restore viewport

		var bounds = camera.bounds;

		if ( bounds !== undefined ) {

			var size = renderer.getSize();
			var pixelRatio = renderer.getPixelRatio();

			viewport.x = bounds.x * size.width * pixelRatio;
			viewport.y = bounds.y * size.height * pixelRatio;
			viewport.z = bounds.z * size.width * pixelRatio;
			viewport.w = bounds.w * size.height * pixelRatio;

			renderer.state.viewport( viewport );

		}

		scope.visible = true;

	};

};

THREE.Mirror.prototype = Object.create( THREE.Mesh.prototype );
<|endoftext|>


<commit_before>var vObj = require('vjs-object')

var a = new vObj() //constructor always the same as a set???

//$define is just a normal wrapped defineProperty , w some added convience also has flavourize
a.$define({
  myboo: {
  	value:'mybooboo'
  }
})

a.bla = true

for(var key$ in a) {
  console.log(key$)
}

console.log( 'hey!', a )

<commit_msg>its pretty broken still but fixed some player shit time:1:00 https://github.com/vigour-io/fake-mtv-play/issues/1<commit_after>var vObj = require('vjs-object')

var a = new vObj() //constructor always the same as a set???

//$define is just a normal wrapped defineProperty , w some added convience also has flavourize
a.$define({
  myboo: {
  	value:'mybooboo'
  }
})

a.bla = true

for(var key$ in a) {
  console.log(key$)
}

console.log( 'hey!', a )

<|endoftext|>


<commit_before>jQuery(document).ready(function() {
    jQuery('body').midgardCreate({
        url: function() {
            if (this.id) {
                return vie_phpcr_path + this.id.substring(1, this.id.length - 1);
            }
            return vie_phpcr_path;
        },
        stanbolUrl: vie_stanbol_url,
        tags: true
    });

    jQuery('body').midgardCreate('configureEditor', 'title', 'halloWidget', {
        plugins: {
            'hallooverlay': {},
            'hallotoolbarlinebreak': {},
            'halloindicator': {}
        },
        floating: false,
        fixed: true,
        parentElement: "body",
        showAlways: true
    });
    jQuery('body').midgardCreate('configureEditor', 'default', 'halloWidget', {
        plugins: {
            'halloimage': {
                search: function (query, limit, offset, successCallback) {
                    limit = limit || 8;
                    offset = offset || 0;
                    jQuery.ajax({
                        type: "GET",
                        url: vie_plugins_image_search,
                        data: "query="+query+"&offset="+offset+"&limit="+limit,
                        success: successCallback
                    });
                },
                // suggestions: function(tags, limit, offset, successCallback) {
                //     limit = limit || 8;
                //     offset = offset || 0;
                //     return jQuery.ajax({
                //         type: "GET",
                //         url: "/app_dev.php/liip/vie/assets/list/",
                //         data: "tags=" + tags + "&offset=" + offset + "&limit=" + limit,
                //         success: successCallback
                //     });
                // },
                uploadUrl: hallo_image_upload,
                'vie': this.vie
            },
            'hallolink': { 'relatedUrl': vie_plugins_link_related_path },
            'halloformat': {'formattings': {'strikeThrough': false, 'underline': false}},
            'halloblock': {},
            'hallolists': {'lists': {'ordered': false}},
            'hallojustify': {},
            'hallotoolbarlinebreak': { 'breakAfter': ['hallolink'] },
            'hallooverlay': {},
            'halloindicator': {}
        },
        floating: false,
        fixed: true,
        parentElement: "body",
        showAlways: true
    });

    jQuery('body').midgardCreate('setEditorForProperty', 'dcterms:title', 'title');
    jQuery('body').midgardCreate('setEditorForProperty', 'default', 'default');
});
<commit_msg>adding todo<commit_after>jQuery(document).ready(function() {
    jQuery('body').midgardCreate({
        url: function() {
            if (this.id) {
                return vie_phpcr_path + this.id.substring(1, this.id.length - 1);
            }
            return vie_phpcr_path;
        },
        stanbolUrl: vie_stanbol_url,
        tags: true
    });

    jQuery('body').midgardCreate('configureEditor', 'title', 'halloWidget', {
        plugins: {
            'hallooverlay': {},
            'hallotoolbarlinebreak': {},
            'halloindicator': {}
        },
        floating: false,
        fixed: true,
        parentElement: "body",
        showAlways: true
    });
    jQuery('body').midgardCreate('configureEditor', 'default', 'halloWidget', {
        plugins: {
            'halloimage': {
                search: function (query, limit, offset, successCallback) {
                    limit = limit || 8;
                    offset = offset || 0;
                    jQuery.ajax({
                        type: "GET",
                        url: vie_plugins_image_search,
                        data: "query="+query+"&offset="+offset+"&limit="+limit,
                        success: successCallback
                    });
                },
                // TODO: this only brings an empty suggestions tab instead of calling the function
                // suggestions: function(tags, limit, offset, successCallback) {
                //     limit = limit || 8;
                //     offset = offset || 0;
                //     return jQuery.ajax({
                //         type: "GET",
                //         url: "/app_dev.php/liip/vie/assets/list/",
                //         data: "tags=" + tags + "&offset=" + offset + "&limit=" + limit,
                //         success: successCallback
                //     });
                // },
                uploadUrl: hallo_image_upload,
                'vie': this.vie
            },
            'hallolink': { 'relatedUrl': vie_plugins_link_related_path },
            'halloformat': {'formattings': {'strikeThrough': false, 'underline': false}},
            'halloblock': {},
            'hallolists': {'lists': {'ordered': false}},
            'hallojustify': {},
            'hallotoolbarlinebreak': { 'breakAfter': ['hallolink'] },
            'hallooverlay': {},
            'halloindicator': {}
        },
        floating: false,
        fixed: true,
        parentElement: "body",
        showAlways: true
    });

    jQuery('body').midgardCreate('setEditorForProperty', 'dcterms:title', 'title');
    jQuery('body').midgardCreate('setEditorForProperty', 'default', 'default');
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014 by Center Open Middleware. All Rights Reserved.
 * Titanium Appcelerator 3.3.0GA
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 *
 */

"use strict";

var instanceManagerView = function (parentWindow, logo, systemLabel, formCallback) {
	var theme = require('ui/style/instanceManagerViewStyle');
	 /* TODO: Change Style names */

	var confView, confViewTitle,
		confInstanceContainer, confInstanceContainerTitle,
		confInstanceMainView, confInstanceListView;

	var createConfiguration = function createConfiguration() {
		/* Create the main configuration view */
		confView = Ti.UI.createView(theme.view);
		confViewTitle = Ti.UI.createLabel(theme.configurationFormTitle);
		confView.add(confViewTitle);

		/* Create a Instance Container View */
		confInstanceContainer = Ti.UI.createView(Yaast.MergeObject(theme.containerView, {
			/* This should be in 'instanceManagerViewStyle' */
			width: parentWindow.getWidth() * 0.9,
			left: '5%',
			height: parentWindow.getHeight() * 0.7,
			bottom: '10%'
			/* TODO: What append if there is a virtual navigationBar, bottom: '5%' doesn't work */
		}));
		confInstanceContainerTitle = Ti.UI.createLabel(theme.instanceTitle);
		confInstanceContainer.add(confInstanceContainerTitle);
		confView.add(confInstanceContainer);

		/* Create Instaces Main View */
		confInstanceMainView = Ti.UI.createView(theme.connectionView);
		confInstanceContainer.add(confInstanceMainView);

		/* Create Instances List View */
		confInstanceListView = Ti.UI.createListView();
		confInstanceMainView.add(confInstanceListView);
		var section = []; /* Array of sections */
		/* Private Instances Section */
		var privateSection = Ti.UI.createListSection();
		var headerPrivate = Ti.UI.createView(theme.headerView);
		/* TODO: Adds '+' button to create new instance */
		headerPrivate.add(Ti.UI.createLabel(Yaast.MergeObject(theme.headerViewLabel, {
			text: 'Private'
		})));
		privateSection.setHeaderView(headerPrivate);
		section.push(privateSection);
		/* Public Instances Section */
		var publicSection = Ti.UI.createListSection();
		var headerPublic = Ti.UI.createView(theme.headerView);
		headerPublic.add(Ti.UI.createLabel(Yaast.MergeObject(theme.headerViewLabel, {
			text: 'Public'
		})));
		publicSection.setHeaderView(headerPublic);
		section.push(publicSection),
		/* Apply sections */
		confInstanceListView.sections = section;

		/* Adding to parent window */
		parentWindow.add(confView);
	};

	var _self = {};
	createConfiguration();
	return _self;
};

module.exports = instanceManagerView;
<commit_msg>Add elements to private list<commit_after>/**
 * Copyright (c) 2014 by Center Open Middleware. All Rights Reserved.
 * Titanium Appcelerator 3.3.0GA
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 *
 */

"use strict";

var instanceManagerView = function (parentWindow, logo, systemLabel, formCallback) {
	var theme = require('ui/style/instanceManagerViewStyle');
	 /* TODO: Change Style names */

	var confView, confViewTitle,
		confInstanceContainer, confInstanceContainerTitle,
		confInstanceMainView, confInstanceListView;

	var createConfiguration = function createConfiguration() {
		/* Create the main configuration view */
		confView = Ti.UI.createView(theme.view);
		confViewTitle = Ti.UI.createLabel(theme.configurationFormTitle);
		confView.add(confViewTitle);

		/* Create a Instance Container View */
		confInstanceContainer = Ti.UI.createView(Yaast.MergeObject(theme.containerView, {
			/* This should be in 'instanceManagerViewStyle' */
			width: parentWindow.getWidth() * 0.9,
			left: '5%',
			height: parentWindow.getHeight() * 0.7,
			bottom: '10%'
			/* TODO: What append if there is a virtual navigationBar, bottom: '5%' doesn't work */
		}));
		confInstanceContainerTitle = Ti.UI.createLabel(theme.instanceTitle);
		confInstanceContainer.add(confInstanceContainerTitle);
		confView.add(confInstanceContainer);

		/* Create Instaces Main View */
		confInstanceMainView = Ti.UI.createView(theme.connectionView);
		confInstanceContainer.add(confInstanceMainView);

		/* Create Instances List View */
		confInstanceListView = Ti.UI.createListView({
			templates: { /* Define diferentes style templates for items in the list view */
				'template' : theme.connectionListViewTemplate,
				'template_connected' : theme.connectionListViewTemplateConected  /* change for ...Connected */
			},
			defaultItemTemplate: 'template'
		});
		confInstanceMainView.add(confInstanceListView);
		var section = []; /* Array of sections */
		/* Private Instances Section */
		var privateSection = Ti.UI.createListSection();
		var headerPrivate = Ti.UI.createView(theme.headerView);
		/* TODO: Adds '+' button to create new instance */
		headerPrivate.add(Ti.UI.createLabel(Yaast.MergeObject(theme.headerViewLabel, {
			text: 'Private'
		})));
		privateSection.setHeaderView(headerPrivate);
		/* Add predefine instances */
		privateSection.setItems([
			/* TODO: Load info from archive or db */
			{ template: 'template', connection: {text: 'Wirecloud CoNWeT'}, url: {text: 'https://wirecloud.conwet.fi.upm.es/'}, id: {text: '1'} },
		]);
		section.push(privateSection);
		/* Public Instances Section */
		var publicSection = Ti.UI.createListSection();
		var headerPublic = Ti.UI.createView(theme.headerView);
		headerPublic.add(Ti.UI.createLabel(Yaast.MergeObject(theme.headerViewLabel, {
			text: 'Public'
		})));
		publicSection.setHeaderView(headerPublic);
		section.push(publicSection),
		/* Apply sections */
		confInstanceListView.sections = section;

		/* Adding to parent window */
		parentWindow.add(confView);
	};

	var _self = {};
	createConfiguration();
	return _self;
};

module.exports = instanceManagerView;
<|endoftext|>