<commit_before>console.log('form-faker: faking data...');
// debugger;
const dictionary = getDictionary();
var inputs = document.getElementsByTagName('input');

for (var i = 0; i < inputs.length; i++) {
  var input = inputs[i];
  if (input.type.toLowerCase() !== 'text' || input.value) {
    continue;
  }

  var name = input.name.toLowerCase();
  var mapping = dictionary.get(name);
  switch (mapping) {
    case 'firstName':
      input.value = faker.name.firstName();
      break;
    case 'lastName':
      input.value = faker.name.firstName();
      break;
    case 'email':
      input.value = faker.internet.email();
      break;
    case 'phone':
      input.value = faker.phone.phoneNumber('(###) ###-####');
      break;
    case 'date-past':
      var date = faker.date.past(50);
      input.value = date.toLocaleDateString();
      break;
    case 'account':
      input.value = faker.finance.account();
      break;
    default:
      if (input.attributes.required) {
        input.value = faker.random.word();
      }
      break;
  }
}

console.log('form-faker: Done!');

function getDictionary() {
  return new Map([
    // firstName
    ['firstname', 'firstName'],
    ['first_name', 'firstName'],
    ['first-name', 'firstName'],
    ['fname', 'firstName'],
    // lastName
    ['lastname', 'lastName'],
    ['last_name', 'lastName'],
    ['last-name', 'lastName'],
    ['lname', 'lastName'],
    // email
    ['email', 'email'],
    ['emailaddress', 'email'],
    ['email_address', 'email'],
    ['email-address', 'email'],
    // phone
    ['phone', 'phone'],
    ['ph', 'phone'],
    ['cellphone', 'phone'],
    ['cell_phone', 'phone'],
    ['cell-phone', 'phone'],
    ['cellph', 'phone'],
    ['cell_ph', 'phone'],
    ['cell-ph', 'phone'],
    ['mobilephone', 'phone'],
    ['mobile_phone', 'phone'],
    ['mobile-phone', 'phone'],
    ['mobileph', 'phone'],
    ['mobile_ph', 'phone'],
    ['mobile-ph', 'phone'],
    ['homephone', 'phone'],
    ['home_phone', 'phone'],
    ['home-phone', 'phone'],
    ['homeph', 'phone'],
    ['home_ph', 'phone'],
    ['home-ph', 'phone'],
    ['hmphone', 'phone'],
    ['hm_phone', 'phone'],
    ['hm-phone', 'phone'],
    ['hmph', 'phone'],
    ['hm_ph', 'phone'],
    ['hm-ph', 'phone'],
    // date-past
    ['birthdate', 'date-past'],
    // account
    ['mrn', 'account'],
  ]);
}
<commit_msg>address fields - resolves #3<commit_after>console.log('form-faker: faking data...');
// debugger;
const dictionary = getDictionary();
var inputs = document.getElementsByTagName('input');

for (var i = 0; i < inputs.length; i++) {
  var input = inputs[i];
  if (input.type.toLowerCase() !== 'text' || input.value) {
    continue;
  }

  var name = input.name.toLowerCase();
  var mapping = dictionary.get(name);
  switch (mapping) {
    case 'firstName':
      input.value = faker.name.firstName();
      break;
    case 'lastName':
      input.value = faker.name.firstName();
      break;
    case 'email':
      input.value = faker.internet.email();
      break;
    case 'phone':
      input.value = faker.phone.phoneNumber('(###) ###-####');
      break;
    // Address
    case 'address1':
      input.value = faker.address.streetAddress();
      break;
    case 'address2':
      input.value = faker.address.secondaryAddress();
      break;
    case 'city':
      input.value = faker.address.city();
      break;
    case 'country':
      input.value = 'United States'; // faker.address.country();
      break;
    case 'county':
      input.value = faker.address.county();
      break;
    case 'state':
      input.value = faker.address.state();
      break;
    case 'zipCode':
      input.value = faker.address.zipCode();
      break;
    // Date
    case 'date-past':
      var date = faker.date.past(50);
      input.value = date.toLocaleDateString();
      break;
    case 'account':
      input.value = faker.finance.account();
      break;
    default:
      if (input.attributes.required) {
        input.value = faker.random.word();
      }
      break;
  }
}

console.log('form-faker: Done!');

function getDictionary() {
  return new Map([
    // firstName
    ['firstname', 'firstName'],
    ['first_name', 'firstName'],
    ['first-name', 'firstName'],
    ['fname', 'firstName'],
    // lastName
    ['lastname', 'lastName'],
    ['last_name', 'lastName'],
    ['last-name', 'lastName'],
    ['lname', 'lastName'],
    // email
    ['email', 'email'],
    ['emailaddress', 'email'],
    ['email_address', 'email'],
    ['email-address', 'email'],
    // phone
    ['phone', 'phone'],
    ['ph', 'phone'],
    ['cellphone', 'phone'],
    ['cell_phone', 'phone'],
    ['cell-phone', 'phone'],
    ['cellph', 'phone'],
    ['cell_ph', 'phone'],
    ['cell-ph', 'phone'],
    ['mobilephone', 'phone'],
    ['mobile_phone', 'phone'],
    ['mobile-phone', 'phone'],
    ['mobileph', 'phone'],
    ['mobile_ph', 'phone'],
    ['mobile-ph', 'phone'],
    ['homephone', 'phone'],
    ['home_phone', 'phone'],
    ['home-phone', 'phone'],
    ['homeph', 'phone'],
    ['home_ph', 'phone'],
    ['home-ph', 'phone'],
    ['hmphone', 'phone'],
    ['hm_phone', 'phone'],
    ['hm-phone', 'phone'],
    ['hmph', 'phone'],
    ['hm_ph', 'phone'],
    ['hm-ph', 'phone'],
    // Address
    ['address', 'address1'],
    ['address1', 'address1'],
    ['addr', 'address1'],
    ['addr1', 'address1'],
    ['address2', 'address2'],
    ['addr2', 'address2'],
    ['city', 'city'],
    ['country', 'country'],
    ['cntry', 'country'],
    ['county', 'county'],
    ['state', 'state'],
    ['st', 'state'],
    ['zipcode', 'zipCode'],
    ['zip', 'zipCode'],
    ['zip-code', 'zipCode'],
    ['zip_code', 'zipCode'],
    ['postalcode', 'zipCode'],
    ['postal-code', 'zipCode'],
    ['postal_code', 'zipCode'],
    ['postcode', 'zipCode'],
    ['post-code', 'zipCode'],
    ['post_code', 'zipCode'],
    // date-past
    ['birthdate', 'date-past'],
    // account
    ['mrn', 'account'],
  ]);
}
<|endoftext|>


<commit_before>/**
 * Created by ingrskar on 3/8/2017.
 */
import React from "react"
import { connect } from "react-redux"
import { bindActionCreators } from 'redux';
import { fetchActivities } from "../actions/activitiesActions"

class ActivityPageContainer extends React.Component {

    componentWillMount() {
        this.showMap = this.showMap.bind(this);
        console.log('mount from ActivityPageContainer');
    }

    createActivityItem(){
        console.log(this.props);
        console.log('^ came from createActivityItem in APC' );
        return this.props.activities.map((activity) => {
            let poster = null;
            return (

                <Thumbnail
                    className="activityBigStyle"
                    src={poster}
                    onClick={this.openActivityModal.bind(this)}
                    title="Klikk på aktiviteten for mer informasjon">

{activity.title}

<Glyphicon glyph="glyphicon glyphicon-calendar"/>

<Glyphicon glyph="glyphicon glyphicon-time"/>

<Glyphicon glyph="glyphicon glyphicon-map-marker"/>

{activity.date.getDate()}. {getMonth(activity.date.getMonth())}

{activity.timeStart} - {activity.timeEnd}

{activity.location}

{activity.description}

                </Thumbnail>
                <ActivityModal id={activity.id} show={activity.show}>Activiy</ActivityModal>

            );
        })
    }

    render() {
        console.log(' su render me from ActivitiesPage Container ');

        // if (this.state.images.length > 0 && this.state.images[0] != "") {
        //     poster = "/media/" + this.state.images[0];
        // }
        return (

                {this.createActivityItem()}

        );
    }

    showMap() {
        window.open('https://www.google.no/maps/place/' + this.state.location, '_blank');
    }

    openActivityModal() {
        this.setState({show: true})
    }
}

// Takes the provider store that is given when called, and gives this container the this.props.whatWeCallIt
function mapStateToProps(state) {
    console.log(state.activity);
    console.log("^ is from mapStateToProps in APC");
    return {
        activities: state.activity
    };
}

function matchDispatchToProps(dispatch){
    return bindActionCreators({fetchActivities: fetchActivities }, dispatch);
}

// connect actually calles the functions so that their purposes are fulfilled
export default connect(mapStateToProps, matchDispatchToProps)(ActivityPageContainer);
<commit_msg>added import of Bootstrap component, so now they can be used, also removed the MODAL, remember to add that back. Changed the usaged of date in render function. Added this.props.activities.activities.map() now it works<commit_after>/**
 * Created by ingrskar on 3/8/2017.
 */
import React from "react"
import { connect } from "react-redux"
import { bindActionCreators } from 'redux';
import { fetchActivities } from "../actions/activitiesActions";
import {Thumbnail, Glyphicon} from 'react-bootstrap';

class ActivityPageContainer extends React.Component {

    componentWillMount() {
        this.showMap = this.showMap.bind(this);
        console.log('mount from ActivityPageContainer');
    }

    createActivityItem(){
        console.log(this.props);
        console.log('^ came from createActivityItem in APC' );
        return this.props.activities.activities.map((activity) => {
            let poster = null;
            return (

                    <Thumbnail
                        className="activityBigStyle"
                        src={poster}
                        onClick={this.openActivityModal.bind(this)}
                        title="Klikk på aktiviteten for mer informasjon"
                    >

{activity.title}

<Glyphicon glyph="glyphicon glyphicon-calendar"/>

<Glyphicon glyph="glyphicon glyphicon-time"/>

<Glyphicon glyph="glyphicon glyphicon-map-marker"/>

{activity.date.getDate()}. {activity.date.getMonth()}

{activity.timeStart} - {activity.timeEnd}

{activity.location}

{activity.description}

                    </Thumbnail>

            );
        })
    }

    render() {
        console.log(' su render me from ActivitiesPage Container ');

        // if (this.state.images.length > 0 && this.state.images[0] != "") {
        //     poster = "/media/" + this.state.images[0];
        // }
        return (

                {this.createActivityItem()}

        );
    }

    showMap() {
        window.open('https://www.google.no/maps/place/' + this.state.location, '_blank');
    }

    openActivityModal() {
        this.setState({show: true})
    }
}

// Takes the provider store that is given when called, and gives this container the this.props.whatWeCallIt
function mapStateToProps(state) {
    console.log(state.activity);
    console.log("^ is from mapStateToProps in APC");
    return {
        activities: state.activity
    };
}

function matchDispatchToProps(dispatch){
    return bindActionCreators({fetchActivities: fetchActivities }, dispatch);
}

// connect actually calles the functions so that their purposes are fulfilled
export default connect(mapStateToProps, matchDispatchToProps)(ActivityPageContainer);
<|endoftext|>


<commit_before>angular.module('FormErrors', [])

// just put <form-errors><form-errors> wherever you want form errors
// to be displayed! (well, not WHEREVER, it has to be in a form/ngForm)
.directive('formErrors', ['FormErrorsOptions', function (opts) {
    return {
        // only works if embedded in a form or an ngForm (that's in a form).
        // It does use its closest parent that is a form OR ngForm
        template: function (elem) {
            if (!angular.isUndefined(elem.attr('errors-tmpl'))) {
                return '

';
            }
            return '' +
                '
' +
                    '
' +
                        '{{ error.message }}' +
                    '
' +
                '
';
        },
        replace: true,
        // this directive needs a higher priority than errorMessages directive
        priority: 1,
        restrict: 'AE',
        require: ['?^form', 'formErrors'],
        // isolated scope is required so we can embed ngForms and errors
        scope: { form: '=?', recurse: '=?showChildErrors' },
        // the controller doesn't need to do anything here, it just
        // needs to exist so that other directives can do stuff with it
        controller: [function () {}],
        link: function postLink(scope, elem, attrs, ctrls) {
            var ngModelCtrl = ctrls[0];
            var formErrorsCtrl = ctrls[1];

            // if we don't provide
            if (scope.form) ngModelCtrl = scope.form;

            if (!ngModelCtrl) throw new Error('You must either specify a "form" attr or place formErrors directive inside a form/ngForm.');

            var thisCrawlErrors = angular.bind(formErrorsCtrl, crawlErrors);
            var getErrors = function () {
                scope.errors = thisCrawlErrors(ngModelCtrl, scope.recurse);
            };

            // only update the list of errors if there was actually a change in $error
            scope.$watch(function () { return ngModelCtrl.$error; }, getErrors, true);
            // or if they changed the value to show child errors for some reason
            scope.$watch('recurse', getErrors);
        }
    };

    // humanize words, turning:
    //     camelCase  --> Camel Case
    //     dash-case  --> Dash Case
    //     snake_case --> Snake Case
    function humanize(str) {
        return str
                  // turn _ and - into spaces
                  .replace(/[-_+]/g, ' ')
                  // put a splace before every capital letter
                  .replace(/([A-Z])/g, ' $1')
                  // capitalize the first letter of each word
                  .replace(/^([a-z])|\s+([a-z])/g,
                        function ($1) { return $1.toUpperCase(); }
        );
    }

    function isController(obj) {
        // if it doesn't have a $modelValue, it's
        // an ngForm (as compared to an ngModel)
        return !obj.hasOwnProperty('$modelValue');
    }

    // this is where we form our message
    function errorMessage(name, error, props, defaultErrorMessages) {
        // get the nice name if they used the niceName
        // directive or humanize the name and call it good
        var niceName = props.$niceName || humanize(name);

        // if it doesn't have a $modelValue, it's an ngForm
        if (isController(props)) {
            error = 'form';
        }

        // get a message from our default set
        var message = defaultErrorMessages[error] || defaultErrorMessages.fallback;

        // if they used the errorMessages directive, grab that message
        if (typeof props.$errorMessages === 'object')
            message = props.$errorMessages[error];
        else if (typeof props.$errorMessages === 'string')
            message = props.$errorMessages;

        // return our nicely formatted message
        return niceName + ' ' + message;
    }

    function crawlErrors(ctrl, recurse, errors) {
        // "this" will be this directive's controller
        var errorMessages = angular.extend(opts.defaultErrorMessages, this.$errorMessages);

        recurse = !!recurse;
        if (!angular.isArray(errors)) errors = [];

        angular.forEach(ctrl, function (props, name) {
            // name has some internal properties we don't want to iterate over
            if (name[0] === '$') return;

            // if show-child-errors was true, this we
            // want to recurse through the child errors
            if (recurse && isController(props)) {
                crawlErrors(props, recurse, errors);
                // if we're recursing, we don't want to show ngForm errors
                // (cuz we're showing their children ngModel errors instead)
                return;
            }

            angular.forEach(props.$error, function (isInvalid, error) {
                // don't need to even try and get a a message unless it's invalid
                if (isInvalid) {
                    errors.push( new Error (errorMessage(name, error, props, errorMessages)));
                }
            });
        });

        return errors;
    }
}])

// set a nice name to $niceName on the ngModel ctrl for later use
.directive('niceName', [function () {
    return {
        require: ['?ngModel', '?form'],
        link: function (scope, elem, attrs, ctrls) {
            var ctrl = ctrls[0] || ctrls[1];

            if (ctrl) ctrl.$niceName = attrs.niceName;
        }
    };
}])

// ngForm version of ngModel's niceName
.directive('formNiceName', [function () {
    return {
        require: 'form',
        link: function (scope, elem, attrs, ctrl) {
            console.warn('formNiceName is deprecated. Please use niceName instead.');
            ctrl.$niceName = attrs.formNiceName;
        }
    };
}])

// set an errorMessage(s) to $errorMessages on the formError or ngModel ctrl for later use
.directive('errorMessages', [function () {
    return {
        require: ['?ngModel', '?formErrors'],
        link: function errorMessagesLink(scope, elem, attrs, ctrls) {

            var ctrl = ctrls[0] || ctrls[1];

            if (!ctrl) throw new Error('You attach errorMessages to either an ngModel or formErrors.');

            // attrs.errorMessages can be:
            //    1) "must be filled out."
            //    2) "'must be filled out.'"
            //    3) "{ required: 'must be filled out.' }"
            // 1 & 2) will be the message for any kind of error
            // 3) allows you to specify each error (it will use the
            // defaultErrorMessages if you don't specify a specific error)
            try {
                ctrl.$errorMessages = scope.$eval(attrs.errorMessages);
            } catch (e) {
                ctrl.$errorMessages = attrs.errorMessages;
            }

            if (ctrls[1] && ctrl.$errorMessages) {
                if (!angular.isObject(ctrl.$errorMessages) || angular.isArray(ctrl.$errorMessages)) {
                    ctrl.$errorMessages = undefined;
                    throw new Error('errorMessages defined on a formErrors must be an object.');
                }
            }
        }
    };
}])

// give us a way to override some options
.provider('FormErrorsOptions', [function () {
    // list of some default error messages
    var options = {
        defaultErrorMessages: {
            required  : 'is required.',
            minlength : 'is too short.',
            maxlength : 'is too long.',
            email     : 'is not a valid email address.',
            pattern   : 'does not match the expected pattern.',
            number    : 'is not a number.',
            url       : 'is not a valid URL.',
            form      : 'has errors.',

            fallback  : 'is invalid.'
        }
    };

    this.extendDefaultErrorMessages = function (messages) {
        options.defaultErrorMessages = angular.extend(options.defaultErrorMessages, messages);
    };

    this.$get = function () {
        return options;
    };
}]);
<commit_msg>Don't show the list at all if there are no errors.<commit_after>angular.module('FormErrors', [])

// just put <form-errors><form-errors> wherever you want form errors
// to be displayed! (well, not WHEREVER, it has to be in a form/ngForm)
.directive('formErrors', ['FormErrorsOptions', function (opts) {
    return {
        // only works if embedded in a form or an ngForm (that's in a form).
        // It does use its closest parent that is a form OR ngForm
        template: function (elem) {
            if (!angular.isUndefined(elem.attr('errors-tmpl'))) {
                return '

';
            }
            return '' +
                '
' +
                    '
' +
                        '{{ error.message }}' +
                    '
' +
                '
';
        },
        replace: true,
        // this directive needs a higher priority than errorMessages directive
        priority: 1,
        restrict: 'AE',
        require: ['?^form', 'formErrors'],
        // isolated scope is required so we can embed ngForms and errors
        scope: { form: '=?', recurse: '=?showChildErrors' },
        // the controller doesn't need to do anything here, it just
        // needs to exist so that other directives can do stuff with it
        controller: [function () {}],
        link: function postLink(scope, elem, attrs, ctrls) {
            var ngModelCtrl = ctrls[0];
            var formErrorsCtrl = ctrls[1];

            // if we don't provide
            if (scope.form) ngModelCtrl = scope.form;

            if (!ngModelCtrl) throw new Error('You must either specify a "form" attr or place formErrors directive inside a form/ngForm.');

            var thisCrawlErrors = angular.bind(formErrorsCtrl, crawlErrors);
            var getErrors = function () {
                scope.errors = thisCrawlErrors(ngModelCtrl, scope.recurse);
            };

            // only update the list of errors if there was actually a change in $error
            scope.$watch(function () { return ngModelCtrl.$error; }, getErrors, true);
            // or if they changed the value to show child errors for some reason
            scope.$watch('recurse', getErrors);
        }
    };

    // humanize words, turning:
    //     camelCase  --> Camel Case
    //     dash-case  --> Dash Case
    //     snake_case --> Snake Case
    function humanize(str) {
        return str
                  // turn _ and - into spaces
                  .replace(/[-_+]/g, ' ')
                  // put a splace before every capital letter
                  .replace(/([A-Z])/g, ' $1')
                  // capitalize the first letter of each word
                  .replace(/^([a-z])|\s+([a-z])/g,
                        function ($1) { return $1.toUpperCase(); }
        );
    }

    function isController(obj) {
        // if it doesn't have a $modelValue, it's
        // an ngForm (as compared to an ngModel)
        return !obj.hasOwnProperty('$modelValue');
    }

    // this is where we form our message
    function errorMessage(name, error, props, defaultErrorMessages) {
        // get the nice name if they used the niceName
        // directive or humanize the name and call it good
        var niceName = props.$niceName || humanize(name);

        // if it doesn't have a $modelValue, it's an ngForm
        if (isController(props)) {
            error = 'form';
        }

        // get a message from our default set
        var message = defaultErrorMessages[error] || defaultErrorMessages.fallback;

        // if they used the errorMessages directive, grab that message
        if (typeof props.$errorMessages === 'object')
            message = props.$errorMessages[error];
        else if (typeof props.$errorMessages === 'string')
            message = props.$errorMessages;

        // return our nicely formatted message
        return niceName + ' ' + message;
    }

    function crawlErrors(ctrl, recurse, errors) {
        // "this" will be this directive's controller
        var errorMessages = angular.extend(opts.defaultErrorMessages, this.$errorMessages);

        recurse = !!recurse;
        if (!angular.isArray(errors)) errors = [];

        angular.forEach(ctrl, function (props, name) {
            // name has some internal properties we don't want to iterate over
            if (name[0] === '$') return;

            // if show-child-errors was true, this we
            // want to recurse through the child errors
            if (recurse && isController(props)) {
                crawlErrors(props, recurse, errors);
                // if we're recursing, we don't want to show ngForm errors
                // (cuz we're showing their children ngModel errors instead)
                return;
            }

            angular.forEach(props.$error, function (isInvalid, error) {
                // don't need to even try and get a a message unless it's invalid
                if (isInvalid) {
                    errors.push( new Error (errorMessage(name, error, props, errorMessages)));
                }
            });
        });

        return errors;
    }
}])

// set a nice name to $niceName on the ngModel ctrl for later use
.directive('niceName', [function () {
    return {
        require: ['?ngModel', '?form'],
        link: function (scope, elem, attrs, ctrls) {
            var ctrl = ctrls[0] || ctrls[1];

            if (ctrl) ctrl.$niceName = attrs.niceName;
        }
    };
}])

// ngForm version of ngModel's niceName
.directive('formNiceName', [function () {
    return {
        require: 'form',
        link: function (scope, elem, attrs, ctrl) {
            console.warn('formNiceName is deprecated. Please use niceName instead.');
            ctrl.$niceName = attrs.formNiceName;
        }
    };
}])

// set an errorMessage(s) to $errorMessages on the formError or ngModel ctrl for later use
.directive('errorMessages', [function () {
    return {
        require: ['?ngModel', '?formErrors'],
        link: function errorMessagesLink(scope, elem, attrs, ctrls) {

            var ctrl = ctrls[0] || ctrls[1];

            if (!ctrl) throw new Error('You attach errorMessages to either an ngModel or formErrors.');

            // attrs.errorMessages can be:
            //    1) "must be filled out."
            //    2) "'must be filled out.'"
            //    3) "{ required: 'must be filled out.' }"
            // 1 & 2) will be the message for any kind of error
            // 3) allows you to specify each error (it will use the
            // defaultErrorMessages if you don't specify a specific error)
            try {
                ctrl.$errorMessages = scope.$eval(attrs.errorMessages);
            } catch (e) {
                ctrl.$errorMessages = attrs.errorMessages;
            }

            if (ctrls[1] && ctrl.$errorMessages) {
                if (!angular.isObject(ctrl.$errorMessages) || angular.isArray(ctrl.$errorMessages)) {
                    ctrl.$errorMessages = undefined;
                    throw new Error('errorMessages defined on a formErrors must be an object.');
                }
            }
        }
    };
}])

// give us a way to override some options
.provider('FormErrorsOptions', [function () {
    // list of some default error messages
    var options = {
        defaultErrorMessages: {
            required  : 'is required.',
            minlength : 'is too short.',
            maxlength : 'is too long.',
            email     : 'is not a valid email address.',
            pattern   : 'does not match the expected pattern.',
            number    : 'is not a number.',
            url       : 'is not a valid URL.',
            form      : 'has errors.',

            fallback  : 'is invalid.'
        }
    };

    this.extendDefaultErrorMessages = function (messages) {
        options.defaultErrorMessages = angular.extend(options.defaultErrorMessages, messages);
    };

    this.$get = function () {
        return options;
    };
}]);
<|endoftext|>


<commit_before>var formfactor = (function() {
  // Some Paul Irish magic
  if (!window.matchMedia){
    window.matchMedia = (function(doc, undefined){
      var bool,
          docElem = doc.documentElement,
          fakeBody = doc.createElement('body'),
          testDiv = doc.createElement('div');

       testDiv.setAttribute('id','ejs-qtest');
       fakeBody.appendChild(testDiv);

       return function(q){
         var styleBlock = doc.createElement('style'),
             cssrule = '@media '+q+' { #ejs-qtest { position: absolute; } }';

         styleBlock.type = "text/css"; //must set type for IE!
         if (styleBlock.styleSheet){
           styleBlock.styleSheet.cssText = cssrule;
         }
         else {
           styleBlock.appendChild(doc.createTextNode(cssrule));
         }
         docElem.insertBefore(fakeBody, docElem.firstChild);
         docElem.insertBefore(styleBlock, docElem.firstChild);
         bool = ((window.getComputedStyle ? window.getComputedStyle(testDiv,null) : testDiv.currentStyle)['position'] == 'absolute');
         docElem.removeChild(fakeBody);
         docElem.removeChild(styleBlock);

         return { matches: bool, media: q };
       };
    })(document);
  }

  var test_media = function(query) {
    var mql = matchMedia(query);
    return mql.matches;
  };

  this.indicates = function(indicator) {
    return (typeof(indicator) == "function" && indicator())
        || (typeof(indicator) == "boolean" && indicator)
        || (typeof(indicator) == "string" && test_media(indicator))
  };

  // A collection of the formfactors and tests.
  var formfactorIndicators = {};

  var isFormfactor = function(formfactor) {
    var indicators = formfactorIndicators[formfactor];
    var indicator;
    for(var i = 0; indicator = indicators[i]; i++) {
      if (this.indicates(indicator)) return true;
    }

    return false;
  };

  var createLinkElement = function(rel, href) {
    var link = document.createElement("link");
    link.rel = rel;
    link.href = href;
    return link;
  };

  var createScriptElement = function(src) {
    var script = document.createElement("script");
    script.src = src;

    return script;
  };

  var initializeFormfactor = function(action) {
    var css, js;
    var callback = action.callback || function() {};
    action.css = action.css || [];
    action.js = action.js || [];

    if(action.css instanceof "") {
      document.head.append(createLinkElement("stylesheet", action.css));
    }
    else if(action.css instanceof []) {
      for(var css_idx = 0; css = action.css[css_idx]; css_idx++ ) {
        document.head.append(createLinkElement("stylesheet", css));
      }
    }

    if(action.js instanceof "") {
      document.head.append(createScriptElement(action.js));
    }
    else if (action.js instanceof []) {
      for(var js_idx = 0; js = action.js[js_idx]; js_idx++ ) {
        document.head.append(createScriptElement(js));
      }
    }

    return callback();
  };

  this.is = function(type) {
    var opts = {};
    opts[type]={};
    return this.detect(opts);
  };

  this.isnt = function(type) {
    return !(this.is(type));
  };

  this.detect = function(formfactorActions, defaultFormfactorAction) {
    defaultFormfactorAction = defaultFormfactorAction || { "css": [], "opts": [], "callback": function() {} };

    var formfactorAction;
    for(var i = 0; formfactorAction = formfactorActions[i]; i++) {
      if(isFormfactor(formfactorAction.formfactor)) {
        return executeFormfactorAction(formfactorAction);
      }
    };

    return executeFormfactorAction(defaultFormfactorAction);
  };

  this.register = function(formfactor) {
    for(var form in formfactor) {
      formfactorIndicators[form] = formfactor[form];
    }
  };

  this.firstOf = function(query) {
    if(!(query instanceof [])) throw "error";

    for(var m = 0; m < query.length; m++) {
      if(test_media(query[m].query)) query[m].callback();
      return;
    }
  };

  this.anyOf = function(query) {
    if(!(query instanceof [])) throw "error";

    for(var m = 0; m < query.length; m++) {
      if(test_media(query[m].query)) query[m].callback();
    }
  };

  this.watch = function(query, callback) {
    var mql = matchMedia(query);
    if(mql.matches) {
      mql.addListener(callback);
    }
  };
})();
<commit_msg>Fixing instanceof errros<commit_after>var formfactor = new (function() {
  // Some Paul Irish magic
  if (!window.matchMedia){
    window.matchMedia = (function(doc, undefined){
      var bool,
          docElem = doc.documentElement,
          fakeBody = doc.createElement('body'),
          testDiv = doc.createElement('div');

       testDiv.setAttribute('id','ejs-qtest');
       fakeBody.appendChild(testDiv);

       return function(q){
         var styleBlock = doc.createElement('style'),
             cssrule = '@media '+q+' { #ejs-qtest { position: absolute; } }';

         styleBlock.type = "text/css"; //must set type for IE!
         if (styleBlock.styleSheet){
           styleBlock.styleSheet.cssText = cssrule;
         }
         else {
           styleBlock.appendChild(doc.createTextNode(cssrule));
         }
         docElem.insertBefore(fakeBody, docElem.firstChild);
         docElem.insertBefore(styleBlock, docElem.firstChild);
         bool = ((window.getComputedStyle ? window.getComputedStyle(testDiv,null) : testDiv.currentStyle)['position'] == 'absolute');
         docElem.removeChild(fakeBody);
         docElem.removeChild(styleBlock);

         return { matches: bool, media: q };
       };
    })(document);
  }

  var test_media = function(query) {
    var mql = matchMedia(query);
    return mql.matches;
  };

  this.indicates = function(indicator) {
    return (typeof(indicator) == "function" && indicator())
        || (typeof(indicator) == "boolean" && indicator)
        || (typeof(indicator) == "string" && test_media(indicator))
  };

  // A collection of the formfactors and tests.
  var formfactorIndicators = {};

  var isFormfactor = function(formfactor) {
    var indicators = formfactorIndicators[formfactor];
    var indicator;
    for(var i = 0; indicator = indicators[i]; i++) {
      if (this.indicates(indicator)) return true;
    }

    return false;
  };

  var createLinkElement = function(rel, href) {
    var link = document.createElement("link");
    link.rel = rel;
    link.href = href;
    return link;
  };

  var createScriptElement = function(src) {
    var script = document.createElement("script");
    script.src = src;

    return script;
  };

  var initializeFormfactor = function(action) {
    var css, js;
    var callback = action.callback || function() {};
    action.css = action.css || [];
    action.js = action.js || [];

    if(action.css instanceof String) {
      document.head.append(createLinkElement("stylesheet", action.css));
    }
    else if(action.css instanceof Array) {
      for(var css_idx = 0; css = action.css[css_idx]; css_idx++ ) {
        document.head.append(createLinkElement("stylesheet", css));
      }
    }

    if(action.js instanceof String) {
      document.head.append(createScriptElement(action.js));
    }
    else if (action.js instanceof Array) {
      for(var js_idx = 0; js = action.js[js_idx]; js_idx++ ) {
        document.head.append(createScriptElement(js));
      }
    }

    return callback();
  };

  this.is = function(type) {
    var opts = {};
    opts[type]={};
    return this.detect(opts);
  };

  this.isnt = function(type) {
    return !(this.is(type));
  };

  this.detect = function(formfactorActions, defaultFormfactorAction) {
    defaultFormfactorAction = defaultFormfactorAction || { "css": [], "opts": [], "callback": function() {} };

    var formfactorAction;
    for(var i = 0; formfactorAction = formfactorActions[i]; i++) {
      if(isFormfactor(formfactorAction.formfactor)) {
        return initializeFormfactor(formfactorAction);
      }
    };

    return initializeFormfactor(defaultFormfactorAction);
  };

  this.register = function(formfactor) {
    for(var form in formfactor) {
      formfactorIndicators[form] = formfactor[form];
    }
  };

  this.firstOf = function(query) {
    if(!(query instanceof Array)) throw "error";

    for(var m = 0; m < query.length; m++) {
      if(test_media(query[m].query)) query[m].callback();
      return;
    }
  };

  this.anyOf = function(query) {
    if(!(query instanceof Array)) throw "error";

    for(var m = 0; m < query.length; m++) {
      if(test_media(query[m].query)) query[m].callback();
    }
  };

  this.watch = function(query, callback) {
    var mql = matchMedia(query);
    if(mql.matches) {
      mql.addListener(callback);
    }
  };
})();
<|endoftext|>


<commit_before>"use strict";
var Questionnaire = {
  current_question_index: 0,

  init: function() {
    this.initVars();
    this.loadQuestions();
    this.bindings();
    this.begin();
  },

  begin: function() {
    setTimeout(function(self) {
      document
        .querySelector("ol li:first-child")
        .setAttribute("aria-hidden", "false");
    }, 300);
  },

  initVars: function() {
    this.questions_list = document.createElement("ol");
    this.questions_container = document.querySelector("#questions-container");
    this.submit_button = this.questions_container.querySelector("button");
  },

  bindings: function() {
    var that = this,
        option_labels = document.querySelectorAll("ol ul li label"),
        len = option_labels.length;

    this.submit_button.addEventListener("click", function() {
      that.showNextQuestion();
    });

    for(var i = 0; i < len; i++) {
      option_labels[i].addEventListener("click", function() {
        that.enableSubmitButton();
      });
    }
  },

  disableSubmitButton: function() {
    this.submit_button.setAttribute("disabled", "disabled");
  },

  enableSubmitButton: function() {
    this.submit_button.removeAttribute("disabled");
  },

  focusFirstOption: function() {
    document.querySelector("ol > li[aria-hidden=false] [type=radio]:first-of-type").focus();
  },

  showNextQuestion: function() {
    this.setListItemState();
    this.setActiveQuestionIndex(this.getActiveQuestionIndex());
    this.setListItemState("false");
    this.disableSubmitButton();
  },

  setListItemState: function() {
    var index = this.getActiveQuestionIndex(),
        state = arguments.length ? "false" : "true";

    document
      .querySelector("ol > li:nth-child(" + index + ")")
      .setAttribute("aria-hidden", state);
  },

  getActiveQuestionIndex: function() {
    return this.current_question_index+1;
  },

  setActiveQuestionIndex: function(index) {
    this.current_question_index = index;
  },

  loadQuestions: function() {
    var question_len = questions.length,
        that = this,
        createCard   = function(index, question) {
          var question_text           = document.createElement("span"),
              question_options        = questions[index].options,
              question_options_length = questions[index].options.length,
              ul                      = document.createElement("ul"),
              li                      = document.createElement("li"),
              li_option,
              option_label,
              option_input,
              option_id;

            question_text.classList.add("question-text");
            question_text.innerHTML = questions[index].question;

            for (var i = 0; i < question_options_length; i++) {
              li_option = document.createElement("li");
              option_label = document.createElement("label");
              option_label.innerHTML = question_options[i];
              option_input = document.createElement("input");
              option_input.type = "radio";
              option_input.name = "rdo_" + index;
              option_label.appendChild(option_input);
              li_option.appendChild(option_label);
              ul.appendChild(li_option);
            }

            li.dataset.questionId = index;
            li.setAttribute("aria-hidden", "true");
            li.appendChild(question_text);
            li.appendChild(ul);
            that.questions_list.appendChild(li);
        };

    for (var i = 0; i < question_len; i++) {
      createCard(i, questions[i]);
    }

    this.questions_container.setAttribute("aria-busy", "false");

    this.questions_container
      .querySelector(".inner")
      .insertBefore(this.questions_list, this.submit_button);
  }
};
<commit_msg>Break up loadQuestions()<commit_after>"use strict";
var Questionnaire = {
  current_question_index: 0,

  init: function() {
    this.initVars();
    this.loadQuestions();
    this.bindings();
    this.begin();
  },

  begin: function() {
    setTimeout(function(self) {
      document
        .querySelector("ol li:first-child")
        .setAttribute("aria-hidden", "false");
    }, 300);
  },

  createElement: function(el) {
    return document.createElement(el);
  },

  initVars: function() {
    this.questions_list = this.createElement("ol");
    this.questions_container = document.querySelector("#questions-container");
    this.submit_button = this.questions_container.querySelector("button");
  },

  bindings: function() {
    var that = this,
        option_labels = document.querySelectorAll("ol ul li label"),
        len = option_labels.length;

    this.submit_button.addEventListener("click", function() {
      that.showNextQuestion();
    });

    for(var i = 0; i < len; i++) {
      option_labels[i].addEventListener("click", function() {
        that.enableSubmitButton();
      });
    }
  },

  disableSubmitButton: function() {
    this.submit_button.setAttribute("disabled", "disabled");
  },

  enableSubmitButton: function() {
    this.submit_button.removeAttribute("disabled");
  },

  focusFirstOption: function() {
    document.querySelector("ol > li[aria-hidden=false] [type=radio]:first-of-type").focus();
  },

  showNextQuestion: function() {
    this.setListItemState();
    this.setActiveQuestionIndex(this.getActiveQuestionIndex());
    this.setListItemState("false");
    this.disableSubmitButton();
  },

  setListItemState: function() {
    var index = this.getActiveQuestionIndex(),
        state = arguments.length ? "false" : "true";

    document
      .querySelector("ol > li:nth-child(" + index + ")")
      .setAttribute("aria-hidden", state);
  },

  getActiveQuestionIndex: function() {
    return this.current_question_index+1;
  },

  setActiveQuestionIndex: function(index) {
    this.current_question_index = index;
  },

  loadQuestions: function() {
    var question_len = questions.length,
        that = this,
        question_options,
        question_options_length,
        ul, li, li_option, i, question_text,
        option_label, option_input, option_id,

        createOptions = function(index) {
          for (var i = 0; i < question_options_length; i++) {
            li_option = that.createElement("li");
            option_label = that.createElement("label");
            option_label.innerHTML = question_options[i];
            option_input = that.createElement("input");
            option_input.type = "radio";
            option_input.name = "rdo_" + index;
            option_label.appendChild(option_input);
            li_option.appendChild(option_label);
            ul.appendChild(li_option);
          }
        },

        createCard = function(index, question) {
          question_options  = questions[index].options;
          question_options_length = questions[index].options.length;

          question_text = that.createElement("span");
          ul = that.createElement("ul");
          li = that.createElement("li");

          question_text.classList.add("question-text");
          question_text.innerHTML = questions[index].question;

          createOptions(index);

          li.dataset.questionId = index;
          li.setAttribute("aria-hidden", "true");
          li.appendChild(question_text);
          li.appendChild(ul);
          that.questions_list.appendChild(li);
        };

    for (i = 0; i < question_len; i++) {
      createCard(i, questions[i]);
    }

    this.questions_container.setAttribute("aria-busy", "false");

    this.questions_container
      .querySelector(".inner")
      .insertBefore(this.questions_list, this.submit_button);
  }
};
<|endoftext|>


<commit_before>import React from 'react';
import CodeEditor from 'components/CodeEditor.js';
import BashOutput from 'components/BashOutput.js';
import CompileConfig from 'components/CompileConfig.js';
import QuickChart from './QuickChart.js';
import { Button, ButtonToolbar, Row, Col, Container, Card, FormCheck, Form, ProgressBar, Nav, Tab } from 'react-bootstrap';
import { MdTimer } from "react-icons/md";
import AssemblyEditor from './AssemblyEditor.js';
import InteropHelper from 'components/InteropHelper.js';
import Palette from 'components/Palette.js';

var request = require('request');
const protocolVersion = 3;

const startCode = `static void StringCreation(benchmark::State& state) {
  // Code inside this loop is measured repeatedly
  for (auto _ : state) {
    std::string created_string("hello");
    // Make sure the variable is not optimized away by compiler
    benchmark::DoNotOptimize(created_string);
  }
}
// Register the function as a benchmark
BENCHMARK(StringCreation);

static void StringCopy(benchmark::State& state) {
  // Code before the loop is not measured
  std::string x = "hello";
  for (auto _ : state) {
    std::string copy(x);
  }
}
BENCHMARK(StringCopy);
`;
const includeStr = '#include <benchmark/benchmark.h>\n';
const mainStr = '\nBENCHMARK_MAIN();';

const PALETTE = [
    "#5ed9cd",
    "#61d6eb",
    "#a1caf4",
    "#c7c0f4",
    "#eab3f4",
    "#f5b3d9",
    "#f5b5c0",
    "#f6b8a0",
    "#edc058",
    "#c4ce58",
    "#7ddc58",
    "#5bdca8"
];
class Benchmark extends React.Component {
    static initialState = {
        text: startCode
        , graph: []
        , message: ''
        , sending: false
        , progress: 0
        , options: {
            compiler: "clang-9.0"
            , cppVersion: "20"
            , optim: "3"
            , lib: "gnu"
        }
        , clean: false
        , force: false
        , benchNames: []
        , annotation: ''
        , isAnnotated: true
        , assemblyFull: false
        , chartIndex: 0
    };
    constructor(props) {
        super(props);
        this.state = JSON.parse(JSON.stringify(Benchmark.initialState));
        this.state.location = props.id;
        this.state.prevLocation = props.id;

        let stateFromHash = this.getStateFromHash();
        if (stateFromHash) {
            this.setState({
                text: this.importCode(stateFromHash.text),
                options: {
                    compiler: stateFromHash.compiler || this.state.options.compiler
                    , cppVersion: stateFromHash.cppVersion || this.state.options.cppVersion
                    , optim: stateFromHash.optim || this.state.options.optim
                    , lib: stateFromHash.lib || this.state.options.lib
                }
            });
        }
    }
    initializeCode() {
        this.setState(Benchmark.initialState);
    }
    getStateFromHash() {
        if (window.location.hash) {
            let state = this.decodeHash(window.location.hash);
            window.location.hash = "";
            if (state.text) {
                return state;
            }
        }

        return false;
    }
    componentDidMount() {
        if (this.props.id) {
            this.setState({
                sending: true,
                graph: [],
                annotation: '',
                message: ''
            });
            this.getCode(this.props.id);
        }
        this.props.onDisplay();
    }
    componentDidUpdate(prevProps) {
        console.log(prevProps.id + " -> " + this.props.id);
        if (prevProps.id !== this.props.id) {
            console.log("new loc " + this.props.id);
            this.setState({
                prevLocation: this.props.id
            });
            if (this.props.id !== this.state.location) {
                this.setState({
                    location: this.props.id
                });
                if (this.props.id) {
                    this.getCode(this.props.id);
                } else {
                    this.initializeCode();
                    this.props.onLocationChange(undefined);
                }
            }
        }
    }
    static getDerivedStateFromProps(props, state) {
        if (props.id !== state.prevLocation && props.id !== state.location && props.id) {
            return {
                sending: true,
                graph: [],
                annotation: '',
                message: ''
            };
        }
        return null;
    }
    getCode(id) {
        request.get(this.props.url + '/quick/' + id, (err, res, body) => {
            this.setState({
                sending: false,
                clean: true,
                force: false
            });
            if (body) {
                let result = JSON.parse(body);
                if (result) {
                    if (result.result) {
                        let compiler = result.tab.compiler === 'clang++-3.8' ? 'clang-3.8' : result.tab.compiler;
                        let options = {
                            compiler: compiler
                            , cppVersion: result.tab.cppVersion
                            , optim: result.tab.optim
                            , lib: result.tab.lib
                        };
                        this.setState({
                            text: result.tab.code
                            , graph: result.result.benchmarks
                            , options: options
                            , location: id
                        });
                    }
                    if (result.message) {
                        this.setState({
                            message: result.message
                        });
                    }
                    if (result.annotation) {
                        this.setState({
                            annotation: result.annotation
                            , isAnnotated: true
                        });
                    } else {
                        this.setState({ isAnnotated: false });
                    }
                }
            }
        });
    }
    sendCode() {
        if (this.state.text.length > this.props.maxCodeSize) {
            this.setState({
                graph: [],
                annotation: '',
                message: `Your code is ${this.state.text.length} characters long, while the maximum code size is ${this.props.maxCodeSize}.
If you think this limitation is stopping you in a legitimate usage of build-bench, please contact me.`
            });
        } else {
            this.setState({
                sending: true,
                graph: [],
                annotation: '',
                message: ''
            });
            this.setState({ progress: 0 });
            let interval = setInterval(() => {
                this.setState({ progress: this.state.progress + 100 / 120 });
            }, 1000);

            var obj = {
                "code": this.state.text,
                "options": this.state.options,
                "protocolVersion": protocolVersion,
                "force": this.state.clean && this.state.force,
                "isAnnotated": this.state.isAnnotated,
            };
            request({
                url: this.props.url + '/quick/'
                , method: "POST"
                , json: true
                , headers: {
                    "content-type": "application/json"
                }
                , body: obj
            }, (err, res, body) => {
                this.setState({
                    sending: false,
                    clean: true,
                    force: false
                });
                clearInterval(interval);
                if (body) {

                    if (body.result) {
                        this.setState({
                            graph: body.result.benchmarks || []
                        });
                    }
                    if (body.id) {
                        console.log("onLocationChange " + body.id);
                        this.setState({ location: body.id }, () => this.props.onLocationChange(body.id));
                    }
                    if (body.annotation) {
                        this.setState({ annotation: body.annotation });
                    }
                    if (body.message) {
                        this.setState({ message: body.message });
                    }
                }
                else if (err) {
                    this.setState({ message: err });
                }
            });
        }
    }
    decodeHash(str) {
        try {
            let base64ascii = str.substr(1);
            if (base64ascii) {
                return JSON.parse(atob(base64ascii));
            }
        } catch (err) {
            console.error(err);
        }
        return false;
    }
    importCode(text) {
        return text.replace(includeStr, '').replace(mainStr, '');
    }
    setDirty() {
        this.setState({
            clean: false,
            force: false
        });
    }
    codeChanged(code) {
        this.setState({
            text: code
        });
        this.setDirty();
    }
    forceChanged(e) {
        this.setState({
            force: e.target.checked
        });
    }
    onOptionsChange(options) {
        this.setState({ options: options });
        this.setDirty();
    }
    toggleAnnotated(e) {
        this.setState({ isAnnotated: e.target.checked });
    }
    buttonHeight() {
        const run = document.getElementById('Run');
        if (run == null)
            return '5px';
        const compStyle = window.getComputedStyle(run, null);
        // We remove 4px more because for some reason otherwise it is possible that the CE button ends-up slightly bigger than the run button
        // Which because the whole toolbar is the same size, would start an infinit loop of
        // "run" growing -> CE grows to react -> is bigger than run -> grows the toolbar
        return `calc(${compStyle.height} - ${compStyle.paddingTop} - ${compStyle.paddingBottom} - 4px)`;
    }
    render() {
        return (
            <Container fluid>
                <Row className="full-size">
                    <Col sm={6} className="full-size">

                            <CodeEditor onChange={c => this.codeChanged(c)}
                                value={this.state.text}
                                names={this.state.benchNames}
                            />

                    </Col>
                    <Col sm={6} className="flex-container">

                                <Card body className="my-2">
                                    <CompileConfig value={this.state.options} onChange={c => this.onOptionsChange(c)} />

                                    <ButtonToolbar className="justify-content-between">
                                        <Form inline>
                                            <Button variant="primary" onClick={() => this.sendCode()} disabled={this.state.sending} className="mr-2" id="Run"> <MdTimer /> Run Benchmark</Button>
                                            <FormCheck ref="force" checked={this.state.isAnnotated} custom type='checkbox' id="disassembly" onChange={e => this.toggleAnnotated(e)} label={"Record disassembly"} className="mr-2" />
                                            {this.state.clean ? <FormCheck ref="force" type="checkbox" custom checked={this.state.force} id="clean-cache" onChange={this.forceChanged.bind(this)} label="Clear cached results" /> : null}
                                        </Form>
                                        <Form inline>
                                            <Button variant="outline-dark" onClick={() => InteropHelper.openCodeInCE(this.state.text, this.state.options)} className="float-right"></Button>
                                        </Form>
                                    </ButtonToolbar>
                                    {this.state.sending ? <ProgressBar animated now={this.state.progress} /> : null}
                                </Card>

                            <Tab.Container defaultActiveKey="charts">
                                {this.state.graph.length > 0 ? (

                                            Charts

                                            Assembly

                                ) : null}
                                <Tab.Content className="fill-content">
                                    <Tab.Pane eventKey="charts" className="fill-content">
                                        <QuickChart benchmarks={this.state.graph}
                                            id={this.state.location}
                                            index={this.state.chartIndex}
                                            onNamesChange={n => this.setState({ benchNames: n })}
                                            onDescriptionChange={d => this.props.onDescriptionChange(d)}
                                            palette={this.props.specialPalette ? Palette.CHRISTMAS_PALETTE : PALETTE}
                                            changeDisplay={d => this.setState({ chartIndex: d })}
                                        />
                                    </Tab.Pane>
                                    <Tab.Pane eventKey="asm" className="fill-content">
                                        <AssemblyEditor code={this.state.annotation} names={this.state.benchNames} setFullScreen={fs => this.setState({ assemblyFull: fs })} />
                                    </Tab.Pane>
                                </Tab.Content>
                            </Tab.Container>

                                <BashOutput value={this.state.message} />

                    </Col>
                </Row>
            </Container >
        );
    }
}

export default Benchmark;
<commit_msg>Update quick-bench to handle new back-end format.<commit_after>import React from 'react';
import CodeEditor from 'components/CodeEditor.js';
import BashOutput from 'components/BashOutput.js';
import CompileConfig from 'components/CompileConfig.js';
import QuickChart from './QuickChart.js';
import { Button, ButtonToolbar, Row, Col, Container, Card, FormCheck, Form, ProgressBar, Nav, Tab } from 'react-bootstrap';
import { MdTimer } from "react-icons/md";
import AssemblyEditor from './AssemblyEditor.js';
import InteropHelper from 'components/InteropHelper.js';
import Palette from 'components/Palette.js';

var request = require('request');
const protocolVersion = 4;

const startCode = `static void StringCreation(benchmark::State& state) {
  // Code inside this loop is measured repeatedly
  for (auto _ : state) {
    std::string created_string("hello");
    // Make sure the variable is not optimized away by compiler
    benchmark::DoNotOptimize(created_string);
  }
}
// Register the function as a benchmark
BENCHMARK(StringCreation);

static void StringCopy(benchmark::State& state) {
  // Code before the loop is not measured
  std::string x = "hello";
  for (auto _ : state) {
    std::string copy(x);
  }
}
BENCHMARK(StringCopy);
`;
const includeStr = '#include <benchmark/benchmark.h>\n';
const mainStr = '\nBENCHMARK_MAIN();';

const PALETTE = [
    "#5ed9cd",
    "#61d6eb",
    "#a1caf4",
    "#c7c0f4",
    "#eab3f4",
    "#f5b3d9",
    "#f5b5c0",
    "#f6b8a0",
    "#edc058",
    "#c4ce58",
    "#7ddc58",
    "#5bdca8"
];
class Benchmark extends React.Component {
    static initialState = {
        text: startCode
        , graph: []
        , message: ''
        , sending: false
        , progress: 0
        , options: {
            compiler: "clang-9.0"
            , cppVersion: "20"
            , optim: "3"
            , lib: "gnu"
        }
        , clean: false
        , force: false
        , benchNames: []
        , annotation: ''
        , isAnnotated: true
        , assemblyFull: false
        , chartIndex: 0
    };
    constructor(props) {
        super(props);
        this.state = JSON.parse(JSON.stringify(Benchmark.initialState));
        this.state.location = props.id;
        this.state.prevLocation = props.id;

        let stateFromHash = this.getStateFromHash();
        if (stateFromHash) {
            this.setState({
                text: this.importCode(stateFromHash.text),
                options: {
                    compiler: stateFromHash.compiler || this.state.options.compiler
                    , cppVersion: stateFromHash.cppVersion || this.state.options.cppVersion
                    , optim: stateFromHash.optim || this.state.options.optim
                    , lib: stateFromHash.lib || this.state.options.lib
                }
            });
        }
    }
    initializeCode() {
        this.setState(Benchmark.initialState);
    }
    getStateFromHash() {
        if (window.location.hash) {
            let state = this.decodeHash(window.location.hash);
            window.location.hash = "";
            if (state.text) {
                return state;
            }
        }

        return false;
    }
    componentDidMount() {
        if (this.props.id) {
            this.setState({
                sending: true,
                graph: [],
                annotation: '',
                message: ''
            });
            this.getCode(this.props.id);
        }
        this.props.onDisplay();
    }
    componentDidUpdate(prevProps) {
        console.log(prevProps.id + " -> " + this.props.id);
        if (prevProps.id !== this.props.id) {
            console.log("new loc " + this.props.id);
            this.setState({
                prevLocation: this.props.id
            });
            if (this.props.id !== this.state.location) {
                this.setState({
                    location: this.props.id
                });
                if (this.props.id) {
                    this.getCode(this.props.id);
                } else {
                    this.initializeCode();
                    this.props.onLocationChange(undefined);
                }
            }
        }
    }
    static getDerivedStateFromProps(props, state) {
        if (props.id !== state.prevLocation && props.id !== state.location && props.id) {
            return {
                sending: true,
                graph: [],
                annotation: '',
                message: ''
            };
        }
        return null;
    }
    getCode(id) {
        request.get(this.props.url + '/quick/' + id, (err, res, body) => {
            this.setState({
                sending: false,
                clean: true,
                force: false
            });
            if (body) {
                let result = JSON.parse(body);
                if (result) {
                    if (result.result) {
                        let compiler = result.tab.compiler === 'clang++-3.8' ? 'clang-3.8' : result.tab.options.compiler;
                        let options = {
                            compiler: compiler
                            , cppVersion: result.tab.options.cppVersion
                            , optim: result.tab.options.optim
                            , lib: result.tab.options.lib
                        };
                        this.setState({
                            text: result.tab.code
                            , graph: result.result.benchmarks
                            , options: options
                            , location: id
                        });
                    }
                    if (result.message) {
                        this.setState({
                            message: result.message
                        });
                    }
                    if (result.annotation) {
                        this.setState({
                            annotation: result.annotation
                            , isAnnotated: true
                        });
                    } else {
                        this.setState({ isAnnotated: false });
                    }
                }
            }
        });
    }
    sendCode() {
        if (this.state.text.length > this.props.maxCodeSize) {
            this.setState({
                graph: [],
                annotation: '',
                message: `Your code is ${this.state.text.length} characters long, while the maximum code size is ${this.props.maxCodeSize}.
If you think this limitation is stopping you in a legitimate usage of build-bench, please contact me.`
            });
        } else {
            this.setState({
                sending: true,
                graph: [],
                annotation: '',
                message: ''
            });
            this.setState({ progress: 0 });
            let interval = setInterval(() => {
                this.setState({ progress: this.state.progress + 100 / 120 });
            }, 1000);

            var obj = {
                "code": this.state.text,
                "options": this.state.options,
                "protocolVersion": protocolVersion,
                "force": this.state.clean && this.state.force,
                "isAnnotated": this.state.isAnnotated,
            };
            request({
                url: this.props.url + '/quick/'
                , method: "POST"
                , json: true
                , headers: {
                    "content-type": "application/json"
                }
                , body: obj
            }, (err, res, body) => {
                this.setState({
                    sending: false,
                    clean: true,
                    force: false
                });
                clearInterval(interval);
                if (body) {

                    if (body.result) {
                        this.setState({
                            graph: body.result.benchmarks || []
                        });
                    }
                    if (body.id) {
                        console.log("onLocationChange " + body.id);
                        this.setState({ location: body.id }, () => this.props.onLocationChange(body.id));
                    }
                    if (body.annotation) {
                        this.setState({ annotation: body.annotation });
                    }
                    if (body.message) {
                        this.setState({ message: body.message });
                    }
                }
                else if (err) {
                    this.setState({ message: err });
                }
            });
        }
    }
    decodeHash(str) {
        try {
            let base64ascii = str.substr(1);
            if (base64ascii) {
                return JSON.parse(atob(base64ascii));
            }
        } catch (err) {
            console.error(err);
        }
        return false;
    }
    importCode(text) {
        return text.replace(includeStr, '').replace(mainStr, '');
    }
    setDirty() {
        this.setState({
            clean: false,
            force: false
        });
    }
    codeChanged(code) {
        this.setState({
            text: code
        });
        this.setDirty();
    }
    forceChanged(e) {
        this.setState({
            force: e.target.checked
        });
    }
    onOptionsChange(options) {
        this.setState({ options: options });
        this.setDirty();
    }
    toggleAnnotated(e) {
        this.setState({ isAnnotated: e.target.checked });
    }
    buttonHeight() {
        const run = document.getElementById('Run');
        if (run == null)
            return '5px';
        const compStyle = window.getComputedStyle(run, null);
        // We remove 4px more because for some reason otherwise it is possible that the CE button ends-up slightly bigger than the run button
        // Which because the whole toolbar is the same size, would start an infinit loop of
        // "run" growing -> CE grows to react -> is bigger than run -> grows the toolbar
        return `calc(${compStyle.height} - ${compStyle.paddingTop} - ${compStyle.paddingBottom} - 4px)`;
    }
    render() {
        return (
            <Container fluid>
                <Row className="full-size">
                    <Col sm={6} className="full-size">

                            <CodeEditor onChange={c => this.codeChanged(c)}
                                value={this.state.text}
                                names={this.state.benchNames}
                            />

                    </Col>
                    <Col sm={6} className="flex-container">

                                <Card body className="my-2">
                                    <CompileConfig value={this.state.options} onChange={c => this.onOptionsChange(c)} />

                                    <ButtonToolbar className="justify-content-between">
                                        <Form inline>
                                            <Button variant="primary" onClick={() => this.sendCode()} disabled={this.state.sending} className="mr-2" id="Run"> <MdTimer /> Run Benchmark</Button>
                                            <FormCheck ref="force" checked={this.state.isAnnotated} custom type='checkbox' id="disassembly" onChange={e => this.toggleAnnotated(e)} label={"Record disassembly"} className="mr-2" />
                                            {this.state.clean ? <FormCheck ref="force" type="checkbox" custom checked={this.state.force} id="clean-cache" onChange={this.forceChanged.bind(this)} label="Clear cached results" /> : null}
                                        </Form>
                                        <Form inline>
                                            <Button variant="outline-dark" onClick={() => InteropHelper.openCodeInCE(this.state.text, this.state.options)} className="float-right"></Button>
                                        </Form>
                                    </ButtonToolbar>
                                    {this.state.sending ? <ProgressBar animated now={this.state.progress} /> : null}
                                </Card>

                            <Tab.Container defaultActiveKey="charts">
                                {this.state.graph.length > 0 ? (

                                            Charts

                                            Assembly

                                ) : null}
                                <Tab.Content className="fill-content">
                                    <Tab.Pane eventKey="charts" className="fill-content">
                                        <QuickChart benchmarks={this.state.graph}
                                            id={this.state.location}
                                            index={this.state.chartIndex}
                                            onNamesChange={n => this.setState({ benchNames: n })}
                                            onDescriptionChange={d => this.props.onDescriptionChange(d)}
                                            palette={this.props.specialPalette ? Palette.CHRISTMAS_PALETTE : PALETTE}
                                            changeDisplay={d => this.setState({ chartIndex: d })}
                                        />
                                    </Tab.Pane>
                                    <Tab.Pane eventKey="asm" className="fill-content">
                                        <AssemblyEditor code={this.state.annotation} names={this.state.benchNames} setFullScreen={fs => this.setState({ assemblyFull: fs })} />
                                    </Tab.Pane>
                                </Tab.Content>
                            </Tab.Container>

                                <BashOutput value={this.state.message} />

                    </Col>
                </Row>
            </Container >
        );
    }
}

export default Benchmark;
<|endoftext|>


<commit_before>
var processor = require('./url');

var factory = function(storeFactory) {
    this.storeFactory = storeFactory;
}

factory.prototype = {

    create: function(url) {
        var store = this.storeFactory.getStore(url);
        return new processor(url, store);
    }
};

module.exports = factory;<commit_msg>removed processFactory file<commit_after><|endoftext|>


<commit_before><commit_msg>ensure trailing slash<commit_after><|endoftext|>


<commit_before>module.exports = {
  rootDir: '..',
  transform: {
    '.(ts|tsx)': 'ts-jest',
  },
  globals: {
    'ts-jest': {
      diagnostics: false,
    },
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
  testURL: 'http://localhost',
  testMatch: ['<rootDir>/src/**/__tests__/**/*.ts'],
  testPathIgnorePatterns: [
    '/node_modules/',
    '/lib/'
  ],
  setupFiles: ['<rootDir>/src/config/jest/setup.ts'],
};
<commit_msg>Remove specific test matching<commit_after>module.exports = {
  rootDir: '..',
  transform: {
    '.(ts|tsx)': 'ts-jest',
  },
  globals: {
    'ts-jest': {
      diagnostics: false,
    },
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
  testURL: 'http://localhost',
  testPathIgnorePatterns: [
    '/node_modules/',
    '/lib/'
  ],
  setupFiles: ['<rootDir>/src/config/jest/setup.ts'],
};
<|endoftext|>


<commit_before>var game_id;

$(document).ready(function(){
	fillSelectBox();

	bindEvents();
});

function showSpinner()
{
	$('#modal').css('display', 'block');
	$('#fade').css('display', 'block');
}

function hideSpinner()
{
	$('#modal').css('display', 'none');
	$('#fade').css('display', 'none');
}

function fillSelectBox()
{
	showSpinner();
	$.ajax({
		type: "POST",
		url: "getServers.php",
		dataType: 'json',
		success: function(response){
			if(response['success'] == true){
			var arr = response['results'];

			for(var i=0; i < arr.length; i++){
				var item = arr[i];
				var serverName = item[1];
				var game_id = item[3];

				$('select').append($("<option></option>")
                    .attr("value", game_id)
                    .text(serverName));
			}
			hideSpinner();
			}else{
				alert("Something went wrong.  We REALLY suck. =(");
			}
		},
		error: function(response){
			alert("Something went wrong.  We REALLY suck. =(");
		}
	});
}

function populatePlayers()
{
	showSpinner();
	//clear out ordered lists, as server will change
	$('#1_list').empty();
	$('#2_list').empty();

	$.ajax({
		type: "POST",
		url: "getPlayers.php",
		data: {
			game_id: game_id
		},
		dataType: 'json',
		success: function(response){
			if(response['success'] == true){
			var arr = response['results'];

			for(var i=0; i < arr.length; i++){
				var item = arr[i];
				var team = item[0];
				var name = item[1];

				if(team == 1){
					$('#1_list').append("
"+name+"
");
				}else if(team == 2){
					$('#2_list').append("
"+name+"
");
				}
			}
			hideSpinner();
			}else{
				alert("Something went wrong.  We REALLY suck. =(");
			}
		},
		error: function(response){
			alert("Something went wrong.  We REALLY suck. =(");
		}
	});
}

function joinTeam1()
{
	$.ajax({
		type: "POST",
		url: "joinTeam.php",
		data: {
			team: 1,
			game_id: game_id
		},
		success: function(response){
			var response = JSON.parse(response);
			if(response['success'] == true){
				populatePlayers();
				showLeaveButton();
			}else{
				alert("Something went wrong.  We REALLY suck. =(");
			}
		},
		error: function(response){
			alert("Something went wrong.  We REALLY suck. =(");
		}
	});
}

function joinTeam2()
{
	$.ajax({
		type: "POST",
		url: "joinTeam.php",
		data: {
			team: 2,
			game_id: game_id
		},
		success: function(response){
			var response = JSON.parse(response);
			if(response['success'] == true){
				populatePlayers();
				showLeaveButton();
			}else{
				alert("Something went wrong.  We REALLY suck. =(");
			}
		},
		error: function(response){
			alert("Something went wrong.  We REALLY suck. =(");
		}
	});
}

function leaveTeam()
{
	showSpinner();
	$.ajax({
		type: "POST",
		url: "leaveTeam.php",
		data: {
			game_id: game_id
		},
		dataType: 'json',
		success: function(response){
			if(response['success'] == true){
				populatePlayers();
				hideLeaveButton();
			}else{
				alert("Something went wrong.  We REALLY suck. =(");
			}
		},
		error: function(response){
			alert("Something went wrong.  We REALLY suck. =(");
		}
	});
}

function showLeaveButton()
{
	$('#leaveTeam').show();
}

function hideLeaveButton()
{
	$('#leaveTeam').hide();
}

function bindEvents()
{
	//when server select box changes, populate it with players currently joined to game
	$('select').on("change", function(){
		game_id = $('select').find(":selected").attr("value");
		populatePlayers();
	});

	//when player clicks on team 1, join player to team 1
	$('#Team1').on('click', function(){
		joinTeam1();
	});

	//when player clicks on team 1, join player to team 1
	$('#Team2').on('click', function(){
		joinTeam2();
	});

	$('#leaveTeam').on('click', function(){
		leaveTeam();
	});
}
<commit_msg>More updates to lobby javascript<commit_after>var game_id;

$(document).ready(function(){
	fillSelectBox();

	bindEvents();
});

function showSpinner()
{
	$('#modal').css('display', 'block');
	$('#fade').css('display', 'block');
}

function hideSpinner()
{
	$('#modal').css('display', 'none');
	$('#fade').css('display', 'none');
}

function fillSelectBox()
{
	showSpinner();
	$.ajax({
		type: "POST",
		url: "getServers.php",
		dataType: 'json',
		success: function(response){
			if(response['success'] == true){
			var arr = response['results'];

			for(var i=0; i < arr.length; i++){
				var item = arr[i];
				var serverName = item[1];
				var game_id = item[3];

				$('select').append($("<option></option>")
                    .attr("value", game_id)
                    .text(serverName));
			}
			hideSpinner();
			}else{
				alert("Something went wrong.  We REALLY suck. =(");
			}
		},
		error: function(response){
			alert("Something went wrong.  We REALLY suck. =(");
		}
	});
}

function populatePlayers()
{
	showSpinner();
	//clear out ordered lists, as server will change
	$('#1_list').empty();
	$('#2_list').empty();

	$.ajax({
		type: "POST",
		url: "getPlayers.php",
		data: {
			game_id: game_id
		},
		dataType: 'json',
		success: function(response){
			if(response['success'] == true){
			var arr = response['results'];

			for(var i=0; i < arr.length; i++){
				var item = arr[i];
				var team = item[0];
				var name = item[1];

				if(team == 1){
					$('#1_list').append("
"+name+"
");
				}else if(team == 2){
					$('#2_list').append("
"+name+"
");
				}
			}
			hideSpinner();
			}else{
				alert("Something went wrong.  We REALLY suck. =(");
			}
		},
		error: function(response){
			alert("Something went wrong.  We REALLY suck. =(");
		}
	});
}

function joinTeam1()
{
	$.ajax({
		type: "POST",
		url: "joinTeam.php",
		data: {
			team: 1,
			game_id: game_id
		},
		success: function(response){
			var response = JSON.parse(response);
			if(response['success'] == true){
				populatePlayers();
				showLeaveButton();
			}else{
				alert("Something went wrong.  We REALLY suck. =(");
			}
		},
		error: function(response){
			alert("Something went wrong.  We REALLY suck. =(");
		}
	});
}

function joinTeam2()
{
	$.ajax({
		type: "POST",
		url: "joinTeam.php",
		data: {
			team: 2,
			game_id: game_id
		},
		success: function(response){
			var response = JSON.parse(response);
			if(response['success'] == true){
				populatePlayers();
				showLeaveButton();
			}else{
				alert("Something went wrong.  We REALLY suck. =(");
			}
		},
		error: function(response){
			alert("Something went wrong.  We REALLY suck. =(");
		}
	});
}

function leaveTeam()
{
	showSpinner();
	$.ajax({
		type: "POST",
		url: "leaveTeam.php",
		data: {
			game_id: game_id
		},
		dataType: 'json',
		success: function(response){
			if(response['success'] == true){
				populatePlayers();
				hideLeaveButton();
			}else{
				alert("Something went wrong.  We REALLY suck. =(");
			}
		},
		error: function(response){
			alert("Something went wrong.  We REALLY suck. =(");
		}
	});
}

function showLeaveButton()
{
	$('#leaveTeam').show();
}

function hideLeaveButton()
{
	$('#leaveTeam').hide();
}

function bindEvents()
{
	//when server select box changes, populate it with players currently joined to game
	$('select').on("change", function(){
		game_id = $('select').find(":selected").attr("value");
		populatePlayers();
		$('#Teams').show();
	});

	//when player clicks on team 1, join player to team 1
	$('#Team1').on('click', function(){
		joinTeam1();
	});

	//when player clicks on team 1, join player to team 1
	$('#Team2').on('click', function(){
		joinTeam2();
	});

	$('#leaveTeam').on('click', function(){
		leaveTeam();
	});
}
<|endoftext|>


<commit_before>BN.addDecl('tinymce-block').onSetMod({
    js: function(){
        tinymce.init({
            selector: "textarea",
            plugins: [
                "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker",
                "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
                "table contextmenu directionality emoticons template textcolor paste fullpage textcolor"
            ],

            toolbar1: "newdocument fullpage | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect",
            toolbar2: "cut copy paste | searchreplace | bullist numlist | outdent indent blockquote | undo redo | link unlink anchor image media code | inserttime preview | forecolor backcolor",
            toolbar3: "table | hr removeformat | subscript superscript | charmap emoticons | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking template pagebreak restoredraft",
            height: 450,

            menubar: false,
            toolbar_items_size: 'small',

            style_formats: [
                {title: 'Bold text', inline: 'b'},
                {title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
                {title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
                {title: 'Example 1', inline: 'span', classes: 'example1'},
                {title: 'Example 2', inline: 'span', classes: 'example2'},
                {title: 'Table styles'},
                {title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}
            ],

            templates: [
                {title: 'Test template 1', content: 'Test 1'},
                {title: 'Test template 2', content: 'Test 2'}
            ],
            init_instance_callback: function(){
                if(article){
                    setinfo(article._res[0]);
                }
                else console.log("it's empty");
            }
        });
        var NewsID = parseInt(this.elemParams('form').id);
        if(NewsID) var article = this._downloadArticle(NewsID);//if we are editing - get info from api
        var setinfo = this._setInfo; //setinfo and article variables are necessary cause tinymce.init() has different context,
                                     // and because of this this._title etc, are not reachable from initi
        this._title = this.findElem('input', 'title', 'true');
        this._checkbox = this.findElem('input', 'checkbox', 'true');
        this._category = this.findElem('select');
        this._btn = this.findElem('submitbutton');
        this._btn.on('click', this._btnClick.bind(this));
    }
}).instanceProp({
        _btnClick: function(){
            var article = {
                title: this._title[0].value,
                content: tinyMCE.activeEditor.getContent({format : 'raw'}),
                category: this._category[0].value,
                isbreaking: this._checkbox[0].checked ? 1 : 0,
                date: new Date()
            };

            var options = {
                body: JSON.stringify(article)
            }
            BN('pressa-api').post('192.168.174.130:8333', options).then(function(data){
                console.log(data);
            });
        },
        _downloadArticle: function(nid) {
            return BN('pressa-api').get(nid).then(function(data){
                return data;
            });
        },
        _setInfo: function(articleObj){
            tinyMCE.activeEditor.setContent(articleObj.content);
            this._category[0].value = articleObj.category;

        }
    }).blockTemplate(function(ctx){
        ctx.js(true);
        var nid = ctx.json().nid;
        ctx.content([
            {elem: 'label', for_atr: 'title', content: 'Назва статті'},
            {elem: 'input', type: 'text', name: 'title', mods: {title: true}},//mod is used to identify particular input among other inputs
            {elem: 'label', content: 'Чи э дана новина важливою?'},
            {elem: 'input', type: 'checkbox', name: 'isbreaking', value: 'checkb1', mods: { checkbox: true}},
            {elem: 'label', content: 'Оберіть категорію'},
            {elem: 'select'},
            {
                elem: 'tinymcesource',
                tag: 'script',
                attrs: {
                    type: 'text/javascript',
                    src: '../../src/tinymce/js/tinymce/tinymce.min.js'
                }
            },
            {
                elem: 'form',
                tag: 'form',
                attrs: {
                    method: 'post'
                },
                js: {id: nid},
                content: {
                    elem: 'textarea',
                    tag: 'textarea'
                }
            },
            {elem: 'submitbutton', tag: 'button', content: 'Додати новину'}
        ]);
    }).elemTemplate({
        input: function(ctx){
            var params = ctx.json();
            ctx.tag('input');
            ctx.attr('name', params.name);
            ctx.attr('type', params.type);
            ctx.attr('id', params.name);
            if(params.value) ctx.param('value', params.value);
        },
        label: function(ctx){
            ctx.tag('label');
            var params = ctx.json();
            if (params.title) ctx.attr('for', params.for_atr);
        },
        select: function(ctx){
            ctx.tag('select');
            ctx.content([
                {
                    elem: 'option',
                    tag: 'option',
                    attrs: {
                        value: 'studentslife'
                    },
                    content: 'Students life'
                },
                {
                    elem: 'option',
                    tag: 'option',
                    attrs: {
                        value: 'news'
                    },
                    content: 'News'
                },
                {
                    elem: 'option',
                    tag: 'option',
                    attrs: {
                        value: 'conferences'
                    },
                    content: 'Conferences'
                }
            ]);
        }
    });<commit_msg>editing existing articles added<commit_after>BN.addDecl('tinymce-block').onSetMod({
    js: function(){
        tinymce.init({
            selector: "textarea",
            plugins: [
                "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker",
                "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
                "table contextmenu directionality emoticons template textcolor paste fullpage textcolor"
            ],

            toolbar1: "newdocument fullpage | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect",
            toolbar2: "cut copy paste | searchreplace | bullist numlist | outdent indent blockquote | undo redo | link unlink anchor image media code | inserttime preview | forecolor backcolor",
            toolbar3: "table | hr removeformat | subscript superscript | charmap emoticons | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking template pagebreak restoredraft",
            height: 450,

            menubar: false,
            toolbar_items_size: 'small',

            style_formats: [
                {title: 'Bold text', inline: 'b'},
                {title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
                {title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
                {title: 'Example 1', inline: 'span', classes: 'example1'},
                {title: 'Example 2', inline: 'span', classes: 'example2'},
                {title: 'Table styles'},
                {title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}
            ],

            templates: [
                {title: 'Test template 1', content: 'Test 1'},
                {title: 'Test template 2', content: 'Test 2'}
            ],
            init_instance_callback: function(){
                if(article){
                    setinfo(article._res[0]);
                }
                else console.log("it's empty");
            }
        });
        var NewsID = parseInt(this.elemParams('form').id);
        if(NewsID) var article = this._downloadArticle(NewsID);//if we are editing - get info from api
        var setinfo = this._setInfo.bind(this); //setinfo and article variables are necessary cause tinymce.init() has different context,
                                     // and because of this this._title etc, are not reachable from initi
        this._title = this.findElem('input', 'title', 'true');
        this._checkbox = this.findElem('input', 'checkbox', 'true');
        this._category = this.findElem('select');
        this._btn = this.findElem('submitbutton');
        this._btn.on('click', this._btnClick.bind(this));
    }
}).instanceProp({
        _btnClick: function(){
            var article = {
                title: this._title[0].value,
                content: tinyMCE.activeEditor.getContent({format : 'raw'}),
                category: this._category[0].value,
                isbreaking: this._checkbox[0].checked ? 1 : 0,
                date: new Date()
            };

            var options = {
                body: JSON.stringify(article)
            }
            BN('pressa-api').post('192.168.174.130:8333', options).then(function(data){
                console.log(data);
            });
        },
        _downloadArticle: function(nid) {
            return BN('pressa-api').get(nid).then(function(data){
                return data;
            });
        },
        _setInfo: function(articleObj){
            tinyMCE.activeEditor.setContent(articleObj.content);
            this._category[0].value = articleObj.category;
            articleObj.isbreaking == 1 ? this._checkbox[0].checked = true : this._checkbox[0].checked = false;
            this._title[0].value = articleObj.title;

        }
    }).blockTemplate(function(ctx){
        ctx.js(true);
        var nid = ctx.json().nid;
        ctx.content([
            {elem: 'label', for_atr: 'title', content: 'Назва статті'},
            {elem: 'input', type: 'text', name: 'title', mods: {title: true}},//mod is used to identify particular input among other inputs
            {elem: 'label', content: 'Чи э дана новина важливою?'},
            {elem: 'input', type: 'checkbox', name: 'isbreaking', value: 'checkb1', mods: { checkbox: true}},
            {elem: 'label', content: 'Оберіть категорію'},
            {elem: 'select'},
            {
                elem: 'tinymcesource',
                tag: 'script',
                attrs: {
                    type: 'text/javascript',
                    src: '../../src/tinymce/js/tinymce/tinymce.min.js'
                }
            },
            {
                elem: 'form',
                tag: 'form',
                attrs: {
                    method: 'post'
                },
                js: {id: nid},
                content: {
                    elem: 'textarea',
                    tag: 'textarea'
                }
            },
            {elem: 'submitbutton', tag: 'button', content: 'Додати новину'}
        ]);
    }).elemTemplate({
        input: function(ctx){
            var params = ctx.json();
            ctx.tag('input');
            ctx.attr('name', params.name);
            ctx.attr('type', params.type);
            ctx.attr('id', params.name);
            if(params.value) ctx.param('value', params.value);
        },
        label: function(ctx){
            ctx.tag('label');
            var params = ctx.json();
            if (params.title) ctx.attr('for', params.for_atr);
        },
        select: function(ctx){
            ctx.tag('select');
            ctx.content([
                {
                    elem: 'option',
                    tag: 'option',
                    attrs: {
                        value: 'studentslife'
                    },
                    content: 'Students life'
                },
                {
                    elem: 'option',
                    tag: 'option',
                    attrs: {
                        value: 'news'
                    },
                    content: 'News'
                },
                {
                    elem: 'option',
                    tag: 'option',
                    attrs: {
                        value: 'conferences'
                    },
                    content: 'Conferences'
                }
            ]);
        }
    });<|endoftext|>


<commit_before>Ui.Linkable.extend('Ui.LinkButton',
/** @lends Ui.LinkButton# */
{
	graphic: undefined,

    /**
     * @constructs
	 * @class A LinkButton is a button that is an hyper link
     * @extends Ui.Linkable
     * @param {String} [config.text] Button's text
     * @param {String} [config.icon] Icon name
     * @param {String} [config.orientation] 'vertical' or 'horizontal'
	 * @param {mixed} [config] see {@link Ui.Linkable} constructor for more options.
     */
	constructor: function(config) {
		this.graphic = new Ui.ButtonGraphic();
		this.setContent(this.graphic);

		this.connect(this, 'down', function() { this.graphic.setIsDown(true); });
		this.connect(this, 'up', function() { this.graphic.setIsDown(false); });
		this.connect(this, 'focus', function() { this.graphic.setColor(this.getStyleProperty('focusColor')); });
		this.connect(this, 'blur', function() { this.graphic.setColor(this.getStyleProperty('color')); });
	},

	getText: function() {
		return this.graphic.getText();
	},

	setText: function(text) {
		this.graphic.setText(text);
	},

	getIcon: function() {
		return this.graphic.getIcon();
	},

	setIcon: function(icon) {
		this.graphic.setIcon(icon);
	},

    /** @return {String} Orientation */
	getOrientation: function() {
		return this.graphic.getOrientation();
	},

    /** @param {String} orientation can be 'vertical' or 'horizontal' */
	setOrientation: function(orientation) {
		this.graphic.setOrientation(orientation);
	}
},
/** @lends Ui.LinkButton# */
{
	onStyleChange: function() {
		this.graphic.setRadius(this.getStyleProperty('radius'));
		this.graphic.setSpacing(this.getStyleProperty('spacing'));
		if(this.getHasFocus())
			this.graphic.setColor(this.getStyleProperty('focusColor'));
		else
			this.graphic.setColor(this.getStyleProperty('color'));
	},

	onDisable: function() {
		Ui.Button.base.onDisable.call(this);
		this.graphic.setIsEnable(false);
	},

	onEnable: function() {
		Ui.Button.base.onEnable.call(this);
		this.graphic.setIsEnable(true);
	}
},
/** @lends Ui.LinkButton */
{
	style: {
		color: '#4fa8ff',
		focusColor: '#f6caa2',
		radius: 4,
		spacing: 3
	}
});

<commit_msg>add iconSize style for Ui.LinkButton<commit_after>Ui.Linkable.extend('Ui.LinkButton',
/** @lends Ui.LinkButton# */
{
	graphic: undefined,

    /**
     * @constructs
	 * @class A LinkButton is a button that is an hyper link
     * @extends Ui.Linkable
     * @param {String} [config.text] Button's text
     * @param {String} [config.icon] Icon name
     * @param {String} [config.orientation] 'vertical' or 'horizontal'
	 * @param {mixed} [config] see {@link Ui.Linkable} constructor for more options.
     */
	constructor: function(config) {
		this.graphic = new Ui.ButtonGraphic();
		this.setContent(this.graphic);

		this.connect(this, 'down', function() { this.graphic.setIsDown(true); });
		this.connect(this, 'up', function() { this.graphic.setIsDown(false); });
		this.connect(this, 'focus', function() { this.graphic.setColor(this.getStyleProperty('focusColor')); });
		this.connect(this, 'blur', function() { this.graphic.setColor(this.getStyleProperty('color')); });
	},

	getText: function() {
		return this.graphic.getText();
	},

	setText: function(text) {
		this.graphic.setText(text);
	},

	getIcon: function() {
		return this.graphic.getIcon();
	},

	setIcon: function(icon) {
		this.graphic.setIcon(icon);
	},

    /** @return {String} Orientation */
	getOrientation: function() {
		return this.graphic.getOrientation();
	},

    /** @param {String} orientation can be 'vertical' or 'horizontal' */
	setOrientation: function(orientation) {
		this.graphic.setOrientation(orientation);
	}
},
/** @lends Ui.LinkButton# */
{
	onStyleChange: function() {
		this.graphic.setRadius(this.getStyleProperty('radius'));
		this.graphic.setSpacing(this.getStyleProperty('spacing'));
		this.graphic.setIconSize(this.getStyleProperty('iconSize'));
		if(this.getHasFocus())
			this.graphic.setColor(this.getStyleProperty('focusColor'));
		else
			this.graphic.setColor(this.getStyleProperty('color'));
	},

	onDisable: function() {
		Ui.Button.base.onDisable.call(this);
		this.graphic.setIsEnable(false);
	},

	onEnable: function() {
		Ui.Button.base.onEnable.call(this);
		this.graphic.setIsEnable(true);
	}
},
/** @lends Ui.LinkButton */
{
	style: {
		color: '#4fa8ff',
		focusColor: '#f6caa2',
		radius: 4,
		spacing: 3,
		iconSize: 24
	}
});

<|endoftext|>


<commit_before>module.exports = function (creep) {
    var spawn = Game.spawns.Spawn1;

    var target = creep.pos.findClosest(FIND_MY_CREEPS, {
        filter: function (creep) {
            return creep.hits < creep.hitsMax;
        }
    });

    if (target) {
        creep.moveTo(target);
        creep.heal(target);
    }

    target = creep.pos.findClosest(FIND_MY_CREEPS, {
       filter: function (creep) {
           return creep.memory.module == 'guard';
       }
    });

    if (target) {
        creep.moveTo(target);
    }
};
<commit_msg>Conflicting move commands.<commit_after>module.exports = function (creep) {
    var spawn = Game.spawns.Spawn1;

    var target = creep.pos.findClosest(FIND_MY_CREEPS, {
        filter: function (creep) {
            return creep.hits < creep.hitsMax;
        }
    });

    if (target) {
        creep.moveTo(target);
        creep.heal(target);
        return;
    }

    target = creep.pos.findClosest(FIND_MY_CREEPS, {
       filter: function (creep) {
           return creep.memory.module == 'guard';
       }
    });

    if (target) {
        creep.moveTo(target);
    }
};
<|endoftext|>