<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    "widgets/js/widget",
    "jqueryui",
    "components/bootstrap/js/bootstrap.min",
], function(widget, $){

    var IntSliderView = widget.DOMWidgetView.extend({
        render : function(){
            // Called when view is rendered.
            this.$el
                .addClass('widget-hbox-single');
            this.$label = $('<div />')
                .appendTo(this.$el)
                .addClass('widget-hlabel')
                .hide();

            this.$slider = $('<div />')
                .slider({})
                .addClass('slider');
            // Put the slider in a container
            this.$slider_container = $('<div />')
                .addClass('widget-hslider')
                .append(this.$slider);
            this.$el_to_style = this.$slider_container; // Set default element to style
            this.$el.append(this.$slider_container);

            this.$readout = $('<div/>')
                .appendTo(this.$el)
                .addClass('widget-hreadout')
                .hide();

            // Set defaults.
            this.update();
        },

        update : function(options){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            if (options === undefined || options.updated_view != this) {
                // JQuery slider option keys.  These keys happen to have a
                // one-to-one mapping with the corrosponding keys of the model.
                var jquery_slider_keys = ['step', 'max', 'min', 'disabled'];
                var that = this;
                that.$slider.slider({});
                _.each(jquery_slider_keys, function(key, i) {
                    var model_value = that.model.get(key);
                    if (model_value !== undefined) {
                        that.$slider.slider("option", key, model_value);
                    }
                });

                // WORKAROUND FOR JQUERY SLIDER BUG.
                // The horizontal position of the slider handle
                // depends on the value of the slider at the time
                // of orientation change.  Before applying the new
                // workaround, we set the value to the minimum to
                // make sure that the horizontal placement of the
                // handle in the vertical slider is always
                // consistent.
                var orientation = this.model.get('orientation');
                var min = this.model.get('min');
                var max = this.model.get('max');
                this.$slider.slider('option', 'value', min);
                this.$slider.slider('option', 'orientation', orientation);
                value = this.model.get('value');
                if(value > max) {
                    value = max;
                }
                else if(value < min){
                    value = min;
                }
                this.model.set('value', value, {updated_view: this});
                this.$slider.slider('option', 'value', value);
                this.$readout.text(value);
                this.touch()

                // Use the right CSS classes for vertical & horizontal sliders
                if (orientation=='vertical') {
                    this.$slider_container
                        .removeClass('widget-hslider')
                        .addClass('widget-vslider');
                    this.$el
                        .removeClass('widget-hbox-single')
                        .addClass('widget-vbox-single');
                    this.$label
                        .removeClass('widget-hlabel')
                        .addClass('widget-vlabel');
                    this.$readout
                        .removeClass('widget-hreadout')
                        .addClass('widget-vreadout');

                } else {
                    this.$slider_container
                        .removeClass('widget-vslider')
                        .addClass('widget-hslider');
                    this.$el
                        .removeClass('widget-vbox-single')
                        .addClass('widget-hbox-single');
                    this.$label
                        .removeClass('widget-vlabel')
                        .addClass('widget-hlabel');
                    this.$readout
                        .removeClass('widget-vreadout')
                        .addClass('widget-hreadout');
                }

                var description = this.model.get('description');
                if (description.length === 0) {
                    this.$label.hide();
                } else {
                    this.$label.text(description);
                    MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.$label.get(0)]);
                    this.$label.show();
                }

                var readout = this.model.get('readout');
                if (readout) {
                    this.$readout.show();
                } else {
                    this.$readout.hide();
                }
            }
            return IntSliderView.__super__.update.apply(this);
        },

        events: {
            // Dictionary of events and their handlers.
            "slide" : "handleSliderChange"
        },

        handleSliderChange: function(e, ui) {
            // Called when the slider value is changed.

            // Calling model.set will trigger all of the other views of the
            // model to update.
            var actual_value = this._validate_slide_value(ui.value);
            this.model.set('value', actual_value, {updated_view: this});
            this.$readout.text(actual_value);
            this.touch();
        },

        _validate_slide_value: function(x) {
            // Validate the value of the slider before sending it to the back-end
            // and applying it to the other views on the page.

            // Double bit-wise not truncates the decimel (int cast).
            return ~~x;
        },
    });

    var IntTextView = widget.DOMWidgetView.extend({
        render : function(){
            // Called when view is rendered.
            this.$el
                .addClass('widget-hbox-single');
            this.$label = $('<div />')
                .appendTo(this.$el)
                .addClass('widget-hlabel')
                .hide();
            this.$textbox = $('<input type="text" />')
                .addClass('form-control')
                .addClass('widget-numeric-text')
                .appendTo(this.$el);
            this.$el_to_style = this.$textbox; // Set default element to style
            this.update(); // Set defaults.
        },

        update : function(options){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            if (options === undefined || options.updated_view != this) {
                var value = this.model.get('value');
                if (this._parse_value(this.$textbox.val()) != value) {
                    this.$textbox.val(value);
                }

                if (this.model.get('disabled')) {
                    this.$textbox.attr('disabled','disabled');
                } else {
                    this.$textbox.removeAttr('disabled');
                }

                var description = this.model.get('description');
                if (description.length === 0) {
                    this.$label.hide();
                } else {
                    this.$label.text(description);
                    MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.$label.get(0)]);
                    this.$label.show();
                }
            }
            return IntTextView.__super__.update.apply(this);
        },

        events: {
            // Dictionary of events and their handlers.
            "keyup input"  : "handleChanging",
            "paste input"  : "handleChanging",
            "cut input"    : "handleChanging",

            // Fires only when control is validated or looses focus.
            "change input" : "handleChanged"
        },

        handleChanging: function(e) {
            // Handles and validates user input.

            // Try to parse value as a int.
            var numericalValue = 0;
            if (e.target.value !== '') {
                var trimmed = e.target.value.trim();
                if (!(['-', '-.', '.', '+.', '+'].indexOf(trimmed) >= 0)) {
                    numericalValue = this._parse_value(e.target.value);
                }
            }

            // If parse failed, reset value to value stored in model.
            if (isNaN(numericalValue)) {
                e.target.value = this.model.get('value');
            } else if (!isNaN(numericalValue)) {
                if (this.model.get('max') !== undefined) {
                    numericalValue = Math.min(this.model.get('max'), numericalValue);
                }
                if (this.model.get('min') !== undefined) {
                    numericalValue = Math.max(this.model.get('min'), numericalValue);
                }

                // Apply the value if it has changed.
                if (numericalValue != this.model.get('value')) {

                    // Calling model.set will trigger all of the other views of the
                    // model to update.
                    this.model.set('value', numericalValue, {updated_view: this});
                    this.touch();
                }
            }
        },

        handleChanged: function(e) {
            // Applies validated input.
            if (this.model.get('value') != e.target.value) {
                e.target.value = this.model.get('value');
            }
        },

        _parse_value: function(value) {
            // Parse the value stored in a string.
            return  parseInt(value);
        },
    });

    var ProgressView = widget.DOMWidgetView.extend({
        render : function(){
            // Called when view is rendered.
            this.$el
                .addClass('widget-hbox-single');
            this.$label = $('<div />')
                .appendTo(this.$el)
                .addClass('widget-hlabel')
                .hide();
            this.$progress = $('<div />')
                .addClass('progress')
                .addClass('widget-progress')
                .appendTo(this.$el);
            this.$el_to_style = this.$progress; // Set default element to style
            this.$bar = $('<div />')
                .addClass('progress-bar')
                .css('width', '50%')
                .appendTo(this.$progress);
            this.update(); // Set defaults.
        },

        update : function(){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            var value = this.model.get('value');
            var max = this.model.get('max');
            var min = this.model.get('min');
            var percent = 100.0 * (value - min) / (max - min);
            this.$bar.css('width', percent + '%');

            var description = this.model.get('description');
            if (description.length === 0) {
                this.$label.hide();
            } else {
                this.$label.text(description);
                MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.$label.get(0)]);
                this.$label.show();
            }
            return ProgressView.__super__.update.apply(this);
        },
    });

    return {
        'IntSliderView': IntSliderView,
        'IntTextView': IntTextView,
        'ProgressView': ProgressView,
    };
});
<commit_msg>A comma after `this.touch`<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    "widgets/js/widget",
    "jqueryui",
    "components/bootstrap/js/bootstrap.min",
], function(widget, $){

    var IntSliderView = widget.DOMWidgetView.extend({
        render : function(){
            // Called when view is rendered.
            this.$el
                .addClass('widget-hbox-single');
            this.$label = $('<div />')
                .appendTo(this.$el)
                .addClass('widget-hlabel')
                .hide();

            this.$slider = $('<div />')
                .slider({})
                .addClass('slider');
            // Put the slider in a container
            this.$slider_container = $('<div />')
                .addClass('widget-hslider')
                .append(this.$slider);
            this.$el_to_style = this.$slider_container; // Set default element to style
            this.$el.append(this.$slider_container);

            this.$readout = $('<div/>')
                .appendTo(this.$el)
                .addClass('widget-hreadout')
                .hide();

            // Set defaults.
            this.update();
        },

        update : function(options){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            if (options === undefined || options.updated_view != this) {
                // JQuery slider option keys.  These keys happen to have a
                // one-to-one mapping with the corrosponding keys of the model.
                var jquery_slider_keys = ['step', 'max', 'min', 'disabled'];
                var that = this;
                that.$slider.slider({});
                _.each(jquery_slider_keys, function(key, i) {
                    var model_value = that.model.get(key);
                    if (model_value !== undefined) {
                        that.$slider.slider("option", key, model_value);
                    }
                });

                // WORKAROUND FOR JQUERY SLIDER BUG.
                // The horizontal position of the slider handle
                // depends on the value of the slider at the time
                // of orientation change.  Before applying the new
                // workaround, we set the value to the minimum to
                // make sure that the horizontal placement of the
                // handle in the vertical slider is always
                // consistent.
                var orientation = this.model.get('orientation');
                var min = this.model.get('min');
                var max = this.model.get('max');
                this.$slider.slider('option', 'value', min);
                this.$slider.slider('option', 'orientation', orientation);
                value = this.model.get('value');
                if(value > max) {
                    value = max;
                }
                else if(value < min){
                    value = min;
                }
                this.model.set('value', value, {updated_view: this});
                this.$slider.slider('option', 'value', value);
                this.$readout.text(value);
                this.touch();

                // Use the right CSS classes for vertical & horizontal sliders
                if (orientation=='vertical') {
                    this.$slider_container
                        .removeClass('widget-hslider')
                        .addClass('widget-vslider');
                    this.$el
                        .removeClass('widget-hbox-single')
                        .addClass('widget-vbox-single');
                    this.$label
                        .removeClass('widget-hlabel')
                        .addClass('widget-vlabel');
                    this.$readout
                        .removeClass('widget-hreadout')
                        .addClass('widget-vreadout');

                } else {
                    this.$slider_container
                        .removeClass('widget-vslider')
                        .addClass('widget-hslider');
                    this.$el
                        .removeClass('widget-vbox-single')
                        .addClass('widget-hbox-single');
                    this.$label
                        .removeClass('widget-vlabel')
                        .addClass('widget-hlabel');
                    this.$readout
                        .removeClass('widget-vreadout')
                        .addClass('widget-hreadout');
                }

                var description = this.model.get('description');
                if (description.length === 0) {
                    this.$label.hide();
                } else {
                    this.$label.text(description);
                    MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.$label.get(0)]);
                    this.$label.show();
                }

                var readout = this.model.get('readout');
                if (readout) {
                    this.$readout.show();
                } else {
                    this.$readout.hide();
                }
            }
            return IntSliderView.__super__.update.apply(this);
        },

        events: {
            // Dictionary of events and their handlers.
            "slide" : "handleSliderChange"
        },

        handleSliderChange: function(e, ui) {
            // Called when the slider value is changed.

            // Calling model.set will trigger all of the other views of the
            // model to update.
            var actual_value = this._validate_slide_value(ui.value);
            this.model.set('value', actual_value, {updated_view: this});
            this.$readout.text(actual_value);
            this.touch();
        },

        _validate_slide_value: function(x) {
            // Validate the value of the slider before sending it to the back-end
            // and applying it to the other views on the page.

            // Double bit-wise not truncates the decimel (int cast).
            return ~~x;
        },
    });

    var IntTextView = widget.DOMWidgetView.extend({
        render : function(){
            // Called when view is rendered.
            this.$el
                .addClass('widget-hbox-single');
            this.$label = $('<div />')
                .appendTo(this.$el)
                .addClass('widget-hlabel')
                .hide();
            this.$textbox = $('<input type="text" />')
                .addClass('form-control')
                .addClass('widget-numeric-text')
                .appendTo(this.$el);
            this.$el_to_style = this.$textbox; // Set default element to style
            this.update(); // Set defaults.
        },

        update : function(options){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            if (options === undefined || options.updated_view != this) {
                var value = this.model.get('value');
                if (this._parse_value(this.$textbox.val()) != value) {
                    this.$textbox.val(value);
                }

                if (this.model.get('disabled')) {
                    this.$textbox.attr('disabled','disabled');
                } else {
                    this.$textbox.removeAttr('disabled');
                }

                var description = this.model.get('description');
                if (description.length === 0) {
                    this.$label.hide();
                } else {
                    this.$label.text(description);
                    MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.$label.get(0)]);
                    this.$label.show();
                }
            }
            return IntTextView.__super__.update.apply(this);
        },

        events: {
            // Dictionary of events and their handlers.
            "keyup input"  : "handleChanging",
            "paste input"  : "handleChanging",
            "cut input"    : "handleChanging",

            // Fires only when control is validated or looses focus.
            "change input" : "handleChanged"
        },

        handleChanging: function(e) {
            // Handles and validates user input.

            // Try to parse value as a int.
            var numericalValue = 0;
            if (e.target.value !== '') {
                var trimmed = e.target.value.trim();
                if (!(['-', '-.', '.', '+.', '+'].indexOf(trimmed) >= 0)) {
                    numericalValue = this._parse_value(e.target.value);
                }
            }

            // If parse failed, reset value to value stored in model.
            if (isNaN(numericalValue)) {
                e.target.value = this.model.get('value');
            } else if (!isNaN(numericalValue)) {
                if (this.model.get('max') !== undefined) {
                    numericalValue = Math.min(this.model.get('max'), numericalValue);
                }
                if (this.model.get('min') !== undefined) {
                    numericalValue = Math.max(this.model.get('min'), numericalValue);
                }

                // Apply the value if it has changed.
                if (numericalValue != this.model.get('value')) {

                    // Calling model.set will trigger all of the other views of the
                    // model to update.
                    this.model.set('value', numericalValue, {updated_view: this});
                    this.touch();
                }
            }
        },

        handleChanged: function(e) {
            // Applies validated input.
            if (this.model.get('value') != e.target.value) {
                e.target.value = this.model.get('value');
            }
        },

        _parse_value: function(value) {
            // Parse the value stored in a string.
            return  parseInt(value);
        },
    });

    var ProgressView = widget.DOMWidgetView.extend({
        render : function(){
            // Called when view is rendered.
            this.$el
                .addClass('widget-hbox-single');
            this.$label = $('<div />')
                .appendTo(this.$el)
                .addClass('widget-hlabel')
                .hide();
            this.$progress = $('<div />')
                .addClass('progress')
                .addClass('widget-progress')
                .appendTo(this.$el);
            this.$el_to_style = this.$progress; // Set default element to style
            this.$bar = $('<div />')
                .addClass('progress-bar')
                .css('width', '50%')
                .appendTo(this.$progress);
            this.update(); // Set defaults.
        },

        update : function(){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            var value = this.model.get('value');
            var max = this.model.get('max');
            var min = this.model.get('min');
            var percent = 100.0 * (value - min) / (max - min);
            this.$bar.css('width', percent + '%');

            var description = this.model.get('description');
            if (description.length === 0) {
                this.$label.hide();
            } else {
                this.$label.text(description);
                MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.$label.get(0)]);
                this.$label.show();
            }
            return ProgressView.__super__.update.apply(this);
        },
    });

    return {
        'IntSliderView': IntSliderView,
        'IntTextView': IntTextView,
        'ProgressView': ProgressView,
    };
});
<|endoftext|>


<commit_before>import React from 'react';
import {
	View,
	Text,
	ListView,
	StyleSheet,
	TouchableHighlight,
	List,
	FlatList
} from 'react-native';

import { getClasses, getFinals } from './scheduleData';
import { FullScheduleListView } from './FullScheduleListView';
import ScrollCard from '../card/ScrollCard';
import Card from '../card/Card';
import Touchable from '../common/Touchable';
import logger from '../../util/logger';
import Icon from 'react-native-vector-icons/Ionicons';
import css from '../../styles/css';
import {
	COLOR_DGREY,
	COLOR_MGREY,
	COLOR_PRIMARY,
	COLOR_LGREY,
	COLOR_SECONDARY,
} from '../../styles/ColorConstants';
import {
	MAX_CARD_WIDTH,
} from '../../styles/LayoutConstants';

var scheduleData = getClasses();
var dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });

var ScheduleCard = () => {
	logger.ga('Card Mounted: Class Schedule');

	return (
		<Card
			id='schedule'
			title='Class Schedule'>
			<ListView
                dataSource={dataSource.cloneWithRows(scheduleData)}
                renderRow={(rowData, sectionID, rowID, highlightRow) => (
					<ScheduleDay
						id={rowID}
						data={rowData}
					/>
                )}
            />
			<View style={css.sc_dayContainer}>
				<TouchableHighlight style={css.dc_locations_row_right} underlayColor={'rgba(200,200,200,.1)'} onPress={() => general.gotoNavigationApp(data.coords.lat, data.coords.lon)}>
					<View style={css.dl_dir_traveltype_container}>
						<Icon name="md-walk" size={32} color={COLOR_SECONDARY} />
					</View>
				</TouchableHighlight>
			</View>
			<Touchable
				style={styles.fullScheduleButton}
				onPress={() => FullScheduleListView()}>
					<Text style={styles.more_label}>
						View Full Schedule
					</Text>
			</Touchable>
		</Card>
	);

	// 	<Card
	// 		id='schedule'
	// 		title= {scheduleData['MO'][0].instructor_name} //'Class Schedule'
	// 		listData={scheduleData}
	// 		renderRow={
	// 			(rowData, sectionID, rowID, highlightRow) => (
	// 				(rowID !== 'SA' && rowID !== 'SU') ? (
	// 					<ScheduleDay
	// 						id={rowID}
	// 						data={rowData}
	// 					/>
	// 				) : (null)
	// 		)}
	// 		actionButton={null}
	// 		extraActions={null}
	// 		updateScroll={null}
	// 		lastScroll={null}
	// 	/>
	// );
};

var ScheduleDay = ({ id, data }) => (
	<View style={css.sc_dayContainer}>
		<Text style={css.sc_dayText}>
			{id}
		</Text>
		<DayList courseItems={data} />
	</View>
);

var DayList = ({ courseItems }) => (
	<ListView
		dataSource={dataSource.cloneWithRows(courseItems)}
		renderRow={(rowData, sectionID, rowID, highlightRow) => (
			<DayItem key={rowID} data={rowData} />
		)}
	/>
);

var DayItem = ({ data }) => (
	<View style={css.sc_dayRow}>
		<Text
			style={css.sc_courseText}
			numberOfLines={1}
		>
			{data.course_title}
		</Text>
		<Text style={css.sc_subText}>
			{data.meeting_type + ' ' + data.time_string + '\n'}
			{data.instructor_name + '\n'}
			{data.building + data.room}
		</Text>
	</View>
);

const styles = StyleSheet.create({
	more: { alignItems: 'center', justifyContent: 'center', padding: 6 },
	more_label: { fontSize: 20, color: COLOR_PRIMARY, fontWeight: '300' },
	specialEventsListView: { borderBottomWidth: 1, borderBottomColor: COLOR_MGREY },
	nextClassContainer: { flexGrow: 1, width: MAX_CARD_WIDTH },
	contentContainer: { flexShrink: 1, width: MAX_CARD_WIDTH },
	fullScheduleButton: { width: MAX_CARD_WIDTH, backgroundColor: COLOR_LGREY, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 4, paddingVertical: 8, borderTopWidth: 1, borderBottomWidth: 1, borderColor: COLOR_MGREY },
});

export default ScheduleCard;
<commit_msg>Adjusting css<commit_after>import React from 'react';
import {
	View,
	Text,
	ListView,
	StyleSheet,
	TouchableHighlight,
	List,
	FlatList
} from 'react-native';

import { getClasses, getFinals } from './scheduleData';
import { FullScheduleListView } from './FullScheduleListView';
import ScrollCard from '../card/ScrollCard';
import Card from '../card/Card';
import Touchable from '../common/Touchable';
import logger from '../../util/logger';
import Icon from 'react-native-vector-icons/Ionicons';
import css from '../../styles/css';
import {
	COLOR_DGREY,
	COLOR_MGREY,
	COLOR_PRIMARY,
	COLOR_LGREY,
	COLOR_SECONDARY,
} from '../../styles/ColorConstants';
import {
	MAX_CARD_WIDTH,
} from '../../styles/LayoutConstants';

var scheduleData = getClasses();
var dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });

var ScheduleCard = () => {
	logger.ga('Card Mounted: Class Schedule');

	return (
		<Card
			id='schedule'
			title='Class Schedule'>
			<ListView
                dataSource={dataSource.cloneWithRows(scheduleData)}
                renderRow={(rowData, sectionID, rowID, highlightRow) => (
					<ScheduleDay
						id={rowID}
						data={rowData}
					/>
                )}
            />
			<View style={css.sc_dayContainer}>
				<TouchableHighlight style={css.dc_locations_row_right} underlayColor={'rgba(200,200,200,.1)'} onPress={() => general.gotoNavigationApp(data.coords.lat, data.coords.lon)}>
					<View style={css.dl_dir_traveltype_container}>
						<Icon name="md-walk" size={32} color={COLOR_SECONDARY} />
					</View>
				</TouchableHighlight>
			</View>
			<Touchable
				style={styles.fullScheduleButton}
				onPress={() => FullScheduleListView()}>
					<Text style={styles.more_label}>
						View Full Schedule
					</Text>
			</Touchable>
		</Card>
	);

	// 	<Card
	// 		id='schedule'
	// 		title= {scheduleData['MO'][0].instructor_name} //'Class Schedule'
	// 		listData={scheduleData}
	// 		renderRow={
	// 			(rowData, sectionID, rowID, highlightRow) => (
	// 				(rowID !== 'SA' && rowID !== 'SU') ? (
	// 					<ScheduleDay
	// 						id={rowID}
	// 						data={rowData}
	// 					/>
	// 				) : (null)
	// 		)}
	// 		actionButton={null}
	// 		extraActions={null}
	// 		updateScroll={null}
	// 		lastScroll={null}
	// 	/>
	// );
};

var ScheduleDay = ({ id, data }) => (
	<View style={css.sc_dayContainer}>
		<Text style={css.sc_dayText}>
			{id}
		</Text>
			<DayList style={{alignSelf: 'flex-end'}}
		courseItems={data} />
	</View>
);

var DayList = ({ courseItems }) => (
	<ListView
		dataSource={dataSource.cloneWithRows(courseItems)}
		renderRow={(rowData, sectionID, rowID, highlightRow) => (
			<DayItem key={rowID} data={rowData} />
		)}
	/>
);

var DayItem = ({ data }) => (
	<View style={css.sc_dayRow}>
		<Text
			style={css.sc_courseText}
			numberOfLines={1}
		>
			{data.course_title}
		</Text>
		<Text style={css.sc_subText}>
			{data.meeting_type + ' ' + data.time_string + '\n'}
			{data.instructor_name + '\n'}
			{data.building + data.room}
		</Text>
	</View>
);

const styles = StyleSheet.create({
	more: { alignItems: 'center', justifyContent: 'center', padding: 6 },
	more_label: { fontSize: 20, color: COLOR_PRIMARY, fontWeight: '300' },
	specialEventsListView: { borderBottomWidth: 1, borderBottomColor: COLOR_MGREY },
	nextClassContainer: { flexGrow: 1, width: MAX_CARD_WIDTH },
	contentContainer: { flexShrink: 1, width: MAX_CARD_WIDTH },
	fullScheduleButton: { width: MAX_CARD_WIDTH, backgroundColor: COLOR_LGREY, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 4, paddingVertical: 8, borderTopWidth: 1, borderBottomWidth: 1, borderColor: COLOR_MGREY },
});

export default ScheduleCard;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import {
	View,
	Text,
	ListView,
	StyleSheet,
	TouchableHighlight,
	ActivityIndicator,
	TextInput
} from 'react-native';

import { getClasses, getFinals } from './scheduleData';
import { FullScheduleListView } from './FullScheduleListView';
import ScrollCard from '../card/ScrollCard';
import Card from '../card/Card';
import FullScheduleButton from './FullScheduleButton';

import Touchable from '../common/Touchable';
import logger from '../../util/logger';
import Icon from 'react-native-vector-icons/Ionicons';
import css from '../../styles/css';
import {
	COLOR_DGREY,
	COLOR_MGREY,
	COLOR_PRIMARY,
	COLOR_LGREY,
	COLOR_SECONDARY,
	COLOR_BLACK,
	COLOR_VDGREY
} from '../../styles/ColorConstants';
import {
	MAX_CARD_WIDTH,
} from '../../styles/LayoutConstants';

// var scheduleData = getClasses();
var dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });

const ScheduleCard = ({ scheduleData, actionButton }) => (
	<Card id="schedule" title="Upcoming Classes" >
		{scheduleData ? (
			<View style={styles.sc_scheduleCard}>
				<View style={styles.sc_scheduleContainer}>
					{/* <TouchableHighlight style={styles.dc_locations_row_right} underlayColor={'rgba(200,200,200,.1)'} onPress={() => general.gotoNavigationApp(data.coords.lat, data.coords.lon)}>
						<View style={css.dl_dir_traveltype_container}>
							<Icon name="md-walk" size={32} color={COLOR_SECONDARY} />
						</View>
					</TouchableHighlight> */}
					<View style = {{flex: 6, alignItems: 'flex-start', }}>
						<View>
							<TextInput style={{height:20, width:150, fontSize:20, fontWeight:'bold', color: COLOR_VDGREY }} value={'Class Time Label'} />
							<TextInput style={{height:20, width:150, fontSize:20, fontWeight:'bold'}} value ={'Course Label'} editable={false} ref={component=> this.courseLabel=component} />
						</View>

						<Text style={{fontSize:20}}>
							{"In session"}
						</Text>

						<View>
							<TextInput style={{height:20, width:150, fontSize:20}} value = 'Location Label' editable={false} ref={component=> this.locationLabel=component} />
						</View>

						<Text style={{fontSize:20}}>
								1 More Class Today
						</Text>
					</View>
					<View style={{flex: 4}}>
						<ListView
							dataSource={dataSource.cloneWithRows(scheduleData)}
							renderRow={(rowData, sectionID, rowID, highlightRow) => (
								(rowID !== 'SA' && rowID !== 'SU') ? (
								<ScheduleDay
									id={rowID}
									data={rowData}
								/>
								) : (null)
							)}
						/>
					</View>
				</View>
				{actionButton}
			</View>
		) : (
			<View style={styles.loadingContainer}>
				<ActivityIndicator size="large" />
			</View>
		)}
	</Card>
);

const styles = StyleSheet.create({
	_rightHalf: {
		flex: 4,
		padding: 0,
	},
	more: { alignItems: 'center', justifyContent: 'center', padding: 6 },
	more_label: { fontSize: 20, color: COLOR_PRIMARY, fontWeight: '300' },
	specialEventsListView: { borderBottomWidth: 1, borderBottomColor: COLOR_MGREY },
	nextClassContainer: { flexGrow: 1, width: MAX_CARD_WIDTH },
	contentContainer: { flexShrink: 1, width: MAX_CARD_WIDTH },
	fullScheduleButton: { width: MAX_CARD_WIDTH, backgroundColor: COLOR_LGREY, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 4, paddingVertical: 8, borderTopWidth: 1, borderBottomWidth: 1, borderColor: COLOR_MGREY },
	loadingContainer: { alignItems: 'center', justifyContent: 'center', width: MAX_CARD_WIDTH },
	scheduleList: { flex: 1, justifyContent: 'flex-end', alignItems: 'flex-end'},
	sc_dayRow: { justifyContent: 'center', padding: 3, borderColor: COLOR_BLACK, borderWidth: 1, flex: 1, width: '100%', flexDirection: 'row'},
	dayListStyle: {flex: 1, paddingRight: 10 /* align0 Items:'flex-end'*/},
	sc_scheduleContainer: { width: MAX_CARD_WIDTH, padding: 10, flexDirection:'row', flex:1, justifyContent: 'center'},
	sc_scheduleCard: { width: MAX_CARD_WIDTH + 2, padding: 7, flexDirection:'column', flex: 1},
	sc_dayText: { fontSize: 16, color: COLOR_BLACK, /*paddingBottom: 6 */},
	dc_locations_row_right: { flex: 6 },
	sc_courseText: { fontSize: 24, color: COLOR_VDGREY, /*paddingBottom: 2 */},
	sc_subText: { fontSize: 16, color: COLOR_VDGREY, paddingBottom: 2},
	sc_timeText: { fontSize: 12, color: COLOR_VDGREY },
});

// Holds the the daylist listview (currently only used as a container for the listview)
var ScheduleDay = ({ id, data }) => (
	// <View style={css.sc_dayContainer}>
	<View style={styles.scheduleList}>
		<DayList
			courseItems={data} />
	</View>
);

// Holds the listview for a day of the week
var DayList = ({ courseItems }) => (
	<ListView
		style={styles.dayListStyle}
		dataSource={dataSource.cloneWithRows(courseItems)}
		renderRow={(rowData, sectionID, rowID, highlightRow) => (

			<DayItem key={rowID} data={rowData} />
		)}
	/>
);

// Holds the view for an individual section/class
var DayItem = ({ data }) => (
	<TouchableHighlight onPress= {
		()=>{this.courseLabel.setNativeProps({text: data.subject_code + ' ' + data.course_code})
		this.timeLabel.setNativeProps({text: data.day_code + ' ' + data.time_string})
		this.locationLabel.setNativeProps({text: data.building + ' ' + data.room}) }
		}>
		<View style={styles.sc_dayRow}>
			<View style={{flex:6, flexDirection: 'column', justifyContent: 'flex-end'}}>
				<Text style={styles.sc_timeText}>
					{data.day_code + ' ' + data.time_string}
				</Text>
				<Text
					style={styles.sc_courseText}
					numberOfLines={1}
				>
					{data.subject_code + ' ' + data.course_code}
				</Text>
			</View>
			<View style={{flex:1, flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'flex-start'}}>
				<Text style={[styles.sc_subText]} numberOfLines={1}>
					{data.meeting_type === 'Lecture' && 'LE'}
					{data.meeting_type === 'Discussion' && 'DI'}
					{/*data.meeting_type/* + ' ' + data.time_string + '\n' */}
					{/* {data.instructor_name + '\n'}
					{data.building + data.room} */}
				</Text>
			</View>
		</View>
	</TouchableHighlight>
);

ScheduleCard.propTypes = {
	scheduleData: PropTypes.object,
	actionButton: PropTypes.element
};

export default ScheduleCard;
<commit_msg>card styling in progress<commit_after>import React, { PropTypes } from 'react';
import {
	View,
	Text,
	ListView,
	StyleSheet,
	TouchableHighlight,
	ActivityIndicator,
	TextInput
} from 'react-native';

import { getClasses, getFinals } from './scheduleData';
import { FullScheduleListView } from './FullScheduleListView';
import ScrollCard from '../card/ScrollCard';
import Card from '../card/Card';
import FullScheduleButton from './FullScheduleButton';

import Touchable from '../common/Touchable';
import logger from '../../util/logger';
import Icon from 'react-native-vector-icons/Ionicons';
import css from '../../styles/css';
import {
	COLOR_DGREY,
	COLOR_MGREY,
	COLOR_PRIMARY,
	COLOR_LGREY,
	COLOR_SECONDARY,
	COLOR_BLACK,
	COLOR_VDGREY
} from '../../styles/ColorConstants';
import {
	MAX_CARD_WIDTH,
} from '../../styles/LayoutConstants';

// var scheduleData = getClasses();
var dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });

const ScheduleCard = ({ scheduleData, actionButton }) => (
	<Card id="schedule" title="Upcoming Classes" >
		{scheduleData ? (
			<View style={styles.sc_scheduleCard}>
				<View style={styles.sc_scheduleContainer}>
					{/* <TouchableHighlight style={styles.dc_locations_row_right} underlayColor={'rgba(200,200,200,.1)'} onPress={() => general.gotoNavigationApp(data.coords.lat, data.coords.lon)}>
						<View style={css.dl_dir_traveltype_container}>
							<Icon name="md-walk" size={32} color={COLOR_SECONDARY} />
						</View>
					</TouchableHighlight> */}
					<View style = {styles._leftHalf}>
						<View>
							<TextInput style={{height:20, width:150, fontSize:20, fontWeight:'bold', color: COLOR_VDGREY }} value={'Class Time Label'} />
							<TextInput style={{height:20, width:150, fontSize:20, fontWeight:'bold'}} value ={'Course Label'} editable={false} ref={component=> this.courseLabel=component} />
						</View>

						<Text style={{fontSize:20}}>
							{"In session"}
						</Text>

						<View>
							<TextInput style={{height:20, width:150, fontSize:20}} value = 'Location Label' editable={false} ref={component=> this.locationLabel=component} />
						</View>

						<Text style={{fontSize:20}}>
								1 More Class Today
						</Text>
					</View>
					<View style={styles._rightHalf}>
						<ListView
							dataSource={dataSource.cloneWithRows(scheduleData)}
							renderRow={(rowData, sectionID, rowID, highlightRow) => (
								(rowID !== 'SA' && rowID !== 'SU') ? (
								<ScheduleDay
									id={rowID}
									data={rowData}
								/>
								) : (null)
							)}
						/>
					</View>
				</View>
				{actionButton}
			</View>
		) : (
			<View style={styles.loadingContainer}>
				<ActivityIndicator size="large" />
			</View>
		)}
	</Card>
);

const styles = StyleSheet.create({
	_leftHalf: {
		flex: 6,
		padding: 0,
		backgroundColor: '#98FB98',
	},
	_rightHalf: {
		flex: 4,
		padding: 0,
		backgroundColor: '#FFC0CB',
	},
	more: { alignItems: 'center', justifyContent: 'center', padding: 6 },
	more_label: { fontSize: 20, color: COLOR_PRIMARY, fontWeight: '300' },
	specialEventsListView: { borderBottomWidth: 1, borderBottomColor: COLOR_MGREY },
	nextClassContainer: { flexGrow: 1, width: MAX_CARD_WIDTH },
	contentContainer: { flexShrink: 1, width: MAX_CARD_WIDTH },
	fullScheduleButton: { width: MAX_CARD_WIDTH, backgroundColor: COLOR_LGREY, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 4, paddingVertical: 8, borderTopWidth: 1, borderBottomWidth: 1, borderColor: COLOR_MGREY },
	loadingContainer: { alignItems: 'center', justifyContent: 'center', width: MAX_CARD_WIDTH },
	scheduleList: { flex: 1, justifyContent: 'flex-end', alignItems: 'flex-end'},
	sc_dayRow: { justifyContent: 'center', padding: 3, borderColor: COLOR_BLACK, borderWidth: 1, flex: 1, width: '100%', flexDirection: 'row'},
	dayListStyle: {flex: 1, paddingRight: 10 /* align0 Items:'flex-end'*/},
	sc_scheduleContainer: { width: MAX_CARD_WIDTH, padding: 10, flexDirection:'row', flex:1, justifyContent: 'center'},
	sc_scheduleCard: { width: MAX_CARD_WIDTH + 2, padding: 0, flexDirection:'column', flex: 1},
	sc_dayText: { fontSize: 16, color: COLOR_BLACK, /*paddingBottom: 6 */},
	dc_locations_row_right: { flex: 6 },
	sc_courseText: { fontSize: 24, color: COLOR_VDGREY, /*paddingBottom: 2 */},
	sc_subText: { fontSize: 16, color: COLOR_VDGREY, paddingBottom: 2},
	sc_timeText: { fontSize: 12, color: COLOR_VDGREY },
});

// Holds the the daylist listview (currently only used as a container for the listview)
var ScheduleDay = ({ id, data }) => (
	// <View style={css.sc_dayContainer}>
	<View style={styles.scheduleList}>
		<DayList
			courseItems={data} />
	</View>
);

// Holds the listview for a day of the week
var DayList = ({ courseItems }) => (
	<ListView
		style={styles.dayListStyle}
		dataSource={dataSource.cloneWithRows(courseItems)}
		renderRow={(rowData, sectionID, rowID, highlightRow) => (

			<DayItem key={rowID} data={rowData} />
		)}
	/>
);

// Holds the view for an individual section/class
var DayItem = ({ data }) => (
	<TouchableHighlight onPress= {
		()=>{this.courseLabel.setNativeProps({text: data.subject_code + ' ' + data.course_code})
		this.timeLabel.setNativeProps({text: data.day_code + ' ' + data.time_string})
		this.locationLabel.setNativeProps({text: data.building + ' ' + data.room}) }
		}>
		<View style={styles.sc_dayRow}>
			<View style={{flex:6, flexDirection: 'column', justifyContent: 'flex-end'}}>
				<Text style={styles.sc_timeText}>
					{data.day_code + ' ' + data.time_string}
				</Text>
				<Text
					style={styles.sc_courseText}
					numberOfLines={1}
				>
					{data.subject_code + ' ' + data.course_code}
				</Text>
			</View>
			<View style={{flex:1, flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'flex-start'}}>
				<Text style={[styles.sc_subText]} numberOfLines={1}>
					{data.meeting_type === 'Lecture' && 'LE'}
					{data.meeting_type === 'Discussion' && 'DI'}
					{/*data.meeting_type/* + ' ' + data.time_string + '\n' */}
					{/* {data.instructor_name + '\n'}
					{data.building + data.room} */}
				</Text>
			</View>
		</View>
	</TouchableHighlight>
);

ScheduleCard.propTypes = {
	scheduleData: PropTypes.object,
	actionButton: PropTypes.element
};

export default ScheduleCard;
<|endoftext|>


<commit_before>// ==UserScript==
// @name        hvFeed
// @name:zh-CN  【HV】喂食
// @author      Dodying
// @namespace   https://github.com/dodying/Dodying-UserJs
// @supportURL  https://github.com/dodying/Dodying-UserJs/issues
// @icon        http://cdn4.iconfinder.com/data/icons/mood-smiles/80/mood-29-48.png
// @include     http://hentaiverse.org/?s=Bazaar&ss=ml
// @version     1.01a
// @grant       none
// @run-at      document-idle
// ==/UserScript==
function init() {
  var items = document.querySelectorAll('.msa .fd4 div');
  var moraleBar = document.querySelectorAll('div[style*="moralebar.png"]');
  var level;
  for (var i = 0; i < moraleBar.length; i++) {
    level = items[5 * i + 2].innerHTML;
    if (level >= 100 && !moraleBar[i].querySelector('img[src*="bar_green.png"]')) break;
  }
  feed(i + 1, moraleBar);
}
function feed(refer, moraleBar) {
  var xhr;
  xhr = new XMLHttpRequest();
  xhr.open('POST', 'http://hentaiverse.org/?s=Bazaar&ss=ml&slot=' + refer);
  var parm = 'food_action=happyhappyjoyjoy';
  xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  xhr.responseType = 'document';
  xhr.send(parm);
  xhr.onload = function (e) {
    var data = e.target.response;
    if (!data.querySelector('div[style*="moralebar.png"]>img[src*="bar_green.png"]')) {
      document.title = 'Happy Pill has been uesd up.';
      return;
    } else {
      document.title = 'No.' + refer + ' Monster has been fed.';
      moraleBar[refer - 1].parentNode.replaceChild(data.querySelector('div[style*="moralebar.png"]'), moraleBar[refer - 1]);
      init();
    }
  }
}
init();
<commit_msg>v1.01b<commit_after>// ==UserScript==
// @name        hvFeed
// @name:zh-CN  【HV】喂食
// @author      Dodying
// @namespace   https://github.com/dodying/Dodying-UserJs
// @supportURL  https://github.com/dodying/Dodying-UserJs/issues
// @icon        http://cdn4.iconfinder.com/data/icons/mood-smiles/80/mood-29-48.png
// @include     http*://alt.hentaiverse.org/?s=Bazaar&ss=ml
// @version     1.01b
// @grant       none
// @run-at      document-idle
// ==/UserScript==
function init() {
  var items = document.querySelectorAll('.msa .fd4 div');
  var moraleBar = document.querySelectorAll('div[style*="moralebar.png"]');
  var level;
  for (var i = 0; i < moraleBar.length; i++) {
    level = items[5 * i + 2].innerHTML;
    if (level >= 100 && !moraleBar[i].querySelector('img[src*="bar_green.png"]')) break;
  }
  feed(i + 1, moraleBar);
}
function feed(refer, moraleBar) {
  var xhr;
  xhr = new XMLHttpRequest();
  xhr.open('POST', location + '&slot=' + refer);
  var parm = 'food_action=happyhappyjoyjoy';
  xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  xhr.responseType = 'document';
  xhr.send(parm);
  xhr.onload = function (e) {
    var data = e.target.response;
    if (!data.querySelector('div[style*="moralebar.png"]>img[src*="bar_green.png"]')) {
      document.title = 'Happy Pill has been uesd up.';
      return;
    } else {
      document.title = 'No.' + refer + ' Monster has been fed.';
      moraleBar[refer - 1].parentNode.replaceChild(data.querySelector('div[style*="moralebar.png"]'), moraleBar[refer - 1]);
      init();
    }
  }
}
init();
<|endoftext|>


<commit_before>import Service from '@ember/service';
import config from 'nomad-ui/config/environment';
import { getOwner } from '@ember/application';

export default class SocketsService extends Service {
  getTaskStateSocket(taskState, command) {
    const mirageEnabled =
      config.environment !== 'production' &&
      config['ember-cli-mirage'] &&
      config['ember-cli-mirage'].enabled !== false;

    if (mirageEnabled) {
      return new Object({
        messageDisplayed: false,

        send(e) {
          if (!this.messageDisplayed) {
            this.messageDisplayed = true;
            this.onmessage({ data: `{"stdout":{"data":"${btoa('unsupported in Mirage\n\r')}"}}` });
          } else {
            this.onmessage({ data: e.replace('stdin', 'stdout') });
          }
        },
      });
    } else {
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      const applicationAdapter = getOwner(this).lookup('adapter:application');
      const prefix = `${applicationAdapter.host ||
        window.location.host}/${applicationAdapter.urlPrefix()}`;

      return new WebSocket(
        `${protocol}//${prefix}/client/allocation/${taskState.allocation.id}` +
          `/exec?task=${taskState.name}&tty=true&ws_handshake=true` +
          `&command=${encodeURIComponent(`["${command}"]`)}`
      );
    }
  }
}
<commit_msg>Fix exec not working for another region (#10539)<commit_after>import Service from '@ember/service';
import config from 'nomad-ui/config/environment';
import { getOwner } from '@ember/application';
import { inject as service } from '@ember/service';

export default class SocketsService extends Service {
  @service system;

  getTaskStateSocket(taskState, command) {
    const mirageEnabled =
      config.environment !== 'production' &&
      config['ember-cli-mirage'] &&
      config['ember-cli-mirage'].enabled !== false;

    if (mirageEnabled) {
      return new Object({
        messageDisplayed: false,

        send(e) {
          if (!this.messageDisplayed) {
            this.messageDisplayed = true;
            this.onmessage({ data: `{"stdout":{"data":"${btoa('unsupported in Mirage\n\r')}"}}` });
          } else {
            this.onmessage({ data: e.replace('stdin', 'stdout') });
          }
        },
      });
    } else {
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      const applicationAdapter = getOwner(this).lookup('adapter:application');
      const prefix = `${applicationAdapter.host ||
        window.location.host}/${applicationAdapter.urlPrefix()}`;
      const region = this.system.activeRegion;

      return new WebSocket(
        `${protocol}//${prefix}/client/allocation/${taskState.allocation.id}` +
          `/exec?task=${taskState.name}&tty=true&ws_handshake=true` +
          (region ? `&region=${region}` : '') +
          `&command=${encodeURIComponent(`["${command}"]`)}`
      );
    }
  }
}
<|endoftext|>


<commit_before>function setEditorSize(){
	// Sets the size of the text editor window.
	fillWindow($('#editor'));
}

function getFileExtension(file){
	var parts=file.split('.');
	return parts[parts.length-1];
}

function setSyntaxMode(ext){
	// Loads the syntax mode files and tells the editor
	var filetype = new Array();
	// Todo finish these
    filetype["h"] = "c_cpp";
    filetype["c"] = "c_cpp";
    filetype["clj"] = "clojure";
    filetype["coffee"] = "coffee"; // coffescript can be compiled to javascript
    filetype["coldfusion"] = "cfc";
    filetype["cpp"] = "c_cpp";
    filetype["cs"] = "csharp";
	filetype["css"] = "css";
    filetype["groovy"] = "groovy";
   	filetype["haxe"] = "hx";
	filetype["html"] = "html";
    filetype["java"] = "java";
	filetype["js"] = "javascript";
    filetype["json"] = "json";
   	filetype["latex"] = "latex";
    filetype["lua"] = "lua";
    filetype["markdown"] = "markdown"; // also: .md .markdown .mdown .mdwn
    filetype["ml"] = "ocaml";
    filetype["mli"] = "ocaml";
	filetype["pl"] = "perl";
	filetype["php"] = "php";
	filetype["powershell"] = "ps1";
	filetype["py"] = "python";
	filetype["rb"] = "ruby";
    filetype["scad"] = "scad"; // seems to be something like 3d model files printed with e.g. reprap
    filetype["scala"] = "scala";
    filetype["scss"] = "scss"; // "sassy css"
    filetype["sql"] = "sql";
    filetype["svg"] = "svg";
    filetype["textile"] = "textile"; // related to markdown
	filetype["xml"] = "xml";

	if(filetype[ext]!=null){
		// Then it must be in the array, so load the custom syntax mode
		// Set the syntax mode
		OC.addScript('files_texteditor','aceeditor/mode-'+filetype[ext], function(){
			var SyntaxMode = require("ace/mode/"+filetype[ext]).Mode;
			window.aceEditor.getSession().setMode(new SyntaxMode());
		});
	}
}

function showControls(filename){
	// Loads the control bar at the top.
	$('.actions,#file_action_panel').fadeOut('slow').promise().done(function() {
		// Load the new toolbar.
		var savebtnhtml = '<input type="button" id="editor_save" value="'+t('files_texteditor','Save')+'">';
		var html = '<input type="button" id="editor_close" value="Close">';
		$('#controls').append(html);
		$('#editorbar').fadeIn('slow');
		var breadcrumbhtml = '

'+filename+'

';
		$('.actions').before(breadcrumbhtml).before(savebtnhtml);
	});
}

function bindControlEvents(){
	$("#editor_save").die('click',doFileSave).live('click',doFileSave);
	$('#editor_close').die('click',hideFileEditor).live('click',hideFileEditor);
}

function editorIsShown(){
	// Not working as intended. Always returns true.
	return is_editor_shown;
}

function doFileSave(){
	if(editorIsShown()){
		// Get file path
		var path = $('#editor').attr('data-dir')+'/'+$('#editor').attr('data-filename');
		// Get original mtime
		var mtime = $('#editor').attr('data-mtime');
		// Show saving spinner
		$("#editor_save").die('click',doFileSave);
		$('#editor_save').after('');
		// Get the data
		var filecontents = window.aceEditor.getSession().getValue();
		// Send the data
		$.post(OC.filePath('files_texteditor','ajax','savefile.php'), { filecontents: filecontents, path: path, mtime: mtime },function(jsondata){
			if(jsondata.status!='success'){
				// Save failed
				$('#saving_icon').remove();
				$('#editor_save').after('
Failed to save file
');
				setTimeout(function() {
					$('#save_result').fadeOut('slow',function(){
						$(this).remove();
						$("#editor_save").live('click',doFileSave);
					});
				}, 2000);
			} else {
				// Save OK
				// Update mtime
				$('#editor').attr('data-mtime',jsondata.data.mtime);
				// Show result
				$('#saving_icon').remove();
				$('#editor_save').after('
Saved
')
				setTimeout(function() {
					$('#save_result').fadeOut('slow',function(){
						$(this).remove();
						$("#editor_save").live('click',doFileSave);
					});
				}, 2000);
			}
		},'json');
	}
};

function giveEditorFocus(){
	window.aceEditor.focus();
};

function showFileEditor(dir,filename){
	if(!editorIsShown()){
		// Loads the file editor and display it.
		var data = $.ajax({
				url: OC.filePath('files_texteditor','ajax','loadfile.php'),
				data: 'file='+encodeURIComponent(filename)+'&dir='+encodeURIComponent(dir),
				complete: function(data){
					result = jQuery.parseJSON(data.responseText);
					if(result.status == 'success'){
						// Save mtime
						$('#editor').attr('data-mtime', result.data.mtime);
						// Initialise the editor
						showControls(filename);
						$('table').fadeOut('slow', function() {
							$('#editor').text(result.data.filecontents);
							$('#editor').attr('data-dir', dir);
							$('#editor').attr('data-filename', filename);
							window.aceEditor = ace.edit("editor");
							aceEditor.setShowPrintMargin(false);
							if(result.data.write=='false'){
								aceEditor.setReadOnly(true);
							}
							setEditorSize();
							setSyntaxMode(getFileExtension(filename));
							OC.addScript('files_texteditor','aceeditor/theme-clouds', function(){
								window.aceEditor.setTheme("ace/theme/clouds");
							});
						});
					} else {
						// Failed to get the file.
						alert(result.data.message);
					}
				// End success
				}
				// End ajax
				});
		is_editor_shown = true;
	}
}

function hideFileEditor(){
	// Fade out controls
	$('#editor_close').fadeOut('slow');
	// Fade out the save button
	$('#editor_save').fadeOut('slow');
	// Fade out breadcrumb
	$('#breadcrumb_file').fadeOut('slow', function(){ $(this).remove();});
	// Fade out editor
	$('#editor').fadeOut('slow', function(){
		$('#editor_close').remove();
		$('#editor_save').remove();
		$('#editor').remove();
		var editorhtml = '

';
		$('table').after(editorhtml);
		$('.actions,#file_access_panel').fadeIn('slow');
		$('table').fadeIn('slow');
	});
	is_editor_shown = false;
}

// Keyboard Shortcuts
var ctrlBtn = false;

function checkForSaveKeyPress(e){
	if(e.which == 17 || e.which == 91) ctrlBtn=true;
	if(e.which == 83 && ctrlBtn == true) {
	e.preventDefault();
	$('#editor_save').trigger('click');
	return false;

	}
}

$(window).resize(function() {
	setEditorSize();
});
var is_editor_shown = false;
$(document).ready(function(){
	if(typeof FileActions!=='undefined'){
		FileActions.register('text','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('text','Edit');
		FileActions.register('application/xml','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('application/xml','Edit');
	}
	OC.search.customResults.Text=function(row,item){
		var text=item.link.substr(item.link.indexOf('file=')+5);
		var a=row.find('a');
		a.data('file',text);
		a.attr('href','#');
		a.click(function(){
			var file=text.split('/').pop();
			var dir=text.substr(0,text.length-file.length-1);
			showFileEditor(dir,file);
		});
	}
	// Binds the file save and close editor events
	bindControlEvents();

	// Binds the save keyboard shortcut events
	$(document).unbind('keydown').bind('keydown',checkForSaveKeyPress);
});
<commit_msg>hide save button for read-only files<commit_after>function setEditorSize(){
	// Sets the size of the text editor window.
	fillWindow($('#editor'));
}

function getFileExtension(file){
	var parts=file.split('.');
	return parts[parts.length-1];
}

function setSyntaxMode(ext){
	// Loads the syntax mode files and tells the editor
	var filetype = new Array();
	// Todo finish these
    filetype["h"] = "c_cpp";
    filetype["c"] = "c_cpp";
    filetype["clj"] = "clojure";
    filetype["coffee"] = "coffee"; // coffescript can be compiled to javascript
    filetype["coldfusion"] = "cfc";
    filetype["cpp"] = "c_cpp";
    filetype["cs"] = "csharp";
	filetype["css"] = "css";
    filetype["groovy"] = "groovy";
   	filetype["haxe"] = "hx";
	filetype["html"] = "html";
    filetype["java"] = "java";
	filetype["js"] = "javascript";
    filetype["json"] = "json";
   	filetype["latex"] = "latex";
    filetype["lua"] = "lua";
    filetype["markdown"] = "markdown"; // also: .md .markdown .mdown .mdwn
    filetype["ml"] = "ocaml";
    filetype["mli"] = "ocaml";
	filetype["pl"] = "perl";
	filetype["php"] = "php";
	filetype["powershell"] = "ps1";
	filetype["py"] = "python";
	filetype["rb"] = "ruby";
    filetype["scad"] = "scad"; // seems to be something like 3d model files printed with e.g. reprap
    filetype["scala"] = "scala";
    filetype["scss"] = "scss"; // "sassy css"
    filetype["sql"] = "sql";
    filetype["svg"] = "svg";
    filetype["textile"] = "textile"; // related to markdown
	filetype["xml"] = "xml";

	if(filetype[ext]!=null){
		// Then it must be in the array, so load the custom syntax mode
		// Set the syntax mode
		OC.addScript('files_texteditor','aceeditor/mode-'+filetype[ext], function(){
			var SyntaxMode = require("ace/mode/"+filetype[ext]).Mode;
			window.aceEditor.getSession().setMode(new SyntaxMode());
		});
	}
}

function showControls(filename,writeperms){
	// Loads the control bar at the top.
	$('.actions,#file_action_panel').fadeOut('slow').promise().done(function() {
		// Load the new toolbar.
		var savebtnhtml;
		if(writeperms=="true"){
			var savebtnhtml = '<input type="button" id="editor_save" value="'+t('files_texteditor','Save')+'">';
		}
		var html = '<input type="button" id="editor_close" value="Close">';
		$('#controls').append(html);
		$('#editorbar').fadeIn('slow');
		var breadcrumbhtml = '

'+filename+'

';
		$('.actions').before(breadcrumbhtml).before(savebtnhtml);
	});
}

function bindControlEvents(){
	$("#editor_save").die('click',doFileSave).live('click',doFileSave);
	$('#editor_close').die('click',hideFileEditor).live('click',hideFileEditor);
}

function editorIsShown(){
	// Not working as intended. Always returns true.
	return is_editor_shown;
}

function doFileSave(){
	if(editorIsShown()){
		// Get file path
		var path = $('#editor').attr('data-dir')+'/'+$('#editor').attr('data-filename');
		// Get original mtime
		var mtime = $('#editor').attr('data-mtime');
		// Show saving spinner
		$("#editor_save").die('click',doFileSave);
		$('#editor_save').after('');
		// Get the data
		var filecontents = window.aceEditor.getSession().getValue();
		// Send the data
		$.post(OC.filePath('files_texteditor','ajax','savefile.php'), { filecontents: filecontents, path: path, mtime: mtime },function(jsondata){
			if(jsondata.status!='success'){
				// Save failed
				$('#saving_icon').remove();
				$('#editor_save').after('
Failed to save file
');
				setTimeout(function() {
					$('#save_result').fadeOut('slow',function(){
						$(this).remove();
						$("#editor_save").live('click',doFileSave);
					});
				}, 2000);
			} else {
				// Save OK
				// Update mtime
				$('#editor').attr('data-mtime',jsondata.data.mtime);
				// Show result
				$('#saving_icon').remove();
				$('#editor_save').after('
Saved
')
				setTimeout(function() {
					$('#save_result').fadeOut('slow',function(){
						$(this).remove();
						$("#editor_save").live('click',doFileSave);
					});
				}, 2000);
			}
		},'json');
	}
};

function giveEditorFocus(){
	window.aceEditor.focus();
};

function showFileEditor(dir,filename){
	if(!editorIsShown()){
		// Loads the file editor and display it.
		var data = $.ajax({
				url: OC.filePath('files_texteditor','ajax','loadfile.php'),
				data: 'file='+encodeURIComponent(filename)+'&dir='+encodeURIComponent(dir),
				complete: function(data){
					result = jQuery.parseJSON(data.responseText);
					if(result.status == 'success'){
						// Save mtime
						$('#editor').attr('data-mtime', result.data.mtime);
						// Initialise the editor
						showControls(filename,result.data.write);
						$('table').fadeOut('slow', function() {
							$('#editor').text(result.data.filecontents);
							$('#editor').attr('data-dir', dir);
							$('#editor').attr('data-filename', filename);
							window.aceEditor = ace.edit("editor");
							aceEditor.setShowPrintMargin(false);
							if(result.data.write=='false'){
								aceEditor.setReadOnly(true);
							}
							setEditorSize();
							setSyntaxMode(getFileExtension(filename));
							OC.addScript('files_texteditor','aceeditor/theme-clouds', function(){
								window.aceEditor.setTheme("ace/theme/clouds");
							});
						});
					} else {
						// Failed to get the file.
						alert(result.data.message);
					}
				// End success
				}
				// End ajax
				});
		is_editor_shown = true;
	}
}

function hideFileEditor(){
	// Fade out controls
	$('#editor_close').fadeOut('slow');
	// Fade out the save button
	$('#editor_save').fadeOut('slow');
	// Fade out breadcrumb
	$('#breadcrumb_file').fadeOut('slow', function(){ $(this).remove();});
	// Fade out editor
	$('#editor').fadeOut('slow', function(){
		$('#editor_close').remove();
		$('#editor_save').remove();
		$('#editor').remove();
		var editorhtml = '

';
		$('table').after(editorhtml);
		$('.actions,#file_access_panel').fadeIn('slow');
		$('table').fadeIn('slow');
	});
	is_editor_shown = false;
}

// Keyboard Shortcuts
var ctrlBtn = false;

function checkForSaveKeyPress(e){
	if(e.which == 17 || e.which == 91) ctrlBtn=true;
	if(e.which == 83 && ctrlBtn == true) {
	e.preventDefault();
	$('#editor_save').trigger('click');
	return false;

	}
}

$(window).resize(function() {
	setEditorSize();
});
var is_editor_shown = false;
$(document).ready(function(){
	if(typeof FileActions!=='undefined'){
		FileActions.register('text','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('text','Edit');
		FileActions.register('application/xml','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('application/xml','Edit');
	}
	OC.search.customResults.Text=function(row,item){
		var text=item.link.substr(item.link.indexOf('file=')+5);
		var a=row.find('a');
		a.data('file',text);
		a.attr('href','#');
		a.click(function(){
			var file=text.split('/').pop();
			var dir=text.substr(0,text.length-file.length-1);
			showFileEditor(dir,file);
		});
	}
	// Binds the file save and close editor events
	bindControlEvents();

	// Binds the save keyboard shortcut events
	$(document).unbind('keydown').bind('keydown',checkForSaveKeyPress);
});
<|endoftext|>


<commit_before>var pm2 = require('pm2')

var instances = process.env.WEB_CONCURRENCY || 2
var maxMemory = process.env.WEB_MEMORY || 400
var killTimeout = process.env.KILL_TIMEOUT || 1600

pm2.connect(true, function () {
  pm2.start({
    script: 'dist/server-iso-entrypoint.js',
    name: 'web',
    exec_mode: 'cluster',
    instances,
    kill_timeout: killTimeout,
    max_memory_restart: maxMemory + 'M',
    cron_restart: "0,15,30,45 * * * *”",
    env: {
      "NODE_ENV": "production",
    },
  }, function (err) {
    if (err)
      return console.error("Error while launching applications", err.stack || err);
    console.log("PM2 and app successfully started")
    pm2.launchBus(function(err, bus) {
      console.log('[PM2] Log streaming started')
      bus.on('log:out', function (packet) {
        console.log('[App:%s-%s] %s',
                    packet.process.name,
                    packet.process.pm_id,
                    packet.data)
      })

      bus.on('log:err', function (packet) {
        console.error('[App:%s][Err] %s', packet.process.name, packet.data)
      })
    })
  })
})
<commit_msg>Update cron pattern<commit_after>var pm2 = require('pm2')

var instances = process.env.WEB_CONCURRENCY || 2
var maxMemory = process.env.WEB_MEMORY || 400
var killTimeout = process.env.KILL_TIMEOUT || 1600

pm2.connect(true, function () {
  pm2.start({
    script: 'dist/server-iso-entrypoint.js',
    name: 'web',
    exec_mode: 'cluster',
    instances,
    kill_timeout: killTimeout,
    max_memory_restart: maxMemory + 'M',
    cron_restart: "0,15,30,45 * * * *",
    env: {
      "NODE_ENV": "production",
    },
  }, function (err) {
    if (err)
      return console.error("Error while launching applications", err.stack || err);
    console.log("PM2 and app successfully started")
    pm2.launchBus(function(err, bus) {
      console.log('[PM2] Log streaming started')
      bus.on('log:out', function (packet) {
        console.log('[App:%s-%s] %s',
                    packet.process.name,
                    packet.process.pm_id,
                    packet.data)
      })

      bus.on('log:err', function (packet) {
        console.error('[App:%s][Err] %s', packet.process.name, packet.data)
      })
    })
  })
})
<|endoftext|>


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

// Run ampm under nodemon in case ampm itself crashes.

var nodemon = require('nodemon');
var path = require('path');

var configFile = process.argv[2] || 'config.json';
var appPath = path.resolve(path.dirname(configFile));

function start() {
    nodemon({
        script: path.join(__dirname, 'server.js'), // Run ampm's server.js
        verbose: true, // verbose doesn't seem to work?
        args: process.argv.slice(2), // Pass arguments on to ampm
        watch: [
            configFile.indexOf(',') !== -1 ? configFile.split(',') : configFile, // Restart when the ampm config file changes
            path.join(appPath, 'restart.json'), // Restart when ampm tries to tigger a restart itself.
            __dirname // Restart when ampm code changes, for doing development.
        ],
        ignore: [
            '.git', 'node_modules', 'logs', path.join(appPath, 'state.json')
        ]
    }).on('crash', start);
}
start();
<commit_msg>pass default args better<commit_after>#! /usr/bin/env node

// Run ampm under nodemon in case ampm itself crashes.

var nodemon = require('nodemon');
var path = require('path');

var configFile = process.argv[2] || 'config.json';
var mode = process.argv[3] || '';
var appPath = path.resolve(path.dirname(configFile));

function start() {
    nodemon({
        script: path.join(__dirname, 'server.js'), // Run ampm's server.js
        verbose: true, // verbose doesn't seem to work?
        args: [configFile, mode], // Pass arguments on to ampm
        watch: [
            configFile.indexOf(',') !== -1 ? configFile.split(',') : configFile, // Restart when the ampm config file changes
            path.join(appPath, 'restart.json'), // Restart when ampm tries to tigger a restart itself.
            __dirname // Restart when ampm code changes, for doing development.
        ],
        ignore: [
            '.git', 'node_modules', 'logs', path.join(appPath, 'state.json')
        ]
    }).on('crash', start);
}
start();
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
module.exports = {
  testRegex: '(\\/spec|\\/src)\\/.*(_spec|\\.test)\\.(j|t)sx?$',
  moduleNameMapper: {
    '\\.(css|less)$': '<rootDir>/spec/__mocks__/styleMock.js',
    '\\.(gif|ttf|eot)$': '<rootDir>/spec/__mocks__/fileMock.js',
    '\\.svg$': '<rootDir>/spec/__mocks__/svgrMock.js',
    '^src/(.*)$': '<rootDir>/src/$1',
    '^spec/(.*)$': '<rootDir>/spec/$1',
  },
  testEnvironment: 'enzyme',
  setupFilesAfterEnv: ['<rootDir>/spec/helpers/setup.ts'],
  testURL: 'http://localhost',
  collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
  coverageDirectory: '<rootDir>/coverage/',
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '^.+\\.tsx?$': 'ts-jest',
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
  globals: {
    'ts-jest': {
      babelConfig: true,
      diagnostics: {
        warnOnly: true,
      },
    },
  },
};
<commit_msg>Change test environment to jsdom (#13149)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
module.exports = {
  testRegex: '(\\/spec|\\/src)\\/.*(_spec|\\.test)\\.(j|t)sx?$',
  moduleNameMapper: {
    '\\.(css|less)$': '<rootDir>/spec/__mocks__/styleMock.js',
    '\\.(gif|ttf|eot)$': '<rootDir>/spec/__mocks__/fileMock.js',
    '\\.svg$': '<rootDir>/spec/__mocks__/svgrMock.js',
    '^src/(.*)$': '<rootDir>/src/$1',
    '^spec/(.*)$': '<rootDir>/spec/$1',
  },
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/spec/helpers/setup.ts'],
  testURL: 'http://localhost',
  collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
  coverageDirectory: '<rootDir>/coverage/',
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '^.+\\.tsx?$': 'ts-jest',
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
  globals: {
    'ts-jest': {
      babelConfig: true,
      diagnostics: {
        warnOnly: true,
      },
    },
  },
};
<|endoftext|>


<commit_before>var appExplorar = angular.module('TransfGovApp', [ 'datatables' ]).factory(
		'transfGovService', function($http) {
			return new TransfGovService($http)
		}).run(function(DTDefaultOptions) {
	DTDefaultOptions.setDisplayLength(30);
});

var prefixoMeses = [ "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago",
		"Set", "Out", "Nov", "Dez" ];

function criaGraficoAnoArea(agregacoesAno) {
	var categorias = new Array();
	var seriesMap = {};
	var ano;
	var series = new Array();
	var nomesSeries = new Array();
	// coleta as categorias (meses disponíveis) e todas séries
	agregacoesAno.forEach(function(agregacaoAno) {
		ano = agregacaoAno.ano;
		categorias.push(prefixoMeses[agregacaoAno.mes - 1]);
		// coleta todas séries possíveis
		for (a in agregacaoAno.dadosAgregados) {
			if(nomesSeries.indexOf(a) == -1)
				nomesSeries.push(a);
		}
	});
	//para cada mês, vamos ver se tem valor, senão tiver, é 0!
	agregacoesAno.forEach(function(agregacaoAno) {
		for (a in nomesSeries) {
			var s = nomesSeries[a];
			if (!seriesMap[s])
				seriesMap[s] = new Array();
			var valor = 0;
			if(agregacaoAno.dadosAgregados[s]) {
				valor = agregacaoAno.dadosAgregados[s];
			}
			seriesMap[s].push(valor);
		}
	});

	for (s in seriesMap) {
		var nome = s;
		if(nome == 'Encargos Especiais')
			nome = 'Uso Geral';
		series.push({
			name : nome,
			data : seriesMap[s]
		});
	}
	$('#divGraficoAreaPorAno').highcharts({
		title : {
			text : 'Transferências no ano ' + ano,
			x : -20
		// center
		},
		subtitle : {
			text : 'Agregadas todas as transferências no ano de ' + ano,
			x : -20
		},
		xAxis : {
			title : {
				text : 'Mês'
			},
			categories : categorias
		},
		tooltip : {
			valuePrefix : "R$ ",
			headerFormat: "{series.name}
",
	        pointFormat: 'R$ {point.y:,.3f}'
	    },
		yAxis : {
			title : {
				text : 'Valor'
			},
			min: 0,
			plotLines : [ {
				value : 0,
				width : 1,
				color : '#808080'
			} ]
		},
		legend : {
			itemWidth : 200,
			layout : 'vertical',
			align : 'right',
			verticalAlign : 'middle',
			borderWidth : 0
		},
		series : series
	});
}

appExplorar.controller('ExplorarController',
		function($scope, transfGovService) {
			Highcharts.setOptions({
			    lang: {
			        decimalPoint: ',',
			        thousandsSep: '.'
			    }
			});
			$('#abasPainel a').click(function(e) {
				e.preventDefault();
				$(this).tab('show');
			});
			var paramsUrl = recuperaMapaUrl();
			transfGovService.agregacoes(function(agregacoes) {
				$scope.agregacoes = agregacoes;
				$scope.agregacaoSelecionada = $scope.agregacoes[0];
			});

			$scope.prefixoMeses = prefixoMeses;

			/* REMOVIDO TEMPORARIAMENTE ENQUANTO FAZEMOS CARGAS
			transfGovService.anos(function(anos) {
				$scope.anos = anos;
				$.each(anos, function(i, ano) {
					if(ano.ano == paramsUrl['ano']){
						$scope.anoSelecionado = ano;
					}
				});
			});*/
			$scope.anos = ANOS;
			$.each(ANOS, function(i, ano) {
				if(ano.ano == paramsUrl['ano']){
					$scope.anoSelecionado = ano;
				}
			});

			transfGovService.estados(function(estados) {
				$scope.estados = estados;
				$.each(estados, function(i, estado) {
					if(estado.sigla == paramsUrl['sigla']) {
						$scope.estadoSelecionado = estado;
						$scope.carregaMunicipios();
					}
				});
			});
			$scope.carregaMunicipios = function() {
				transfGovService.municipiosPorEstado(
						$scope.estadoSelecionado.sigla, function(municipios) {
							$scope.municipios = municipios;
							$.each(municipios, function(i, m) {
								if(m.id == paramsUrl['id']){
									$scope.municipioSelecionado = m;
									$scope.carregaApp();
								}
							});
				});
			}

			$scope.carregaApp = function() {
				$scope.carregaAgregacaoAno();
				$scope.carregaGraficosAgregacao();
				$scope.municipioBusca = $scope.municipioSelecionado;
				var mapa = {};
				mapa['sigla'] = $scope.estadoSelecionado.sigla;
				mapa['id'] = $scope.municipioSelecionado.id;
				mapa['ano'] =  $scope.anoSelecionado.ano;
				salvaMapaUrl(mapa);
				$scope.linkFontePorAno = linkFontePorAno($scope.anoSelecionado.ano,
						$scope.estadoSelecionado.sigla,
					    $scope.municipioSelecionado.codigoSIAFI);
			}

			$scope.listenerAgregacao = function() {
				$scope.carregaAgregacaoAno();
			}

			$scope.carregaAgregacaoAno = function() {
				var ano = $scope.anoSelecionado.ano;
				var id = $scope.municipioSelecionado.id;
				var agreg = $scope.agregacaoSelecionada;
				$scope.anoBusca = ano;
				$scope.mesSelecionado = $scope.anoSelecionado.meses[0];
				$scope.municipioBusca = $scope.municipioSelecionado;
				transfGovService.agregacaoPorAnoMun(agreg, ano, id, criaGraficoAnoArea);
				$scope.carregaDadosMes();
			}

			$scope.carregaDadosMes = function() {
				if (!$scope.mesSelecionado) {
					return;
				}
				var ano = $scope.anoSelecionado.ano;
				var mes = $scope.mesSelecionado;
				var id = $scope.municipioSelecionado.id;
				$scope.carregaGraficosAgregacao();
				transfGovService.transfPorAnoMesMunicipio(ano, mes, id,
						function(transfMes, linkAnterior, linkProxima) {
							$scope.transferenciasMes = transfMes;
							$scope.linkAnterior = linkAnterior;
							$scope.linkProxima = linkProxima;
						});
			}

			$scope.carregaTransferencias = function(url) {
				transfGovService.dadosPaginados(url, function(transfMes,
						linkAnterior, linkProxima) {
					$scope.transferenciasMes = transfMes;
					$scope.linkAnterior = linkAnterior;
					$scope.linkProxima = linkProxima;
				});
			}

			$scope.carregaGraficosAgregacao = function() {
				var a = $scope.agregacaoSelecionada;
				var ano = $scope.anoSelecionado.ano;
				var mes = $scope.mesSelecionado;
				var id = $scope.municipioSelecionado.id;
				if (!a)
					return;
				$scope.gerandoGraficoAgregacao = true;
				transfGovService.comparaPorAnoMesAgregaPorArea(ano, mes, id, function(dados){
					var categorias = [];
					var series = new Array();
					for(i in dados[$scope.municipioSelecionado.nome]) {
						categorias.push(i);
					}
					for(i in dados) {
						var serie = {};
						serie.name = i;
						serie.data = [];
						for(j in categorias) {
							var area = categorias[j];
							serie.data.push(dados[i][area]);
						}
						series.push(serie);
					}
					// renomear categoria de outras transferências para nome mais popular
					for(i in categorias) {
						if(categorias[i] == 'Encargos Especiais') {
							categorias[i] = 'Uso Geral';
							break;
						}
					}
					criaGraficoBarra('#containerGraficoAgregacao', 'Comparação per capita', categorias, series);
				});
				transfGovService.agregacaoPorAnoMesMun('AREA', ano, mes, id,
						function(agregacao) {
							$scope.dadosAgregados = agregacao.dadosAgregados;
							var dados = new Array();
							$scope.valorTotalMes = 0;
							for (i in agregacao.dadosAgregados) {
								var nome = i;
								if(i == 'Encargos Especiais') {
									nome  = 'Uso Geral';
								}
								$scope.valorTotalMes += agregacao.dadosAgregados[i];
								dados.push({
									name: nome,
									y:	agregacao.dadosAgregados[i]
								});
							}
							$('#containerGraficoAgregacaoPizza').highcharts(
									{
										title : {
											text : 'Valores Totais'
										},
										chart : {
											type : 'pie',
								            options3d: {
								                enabled: true
								            }
										},
										tooltip : {
									        pointFormat: 'R$ {point.y:,.3f}'
									    },
										series : [ {
											name: "",
											type: 'pie',
											data : dados
										} ]
									});
						});
				$scope.gerandoGraficoAgregacao = false;
			}
		});

function criaGraficoBarra(elemento, titulo, categorias, series) {
	$(elemento).highcharts(
			{
				title : {
					text : titulo
				},
				chart : {
					type : 'bar'
				},
				tooltip : {
					headerFormat: '{point.key} - {series.name}
',
			        pointFormat: 'R$ {point.y:,.3f}'
			    },
				xAxis : {
					categories : categorias
				},
				plotOptions : {
					series : {
						allowPointSelect : true
					}
				},
				series : series
			});
}<commit_msg>closes #70 provisioriamente. Mostrando uma coluna Y mais amigável no eixo Y do gráfico de linhas do Explorar<commit_after>var appExplorar = angular.module('TransfGovApp', [ 'datatables' ]).factory(
		'transfGovService', function($http) {
			return new TransfGovService($http)
		}).run(function(DTDefaultOptions) {
	DTDefaultOptions.setDisplayLength(30);
});

var prefixoMeses = [ "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago",
		"Set", "Out", "Nov", "Dez" ];

appExplorar.controller('ExplorarController',
		function($scope, transfGovService) {
			Highcharts.setOptions({
			    lang: {
			        decimalPoint: ',',
			        thousandsSep: '.',
			        numericSymbols:  [ " mil" , " milhões" , " bilhões" , "T" , "P" , "E"]
			    }
			});
			$('#abasPainel a').click(function(e) {
				e.preventDefault();
				$(this).tab('show');
			});
			var paramsUrl = recuperaMapaUrl();
			transfGovService.agregacoes(function(agregacoes) {
				$scope.agregacoes = agregacoes;
				$scope.agregacaoSelecionada = $scope.agregacoes[0];
			});

			$scope.prefixoMeses = prefixoMeses;

			/* REMOVIDO TEMPORARIAMENTE ENQUANTO FAZEMOS CARGAS
			transfGovService.anos(function(anos) {
				$scope.anos = anos;
				$.each(anos, function(i, ano) {
					if(ano.ano == paramsUrl['ano']){
						$scope.anoSelecionado = ano;
					}
				});
			});*/
			$scope.anos = ANOS;
			$.each(ANOS, function(i, ano) {
				if(ano.ano == paramsUrl['ano']){
					$scope.anoSelecionado = ano;
				}
			});

			transfGovService.estados(function(estados) {
				$scope.estados = estados;
				$.each(estados, function(i, estado) {
					if(estado.sigla == paramsUrl['sigla']) {
						$scope.estadoSelecionado = estado;
						$scope.carregaMunicipios();
					}
				});
			});
			$scope.carregaMunicipios = function() {
				transfGovService.municipiosPorEstado(
						$scope.estadoSelecionado.sigla, function(municipios) {
							$scope.municipios = municipios;
							$.each(municipios, function(i, m) {
								if(m.id == paramsUrl['id']){
									$scope.municipioSelecionado = m;
									$scope.carregaApp();
								}
							});
				});
			}

			$scope.carregaApp = function() {
				$scope.carregaAgregacaoAno();
				$scope.carregaGraficosAgregacao();
				$scope.municipioBusca = $scope.municipioSelecionado;
				var mapa = {};
				mapa['sigla'] = $scope.estadoSelecionado.sigla;
				mapa['id'] = $scope.municipioSelecionado.id;
				mapa['ano'] =  $scope.anoSelecionado.ano;
				salvaMapaUrl(mapa);
				$scope.linkFontePorAno = linkFontePorAno($scope.anoSelecionado.ano,
						$scope.estadoSelecionado.sigla,
					    $scope.municipioSelecionado.codigoSIAFI);
			}

			$scope.listenerAgregacao = function() {
				$scope.carregaAgregacaoAno();
			}

			$scope.carregaAgregacaoAno = function() {
				var ano = $scope.anoSelecionado.ano;
				var id = $scope.municipioSelecionado.id;
				var agreg = $scope.agregacaoSelecionada;
				$scope.anoBusca = ano;
				$scope.mesSelecionado = $scope.anoSelecionado.meses[0];
				$scope.municipioBusca = $scope.municipioSelecionado;
				transfGovService.agregacaoPorAnoMun(agreg, ano, id, criaGraficoAnoArea);
				$scope.carregaDadosMes();
			}

			$scope.carregaDadosMes = function() {
				if (!$scope.mesSelecionado) {
					return;
				}
				var ano = $scope.anoSelecionado.ano;
				var mes = $scope.mesSelecionado;
				var id = $scope.municipioSelecionado.id;
				$scope.carregaGraficosAgregacao();
				transfGovService.transfPorAnoMesMunicipio(ano, mes, id,
						function(transfMes, linkAnterior, linkProxima) {
							$scope.transferenciasMes = transfMes;
							$scope.linkAnterior = linkAnterior;
							$scope.linkProxima = linkProxima;
						});
			}

			$scope.carregaTransferencias = function(url) {
				transfGovService.dadosPaginados(url, function(transfMes,
						linkAnterior, linkProxima) {
					$scope.transferenciasMes = transfMes;
					$scope.linkAnterior = linkAnterior;
					$scope.linkProxima = linkProxima;
				});
			}

			$scope.carregaGraficosAgregacao = function() {
				var a = $scope.agregacaoSelecionada;
				var ano = $scope.anoSelecionado.ano;
				var mes = $scope.mesSelecionado;
				var id = $scope.municipioSelecionado.id;
				if (!a)
					return;
				$scope.gerandoGraficoAgregacao = true;
				transfGovService.comparaPorAnoMesAgregaPorArea(ano, mes, id, function(dados){
					var categorias = [];
					var series = new Array();
					for(i in dados[$scope.municipioSelecionado.nome]) {
						categorias.push(i);
					}
					for(i in dados) {
						var serie = {};
						serie.name = i;
						serie.data = [];
						for(j in categorias) {
							var area = categorias[j];
							serie.data.push(dados[i][area]);
						}
						series.push(serie);
					}
					// renomear categoria de outras transferências para nome mais popular
					for(i in categorias) {
						if(categorias[i] == 'Encargos Especiais') {
							categorias[i] = 'Uso Geral';
							break;
						}
					}
					criaGraficoBarra('#containerGraficoAgregacao', 'Comparação per capita', categorias, series);
				});
				transfGovService.agregacaoPorAnoMesMun('AREA', ano, mes, id,
						function(agregacao) {
							$scope.dadosAgregados = agregacao.dadosAgregados;
							var dados = new Array();
							$scope.valorTotalMes = 0;
							for (i in agregacao.dadosAgregados) {
								var nome = i;
								if(i == 'Encargos Especiais') {
									nome  = 'Uso Geral';
								}
								$scope.valorTotalMes += agregacao.dadosAgregados[i];
								dados.push({
									name: nome,
									y:	agregacao.dadosAgregados[i]
								});
							}
							$('#containerGraficoAgregacaoPizza').highcharts(
									{
										title : {
											text : 'Valores Totais'
										},
										chart : {
											type : 'pie',
								            options3d: {
								                enabled: true
								            }
										},
										tooltip : {
									        pointFormat: 'R$ {point.y:,.3f}'
									    },
										series : [ {
											name: "",
											type: 'pie',
											data : dados
										} ]
									});
						});
				$scope.gerandoGraficoAgregacao = false;
			}
		});

function criaGraficoBarra(elemento, titulo, categorias, series) {
	$(elemento).highcharts(
			{
				title : {
					text : titulo
				},
				chart : {
					type : 'bar'
				},
				tooltip : {
					headerFormat: '{point.key} - {series.name}
',
			        pointFormat: 'R$ {point.y:,.3f}'
			    },
				xAxis : {
					categories : categorias
				},
				plotOptions : {
					series : {
						allowPointSelect : true
					}
				},
				series : series
			});
}

function criaGraficoAnoArea(agregacoesAno) {
	var categorias = new Array();
	var seriesMap = {};
	var ano;
	var series = new Array();
	var nomesSeries = new Array();
	// coleta as categorias (meses disponíveis) e todas séries
	agregacoesAno.forEach(function(agregacaoAno) {
		ano = agregacaoAno.ano;
		categorias.push(prefixoMeses[agregacaoAno.mes - 1]);
		// coleta todas séries possíveis
		for (a in agregacaoAno.dadosAgregados) {
			if(nomesSeries.indexOf(a) == -1)
				nomesSeries.push(a);
		}
	});
	//para cada mês, vamos ver se tem valor, senão tiver, é 0!
	agregacoesAno.forEach(function(agregacaoAno) {
		for (a in nomesSeries) {
			var s = nomesSeries[a];
			if (!seriesMap[s])
				seriesMap[s] = new Array();
			var valor = 0;
			if(agregacaoAno.dadosAgregados[s]) {
				valor = agregacaoAno.dadosAgregados[s];
			}
			seriesMap[s].push(valor);
		}
	});

	for (s in seriesMap) {
		var nome = s;
		if(nome == 'Encargos Especiais')
			nome = 'Uso Geral';
		series.push({
			name : nome,
			data : seriesMap[s]
		});
	}
	$('#divGraficoAreaPorAno').highcharts({
		title : {
			text : 'Transferências no ano ' + ano,
			x : -20
		// center
		},
		subtitle : {
			text : 'Agregadas todas as transferências no ano de ' + ano,
			x : -20
		},
		xAxis : {
			title : {
				text : 'Mês'
			},
			categories : categorias
		},
		tooltip : {
			valuePrefix : "R$ ",
			headerFormat: "{series.name}
",
	        pointFormat: 'R$ {point.y:,.3f}'
	    },
		yAxis : {
			title : {
				text : 'Valor'
			},
			labels: {
				formatter: function() {
					return 'R$ ' + this.value.toLocaleString();
				}
			},
			min: 0,
			plotLines : [ {
				value : 0,
				width : 1,
				color : '#808080'
			} ]
		},
		legend : {
			itemWidth : 200,
			layout : 'vertical',
			align : 'right',
			verticalAlign : 'middle',
			borderWidth : 0
		},
		series : series
	});
}
<|endoftext|>


<commit_before>
/** Module dependencies. */

var config  = require('../config/config.js');
var _ = require("lodash");

var elastic = require('elasticsearch');
var elasticClient = new elastic.Client({
    "apiVersion" : "1.4"
***REMOVED***);

const source = ["cui", "exact", "pref", "source", "types"];

module.exports = function *() {
  var query = this.request.body.query;

  var exactMatches = yield findExact(query);
  var closeMatches = yield findMatches(query);

  this.body = {
    "took": exactMatches.took + closeMatches.took,
    "hits": _.uniq(exactMatches.hits.concat(closeMatches.hits), "exact")
  ***REMOVED***

***REMOVED***;

function findExact(query) {
    var wantedTerm = query.trim().toLowerCase();

***REMOVED*** Filter out CUI codes that the user already selected
    return function(callback) {
        var elastic_query =  {
            "_source": source,

            "size": 3,

            "query": {
                "term" : {
                    "exact" : wantedTerm
            ***REMOVED***
        ***REMOVED***
    ***REMOVED***;

        var queryObj = {
            "index" : 'autocomplete',
            "type"  : 'records',
            "body"  : elastic_query
    ***REMOVED***;

        elasticClient.search(queryObj, function(err, res) {
            var hits = res.hits;
            var result = [];

            if (hits && hits.total > 0) {
                for (var i=0; i < hits.hits.length; i++) {
                    result.push(hits.hits[i]._source);
            ***REMOVED***
        ***REMOVED***

            callback(err, {
                "took": res.took,
                "hits": result
        ***REMOVED***);
    ***REMOVED***);
***REMOVED***
***REMOVED***

function findMatches(query) {
***REMOVED*** Filter out CUI codes that the user already selected
    return function(callback) {
        var elastic_query =  {
            "_source": source,

            "size": 6,

            "query": {
                "function_score" : {
                    "query" : {
                        "match_phrase" : {
                            "str" : query.trim()
                    ***REMOVED***
                ***REMOVED***,

                    "functions" : [
                    ***REMOVED*** Prefer SnomedCT / MeSH
                        {
                            "filter": {
                                "terms": { "source": ["SNOMEDCT_US", "MSH", "MSHDUT"] ***REMOVED***
                        ***REMOVED***,
                            "weight": 1.25
                    ***REMOVED***,

                    ***REMOVED*** Negative weight for some categories
                        {
                            "filter": {
                                "terms": { "types": ["Health Care Activity", "Temporal Concept", "Biomedical Occupation or Discipline"] ***REMOVED***
                        ***REMOVED***,
                            "weight": 0.7
                    ***REMOVED***
                    ]
            ***REMOVED***
        ***REMOVED***
    ***REMOVED***;

        var queryObj = {
            "index" : 'autocomplete',
            "type"  : 'records',
            "body"  : elastic_query
    ***REMOVED***;

        elasticClient.search(queryObj, function(err, res) {
            var hits = res.hits;
            var result = [];

            if (hits && hits.total > 0) {
                for (var i=0; i<hits.hits.length; i++) {
                    result.push(hits.hits[i]._source);
            ***REMOVED***
        ***REMOVED***

            callback(err, {
                "took": res.took,
                "hits": result
        ***REMOVED***);
    ***REMOVED***);
***REMOVED***
***REMOVED***
<commit_msg>Also include str<commit_after>
/** Module dependencies. */

var config  = require('../config/config.js');
var _ = require("lodash");

var elastic = require('elasticsearch');
var elasticClient = new elastic.Client({
    "apiVersion" : "1.4"
***REMOVED***);

const source = ["cui", "str", "exact", "pref", "source", "types"];

module.exports = function *() {
  var query = this.request.body.query;

  var exactMatches = yield findExact(query);
  var closeMatches = yield findMatches(query);

  this.body = {
    "took": exactMatches.took + closeMatches.took,
    "hits": _.uniq(exactMatches.hits.concat(closeMatches.hits), "exact")
  ***REMOVED***

***REMOVED***;

function findExact(query) {
    var wantedTerm = query.trim().toLowerCase();

***REMOVED*** Filter out CUI codes that the user already selected
    return function(callback) {
        var elastic_query =  {
            "_source": source,

            "size": 3,

            "query": {
                "term" : {
                    "exact" : wantedTerm
            ***REMOVED***
        ***REMOVED***
    ***REMOVED***;

        var queryObj = {
            "index" : 'autocomplete',
            "type"  : 'records',
            "body"  : elastic_query
    ***REMOVED***;

        elasticClient.search(queryObj, function(err, res) {
            var hits = res.hits;
            var result = [];

            if (hits && hits.total > 0) {
                for (var i=0; i < hits.hits.length; i++) {
                    result.push(hits.hits[i]._source);
            ***REMOVED***
        ***REMOVED***

            callback(err, {
                "took": res.took,
                "hits": result
        ***REMOVED***);
    ***REMOVED***);
***REMOVED***
***REMOVED***

function findMatches(query) {
***REMOVED*** Filter out CUI codes that the user already selected
    return function(callback) {
        var elastic_query =  {
            "_source": source,

            "size": 6,

            "query": {
                "function_score" : {
                    "query" : {
                        "match_phrase" : {
                            "str" : query.trim()
                    ***REMOVED***
                ***REMOVED***,

                    "functions" : [
                    ***REMOVED*** Prefer SnomedCT / MeSH
                        {
                            "filter": {
                                "terms": { "source": ["SNOMEDCT_US", "MSH", "MSHDUT"] ***REMOVED***
                        ***REMOVED***,
                            "weight": 1.25
                    ***REMOVED***,

                    ***REMOVED*** Negative weight for some categories
                        {
                            "filter": {
                                "terms": { "types": ["Health Care Activity", "Temporal Concept", "Biomedical Occupation or Discipline"] ***REMOVED***
                        ***REMOVED***,
                            "weight": 0.7
                    ***REMOVED***
                    ]
            ***REMOVED***
        ***REMOVED***
    ***REMOVED***;

        var queryObj = {
            "index" : 'autocomplete',
            "type"  : 'records',
            "body"  : elastic_query
    ***REMOVED***;

        elasticClient.search(queryObj, function(err, res) {
            var hits = res.hits;
            var result = [];

            if (hits && hits.total > 0) {
                for (var i=0; i<hits.hits.length; i++) {
                    result.push(hits.hits[i]._source);
            ***REMOVED***
        ***REMOVED***

            callback(err, {
                "took": res.took,
                "hits": result
        ***REMOVED***);
    ***REMOVED***);
***REMOVED***
***REMOVED***
<|endoftext|>


<commit_before>var Repository  = require('../models/repository.js').Repository,
    Build       = require('../models/build.js').Build,
    resque      = require('../config/resque');

var findOrCreateRepository = require('../lib/repositories.js').findOrCreateRepository,
    triggerRepositoryBuild = require('../lib/repositories.js').triggerRepositoryBuild;

module.exports.create = function(request, response) {
  if (!request.body && req.is('application/json')) {
    console.log("Received invalid post:", request.headers['content-type'], request.body);
    response.end();
    return;
  }

  var branch            = "master";
  var repository        = request.body.repository;
  repository.ownerName  = repository.owner.name;
  delete repository.owner;

  if(repository.url.indexOf('http') == 0) {
    repository.url = repository.url.replace(/\.git$/,"");
  }

  findOrCreateRepository(repository, function(err, repository) {
    triggerRepositoryBuild(repository, branch, function() {
      response.send("OK");
    });
  });
};

module.exports.list = function (request, response) {
  var ownerName = request.params.ownerName;

  if(ownerName) {
    Repository.find({ ownerName: ownerName }, function (err, repositories) {
      if(err) throw err;
      response.send(repositories);
    });
  } else {
    Repository.find(function (err, repositories) {
      if(err) throw err;
      response.send(repositories);
    });
  }
};

module.exports.show = function (request, response) {
  var name      = request.params.name,
      ownerName = request.params.ownerName;

  Repository.findOne({ ownerName: ownerName, name: name  }, function (err, repository) {
    if (err) throw err;
    response.send(repository);
  });
};
<commit_msg>change require to not use .js.<commit_after>var Repository  = require('../models/repository').Repository,
    Build       = require('../models/build').Build,
    resque      = require('../config/resque');

var findOrCreateRepository = require('../lib/repositories').findOrCreateRepository,
    triggerRepositoryBuild = require('../lib/repositories').triggerRepositoryBuild;

module.exports.create = function(request, response) {
  if (!request.body && req.is('application/json')) {
    console.log("Received invalid post:", request.headers['content-type'], request.body);
    response.end();
    return;
  }

  var branch            = "master";
  var repository        = request.body.repository;
  repository.ownerName  = repository.owner.name;
  delete repository.owner;

  if(repository.url.indexOf('http') == 0) {
    repository.url = repository.url.replace(/\.git$/,"");
  }

  findOrCreateRepository(repository, function(err, repository) {
    triggerRepositoryBuild(repository, branch, function() {
      response.send("OK");
    });
  });
};

module.exports.list = function (request, response) {
  var ownerName = request.params.ownerName;

  if(ownerName) {
    Repository.find({ ownerName: ownerName }, function (err, repositories) {
      if(err) throw err;
      response.send(repositories);
    });
  } else {
    Repository.find(function (err, repositories) {
      if(err) throw err;
      response.send(repositories);
    });
  }
};

module.exports.show = function (request, response) {
  var name      = request.params.name,
      ownerName = request.params.ownerName;

  Repository.findOne({ ownerName: ownerName, name: name  }, function (err, repository) {
    if (err) throw err;
    response.send(repository);
  });
};
<|endoftext|>