<commit_before>/*************************************************
 * Copyright (c) 2015 Ansible, Inc.
 *
 * All Rights Reserved
 *************************************************/

import inventoryAdd from './add/main';
import inventoryEdit from './edit/main';
import inventoryList from './list/main';
import inventoryManage from './manage/main';
import inventoryManageListRoute from './manage/inventory-manage.route';
import { copyMoveGroupRoute, copyMoveHostRoute } from './manage/copy-move/copy-move.route';
import adHocRoute from './manage/adhoc/adhoc.route';
import { templateUrl } from '../shared/template-url/template-url.factory';
export default
angular.module('inventory', [
        inventoryAdd.name,
        inventoryEdit.name,
        inventoryList.name,
        inventoryManage.name,
    ])
    .config(['$stateProvider', '$stateExtenderProvider', 'stateDefinitionsProvider',
        function($stateProvider, $stateExtenderProvider, stateDefinitionsProvider) {
            // When stateDefinition.lazyLoad() resolves, states matching name.** or /url** will be de-registered and replaced with resolved states
            // This means inventoryManage states will not be registered correctly on page refresh, unless they're registered at the same time as the inventories state tree
            let stateTree, inventories,
                addGroup, editGroup, addHost, editHost,
                listSchedules, addSchedule, editSchedule, adhocCredentialLookup,
                stateDefinitions = stateDefinitionsProvider.$get(),
                stateExtender = $stateExtenderProvider.$get();

            function generateStateTree() {

                // inventories state node
                inventories = stateDefinitions.generateTree({
                    parent: 'inventories', // top-most node in the generated tree (will replace this state definition)
                    modes: ['add', 'edit'],
                    list: 'InventoryList',
                    form: 'InventoryForm',
                    controllers: {
                        list: 'InventoryListController',
                        add: 'InventoryAddController',
                        edit: 'InventoryEditController'
                    },
                    data: {
                        activityStream: true,
                        activityStreamTarget: 'inventory'
                    }
                });

                // scheduler state nodes
                listSchedules = {
                    name: 'inventoryManage.editGroup.schedules',
                    url: '/schedules',
                    searchPrefix: 'schedule',
                    ncyBreadcrumb: {
                        parent: 'inventoryManage.editGroup({group_id: parentObject.id})',
                        label: 'SCHEDULES'
                    },
                    resolve: {
                        Dataset: ['SchedulesList', 'QuerySet', '$stateParams', 'GetBasePath', 'groupData',
                            function(list, qs, $stateParams, GetBasePath, groupData) {
                                let path = `${groupData.related.inventory_source}schedules`;
                                return qs.search(path, $stateParams[`${list.iterator}_search`]);
                            }
                        ],
                        ParentObject: ['groupData', function(groupData) {
                            return groupData;
                        }]
                    },
                    views: {
                        // clear form template when views render in this substate
                        'form': {
                            templateProvider: () => ''
                        },
                        // target the un-named ui-view @ root level
                        '@': {
                            templateProvider: function(SchedulesList, generateList, ParentObject) {
                                // include name of parent resource in listTitle
                                SchedulesList.listTitle = `${ParentObject.name}<div class='List-titleLockup'></div>Schedules`;
                                let html = generateList.build({
                                    list: SchedulesList,
                                    mode: 'edit'
                                });
                                html = generateList.wrapPanel(html);
                                return generateList.insertFormView() + html;
                            },
                            controller: 'schedulerListController'
                        }
                    }
                };

                addSchedule = {
                    name: 'inventoryManage.editGroup.schedules.add',
                    url: '/add',
                    ncyBreadcrumb: {
                        label: "CREATE SCHEDULE"
                    },
                    views: {
                        'form': {
                            controller: 'schedulerAddController',
                            templateUrl: templateUrl("scheduler/schedulerForm")
                        }
                    }
                };

                editSchedule = {
                    name: 'inventoryManage.editGroup.schedules.edit',
                    url: '/:schedule_id',
                    ncyBreadcrumb: {
                        label: "{{schedule_obj.name}}"
                    },
                    views: {
                        'form': {
                            templateUrl: templateUrl("scheduler/schedulerForm"),
                            controller: 'schedulerEditController',
                        }
                    }
                };

                // group state nodes
                addGroup = stateDefinitions.generateTree({
                    url: '/add-group',
                    name: 'inventoryManage.addGroup',
                    modes: ['add'],
                    form: 'GroupForm',
                    controllers: {
                        add: 'GroupAddController'
                    }
                });

                editGroup = stateDefinitions.generateTree({
                    url: '/edit-group/:group_id',
                    name: 'inventoryManage.editGroup',
                    modes: ['edit'],
                    form: 'GroupForm',
                    controllers: {
                        edit: 'GroupEditController'
                    },
                    resolve: {
                        edit: {
                            groupData: ['$stateParams', 'GroupManageService', function($stateParams, GroupManageService) {
                                return GroupManageService.get({ id: $stateParams.group_id }).then(res => res.data.results[0]);
                            }],
                            inventorySourceData: ['$stateParams', 'GroupManageService', function($stateParams, GroupManageService) {
                                return GroupManageService.getInventorySource({ group: $stateParams.group_id }).then(res => res.data.results[0]);
                            }]
                        }
                    },
                    // concat boilerplate schedule state definitions with generated editGroup state definitions
                }).then((generated) => {
                    let schedulerDefinitions = _.map([
                            stateExtender.buildDefinition(listSchedules),
                            stateExtender.buildDefinition(addSchedule),
                            stateExtender.buildDefinition(editSchedule)
                        ],
                        (state) => stateExtender.buildDefinition(state));
                    return {
                        states: _(generated.states)
                            .concat(schedulerDefinitions)
                            .value()
                    };
                });

                // host state nodes
                addHost = stateDefinitions.generateTree({
                    url: '/add-host',
                    name: 'inventoryManage.addHost',
                    modes: ['add'],
                    form: 'HostForm',
                    controllers: {
                        add: 'HostsAddController'
                    }
                });

                editHost = stateDefinitions.generateTree({
                    url: '/edit-host/:host_id',
                    name: 'inventoryManage.editHost',
                    modes: ['edit'],
                    form: 'HostForm',
                    controllers: {
                        edit: 'HostEditController'
                    },
                    resolve: {
                        edit: {
                            host: ['$stateParams', 'HostManageService', function($stateParams, HostManageService) {
                                return HostManageService.get({ id: $stateParams.host_id }).then(function(res) {
                                    return res.data.results[0];
                                });
                            }]
                        }
                    },
                    ncyBreadcrumb: {
                        label: "{{host.name}}",
                    },
                });

                adhocCredentialLookup = {
                    searchPrefix: 'credential',
                    name: 'inventoryManage.adhoc.credential',
                    url: '/credential',
                    data: {
                        formChildState: true
                    },
                    params: {
                        credential_search: {
                            value: {
                                page_size: '5'
                            },
                            squash: true,
                            dynamic: true
                        }
                    },
                    ncyBreadcrumb: {
                        skip: true
                    },
                    views: {
                        'related': {
                            templateProvider: function(ListDefinition, generateList) {
                                let list_html = generateList.build({
                                    mode: 'lookup',
                                    list: ListDefinition,
                                    input_type: 'radio'
                                });
                                return `<lookup-modal>${list_html}</lookup-modal>`;

                            }
                        }
                    },
                    resolve: {
                        ListDefinition: ['CredentialList', function(CredentialList) {
                            let list = _.cloneDeep(CredentialList);
                            list.lookupConfirmText = 'SELECT';
                            return list;
                        }],
                        Dataset: ['ListDefinition', 'QuerySet', '$stateParams', 'GetBasePath',
                            (list, qs, $stateParams, GetBasePath) => {
                                let path = GetBasePath(list.name) || GetBasePath(list.basePath);
                                return qs.search(path, $stateParams[`${list.iterator}_search`]);
                            }
                        ]
                    },
                    onExit: function($state) {
                        if ($state.transition) {
                            $('#form-modal').modal('hide');
                            $('.modal-backdrop').remove();
                            $('body').removeClass('modal-open');
                        }
                    },
                };

                return Promise.all([
                    inventories,
                    addGroup,
                    editGroup,
                    addHost,
                    editHost,
                ]).then((generated) => {
                    return {
                        states: _.reduce(generated, (result, definition) => {
                            return result.concat(definition.states);
                        }, [
                            stateExtender.buildDefinition(inventoryManageListRoute),
                            stateExtender.buildDefinition(copyMoveGroupRoute),
                            stateExtender.buildDefinition(copyMoveHostRoute),
                            stateExtender.buildDefinition(adHocRoute),
                            stateExtender.buildDefinition(adhocCredentialLookup)

                        ])
                    };
                });
            }

            stateTree = {
                name: 'inventories',
                url: '/inventories',
                lazyLoad: () => generateStateTree()
            };

            $stateProvider.state(stateTree);
        }
    ]);
<commit_msg>Fixed resolve in route<commit_after>/*************************************************
 * Copyright (c) 2015 Ansible, Inc.
 *
 * All Rights Reserved
 *************************************************/

import inventoryAdd from './add/main';
import inventoryEdit from './edit/main';
import inventoryList from './list/main';
import inventoryManage from './manage/main';
import inventoryManageListRoute from './manage/inventory-manage.route';
import { copyMoveGroupRoute, copyMoveHostRoute } from './manage/copy-move/copy-move.route';
import adHocRoute from './manage/adhoc/adhoc.route';
import { templateUrl } from '../shared/template-url/template-url.factory';
export default
angular.module('inventory', [
        inventoryAdd.name,
        inventoryEdit.name,
        inventoryList.name,
        inventoryManage.name,
    ])
    .config(['$stateProvider', '$stateExtenderProvider', 'stateDefinitionsProvider',
        function($stateProvider, $stateExtenderProvider, stateDefinitionsProvider) {
            // When stateDefinition.lazyLoad() resolves, states matching name.** or /url** will be de-registered and replaced with resolved states
            // This means inventoryManage states will not be registered correctly on page refresh, unless they're registered at the same time as the inventories state tree
            let stateTree, inventories,
                addGroup, editGroup, addHost, editHost,
                listSchedules, addSchedule, editSchedule, adhocCredentialLookup,
                stateDefinitions = stateDefinitionsProvider.$get(),
                stateExtender = $stateExtenderProvider.$get();

            function generateStateTree() {

                // inventories state node
                inventories = stateDefinitions.generateTree({
                    parent: 'inventories', // top-most node in the generated tree (will replace this state definition)
                    modes: ['add', 'edit'],
                    list: 'InventoryList',
                    form: 'InventoryForm',
                    controllers: {
                        list: 'InventoryListController',
                        add: 'InventoryAddController',
                        edit: 'InventoryEditController'
                    },
                    data: {
                        activityStream: true,
                        activityStreamTarget: 'inventory'
                    }
                });

                // scheduler state nodes
                listSchedules = {
                    name: 'inventoryManage.editGroup.schedules',
                    url: '/schedules',
                    searchPrefix: 'schedule',
                    ncyBreadcrumb: {
                        parent: 'inventoryManage.editGroup({group_id: parentObject.id})',
                        label: 'SCHEDULES'
                    },
                    resolve: {
                        Dataset: ['SchedulesList', 'QuerySet', '$stateParams', 'GetBasePath', 'groupData',
                            function(list, qs, $stateParams, GetBasePath, groupData) {
                                let path = `${groupData.related.inventory_source}schedules`;
                                return qs.search(path, $stateParams[`${list.iterator}_search`]);
                            }
                        ],
                        ParentObject: ['groupData', function(groupData) {
                            return groupData;
                        }],
                        UnifiedJobsOptions: ['Rest', 'GetBasePath', '$stateParams', '$q',
                            function(Rest, GetBasePath, $stateParams, $q) {
                                Rest.setUrl(GetBasePath('unified_jobs'));
                                var val = $q.defer();
                                Rest.options()
                                    .then(function(data) {
                                        val.resolve(data.data);
                                    }, function(data) {
                                        val.reject(data);
                                    });
                                return val.promise;
                            }]
                    },
                    views: {
                        // clear form template when views render in this substate
                        'form': {
                            templateProvider: () => ''
                        },
                        // target the un-named ui-view @ root level
                        '@': {
                            templateProvider: function(SchedulesList, generateList, ParentObject) {
                                // include name of parent resource in listTitle
                                SchedulesList.listTitle = `${ParentObject.name}<div class='List-titleLockup'></div>Schedules`;
                                let html = generateList.build({
                                    list: SchedulesList,
                                    mode: 'edit'
                                });
                                html = generateList.wrapPanel(html);
                                return generateList.insertFormView() + html;
                            },
                            controller: 'schedulerListController'
                        }
                    }
                };

                addSchedule = {
                    name: 'inventoryManage.editGroup.schedules.add',
                    url: '/add',
                    ncyBreadcrumb: {
                        label: "CREATE SCHEDULE"
                    },
                    views: {
                        'form': {
                            controller: 'schedulerAddController',
                            templateUrl: templateUrl("scheduler/schedulerForm")
                        }
                    }
                };

                editSchedule = {
                    name: 'inventoryManage.editGroup.schedules.edit',
                    url: '/:schedule_id',
                    ncyBreadcrumb: {
                        label: "{{schedule_obj.name}}"
                    },
                    views: {
                        'form': {
                            templateUrl: templateUrl("scheduler/schedulerForm"),
                            controller: 'schedulerEditController',
                        }
                    }
                };

                // group state nodes
                addGroup = stateDefinitions.generateTree({
                    url: '/add-group',
                    name: 'inventoryManage.addGroup',
                    modes: ['add'],
                    form: 'GroupForm',
                    controllers: {
                        add: 'GroupAddController'
                    }
                });

                editGroup = stateDefinitions.generateTree({
                    url: '/edit-group/:group_id',
                    name: 'inventoryManage.editGroup',
                    modes: ['edit'],
                    form: 'GroupForm',
                    controllers: {
                        edit: 'GroupEditController'
                    },
                    resolve: {
                        edit: {
                            groupData: ['$stateParams', 'GroupManageService', function($stateParams, GroupManageService) {
                                return GroupManageService.get({ id: $stateParams.group_id }).then(res => res.data.results[0]);
                            }],
                            inventorySourceData: ['$stateParams', 'GroupManageService', function($stateParams, GroupManageService) {
                                return GroupManageService.getInventorySource({ group: $stateParams.group_id }).then(res => res.data.results[0]);
                            }]
                        }
                    },
                    // concat boilerplate schedule state definitions with generated editGroup state definitions
                }).then((generated) => {
                    let schedulerDefinitions = _.map([
                            stateExtender.buildDefinition(listSchedules),
                            stateExtender.buildDefinition(addSchedule),
                            stateExtender.buildDefinition(editSchedule)
                        ],
                        (state) => stateExtender.buildDefinition(state));
                    return {
                        states: _(generated.states)
                            .concat(schedulerDefinitions)
                            .value()
                    };
                });

                // host state nodes
                addHost = stateDefinitions.generateTree({
                    url: '/add-host',
                    name: 'inventoryManage.addHost',
                    modes: ['add'],
                    form: 'HostForm',
                    controllers: {
                        add: 'HostsAddController'
                    }
                });

                editHost = stateDefinitions.generateTree({
                    url: '/edit-host/:host_id',
                    name: 'inventoryManage.editHost',
                    modes: ['edit'],
                    form: 'HostForm',
                    controllers: {
                        edit: 'HostEditController'
                    },
                    resolve: {
                        edit: {
                            host: ['$stateParams', 'HostManageService', function($stateParams, HostManageService) {
                                return HostManageService.get({ id: $stateParams.host_id }).then(function(res) {
                                    return res.data.results[0];
                                });
                            }]
                        }
                    },
                    ncyBreadcrumb: {
                        label: "{{host.name}}",
                    },
                });

                adhocCredentialLookup = {
                    searchPrefix: 'credential',
                    name: 'inventoryManage.adhoc.credential',
                    url: '/credential',
                    data: {
                        formChildState: true
                    },
                    params: {
                        credential_search: {
                            value: {
                                page_size: '5'
                            },
                            squash: true,
                            dynamic: true
                        }
                    },
                    ncyBreadcrumb: {
                        skip: true
                    },
                    views: {
                        'related': {
                            templateProvider: function(ListDefinition, generateList) {
                                let list_html = generateList.build({
                                    mode: 'lookup',
                                    list: ListDefinition,
                                    input_type: 'radio'
                                });
                                return `<lookup-modal>${list_html}</lookup-modal>`;

                            }
                        }
                    },
                    resolve: {
                        ListDefinition: ['CredentialList', function(CredentialList) {
                            let list = _.cloneDeep(CredentialList);
                            list.lookupConfirmText = 'SELECT';
                            return list;
                        }],
                        Dataset: ['ListDefinition', 'QuerySet', '$stateParams', 'GetBasePath',
                            (list, qs, $stateParams, GetBasePath) => {
                                let path = GetBasePath(list.name) || GetBasePath(list.basePath);
                                return qs.search(path, $stateParams[`${list.iterator}_search`]);
                            }
                        ]
                    },
                    onExit: function($state) {
                        if ($state.transition) {
                            $('#form-modal').modal('hide');
                            $('.modal-backdrop').remove();
                            $('body').removeClass('modal-open');
                        }
                    },
                };

                return Promise.all([
                    inventories,
                    addGroup,
                    editGroup,
                    addHost,
                    editHost,
                ]).then((generated) => {
                    return {
                        states: _.reduce(generated, (result, definition) => {
                            return result.concat(definition.states);
                        }, [
                            stateExtender.buildDefinition(inventoryManageListRoute),
                            stateExtender.buildDefinition(copyMoveGroupRoute),
                            stateExtender.buildDefinition(copyMoveHostRoute),
                            stateExtender.buildDefinition(adHocRoute),
                            stateExtender.buildDefinition(adhocCredentialLookup)

                        ])
                    };
                });
            }

            stateTree = {
                name: 'inventories',
                url: '/inventories',
                lazyLoad: () => generateStateTree()
            };

            $stateProvider.state(stateTree);
        }
    ]);
<|endoftext|>


<commit_before>import React from 'react'
import {StyleSheet, Text as RNText} from 'react-native'

import * as Colors from './PyColors'

export function Text ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, style]} {...props} />
}

export function Heading1 ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.h1, style]} {...props} />
}

export function Heading2 ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.h2, style]} {...props} />
}

export function Heading3 ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.h3, style]} {...props} />
}

export function Heading4 ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.h4, style]} {...props} />
}

export function Heading5 ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.h5, style]} {...props} />
}

export function Paragraph ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.p, style]} {...props} />
}

export function SmallText ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.small, style]} {...props} />
}

export function LargeText ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.large, style]} {...props} />
}

function getHeadingStyles ({prefix = 'heading', otherStyles}) {
  const styles = {}
  ;[1, 2, 3, 4, 5, 6].forEach(i => {
    const fontSize = 28 - 2 * i
    const lineHeight = Math.round(fontSize * 1.375)
    const fontWeight = 'bold'
    styles[`${prefix}${i}`] = {fontSize, lineHeight, fontWeight, ...otherStyles}
  })
  return styles
}

const headingStyles = getHeadingStyles({prefix: 'h'})

const styles = StyleSheet.create({
  ...headingStyles,
  font: {
    color: Colors.DARK_TEXT
  },
  p: {
    fontSize: 15,
    lineHeight: 24
  },
  small: {
    fontSize: 12,
    lineHeight: 17
  },
  large: {
    fontSize: 18
  }
})
<commit_msg>fix: normalize font-size<commit_after>import React from 'react'
import {Dimensions, StyleSheet, Text as RNText} from 'react-native'

import * as Colors from './PyColors'

export function Text ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, style]} {...props} />
}

export function Heading1 ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.h1, style]} {...props} />
}

export function Heading2 ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.h2, style]} {...props} />
}

export function Heading3 ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.h3, style]} {...props} />
}

export function Heading4 ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.h4, style]} {...props} />
}

export function Heading5 ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.h5, style]} {...props} />
}

export function Paragraph ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.p, style]} {...props} />
}

export function SmallText ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.small, style]} {...props} />
}

export function LargeText ({style, ...props}) { // eslint-disable-line
  return <RNText style={[styles.font, styles.large, style]} {...props} />
}

const scale = Dimensions.get('window').width / 375

function normalize (size) {
  return Math.round(scale * size)
}

function getHeadingStyles ({prefix = 'heading', otherStyles}) {
  const styles = {}
  ;[1, 2, 3, 4, 5, 6].forEach(i => {
    const fontSize = normalize(28 - 2 * i)
    const lineHeight = Math.round(fontSize * 1.375)
    const fontWeight = 'bold'
    styles[`${prefix}${i}`] = {fontSize, lineHeight, fontWeight, ...otherStyles}
  })
  return styles
}

const headingStyles = getHeadingStyles({prefix: 'h'})

const styles = StyleSheet.create({
  ...headingStyles,
  font: {
    color: Colors.DARK_TEXT
  },
  p: {
    fontSize: normalize(15),
    lineHeight: normalize(24)
  },
  small: {
    fontSize: normalize(12),
    lineHeight: normalize(17)
  },
  large: {
    fontSize: normalize(18),
    lineHeight: normalize(25)
  }
})
<|endoftext|>


<commit_before>
// Setup depends on: -
// Runtime depends on: console.js, helpers.js

// API:
// st.communication.send(data, handlerId)
// st.communication.sendForked(data, handlerId)
// st.communication.addMessageHandler(string, function)
// st.communication.getMessageHandler(string)

// (st.setup_session_id(int) can be called only once)

// Settings:
// st.communication.MESSAGE_PATH (string)

(function() {

	// Set up the namespace
	if (!window.st) window.st = {};
	var home = st.communication ? st.communication : (st.communication = {});

	//
	// Settings
	//

	if (!("MESSAGE_PATH" in home)) home.MESSAGE_PATH = "message";

	//
	// Local variables
	//

	var messageHandlers = [];
	var session_id = -1;

	//
	// API functions
	//

	home.send = function(data, handlerId) {
		awaitedAnswers++;
		return doSend(data, true, "blocked", handlerId);
	};

	home.sendForked = function(data, handlerId) {
		// No meaningfull result-value when sending forked
		awaitedAnswers++;
		doSend(data, false, "forked", handlerId, true);
		return null;
	};

	home.addMessageHandler = function(handlerId, handlerFunction) {
		messageHandlers[handlerId] = handlerFunction;
	};

	home.getMessageHandler = function(handlerId) {
		return messageHandlers[handlerId];
	}

	home.setup_session_id = function(id) {
		// Allow calling this function only once - delete after usage
		delete home.setup_session_id;
		st.console.log("This session-id is " + id);
		session_id = id;
		openLongPoll(); // Open the connection initially
	};

	//
	// Private functions
	//

	// Set up default handler
	home.addMessageHandler("default",
		function(messageString) { st.console.log("Received unhandled message: " + messageString); });
	home.addMessageHandler("code",
		function(messageString) { return st.globalEval(messageString); });

	// Use the configured message-handler to evaluate and log the content
	var handleMessage = function(content, handlerId) {
		var result;
		try {
			st.console.log("Received message to '" + handlerId + "': " + content);
			var handler = messageHandlers[handlerId];
			if (!handler) {
				// Use the default handler or do nothing by default
				handler = messageHandlers["default"];
			}
			if (handler)
				result = handler(content);
		} catch (e) {
			st.console.log("Error handling the content of a server-message: " + e + ".\r\n" +
			"Message was: " + content);
		}
		return result;
	};

	// Increased with every send and decreased with every received "answer"
	var awaitedAnswers = 0;

	var openLongPoll = function() {
		sendAndHandleResponse("", false, "longPoll", "default", function(request) {
			// If the server answeres the long-poll-request,
			// it must be renewed immediately to allow it to send more requests.
			// In addition to reopening the long-poll, the server-message is handled.
			// This handling could result in another connection being opened,
			// especially when the server-request was a blocking send and the client sends an answer.
			openLongPoll();
			return answerToMessage(request);
		});
	}

	var doSend = function(data, isSynchronous, status, handlerId, ignoreResponse) {
		return sendAndHandleResponse(data, isSynchronous, status, handlerId, ignoreResponse ? null : answerToMessage);
	}

	var sendAndHandleResponse = function(data, isSynchronous, status, handlerId, responseHandlerFunction) {
		if (session_id == -1) {
			throw "Session-ID has not been set up yet! Cannot send.";
		}
		var url = st.fullURL(home.MESSAGE_PATH) + "?id=" + session_id;

		var request = st.createRequest();
		var content = "status=" + st.escapeAll(status);
		content += "&message=" + st.escapeAll(data);
		content += "&handlerId=" + st.escapeAll(handlerId ? handlerId : "default");
		if (responseHandlerFunction && !isSynchronous)
			request.onreadystatechange = function() { responseHandlerFunction(request); };
		request.open("POST", url, !isSynchronous);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		st.console.log("Sending (synchronous: " +isSynchronous + ", awaited answers: " + awaitedAnswers + ") " + status + " to " + handlerId + ": " + data);
		request.send(content);
		if (responseHandlerFunction && isSynchronous)
			return responseHandlerFunction(request);
		return request.responseText;
	}

	// Answering a message can recursively cause doing more sends
	// (either by sending the answer or from inside a message handler)
	// The execution stack will preserve the info, where to return after all the sends
	var answerToMessage = function(request) {
		if (request.readyState == 4) {
			if (request.status == 200) {
				var response = /status=([^&]*)&handlerId=([^&]*)&message=([^&]*)/.exec(request.responseText);
				if (response && response.length >= 2) {
					var status = unescape(response[1]);
					var handlerId = unescape(response[2]);
					var message = unescape(response[3]);
					if (status == "empty") {
						// do nothing. The server has answered to a request,
						// that has no meaningfull answer-semanitcs.
						// Mainly this happens in return to an answer sent from the client.
						return message;
					} else if (status == "answer") {
						// "answerTo: (answer)"
						console.log("Received answer: " + message);
						awaitedAnswers--;
						if (awaitedAnswers < 0) {
							awaitedAnswers = 0;
							st.console.log("Illegal state: Received more answers than sends!");
						}
						return message; // No new connection
					} else if (status == "blocked") {
						// "answerTo: (blocked)"
						var result = handleMessage(message, handlerId);
						if (awaitedAnswers > 0) {
							return doSend(result, true, "answer");
						} else {
							return doSend(result, false, "answer");
						}
					} else if (status == "forked") {
						// "answerTo: (forked)"
						if (awaitedAnswers > 0) {
							// Inside any blocking send from the client, a forked
							// send from the server becomes blocking, because we need
							// to keep the context on the client intact.
							handleMessage(message, handlerId); // Ignore result
							return doSend("", true, "answer");
						} else {
							var result = doSend("", false , "answer");
							handleMessage(message, handlerId); // Ignore result
							return result;
						}
					}
				}
				st.console.log("Illegal message received from the server: " + request.responseText);
			} else if (request.status == 299) { // Server-request to reconnect (timeout), not 408 since that's displayed as error in chrome
				st.console.statusInfo("Server-timeout, reconnecting. (Opening server-send connection)", 229);
				// TODO Server needs to send info, which kind of connection is timed out (synchronous or not)
				// re-open same kind of connection here
				doSend("", false, "forked");
			} else {
				st.console.statusInfo("Channel disconnected: " + request.responseText, request.status);
			}
		}
	}

})();
<commit_msg>fixing the communication-management.<commit_after>
// Setup depends on: -
// Runtime depends on: console.js, helpers.js

// API:
// st.communication.send(data, handlerId)
// st.communication.sendForked(data, handlerId)
// st.communication.addMessageHandler(string, function)
// st.communication.getMessageHandler(string)

// (st.setup_session_id(int) can be called only once)

// Settings:
// st.communication.MESSAGE_PATH (string)

(function() {

	// Set up the namespace
	if (!window.st) window.st = {};
	var home = st.communication ? st.communication : (st.communication = {});

	//
	// Settings
	//

	if (!("MESSAGE_PATH" in home)) home.MESSAGE_PATH = "message";

	//
	// Local variables
	//

	var messageHandlers = [];
	var session_id = -1;

	//
	// API functions
	//

	home.send = function(data, handlerId) {
		awaitedAnswers++;
		return doSend(data, true, "blocked", handlerId);
	};

	home.sendForked = function(data, handlerId) {
		// No meaningfull result-value when sending forked
		awaitedAnswers++;
		doSend(data, false, "forked", handlerId, true);
		return null;
	};

	home.addMessageHandler = function(handlerId, handlerFunction) {
		messageHandlers[handlerId] = handlerFunction;
	};

	home.getMessageHandler = function(handlerId) {
		return messageHandlers[handlerId];
	}

	home.setup_session_id = function(id) {
		// Allow calling this function only once - delete after usage
		delete home.setup_session_id;
		st.console.log("This session-id is " + id);
		session_id = id;
		openLongPoll(); // Open the connection initially
	};

	//
	// Private functions
	//

	// Set up default handler
	home.addMessageHandler("default",
		function(messageString) { st.console.log("Received unhandled message: " + messageString); });
	home.addMessageHandler("code",
		function(messageString) { return st.globalEval(messageString); });

	// Use the configured message-handler to evaluate and log the content
	var handleMessage = function(content, handlerId) {
		var result;
		try {
			st.console.log("Received message to '" + handlerId + "': " + content);
			var handler = messageHandlers[handlerId];
			if (!handler) {
				// Use the default handler or do nothing by default
				handler = messageHandlers["default"];
			}
			if (handler)
				result = handler(content);
		} catch (e) {
			st.console.log("Error handling the content of a server-message: " + e + ".\r\n" +
			"Message was: " + content);
		}
		return result;
	};

	// Increased with every send and decreased with every received "answer"
	var awaitedAnswers = 0;

	var openLongPoll = function() {
		sendAndHandleResponse("", false, "longPoll", "default", function(request) {
			// If the server answeres the long-poll-request,
			// it must be renewed immediately to allow it to send more requests.
			// In addition to reopening the long-poll, the server-message is handled.
			// This handling could result in another connection being opened,
			// especially when the server-request was a blocking send and the client sends an answer.
			openLongPoll();
			return answerToMessage(request);
		});
	}

	var doSend = function(data, isSynchronous, status, handlerId, ignoreResponse) {
		return sendAndHandleResponse(data, isSynchronous, status, handlerId, ignoreResponse ? null : answerToMessage);
	}

	var sendAndHandleResponse = function(data, isSynchronous, status, handlerId, responseHandlerFunction) {
		if (session_id == -1) {
			throw "Session-ID has not been set up yet! Cannot send.";
		}
		var url = st.fullURL(home.MESSAGE_PATH) + "?id=" + session_id;

		var request = st.createRequest();
		var content = "status=" + st.escapeAll(status);
		content += "&message=" + st.escapeAll(data);
		content += "&handlerId=" + st.escapeAll(handlerId ? handlerId : "default");
		if (responseHandlerFunction && !isSynchronous)
			request.onreadystatechange = function() { responseHandlerFunction(request); };
		request.open("POST", url, !isSynchronous);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		st.console.log("Sending (synchronous: " + isSynchronous + ", awaited answers: " + awaitedAnswers + ") " + status + " to " + handlerId + ": " + data);
		request.send(content);
		if (responseHandlerFunction && isSynchronous)
			return responseHandlerFunction(request);
		return request.responseText;
	}

	// Answering a message can recursively cause doing more sends
	// (either by sending the answer or from inside a message handler)
	// The execution stack will preserve the info, where to return after all the sends
	var answerToMessage = function(request) {
		if (request.readyState == 4) {
			if (request.status == 200) {
				var response = /status=([^&]*)&handlerId=([^&]*)&message=([^&]*)/.exec(request.responseText);
				if (response && response.length >= 2) {
					var status = unescape(response[1]);
					var handlerId = unescape(response[2]);
					var message = unescape(response[3]);
					if (status == "empty") {
						// do nothing. The server has answered to a request,
						// that has no meaningfull answer-semanitcs.
						// Mainly this happens in return to an answer sent from the client.
						return message;
					else if (status == "renewLongPoll") {
						// The long-poll-connection has timed out. Reopen it to show that we're still alive.
						openLongPoll();
					} else if (status == "answer") {
						// "answerTo: (answer)"
						console.log("Received answer: " + message);
						awaitedAnswers--;
						if (awaitedAnswers < 0) {
							awaitedAnswers = 0;
							st.console.log("Illegal state: Received more answers than sends!");
						}
						return message; // No new connection
					} else if (status == "blocked") {
						// "answerTo: (blocked)"
						var result = handleMessage(message, handlerId);
						if (awaitedAnswers > 0) {
							return doSend(result, true, "answer");
						} else {
							return doSend(result, false, "answer");
						}
					} else if (status == "forked") {
						// "answerTo: (forked)"
						if (awaitedAnswers > 0) {
							// Inside any blocking send from the client, a forked
							// send from the server becomes blocking, because we need
							// to keep the context on the client intact.
							handleMessage(message, handlerId); // Ignore result
							return doSend("", true, "answer");
						} else {
							var result = doSend("", false , "answer");
							handleMessage(message, handlerId); // Ignore result
							return result;
						}
					}
				}
				st.console.log("Illegal message received from the server: " + request.responseText);
			} else {
				st.console.statusInfo("Channel disconnected (" +
					(request.responseText ? ("text: " + request.responseText) : "no text")
					+ "). Reconnecting..."
				, request.status);
				// TODO This is maybe not good; the long poll connection might be still up.
				// Maybe just drop reconnecting here, something has gone wrong after all.
				openLongPoll();
			}
		}
	}

})();
<|endoftext|>


<commit_before>//
// @Title = feed-the-burn.js
// @Author = Chris King
// @Description = The main JS file for feed-the-burn a soundcloud app for finding mixes for your workout.
//
//

//Add Tracks to Tracklist:
function AddTracksToTracklist(tracks, list){
    $(tracks).each(function(track) {
        console.log(this);
        list.append("
 "+ this.user.username + " - " + this.title + "
");
    });
}

//Setup
$(document).ready(function() {
    //Initialize the connection to soundcloud
    SC.initialize({
        client_id: 'e30e2c947a1035c10c66b6ab5780d629'
    });

    // BPM
    // Find all tracks with a bpm of 120.
    // Log them to the console, then add them to a list
    //
    SC.get('/tracks', { bpm: { from: 120 } }, function(tracks) {
        console.log(tracks);
        AddTracksToTracklist(tracks, $('#BPMList'));
    });

    // Duration
    // Find all tacks with a duration of 30 - 40 minutes
    // Then Add them to a list
    //
    var thirty_minutes_in_milis = 1800000;
    var fourty_minutes_in_milis = 2400000;
    SC.get('/tracks', { duration: { from: thirty_minutes_in_milis, to: fourty_minutes_in_milis } }, function(tracks) {
        console.log(tracks);
        AddTracksToTracklist(tracks, $('#DurationList'));
    });

    // Genre
    // Find all tracks with a genre of "dubstep"
    //
    SC.get('/tracks', { genre: "dubstep" }, function(tracks) {
        console.log(tracks);
        AddTracksToTracklist(tracks, $('#GenreList'));
    });
});<commit_msg>improved readability of js code<commit_after>//
// @Title = feed-the-burn.js
// @Author = Chris King
// @Description = The main JS file for feed-the-burn a soundcloud app for finding mixes for your workout.
//
//

//Add Tracks to Tracklist:
function AddTracksToTracklist(tracks, list){
    $(tracks).each(function(track) {
        console.log(this);
        list.append("
 "+ this.user.username + " - " + this.title + "
");
    });
}

//Setup
$(document).ready(function() {
    //Initialize the connection to soundcloud
    SC.initialize({
        client_id: 'e30e2c947a1035c10c66b6ab5780d629'
    });

    // BPM
    // Find all tracks with a bpm of 120.
    // Log them to the console, then add them to a list
    //
    SC.get('/tracks', {
        bpm: {
            from: 120
        }
    }, function(tracks) {
        console.log(tracks);
        AddTracksToTracklist(tracks, $('#BPMList'));
    });

    // Duration
    // Find all tacks with a duration of 30 - 40 minutes
    // Then Add them to a list
    //
    var thirty_minutes_in_milis = 1800000;
    var fourty_minutes_in_milis = 2400000;
    SC.get('/tracks', {
        duration: {
            from: thirty_minutes_in_milis,
            to: fourty_minutes_in_milis
        }
    }, function(tracks) {
        console.log(tracks);
        AddTracksToTracklist(tracks, $('#DurationList'));
    });

    // Genre
    // Find all tracks with a genre of "dubstep"
    //
    SC.get('/tracks', {
        genre: "dubstep"
    }, function(tracks) {
        console.log(tracks);
        AddTracksToTracklist(tracks, $('#GenreList'));
    });
});<|endoftext|>


<commit_before>var lifx = {
    base_url: window.localStorage['base_url'] ? window.localStorage['base_url'] : 'http://localhost:56780/',
    tags: {},
    lights: {},
    selected: [],
    getLights: function () {
        $.get(this.base_url + 'lights.json', function (response) {
                $('#lights').empty()
                $.each(response, function (i, light) {
                    var toggle = $('<input>').attr('type', 'checkbox').addClass('lightToggle pull-right')
                    light.on ? toggle.attr('checked', 'checked') : ''
                    var tmp = $('').addClass('list-group-item light').attr('id', light.id)
                    tmp.append('' + light.label + '')
                    tmp.append('')
                    tmp.append(toggle)
                    $('#lights').append(tmp)
                    $.each(light.tags, function (i, tag) {
                        lifx.tags[tag] = []
                    })
                    lifx.lights[light.id] = light
                })

                $.each(lifx.lights, function (id, light) {
                    $.each(light.tags, function (u, tag) {
                        lifx.tags[tag].push(id)
                    })
                })

                $('#tags').empty
                $.each(lifx.tags, function (tag, lights) {
                    var allOn = true
                    $.each(lights, function (i, id) {
                        lifx.lights[id].on ? '' : allOn = false
                    })
                    var toggle = $('<input>').attr('type', 'checkbox').addClass('lightToggle pull-right')
                    allOn ? toggle.attr('checked', 'checked') : ''
                    var tmp = $('').addClass('list-group-item tag').attr('id', 'tag:' + tag)
                    tmp.append('' + tag + '')
                    tmp.append(toggle)
                    $('#tags').append(tmp)
                })

                if (Object.keys(lifx.lights).length == 1) {
                    $('#lights a').addClass('active')
                    var id = $('.list-group-item.active').attr('id')
                    lifx.selected.push(id)
                    colorwheel.setColorandTemp(lifx.lights[id].color)
                }

                $('.lightToggle').bootstrapSwitch({
                    size: 'small',
                    onSwitchChange: function (e, state) {
                        e.preventDefault()
                        var selector = $(this).parents('a').first().attr('id')
                        state ? lifx.setLight(selector, true) : lifx.setLight(selector, false)
                    }
                });

            }
        )
    },
    setLight: function (selector, state) {
        var state = state ? 'on' : 'off'
        $.put(this.base_url + 'lights/' + selector + '/' + state + '.json', function (response) {
            if (!selector.contains('tag')) {
                response = [response]
            }
            $.each(response, function (i, light) {
                lifx.lights[light.id] = light
                $('#' + light.id + ' .lightToggle').bootstrapSwitch('state', light.on, true)
                lifx.setTagStates()
            })
        })
    },
    setTagStates: function () {
        $.each(lifx.tags, function (tag, lights) {
            var allOn = true
            $.each(lights, function (i, id) {
                lifx.lights[id].on ? '' : allOn = false
            })
            $('#tag\\:' + tag + ' .lightToggle').bootstrapSwitch('state', allOn, true)
        })
    },
    setColor: function (selector, hsb, kelvin, duration) {
        $.put(this.base_url + 'lights/' + selector + '/color.json', {
            hue: hsb.hue * 360,
            saturation: hsb.sat,
            brightness: hsb.bri,
            kelvin: kelvin ? kelvin : 10000,
            duration: duration ? duration : '0.3s'
        })
    }, setLabel: function (id, label) {
        $.put(this.base_url + 'lights/' + id + '/label.json', {
            label: label
        }, function (response) {
            $('#' + response.id + '> span').text(response.label)
        })
    }
}

var colorwheel = {
    init: function () {
        $('#colorWheel').minicolors({
            inline: true
        })
    },
    getColor: function () {
        var color = $('#colorWheel').minicolors('rgbObject')
        var hsb = rgbToHsb(color.r, color.g, color.b)
        return hsb
    },
    setColorandTemp: function (color) {
        var rgb = hsbToRgb(color.hue / 360, color.saturation, color.brightness)
        var hex = rgbToHex(rgb.red, rgb.green, rgb.blue)
        $('#colorWheel').minicolors('value', hex);
        $('#colorTemp').val(color.kelvin)
    },
    getTemp: function () {
        return $('#colorTemp').val()
    }
}

$(function () {
    lifx.getLights()
    colorwheel.init()

    $('#setColor').click(function (e) {
        e.preventDefault()
        var hsb = colorwheel.getColor()
        var kelvin = colorwheel.getTemp()
        $.each(lifx.selected, function (i, selector) {
            lifx.setColor(selector, hsb, kelvin)
        })
    })

    $('#host').val(lifx.base_url)
    $('#saveSettings').click(function (e) {
        e.preventDefault()
        var newURL = $('#host').val()
        $.get(newURL + '/lights.json').success(function (result) {
            window.localStorage['base_url'] = newURL
            window.location.reload()
        }).error(function () {
            alert('No response..')
        })

    })

    $(document).on('click', '.editLabel', function (e) {
        e.preventDefault()
        var label = $(this).prev().text()
        var newlabel = prompt('New label', label)
        if (newlabel) {
            var id = $(this).parent().attr('id')
            lifx.setLabel(id, newlabel)
        }
    })

    $(document).on('click', '.list-group-item', function (e) {
        var item = $(this)
        if (e.ctrlKey) {
            if (item.hasClass('active')) {
                item.removeClass('active')
                lifx.selected.pop(item.attr('id'))
            } else {
                item.addClass('active')
                lifx.selected.push(item.attr('id'))
            }
        } else {
            $('.list-group-item').removeClass('active')
            item.addClass('active')
            lifx.selected = [item.attr('id')]
        }
        if ($('.list-group-item.active').length != 0) {
            $('#colorBox').slideDown()
        } else {
            $('#colorBox').slideUp()
        }
        if ($('.list-group-item.active').length == 1) {
            var id = $('.list-group-item.active').attr('id')
            colorwheel.setColorandTemp(lifx.lights[id].color)
        }
    })

//    Make bootstrap-switch buttons react when clicking on "white" part of switch also
    $(document).on('click', '.bootstrap-switch-label', function (e) {
        e.preventDefault()
        $(this).next().next().bootstrapSwitch('toggleState')
    })
})
<commit_msg>setLabel updates light also<commit_after>var lifx = {
    base_url: window.localStorage['base_url'] ? window.localStorage['base_url'] : 'http://localhost:56780/',
    tags: {},
    lights: {},
    selected: [],
    getLights: function () {
        $.get(this.base_url + 'lights.json', function (response) {
                $('#lights').empty()
                $.each(response, function (i, light) {
                    var toggle = $('<input>').attr('type', 'checkbox').addClass('lightToggle pull-right')
                    light.on ? toggle.attr('checked', 'checked') : ''
                    var tmp = $('').addClass('list-group-item light').attr('id', light.id)
                    tmp.append('' + light.label + '')
                    tmp.append('')
                    tmp.append(toggle)
                    $('#lights').append(tmp)
                    $.each(light.tags, function (i, tag) {
                        lifx.tags[tag] = []
                    })
                    lifx.lights[light.id] = light
                })

                $.each(lifx.lights, function (id, light) {
                    $.each(light.tags, function (u, tag) {
                        lifx.tags[tag].push(id)
                    })
                })

                $('#tags').empty
                $.each(lifx.tags, function (tag, lights) {
                    var allOn = true
                    $.each(lights, function (i, id) {
                        lifx.lights[id].on ? '' : allOn = false
                    })
                    var toggle = $('<input>').attr('type', 'checkbox').addClass('lightToggle pull-right')
                    allOn ? toggle.attr('checked', 'checked') : ''
                    var tmp = $('').addClass('list-group-item tag').attr('id', 'tag:' + tag)
                    tmp.append('' + tag + '')
                    tmp.append(toggle)
                    $('#tags').append(tmp)
                })

                if (Object.keys(lifx.lights).length == 1) {
                    $('#lights a').addClass('active')
                    var id = $('.list-group-item.active').attr('id')
                    lifx.selected.push(id)
                    colorwheel.setColorandTemp(lifx.lights[id].color)
                }

                $('.lightToggle').bootstrapSwitch({
                    size: 'small',
                    onSwitchChange: function (e, state) {
                        e.preventDefault()
                        var selector = $(this).parents('a').first().attr('id')
                        state ? lifx.setLight(selector, true) : lifx.setLight(selector, false)
                    }
                });

            }
        )
    },
    setLight: function (selector, state) {
        var state = state ? 'on' : 'off'
        $.put(this.base_url + 'lights/' + selector + '/' + state + '.json', function (response) {
            if (!selector.contains('tag')) {
                response = [response]
            }
            $.each(response, function (i, light) {
                lifx.lights[light.id] = light
                $('#' + light.id + ' .lightToggle').bootstrapSwitch('state', light.on, true)
                lifx.setTagStates()
            })
        })
    },
    setTagStates: function () {
        $.each(lifx.tags, function (tag, lights) {
            var allOn = true
            $.each(lights, function (i, id) {
                lifx.lights[id].on ? '' : allOn = false
            })
            $('#tag\\:' + tag + ' .lightToggle').bootstrapSwitch('state', allOn, true)
        })
    },
    setColor: function (selector, hsb, kelvin, duration) {
        $.put(this.base_url + 'lights/' + selector + '/color.json', {
            hue: hsb.hue * 360,
            saturation: hsb.sat,
            brightness: hsb.bri,
            kelvin: kelvin ? kelvin : 10000,
            duration: duration ? duration : '0.3s'
        })
    }, setLabel: function (id, label) {
        $.put(this.base_url + 'lights/' + id + '/label.json', {
            label: label
        }, function (light) {
            $('#' + light.id + '> span').text(light.label)
            lifx.lights[light.id] = light
        })
    }
}

var colorwheel = {
    init: function () {
        $('#colorWheel').minicolors({
            inline: true
        })
    },
    getColor: function () {
        var color = $('#colorWheel').minicolors('rgbObject')
        var hsb = rgbToHsb(color.r, color.g, color.b)
        return hsb
    },
    setColorandTemp: function (color) {
        var rgb = hsbToRgb(color.hue / 360, color.saturation, color.brightness)
        var hex = rgbToHex(rgb.red, rgb.green, rgb.blue)
        $('#colorWheel').minicolors('value', hex);
        $('#colorTemp').val(color.kelvin)
    },
    getTemp: function () {
        return $('#colorTemp').val()
    }
}

$(function () {
    lifx.getLights()
    colorwheel.init()

    $('#setColor').click(function (e) {
        e.preventDefault()
        var hsb = colorwheel.getColor()
        var kelvin = colorwheel.getTemp()
        $.each(lifx.selected, function (i, selector) {
            lifx.setColor(selector, hsb, kelvin)
        })
    })

    $('#host').val(lifx.base_url)
    $('#saveSettings').click(function (e) {
        e.preventDefault()
        var newURL = $('#host').val()
        $.get(newURL + '/lights.json').success(function (result) {
            window.localStorage['base_url'] = newURL
            window.location.reload()
        }).error(function () {
            alert('No response..')
        })

    })

    $(document).on('click', '.editLabel', function (e) {
        e.preventDefault()
        var label = $(this).prev().text()
        var newlabel = prompt('New label', label)
        if (newlabel) {
            var id = $(this).parent().attr('id')
            lifx.setLabel(id, newlabel)
        }
    })

    $(document).on('click', '.list-group-item', function (e) {
        var item = $(this)
        if (e.ctrlKey) {
            if (item.hasClass('active')) {
                item.removeClass('active')
                lifx.selected.pop(item.attr('id'))
            } else {
                item.addClass('active')
                lifx.selected.push(item.attr('id'))
            }
        } else {
            $('.list-group-item').removeClass('active')
            item.addClass('active')
            lifx.selected = [item.attr('id')]
        }
        if ($('.list-group-item.active').length != 0) {
            $('#colorBox').slideDown()
        } else {
            $('#colorBox').slideUp()
        }
        if ($('.list-group-item.active').length == 1) {
            var id = $('.list-group-item.active').attr('id')
            colorwheel.setColorandTemp(lifx.lights[id].color)
        }
    })

//    Make bootstrap-switch buttons react when clicking on "white" part of switch also
    $(document).on('click', '.bootstrap-switch-label', function (e) {
        e.preventDefault()
        $(this).next().next().bootstrapSwitch('toggleState')
    })
})
<|endoftext|>


<commit_before>define("Evolution", function () {
    var Evolution = function(areaEvolutionStrategy, cycleTimeMiliseconds, mediator)
    {
        this.subjects = [];
        this.areaEvolutionStrategy = areaEvolutionStrategy;
        this.cycleTimeMiliseconds = cycleTimeMiliseconds;
        this.timeIntervalHandler;
        this.mediator = mediator;
    };

    Evolution.prototype.addSubject = function(area)
    {
        this.subjects.push(area);
    };

    Evolution.prototype.start = function()
    {
        this.timeIntervalHandler = setInterval((function () {
            this.subjects.forEach((function (area) {
                this.areaEvolutionStrategy.replaceCellsOfAreaWithNewGeneration(area);
                this.mediator.publish("area.cells.new_generation", area);
            }).bind(this));
        }).bind(this), this.cycleTimeMiliseconds);
    };

    Evolution.prototype.stop = function()
    {
        clearInterval(this.timeIntervalHandler);
    };

    Evolution.prototype.killAllCells = function() {
        this.subjects.forEach((function (area) {
            area.getAllCells().forEach(function (cell) {
                cell.kill();
            });
            this.mediator.publish("area.cells.new_generation", area);
        }).bind(this));
    };

    return Evolution;
});
    <commit_msg>new evolution start stops previous interation<commit_after>define("Evolution", function () {
    var Evolution = function(areaEvolutionStrategy, cycleTimeMiliseconds, mediator)
    {
        this.subjects = [];
        this.areaEvolutionStrategy = areaEvolutionStrategy;
        this.cycleTimeMiliseconds = cycleTimeMiliseconds;
        this.timeIntervalHandler;
        this.mediator = mediator;
    };

    Evolution.prototype.addSubject = function(area)
    {
        this.subjects.push(area);
    };

    Evolution.prototype.start = function()
    {
        clearInterval(this.timeIntervalHandler);
        this.timeIntervalHandler = setInterval((function () {
            this.subjects.forEach((function (area) {
                this.areaEvolutionStrategy.replaceCellsOfAreaWithNewGeneration(area);
                this.mediator.publish("area.cells.new_generation", area);
            }).bind(this));
        }).bind(this), this.cycleTimeMiliseconds);
    };

    Evolution.prototype.stop = function()
    {
        clearInterval(this.timeIntervalHandler);
    };

    Evolution.prototype.killAllCells = function() {
        this.subjects.forEach((function (area) {
            area.getAllCells().forEach(function (cell) {
                cell.kill();
            });
            this.mediator.publish("area.cells.new_generation", area);
        }).bind(this));
    };

    return Evolution;
});
    <|endoftext|>


<commit_before>/*global require: false, module: false */
'use strict';

var d3 = require('d3');
var _ = require('underscore');
var multi = require('multi');

var isNumber = _.isNumber,
	// d3_category20, replace #7f7f7f gray (that aliases with our N/A gray of #808080) with dark grey #434348
	categoryMore = [
		"#1f77b4", // dark blue
		"#aec7e8", // light blue
		"#2ca02c", // dark green
		"#98df8a", // light green
		"#d62728", // dark red
		"#ff9896", // light salmon
		"#ff7f0e", // dark orange
		"#ffbb78", // light orange
		"#9467bd", // dark purple
		"#c5b0d5", // light lavender
		"#8c564b", // dark brown
		"#c49c94", // light tan
		"#e377c2", // dark pink
		"#f7b6d2", // light pink
		"#bcbd22", // dark mustard
		"#dbdb8d", // light mustard
		"#17becf", // dark blue-green
		"#9edae5", // light blue-green
		"#434348", // very dark grey
		"#c7c7c7"  // light grey
	];

var defaultColors = (function () {
	var schemes = {
			blueWhiteRed: ['#0000ff', '#ffffff', '#ff0000'],
			greenBlackRed: ['#00ff00', '#000000', '#ff0000'],
			greenWhiteRed: ['#00ff00', '#ffffff', '#ff0000'],
			greenBlackYellow: ['#007f00', '#000000', '#ffff00']
			/* with clinical category palette:
			blueWhiteRed: ['#377eb8', '#ffffff', '#e41a1c'],
			greenBlackRed: ['#4daf4a', '#000000', '#e41a1c'],
			greenBlackYellow: ['#4daf4a', '#000000', '#ffff33']
			*/
		},

		defaults = {
			"gene expression": schemes.greenBlackRed,
			"gene expression RNAseq": schemes.greenBlackRed,
			"gene expression array": schemes.greenBlackRed,
			"exon expression RNAseq": schemes.greenBlackRed,
			"phenotype": schemes.greenBlackYellow
		};

	// XXX it's rather broken that these conditionals appear here, in
	// addition to in the colorRange multi
	return function (column) {
		var {type, dataSubType} = column || {};
		var t = (type === 'clinicalMatrix') ?  'phenotype' : dataSubType;
		return defaults[t] || schemes.blueWhiteRed;
	};
}());

// Return a new function that preserves undefined arguments, otherwise calls the original function.
// This is to work-around d3 scales.
function saveMissing(fn) {
	var newfn = function (v) {
		return v == null ? v : fn(v);
	};
	return _.extend(newfn, fn); // This weirdness copies d3 fn methods
}

var ordinal = count => d3.scale.ordinal().range(categoryMore).domain(_.range(count));

// 'column' is the column type set by the UI. It's not the dataset metadata.
// It is *based on* the dataset metadata. We use it to decide whether to
// use clinical vs. genomic scaling for floats.
// 'settings' is the vizSettings: user override of min/max, etc.
// 'codes' is also used to pick categorical.
// 'data' is used to find min/max.
//
//  Of these, we can't drop 'data' or 'codes'.
//  Perhaps we should just pass in column.type and dataSubType, since we don't
//  need all the other params.
function colorRangeType(column, settings, codes) {
	return codes ? 'coded' :
		(column.dataType === 'clinicalMatrix' ? 'float' : 'floatGenomicData');
}

var colorRange = multi(colorRangeType);

var scaleFloatSingle = (low, high, min, max) =>
	d3.scale.linear().domain([min, max]).range([low, high]);

function scaleFloatDouble(low, zero, high, min, max) {
	var absmax = Math.max(-min, max);

	return d3.scale.linear()
		.domain([-absmax, 0, absmax])
		.range([low, zero, high]);
}

function colorFloat(column, settings, codes, data, dataset) {
	var values = _.values(data || [0]), // handle degenerate case XXX needed?
		max = d3.max(values),
		[low, zero, high] = defaultColors(dataset),
		spec,
		min;

	if (!isNumber(max)) {
		return null;
	}
	min = d3.min(values);
	if (min >= 0 && max >= 0) {
		spec = ['float-pos', zero, high, min, max];
	} else if (min <= 0 && max <= 0) {
		spec = ['float-neg', low, zero, min, max];
	} else {
		spec = ['float', low, zero, high, min, max];
	}
	return spec;
}

function colorCoded(column, settings, codes) {
	return ['ordinal', codes.length];
}

var scaleFloatThresholdNegative = (low, zero, min, thresh, max) =>
	d3.scale.linear()
		.domain(_.map([min, thresh, max], x => x.toPrecision(2)))
		.range([low, zero, zero]);

var scaleFloatThresholdPositive = (zero, high, min, thresh, max) =>
	d3.scale.linear()
		.domain(_.map([min, thresh, max], x => x.toPrecision(2)))
		.range([zero, zero, high]);

var scaleFloatThreshold = (low, zero, high, min, minThresh, maxThresh, max) =>
	d3.scale.linear()
		.domain(_.map([min, minThresh, maxThresh, max], x => x.toPrecision(2)))
		.range([low, zero, zero, high]);

function colorFloatGenomicData(column, settings = {}, codes, data, dataset) {
	var values = _.values(data), // handle degenerate case
		[low, zero, high] = defaultColors(dataset),
		min = settings.min || d3.min(values),
		max = settings.max ||  d3.max(values),
		minStart = settings.minStart,
		maxStart = settings.maxStart,
		spec,
		mid,
		absmax,
		zone;

	if (!isNumber(max) || !isNumber(min)) {
		return null; // XXX should verify that we handle this downstream.
	}

	if ( (settings.min!== undefined) && (settings.min !== null) && !isNaN(settings.min)) { //custom setting
		if (isNaN(minStart)  || isNaN(maxStart) || (minStart === null) || (maxStart===null)) {
			mid = (max + min) / 2.0;
			zone = (max - min) / 4.0;
			minStart = mid  -  zone / 2.0;
			maxStart = mid  +  zone / 2.0;
		}
		spec = ['float-thresh', low, zero, high, min, minStart, maxStart, max];
	} else if (min < 0 && max > 0) {
		absmax = Math.max(-min, max);
		zone = absmax / 4.0;
		spec = ['float-thresh', low, zero, high, -absmax / 2.0, -zone / 2.0,
			 zone / 2.0, absmax / 2.0];
	} else	if (min >= 0 && max >= 0) {
		zone = (max - min) / 4.0;
		spec = ['float-thresh-pos', zero, high, min, min + zone, max - zone / 2.0];
	} else { // min <= 0 && max <= 0
		zone = (max - min) / 4.0;
		spec = ['float-thresh-neg', low, zero, min + zone / 2.0, max - zone, max];
	}
	return spec;
}

colorRange.add('float', colorFloat);
colorRange.add('coded', colorCoded);
colorRange.add('floatGenomicData', colorFloatGenomicData);

var colorScale = {
	'float-pos': (__, ...args) => scaleFloatSingle(...args),
	'float-neg': (__, ...args) => scaleFloatSingle(...args),
	'float': (__, ...args) => scaleFloatDouble(...args),
	'float-thresh-pos': (__, ...args) => scaleFloatThresholdPositive(...args),
	'float-thresh-neg': (__, ...args) => scaleFloatThresholdNegative(...args),
	'float-thresh': (__, ...args) => scaleFloatThreshold(...args),
	'ordinal': (__, count) => ordinal(count)
};

module.exports =  {
	colorScale: ([type, ...args]) => saveMissing(colorScale[type](type, ...args)),
	colorSpec: colorRange,
	defaultColors: defaultColors
};
<commit_msg>Fix variable name.<commit_after>/*global require: false, module: false */
'use strict';

var d3 = require('d3');
var _ = require('underscore');
var multi = require('multi');

var isNumber = _.isNumber,
	// d3_category20, replace #7f7f7f gray (that aliases with our N/A gray of #808080) with dark grey #434348
	categoryMore = [
		"#1f77b4", // dark blue
		"#aec7e8", // light blue
		"#2ca02c", // dark green
		"#98df8a", // light green
		"#d62728", // dark red
		"#ff9896", // light salmon
		"#ff7f0e", // dark orange
		"#ffbb78", // light orange
		"#9467bd", // dark purple
		"#c5b0d5", // light lavender
		"#8c564b", // dark brown
		"#c49c94", // light tan
		"#e377c2", // dark pink
		"#f7b6d2", // light pink
		"#bcbd22", // dark mustard
		"#dbdb8d", // light mustard
		"#17becf", // dark blue-green
		"#9edae5", // light blue-green
		"#434348", // very dark grey
		"#c7c7c7"  // light grey
	];

var defaultColors = (function () {
	var schemes = {
			blueWhiteRed: ['#0000ff', '#ffffff', '#ff0000'],
			greenBlackRed: ['#00ff00', '#000000', '#ff0000'],
			greenWhiteRed: ['#00ff00', '#ffffff', '#ff0000'],
			greenBlackYellow: ['#007f00', '#000000', '#ffff00']
			/* with clinical category palette:
			blueWhiteRed: ['#377eb8', '#ffffff', '#e41a1c'],
			greenBlackRed: ['#4daf4a', '#000000', '#e41a1c'],
			greenBlackYellow: ['#4daf4a', '#000000', '#ffff33']
			*/
		},

		defaults = {
			"gene expression": schemes.greenBlackRed,
			"gene expression RNAseq": schemes.greenBlackRed,
			"gene expression array": schemes.greenBlackRed,
			"exon expression RNAseq": schemes.greenBlackRed,
			"phenotype": schemes.greenBlackYellow
		};

	// XXX it's rather broken that these conditionals appear here, in
	// addition to in the colorRange multi
	return function (dataset) {
		var {type, dataSubType} = dataset || {};
		var t = (type === 'clinicalMatrix') ?  'phenotype' : dataSubType;
		return defaults[t] || schemes.blueWhiteRed;
	};
}());

// Return a new function that preserves undefined arguments, otherwise calls the original function.
// This is to work-around d3 scales.
function saveMissing(fn) {
	var newfn = function (v) {
		return v == null ? v : fn(v);
	};
	return _.extend(newfn, fn); // This weirdness copies d3 fn methods
}

var ordinal = count => d3.scale.ordinal().range(categoryMore).domain(_.range(count));

// 'column' is the column type set by the UI. It's not the dataset metadata.
// It is *based on* the dataset metadata. We use it to decide whether to
// use clinical vs. genomic scaling for floats.
// 'settings' is the vizSettings: user override of min/max, etc.
// 'codes' is also used to pick categorical.
// 'data' is used to find min/max.
//
//  Of these, we can't drop 'data' or 'codes'.
//  Perhaps we should just pass in column.type and dataSubType, since we don't
//  need all the other params.
function colorRangeType(column, settings, codes) {
	return codes ? 'coded' :
		(column.dataType === 'clinicalMatrix' ? 'float' : 'floatGenomicData');
}

var colorRange = multi(colorRangeType);

var scaleFloatSingle = (low, high, min, max) =>
	d3.scale.linear().domain([min, max]).range([low, high]);

function scaleFloatDouble(low, zero, high, min, max) {
	var absmax = Math.max(-min, max);

	return d3.scale.linear()
		.domain([-absmax, 0, absmax])
		.range([low, zero, high]);
}

function colorFloat(column, settings, codes, data, dataset) {
	var values = _.values(data || [0]), // handle degenerate case XXX needed?
		max = d3.max(values),
		[low, zero, high] = defaultColors(dataset),
		spec,
		min;

	if (!isNumber(max)) {
		return null;
	}
	min = d3.min(values);
	if (min >= 0 && max >= 0) {
		spec = ['float-pos', zero, high, min, max];
	} else if (min <= 0 && max <= 0) {
		spec = ['float-neg', low, zero, min, max];
	} else {
		spec = ['float', low, zero, high, min, max];
	}
	return spec;
}

function colorCoded(column, settings, codes) {
	return ['ordinal', codes.length];
}

var scaleFloatThresholdNegative = (low, zero, min, thresh, max) =>
	d3.scale.linear()
		.domain(_.map([min, thresh, max], x => x.toPrecision(2)))
		.range([low, zero, zero]);

var scaleFloatThresholdPositive = (zero, high, min, thresh, max) =>
	d3.scale.linear()
		.domain(_.map([min, thresh, max], x => x.toPrecision(2)))
		.range([zero, zero, high]);

var scaleFloatThreshold = (low, zero, high, min, minThresh, maxThresh, max) =>
	d3.scale.linear()
		.domain(_.map([min, minThresh, maxThresh, max], x => x.toPrecision(2)))
		.range([low, zero, zero, high]);

function colorFloatGenomicData(column, settings = {}, codes, data, dataset) {
	var values = _.values(data), // handle degenerate case
		[low, zero, high] = defaultColors(dataset),
		min = settings.min || d3.min(values),
		max = settings.max ||  d3.max(values),
		minStart = settings.minStart,
		maxStart = settings.maxStart,
		spec,
		mid,
		absmax,
		zone;

	if (!isNumber(max) || !isNumber(min)) {
		return null; // XXX should verify that we handle this downstream.
	}

	if ( (settings.min!== undefined) && (settings.min !== null) && !isNaN(settings.min)) { //custom setting
		if (isNaN(minStart)  || isNaN(maxStart) || (minStart === null) || (maxStart===null)) {
			mid = (max + min) / 2.0;
			zone = (max - min) / 4.0;
			minStart = mid  -  zone / 2.0;
			maxStart = mid  +  zone / 2.0;
		}
		spec = ['float-thresh', low, zero, high, min, minStart, maxStart, max];
	} else if (min < 0 && max > 0) {
		absmax = Math.max(-min, max);
		zone = absmax / 4.0;
		spec = ['float-thresh', low, zero, high, -absmax / 2.0, -zone / 2.0,
			 zone / 2.0, absmax / 2.0];
	} else	if (min >= 0 && max >= 0) {
		zone = (max - min) / 4.0;
		spec = ['float-thresh-pos', zero, high, min, min + zone, max - zone / 2.0];
	} else { // min <= 0 && max <= 0
		zone = (max - min) / 4.0;
		spec = ['float-thresh-neg', low, zero, min + zone / 2.0, max - zone, max];
	}
	return spec;
}

colorRange.add('float', colorFloat);
colorRange.add('coded', colorCoded);
colorRange.add('floatGenomicData', colorFloatGenomicData);

var colorScale = {
	'float-pos': (__, ...args) => scaleFloatSingle(...args),
	'float-neg': (__, ...args) => scaleFloatSingle(...args),
	'float': (__, ...args) => scaleFloatDouble(...args),
	'float-thresh-pos': (__, ...args) => scaleFloatThresholdPositive(...args),
	'float-thresh-neg': (__, ...args) => scaleFloatThresholdNegative(...args),
	'float-thresh': (__, ...args) => scaleFloatThreshold(...args),
	'ordinal': (__, count) => ordinal(count)
};

module.exports =  {
	colorScale: ([type, ...args]) => saveMissing(colorScale[type](type, ...args)),
	colorSpec: colorRange,
	defaultColors: defaultColors
};
<|endoftext|>


<commit_before>var Flow = require('./flow');
var Instance = require('./instance');

// client flag
engine.client = true;

// extend engine with flow emitter
engine = Flow(engine);

// extend engine with logging methods
engine.log = require('./logs') || function () {};

// listen to core engine events
engine.mind([
    'C',
    ['link', '@/C']
]).mind([
    'M',
    ['link', '@/M'],
    ":trucken/test"
]);

/**
 * Create server module instances
 */
engine.load = function (name, role, callback, loaderInstance) {

    // ensure callback
    callback = callback || function () {};

    // check instance chache
    if (engine.instances[name]) {
        return callback(null, engine.instances[name]);
    }

    // get composition
    engine.flow('C').data(function (err, composition) {

        if (err) {
            return callback(engine.log('E', err));
        }

        // require module
        require(composition.module, function (module) {

            if (!module) {
                return callback(engine.log('E', new Error('Module "' + composition.module + '" not found.')));
            }

            // create instance
            Instance(module, composition, role, callback, loaderInstance);
        });
    }).write(null, name);
};

// load entrypoint
engine.load();

/**
 * Empties all caches and reloads the modules.
 *
 * @public
 * @param {boolean} Don't remove the DOM nodes.
 * @todo be aware of memory leaks
 */
engine.reload = function (keepDom) {

    //reset instances cache
    engine.instances = {};

    // close all websockets
    for (var socket in engine.sockets) {
        engine.sockets[socket].close(3000);
    }

    // reset DOM body
    if (!keepDom) {
        document.body.innerHTML = '';
    }
};
<commit_msg>chaining calls is not so great for setting breakpoints<commit_after>var Flow = require('./flow');
var Instance = require('./instance');

// client flag
engine.client = true;

// extend engine with flow emitter
engine = Flow(engine);

// extend engine with logging methods
engine.log = require('./logs') || function () {};

// listen to core engine events
engine.mind([
    'C',
    ['link', '@/C']
]).mind([
    'M',
    ['link', '@/M']
]);

/**
 * Create server module instances
 */
engine.load = function (name, role, callback, loaderInstance) {

    // ensure callback
    callback = callback || function () {};

    // check instance chache
    if (engine.instances[name]) {
        return callback(null, engine.instances[name]);
    }

    // get composition
    var stream = engine.flow('C');
    stream.data(function (err, composition) {

        if (err) {
            return callback(engine.log('E', err));
        }

        // require module
        require(composition.module, function (module) {

            if (!module) {
                return callback(engine.log('E', new Error('Module "' + composition.module + '" not found.')));
            }

            // create instance
            Instance(module, composition, role, callback, loaderInstance);
        });
    });
    stream.write(null, name);
};

// load entrypoint
engine.load();

/**
 * Empties all caches and reloads the modules.
 *
 * @public
 * @param {boolean} Don't remove the DOM nodes.
 * @todo be aware of memory leaks
 */
engine.reload = function (keepDom) {

    //reset instances cache
    engine.instances = {};

    // close all websockets
    for (var socket in engine.sockets) {
        engine.sockets[socket].close(3000);
    }

    // reset DOM body
    if (!keepDom) {
        document.body.innerHTML = '';
    }
};
<|endoftext|>