<commit_before>import React from 'react';
import {connect} from 'react-redux';
import { Link } from 'react-router';
import ConnectedLink from '../ConnectedLink';
import isEmpty from 'lodash/isEmpty';

import { Body, ReviewHeader, PrivateInfo } from '../../../../shared/SellerProfile';

import styles from './ApplicationPreview.css'; // eslint-disable-line no-unused-vars

const ApplicationPreview = ({ header, body, privateInfo, onClick }) => (

      {onClick &&

Preview your profile

Buyers will see your business information previewed below. If the information is correct, continue to the final step to submit your application or continue editing.

        <Link to="/submit">{({ href }) => (
            Save and continue
          )
        }</Link>
          <Link  to="/review">Go back and edit</Link>

}
    <ReviewHeader
      {...header}
    />

        {!onClick && privateInfo.disclosures && <PrivateInfo {...privateInfo} />}

);

const mapStateToProps = ({ application }, { documentsUrl, onClick, ...rest }) => {
    let {
      name,
      seller_type,
      summary,
      website,
      twitter,
      contact_email,
      contact_phone,
      contact_name,
      services,
      domains = {},
      case_studies,
      travel: interstate,
      linkedin,
      local_government_experience,
      state_government_experience,
      federal_government_experience,
      other_panels,
      disclosures,
      documents_url = '../documents/',
      case_study_url,
      public_profile,
      signed_agreements,
      ...body
    } = application;

    let caseStudyLink = null;
    if (typeof case_study_url !== 'undefined') {
      caseStudyLink = ({id, children}) => (<a href={`${case_study_url}${id}`}>{children});
    } else {
      caseStudyLink = ({id, children}) => (
        <ConnectedLink to={`${rest.pathname}/case-study/${id}`}>{children}</ConnectedLink>
      );
    }

    // FIXME this is a workaround, somehow python returns empty case studies as a list.
    // Either there is bad data floating around or something is turning empty objects
    // into an array.
    // Body expects object not array.
    if (Array.isArray(case_studies)) {
      if (isEmpty(case_studies)) {
        case_studies = {};
      } else {
        // Convert case study array to object format.
        case_studies = case_studies.reduce((cso, study) => {
          cso[study.id] = study;
          return cso;
        }, {});
      }
    }

    let { assessed, unassessed } = domains;
    // If unassessed is falsy, assume we are on preview
    // Where we just want to show the current selected
    // services. Filter out falsy services and convert
    // to an Array to keep type consistent
    if (!unassessed) {
      unassessed = Object
        .keys(services)
        .filter(key => services[key]);
    }

    return {
        header: {
          name,
          seller_type,
          summary,
          website,
          twitter,
          contact_email,
          contact_phone,
          contact_name,
          linkedin,
          public_profile
        },
        body: {
          assessed,
          unassessed,
          case_studies,
          interstate,
          CaseStudyLink: caseStudyLink,
          documentsUrl: documents_url,
          public_profile,
          ...body
        },
        privateInfo: (disclosures ? {
            case_studies,
            local_government_experience,
            state_government_experience,
            federal_government_experience,
            other_panels,
            disclosures,
            signed_agreements
        } : {}),
        onClick
    }
}

export {
    mapStateToProps
}

export default connect(mapStateToProps)(ApplicationPreview);<commit_msg>Add default for services (#195)<commit_after>import React from 'react';
import {connect} from 'react-redux';
import { Link } from 'react-router';
import ConnectedLink from '../ConnectedLink';
import isEmpty from 'lodash/isEmpty';

import { Body, ReviewHeader, PrivateInfo } from '../../../../shared/SellerProfile';

import styles from './ApplicationPreview.css'; // eslint-disable-line no-unused-vars

const ApplicationPreview = ({ header, body, privateInfo, onClick }) => (

      {onClick &&

Preview your profile

Buyers will see your business information previewed below. If the information is correct, continue to the final step to submit your application or continue editing.

        <Link to="/submit">{({ href }) => (
            Save and continue
          )
        }</Link>
          <Link  to="/review">Go back and edit</Link>

}
    <ReviewHeader
      {...header}
    />

        {!onClick && privateInfo.disclosures && <PrivateInfo {...privateInfo} />}

);

const mapStateToProps = ({ application }, { documentsUrl, onClick, ...rest }) => {
    let {
      name,
      seller_type,
      summary,
      website,
      twitter,
      contact_email,
      contact_phone,
      contact_name,
      services = {},
      domains = {},
      case_studies,
      travel: interstate,
      linkedin,
      local_government_experience,
      state_government_experience,
      federal_government_experience,
      other_panels,
      disclosures,
      documents_url = '../documents/',
      case_study_url,
      public_profile,
      signed_agreements,
      ...body
    } = application;

    let caseStudyLink = null;
    if (typeof case_study_url !== 'undefined') {
      caseStudyLink = ({id, children}) => (<a href={`${case_study_url}${id}`}>{children});
    } else {
      caseStudyLink = ({id, children}) => (
        <ConnectedLink to={`${rest.pathname}/case-study/${id}`}>{children}</ConnectedLink>
      );
    }

    // FIXME this is a workaround, somehow python returns empty case studies as a list.
    // Either there is bad data floating around or something is turning empty objects
    // into an array.
    // Body expects object not array.
    if (Array.isArray(case_studies)) {
      if (isEmpty(case_studies)) {
        case_studies = {};
      } else {
        // Convert case study array to object format.
        case_studies = case_studies.reduce((cso, study) => {
          cso[study.id] = study;
          return cso;
        }, {});
      }
    }

    let { assessed, unassessed } = domains;
    // If unassessed is falsy, assume we are on preview
    // Where we just want to show the current selected
    // services. Filter out falsy services and convert
    // to an Array to keep type consistent
    if (!unassessed) {
      unassessed = Object
        .keys(services)
        .filter(key => services[key]);
    }

    return {
        header: {
          name,
          seller_type,
          summary,
          website,
          twitter,
          contact_email,
          contact_phone,
          contact_name,
          linkedin,
          public_profile
        },
        body: {
          assessed,
          unassessed,
          case_studies,
          interstate,
          CaseStudyLink: caseStudyLink,
          documentsUrl: documents_url,
          public_profile,
          ...body
        },
        privateInfo: (disclosures ? {
            case_studies,
            local_government_experience,
            state_government_experience,
            federal_government_experience,
            other_panels,
            disclosures,
            signed_agreements
        } : {}),
        onClick
    }
}

export {
    mapStateToProps
}

export default connect(mapStateToProps)(ApplicationPreview);<|endoftext|>


<commit_before>/*jslint indent: 2, plusplus: true*/
"use strict";

module.exports = function (options) {
  this.checkAnswer = function (playlistItem, answer) {
    return playlistItem &&
      answer.toLowerCase() === playlistItem.title.toLowerCase();
  };
};

<commit_msg>Improves answer_checker a bit<commit_after>/*jslint indent: 2, plusplus: true*/
"use strict";

module.exports = function (options) {
  var
    nonAlphanum = /[^a-zA-Z0-9 ]/g,
    mulSpace = /  +/g,
    trimSpace = /^ | $/g;

  this.normalize = function (str) {
    str = str.toLowerCase();
    str = str.replace(nonAlphanum, '');
    str = str.replace(mulSpace, ' ');
    str = str.replace(trimSpace, '');
    return str;
  }

  this.checkAnswer = function (playlistItem, answer) {
    if (playlistItem === undefined) return false;

    return normalize(answer) === normalize(playlistItem.title);
  };
};

<|endoftext|>


<commit_before>angular.module('Aggie')

.controller('SourcesIndexController', [
  '$scope',
  '$rootScope',
  'FlashService',
  'sources',
  'Source',
  'Tags',
  function($scope, $rootScope, flash, sources, Source, Tags) {
    $scope.sources = sources;

    $scope.saveSource = function(source) {
      Source.save({ id: source._id }, source, function() {
      }, function() {
        flash.setAlertNow('source.save.error');
        source.enabled = !source.enabled;
      });
    };

    $scope.target = function(source) {
      return source.media == 'twitter' || source.media == 'smsgh' || source.media == 'whatsapp' || source.media == 'crowdtangle' ? source.keywords : source.url;
    };

    $scope.sourceClass = function(source) {
      var mediaOptions = ['twitter', 'crowdtangle'];

      if (mediaOptions.indexOf(source.media) !== -1) {
        return source.media + '-source';
      } else {
        return 'unknown-source';
      }
    };

    $scope.viewSource = function(event, source) {
      $rootScope.$state.go('source', { id: source._id });
    };

    $scope.tagsToString = Tags.tagsToString;
  }
]);
<commit_msg>Reintroduced previous media options for future use<commit_after>angular.module('Aggie')

.controller('SourcesIndexController', [
  '$scope',
  '$rootScope',
  'FlashService',
  'sources',
  'Source',
  'Tags',
  function($scope, $rootScope, flash, sources, Source, Tags) {
    $scope.sources = sources;

    $scope.saveSource = function(source) {
      Source.save({ id: source._id }, source, function() {
      }, function() {
        flash.setAlertNow('source.save.error');
        source.enabled = !source.enabled;
      });
    };

    $scope.target = function(source) {
      return source.media == 'twitter' || source.media == 'smsgh' || source.media == 'whatsapp' || source.media == 'crowdtangle' ? source.keywords : source.url;
    };

    $scope.sourceClass = function(source) {

      // keeping the previous mediaoptions incase any of them makes a comeback
      //var mediaOptions = ['twitter', 'facebook', 'rss', 'elmo', 'smsgh', 'whatsapp'];

      var mediaOptions = ['twitter', 'crowdtangle'];

      if (mediaOptions.indexOf(source.media) !== -1) {
        return source.media + '-source';
      } else {
        return 'unknown-source';
      }
    };

    $scope.viewSource = function(event, source) {
      $rootScope.$state.go('source', { id: source._id });
    };

    $scope.tagsToString = Tags.tagsToString;
  }
]);
<|endoftext|>


<commit_before>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})
<commit_msg>Updated the ioninc sample<commit_after>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }

    console.log('Started BMSpush initialize');
    BMSClient.initialize("Push service region");
      var appGUID = "Your Push service AppGUID";
      var clientSecret = "Your Push service clientSecret";

          BMSPush.initialize(appGUID,clientSecret);
        BMSPush.registerNotificationsCallback(function(notification) {
          console.log('registering NotificationsCallback: '+JSON.parse(notification));
          //alert(JSON.parse(notification) + ' register notification');
        });
        var settings = {};

        BMSPush.registerDevice(settings,
          function(success){
            console.log('registering Device Success: '+JSON.parse(success));

            //Get a list of available tags to which the device can subscribe
            BMSPush.retrieveAvailableTags(function(tags) {
              console.log("retrieveAvailableTags : " + tags);
                BMSPush.subscribe(tags, null, null);
            }, null);

            //Get a list of available tags to which the device is subscribed.
            BMSPush.retrieveSubscriptions(function(tags) {
              console.log("retrieveSubscriptions : " + tags);
            }, null);
        },
         function(failure){
           console.log('registering Device Failed: '+JSON.parse(failure));
        });
  });
})
<|endoftext|>


<commit_before>import React, {View} from 'react-native'
import R from 'ramda'
import DebugSettings from '../Config/DebugSettings'
let globalExamplesRegistry = []

export const addExample = (renderExampleFunc) => { if (DebugSettings.includeExamples) globalExamplesRegistry.push(renderExampleFunc) }

const renderExample = (example) => example.call()

export const renderExamples = () => (
  <View>
    {R.map(renderExample, globalExamplesRegistry)}
  </View>
)

// Default for readability
export default {
  render: renderExamples,
  add: addExample
}
<commit_msg>simplify render all<commit_after>import R from 'ramda'
import DebugSettings from '../Config/DebugSettings'
let globalExamplesRegistry = []

export const addExample = (renderExampleFunc) => { if (DebugSettings.includeExamples) globalExamplesRegistry.push(renderExampleFunc) }

const renderExample = (example) => example.call()

export const renderExamples = () => R.map(renderExample, globalExamplesRegistry)

// Default for readability
export default {
  render: renderExamples,
  add: addExample
}
<|endoftext|>


<commit_before>define(['bunit', '../src/turtle'], function(bunit, turtle) {
    var suite = bunit.suite;
    var assert = bunit.assert;
    var turtle = turtle.turtle;

    var context = function() {
        return {
            center: function() {
                this.atCenter = true;
            },
            translate: function(x, y) {
                this.translation = y;
            },
            rotate: function(degrees) {
                if(degrees == 180) {
                    this.pointsNorth = true;
                }
            },
            line: function() {},
            clear: function() {},
            atCenter: false,
            pointsNorth: false,
            translation: 0
        };
    };

    suite('Turtle initializers', {
        empty: function() {
            // XXX: might want to raise an exception instead
            assert(turtle()).equals(null);
        },
        context: function() {
            assert(turtle(context())).is('object');
        },
        invalidContext: function() {
            // XXX: might want to raise an exception instead
            assert(turtle({})).equals(null);
        },
        atCenter: function() {
            var ctx = context();
            var joe = turtle(ctx);

            assert(ctx.atCenter).equals(true);
            assert(ctx.pointsNorth).equals(true);
            assert(joe.penState()).equals('down');
        }
    });

    suite('Turtle pen', {
        _: {
            joe: turtle(context())
        },
        setPenDown: function() {
            this.joe.penDown();

            assert(this.joe.penState()).equals('down');
        },
        setPenUp: function() {
            this.joe.penUp();

            assert(this.joe.penState()).equals('up');
        }
    });

    var setUpTurtle = function() {
        var ctx = context();
        var joe = turtle(ctx);

        return [ctx, joe];
    };

    suite('Turtle move', {
        setUp: setUpTurtle,
        forward: function(ctx, joe) {
            joe.forward(100);

            assert(ctx.translation).equals(100);
        },
        backward: function(ctx, joe) {
            joe.backward(100);

            assert(ctx.translation).equals(-100);
        }
    });

    suite('Turtle rotate', {
        setUp: setUpTurtle,
        left: function() {
            //this.joe.rotate(-90);
        },
        right: function() {
            //this.joe.rotate(90);
        }
    });

    suite('Turtle recording', {

    });

    suite('Turtle reset', {

    });

    suite('Turtle repeat', {

    });

    // TODO: test the API commands and recording
});
<commit_msg>Test turtle rotation<commit_after>define(['bunit', '../src/turtle'], function(bunit, turtle) {
    var suite = bunit.suite;
    var assert = bunit.assert;
    var turtle = turtle.turtle;

    var context = function() {
        return {
            center: function() {
                this.atCenter = true;
            },
            translate: function(x, y) {
                this.translation = y;
            },
            rotate: function(degrees) {
                this.rotation = degrees;

                if(degrees == 180) {
                    this.pointsNorth = true;
                }
            },
            line: function() {},
            clear: function() {},
            atCenter: false,
            pointsNorth: false,
            translation: 0,
            rotation: 0
        };
    };

    suite('Turtle initializers', {
        empty: function() {
            // XXX: might want to raise an exception instead
            assert(turtle()).equals(null);
        },
        context: function() {
            assert(turtle(context())).is('object');
        },
        invalidContext: function() {
            // XXX: might want to raise an exception instead
            assert(turtle({})).equals(null);
        },
        atCenter: function() {
            var ctx = context();
            var joe = turtle(ctx);

            assert(ctx.atCenter).equals(true);
            assert(ctx.pointsNorth).equals(true);
            assert(joe.penState()).equals('down');
        }
    });

    suite('Turtle pen', {
        _: {
            joe: turtle(context())
        },
        setPenDown: function() {
            this.joe.penDown();

            assert(this.joe.penState()).equals('down');
        },
        setPenUp: function() {
            this.joe.penUp();

            assert(this.joe.penState()).equals('up');
        }
    });

    var setUpTurtle = function() {
        var ctx = context();
        var joe = turtle(ctx);

        return [ctx, joe];
    };

    suite('Turtle move', {
        setUp: setUpTurtle,
        forward: function(ctx, joe) {
            joe.forward(100);

            assert(ctx.translation).equals(100);
        },
        backward: function(ctx, joe) {
            joe.backward(100);

            assert(ctx.translation).equals(-100);
        }
    });

    suite('Turtle rotate', {
        setUp: setUpTurtle,
        left: function(ctx, joe) {
            joe.rotate(-90);

            assert(ctx.rotation).equals(-90);
        },
        right: function(ctx, joe) {
            joe.rotate(90);

            assert(ctx.rotation).equals(90);
        }
    });

    suite('Turtle recording', {

    });

    suite('Turtle reset', {

    });

    suite('Turtle repeat', {

    });

    // TODO: test the API commands and recording
});
<|endoftext|>


<commit_before>exports.shuffleTeamsArray = teamsArray => {
    let m = teamsArray.length, t, i;
    // While there remain elements to shuffle…
    while (m) {
        // Pick a remaining element…
        i = Math.floor(Math.random() * m--);
        // Swap with the current
        t = teamsArray[m];
        teamsArray[m] = teamsArray[i];
        teamsArray[i] = t;
    }
    return teamsArray;
}

exports.incompleteTeamArray = teamArray => {
    if (teamArray.length > 15) return teamArray;
    let phaseMatch = new Array(16);
    for (let i = 0; i < phaseMatch.length; i += 2) {
        phaseMatch[i] = teamArray[0];
        teamArray.shift();
    }
    if (teamArray.length) {
        for (let i = 0; i < teamArray.length; i++) {
            phaseMatch[i + 1] = teamArray[i];
        }
    }
    return phaseMatch;
}
<commit_msg>fix de shuffle de sorteo que mostraba menos teams<commit_after>exports.shuffleTeamsArray = teamsArray => {
    let m = teamsArray.length, t, i;
    // While there remain elements to shuffle…
    while (m) {
        // Pick a remaining element…
        i = Math.floor(Math.random() * m--);
        // Swap with the current
        t = teamsArray[m];
        teamsArray[m] = teamsArray[i];
        teamsArray[i] = t;
    }
    return teamsArray;
}

exports.incompleteTeamArray = teamArray => {
    if (teamArray.length > 15) return teamArray;
    let phaseMatch = new Array(16);
    for (let i = 0; i < phaseMatch.length; i += 2) {
        phaseMatch[i] = teamArray[0];
        teamArray.shift();
    }
    if (teamArray.length) {
        let i = 1;
        teamArray.forEach(team => {
            phaseMatch[i] = team;
            i += 2;
        })
    }
    return phaseMatch;
}
<|endoftext|>


<commit_before>import React from 'react';
import { Formik, Field, Form } from 'formik';
import * as Yup from 'yup';

const SignUp = () => (

Sign Up

    <Formik
      initialValues={{
        email: '',
        color: '',
        animal: '',
        website: '',
      }}
      validationSchema={Yup.object().shape({
        email: Yup.string()
          .email('Invalid email address')
          .required('Required'),
        color: Yup.string().required('Required'),
        website: Yup.string()
          .url('Invalid URL')
          .required('Required'),
        animal: Yup.string().required('Required'),
      })}
      onSubmit={values => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
        }, 500);
      }}
      render={({ resetForm }) => (
        <Form>
          <TextInput name="email" label="Email" placeholder="jane@acme.com" />
          <Select name="color" label="Favorite Color">
            <option value="">Select a Color</option>
            <option value="red">Red</option>
            <option value="green">Green</option>
            <option value="blue">Blue</option>
          </Select>

          <Fieldset
            name="website"
            type="url"
            label="Website"
            placeholder="https://example.com"
          />

          <Fieldset name="animal" component="select" label="Favorite Animal">
            <option value="">Select an animal</option>
            <option value="tiger">Tiger</option>
            <option value="bear">Bear</option>
            <option value="shark">Shark</option>
          </Fieldset>

          <button type="button" className="reset" onClick={resetForm}>
            Reset
          </button>

          <button type="submit">Submit</button>
        </Form>
      )}
    />

);

const TextInput = ({ name, label, ...rest }) => (
  <Field
    name={name}
    render={({ field, form }) => {
      const error = form.touched[name] && form.errors[name];
      const classes = error ? 'fieldset fieldset--error' : 'fieldset';
      return (

          {label}
          <input {...field} {...rest} />
          {form.errors[name] &&
            form.touched[name] && (

{form.errors[name]}

            )}

      );
    }}
  />
);

// This is identical to TextInput, except we will render a <select> instead.
// If this code seems smelly, it's because it is. Keep reading...
const Select = ({ name, label, ...rest }) => (
  <Field
    name={name}
    render={({ field, form }) => {
      const error = form.touched[name] && form.errors[name];
      const classes = error ? 'fieldset fieldset--error' : 'fieldset';
      return (

          {label}
          <select {...field} {...rest} />
          {form.errors[name] &&
            form.touched[name] && (

{form.errors[name]}

            )}

      );
    }}
  />
);

// <TextInput> and <Select> are repetitive. At this point, we
// have some options. We could abstract away the label and error stuff into
// separate components and then reuse those. Or, better yet, you could wrap
// <Field>'s render and component props to make a new <Fieldset/> component
// that will add the label and display our errors while keeping almost the
// same API as <Field />
const Fieldset = ({ component = 'input', render, name, label, ...rest }) => (
  <Field
    name={name}
    render={({ field, form }) => {
      const error = form.touched[name] && form.errors[name];
      const classes = error ? 'fieldset fieldset--error' : 'fieldset';

      return (

          {label}
          {render
            ? render({ field, form, ...rest }) // render prop inception
            : component
              ? React.createElement(component, {
                  ...field,
                  ...rest,
                  invalid: !!error,
                })
              : null}
          {error &&
{error}
}

      );
    }}
  />
);

export default SignUp;
<commit_msg>Fix example<commit_after>import React from 'react';
import { Formik, Field, Form } from 'formik';
import * as Yup from 'yup';

const SignUp = () => (

Sign Up

    <Formik
      initialValues={{
        email: '',
        color: '',
        animal: '',
        website: '',
      }}
      validationSchema={Yup.object().shape({
        email: Yup.string()
          .email('Invalid email address')
          .required('Required'),
        color: Yup.string().required('Required'),
        website: Yup.string()
          .url('Invalid URL')
          .required('Required'),
        animal: Yup.string().required('Required'),
      })}
      onSubmit={values => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
        }, 500);
      }}
      render={({ resetForm }) => (
        <Form>
          <TextInput name="email" label="Email" placeholder="jane@acme.com" />
          <Select name="color" label="Favorite Color">
            <option value="">Select a Color</option>
            <option value="red">Red</option>
            <option value="green">Green</option>
            <option value="blue">Blue</option>
          </Select>

          <Fieldset
            name="website"
            type="url"
            label="Website"
            placeholder="https://example.com"
          />

          <Fieldset name="animal" component="select" label="Favorite Animal">
            <option value="">Select an animal</option>
            <option value="tiger">Tiger</option>
            <option value="bear">Bear</option>
            <option value="shark">Shark</option>
          </Fieldset>

          <button type="button" className="reset" onClick={resetForm}>
            Reset
          </button>

          <button type="submit">Submit</button>
        </Form>
      )}
    />

);

const TextInput = ({ name, label, ...rest }) => (
  <Field
    name={name}
    render={({ field, form }) => {
      const error = form.touched[name] && form.errors[name];
      const classes = error ? 'fieldset fieldset--error' : 'fieldset';
      return (

          {label}
          <input {...field} {...rest} />
          {form.errors[name] &&
            form.touched[name] && (

{form.errors[name]}

            )}

      );
    }}
  />
);

// This is identical to TextInput, except we will render a <select> instead.
// If this code seems smelly, it's because it is. Keep reading...
const Select = ({ name, label, ...rest }) => (
  <Field
    name={name}
    render={({ field, form }) => {
      const error = form.touched[name] && form.errors[name];
      const classes = error ? 'fieldset fieldset--error' : 'fieldset';
      return (

          {label}
          <select {...field} {...rest} />
          {form.errors[name] &&
            form.touched[name] && (

{form.errors[name]}

            )}

      );
    }}
  />
);

// <TextInput> and <Select> are repetitive. At this point, we
// have some options. We could abstract away the label and error stuff into
// separate components and then reuse those. Or, better yet, you could wrap
// <Field>'s render and component props to make a new <Fieldset/> component
// that will add the label and display our errors while keeping almost the
// same API as <Field />
const Fieldset = ({ component = 'input', render, name, label, ...rest }) => (
  <Field
    name={name}
    render={({ field, form }) => {
      const error = form.touched[name] && form.errors[name];
      const classes = error ? 'fieldset fieldset--error' : 'fieldset';

      return (

          {label}
          {render
            ? render({ field, form, ...rest }) // render prop inception
            : component
              ? React.createElement(component, {
                  ...field,
                  ...rest,
                  invalid: (!!error).toString(),
                })
              : null}
          {error &&
{error}
}

      );
    }}
  />
);

export default SignUp;
<|endoftext|>


<commit_before>
var fs = require('fs');

var selectorNotFoundPath = 'capture/resources/selectorNotFound_noun_164558_cc.png'
var hiddenSelectorPath = 'capture/resources/hiddenSelector_noun_63405.png'
var genConfigPath = 'capture/config.json'

var configJSON = fs.read(genConfigPath);
var config = JSON.parse(configJSON);
if (!config.paths) {
  config.paths = {};
}

var bitmaps_reference = config.paths.bitmaps_reference || 'bitmaps_reference';
var bitmaps_test = config.paths.bitmaps_test || 'bitmaps_test';
var casper_scripts = config.paths.casper_scripts || null;
var compareConfigFileName = config.paths.compare_data || 'compare/config.json';
var viewports = config.viewports;
var scenarios = config.scenarios||config.grabConfigs;

var compareConfig = {testPairs:[]};

var casper = require("casper").create({
  // clientScripts: ["jquery.js"] // uncomment to add jQuery if you need that.
  // TODO: if (config.debug) { add prop debug true }
});

if (config.debug) {
  console.log('Debug is enabled!');

  casper.on("page.error", function(msg, trace) {
      this.echo("Remote Error >    " + msg, "error");
      this.echo("file:     " + trace[0].file, "WARNING");
      this.echo("line:     " + trace[0].line, "WARNING");
      this.echo("function: " + trace[0]["function"], "WARNING");
  });
}

casper.on('remote.message', function(message) {
  this.echo('remote console > ' + message);
});

casper.on('resource.received', function(resource) {
  var status = resource.status;
  if(status >= 400) {
    casper.log('remote error > ' + resource.url + ' failed to load (' + status + ')', 'error');
  }
});

function capturePageSelectors(url,scenarios,viewports,bitmaps_reference,bitmaps_test,isReference){

  var
    screenshotNow = new Date(),
    screenshotDateTime = screenshotNow.getFullYear() + pad(screenshotNow.getMonth() + 1) + pad(screenshotNow.getDate()) + '-' + pad(screenshotNow.getHours()) + pad(screenshotNow.getMinutes()) + pad(screenshotNow.getSeconds());

  var consoleBuffer = '';
  var scriptTimeout = 20000;

  casper.on('remote.message', function(message) {
      this.echo(message);
      consoleBuffer = consoleBuffer + '\n' + message;
  });

  casper.start();

  casper.each(scenarios,function(casper, scenario, scenario_index){

    casper.each(viewports, function(casper, vp, viewport_index) {
      this.then(function() {
        this.viewport(vp.width||vp.viewport.width, vp.height||vp.viewport.height);
      });

      var url = scenario.url;
      if (isReference && scenario.referenceUrl) {
        url = scenario.referenceUrl;
      }

      var onBeforeScript = scenario.onBeforeScript || config.onBeforeScript;
      if (onBeforeScript) {
        require(getScriptPath(onBeforeScript))(casper, scenario, vp);
      }

      this.thenOpen(url, function() {
        casper.waitFor(
          function(){ //test
            var readyEvent = scenario.readyEvent || config.readyEvent;
            if(!readyEvent) {
              return true;
            }
            var regExReadyFlag = new RegExp(readyEvent,'i');
            return consoleBuffer.search(regExReadyFlag) >= 0;
          }
          ,function(){//on done
            consoleBuffer = '';
            casper.echo('Ready event received.');
          }
          ,function(){casper.echo('ERROR: casper timeout.')} //on timeout
          ,scriptTimeout
        );
        casper.wait(scenario.delay||1);
      });

      casper.then(function() {
        this.echo('Current location is ' + url, 'info');

        if (config.debug) {
          var src = this.evaluate(function() {return document.body.outerHTML; });
          this.echo(src);
        }
      });

      // Custom casperjs scripting after ready event and delay
      casper.then(function() {
        // onReadyScript files should export a module like so:
        //
        // module.exports = function(casper, scenario, vp) {
        //   // run custom casperjs code
        // };
        //
        var onReadyScript = scenario.onReadyScript || config.onReadyScript;
        if (onReadyScript) {
          require(getScriptPath(onReadyScript))(casper, scenario, vp);
        }
      });

      this.then(function(){

        this.echo('Screenshots for ' + vp.name + ' (' + (vp.width||vp.viewport.width) + 'x' + (vp.height||vp.viewport.height) + ')', 'info');

        //HIDE SELECTORS WE WANT TO AVOID
            if ( scenario.hasOwnProperty('hideSelectors') ) {
              scenario.hideSelectors.forEach(function(o,i,a){
                casper.evaluate(function(o){
                  Array.prototype.forEach.call(document.querySelectorAll(o), function(s, j){
                    s.style.visibility='hidden';
                  });
                },o);
              });
            }

        //REMOVE UNWANTED SELECTORS FROM RENDER TREE
            if ( scenario.hasOwnProperty('removeSelectors') ) {
              scenario.removeSelectors.forEach(function(o,i,a){
                casper.evaluate(function(o){
                  Array.prototype.forEach.call(document.querySelectorAll(o), function(s, j){
                    s.style.display='none';
                  });
                },o);
              });
            }

        //CREATE SCREEN SHOTS AND TEST COMPARE CONFIGURATION (CONFIG FILE WILL BE SAVED WHEN THIS PROCESS RETURNS)
            // If no selectors are provided then set the default 'body'
            if ( !scenario.hasOwnProperty('selectors') ) {
              scenario.selectors = [ 'body' ];
            }
        scenario.selectors.forEach(function(o,i,a){
          var cleanedSelectorName = o.replace(/[^a-z0-9_\-]/gi,'');//remove anything that's not a letter or a number
          //var cleanedUrl = scenario.url.replace(/[^a-zA-Z\d]/,'');//remove anything that's not a letter or a number
          var fileName = scenario_index + '_' + i + '_' + cleanedSelectorName + '_' + viewport_index + '_' + vp.name + '.png';;

          var reference_FP  = bitmaps_reference + '/' + fileName;
          var test_FP       = bitmaps_test + '/' + screenshotDateTime + '/' + fileName;

          var filePath      = (isReference)?reference_FP:test_FP;

          if(o === "body:noclip" || o === "document") {
            casper.capture(filePath);
          } else if (casper.exists(o)) {
            if (casper.visible(o)) {
              casper.captureSelector(filePath, o);
            } else {
              var assetData = fs.read(hiddenSelectorPath, 'b');
              fs.write(filePath, assetData, 'b');
            }
          } else {
            var assetData = fs.read(selectorNotFoundPath, 'b');
            fs.write(filePath, assetData, 'b');
          }

          if (!isReference) {
            compareConfig.testPairs.push({
              reference:reference_FP,
              test:test_FP,
              selector:o,
              fileName:fileName,
              label:scenario.label,
              misMatchThreshold: scenario.misMatchThreshold || config.misMatchThreshold
            });
          }
          //casper.echo('remote capture to > '+filePath,'info');

        });//end topLevelModules.forEach

      });

    });//end casper.each viewports

  });//end casper.each scenario

}

//========================
//this query should be moved to the prior process
//`isReference` could be better passed as env parameter
var exists = fs.exists(bitmaps_reference);
var isReference = false;
if(!exists){isReference=true; console.log('CREATING NEW REFERENCE FILES')}
//========================

capturePageSelectors(
  'index.html'
  ,scenarios
  ,viewports
  ,bitmaps_reference
  ,bitmaps_test
  ,isReference
);

casper.run(function(){
  complete();
  this.exit();
});

function complete(){
  fs.touch(compareConfigFileName);
  var compareConfigFile = fs.read(compareConfigFileName);
  var compareConfigJSON = JSON.parse(compareConfigFile || '{}');
  compareConfigJSON.compareConfig = compareConfig;
  fs.write(compareConfigFileName, JSON.stringify(compareConfigJSON,null,2), 'w');
  console.log(
    'Comparison config file updated.'
    //,configData
  );
}

function pad(number) {
  var r = String(number);
  if ( r.length === 1 ) {
    r = '0' + r;
  }
  return r;
}

function getScriptPath(scriptFilePath) {
  var script_path = ensureFileSuffix(scriptFilePath, 'js');

  if (casper_scripts) {
    script_path = glueStringsWithSlash(casper_scripts, script_path);
  }

  // make sure it's there...
  if (!fs.isFile(script_path)) {
    casper.echo(script_path + ' was not found.', 'ERROR');
    return;
  }

  return shimRelativePath(script_path);
}

function ensureFileSuffix(filename, suffix) {
  var re = new RegExp('\.' + suffix + '$', '');

  return filename.replace(re, '') + '.' + suffix;
}

// merge both strings while soft-enforcing a single slash between them
function glueStringsWithSlash(stringA, stringB) {
  return stringA.replace(/\/$/, '') + '/' + stringB.replace(/^\//, '');
}

// require() calls are relative to this file `genBitmaps.js` (not CWD) -- therefore relative paths need shimmimg
function shimRelativePath(path) {
  return path.replace(/^\.\.\//, '../../../').replace(/^\.\//, '../../');
}
<commit_msg>pass flag if capture is used for reference<commit_after>
var fs = require('fs');

var selectorNotFoundPath = 'capture/resources/selectorNotFound_noun_164558_cc.png'
var hiddenSelectorPath = 'capture/resources/hiddenSelector_noun_63405.png'
var genConfigPath = 'capture/config.json'

var configJSON = fs.read(genConfigPath);
var config = JSON.parse(configJSON);
if (!config.paths) {
  config.paths = {};
}

var bitmaps_reference = config.paths.bitmaps_reference || 'bitmaps_reference';
var bitmaps_test = config.paths.bitmaps_test || 'bitmaps_test';
var casper_scripts = config.paths.casper_scripts || null;
var compareConfigFileName = config.paths.compare_data || 'compare/config.json';
var viewports = config.viewports;
var scenarios = config.scenarios||config.grabConfigs;

var compareConfig = {testPairs:[]};

var casper = require("casper").create({
  // clientScripts: ["jquery.js"] // uncomment to add jQuery if you need that.
  // TODO: if (config.debug) { add prop debug true }
});

if (config.debug) {
  console.log('Debug is enabled!');

  casper.on("page.error", function(msg, trace) {
      this.echo("Remote Error >    " + msg, "error");
      this.echo("file:     " + trace[0].file, "WARNING");
      this.echo("line:     " + trace[0].line, "WARNING");
      this.echo("function: " + trace[0]["function"], "WARNING");
  });
}

casper.on('remote.message', function(message) {
  this.echo('remote console > ' + message);
});

casper.on('resource.received', function(resource) {
  var status = resource.status;
  if(status >= 400) {
    casper.log('remote error > ' + resource.url + ' failed to load (' + status + ')', 'error');
  }
});

function capturePageSelectors(url,scenarios,viewports,bitmaps_reference,bitmaps_test,isReference){

  var
    screenshotNow = new Date(),
    screenshotDateTime = screenshotNow.getFullYear() + pad(screenshotNow.getMonth() + 1) + pad(screenshotNow.getDate()) + '-' + pad(screenshotNow.getHours()) + pad(screenshotNow.getMinutes()) + pad(screenshotNow.getSeconds());

  var consoleBuffer = '';
  var scriptTimeout = 20000;

  casper.on('remote.message', function(message) {
      this.echo(message);
      consoleBuffer = consoleBuffer + '\n' + message;
  });

  casper.start();

  casper.each(scenarios,function(casper, scenario, scenario_index){

    casper.each(viewports, function(casper, vp, viewport_index) {
      this.then(function() {
        this.viewport(vp.width||vp.viewport.width, vp.height||vp.viewport.height);
      });

      var url = scenario.url;
      if (isReference && scenario.referenceUrl) {
        url = scenario.referenceUrl;
      }

      var onBeforeScript = scenario.onBeforeScript || config.onBeforeScript;
      if (onBeforeScript) {
        require(getScriptPath(onBeforeScript))(casper, scenario, vp, isReference);
      }

      this.thenOpen(url, function() {
        casper.waitFor(
          function(){ //test
            var readyEvent = scenario.readyEvent || config.readyEvent;
            if(!readyEvent) {
              return true;
            }
            var regExReadyFlag = new RegExp(readyEvent,'i');
            return consoleBuffer.search(regExReadyFlag) >= 0;
          }
          ,function(){//on done
            consoleBuffer = '';
            casper.echo('Ready event received.');
          }
          ,function(){casper.echo('ERROR: casper timeout.')} //on timeout
          ,scriptTimeout
        );
        casper.wait(scenario.delay||1);
      });

      casper.then(function() {
        this.echo('Current location is ' + url, 'info');

        if (config.debug) {
          var src = this.evaluate(function() {return document.body.outerHTML; });
          this.echo(src);
        }
      });

      // Custom casperjs scripting after ready event and delay
      casper.then(function() {
        // onReadyScript files should export a module like so:
        //
        // module.exports = function(casper, scenario, vp) {
        //   // run custom casperjs code
        // };
        //
        var onReadyScript = scenario.onReadyScript || config.onReadyScript;
        if (onReadyScript) {
          require(getScriptPath(onReadyScript))(casper, scenario, vp, isReference);
        }
      });

      this.then(function(){

        this.echo('Screenshots for ' + vp.name + ' (' + (vp.width||vp.viewport.width) + 'x' + (vp.height||vp.viewport.height) + ')', 'info');

        //HIDE SELECTORS WE WANT TO AVOID
            if ( scenario.hasOwnProperty('hideSelectors') ) {
              scenario.hideSelectors.forEach(function(o,i,a){
                casper.evaluate(function(o){
                  Array.prototype.forEach.call(document.querySelectorAll(o), function(s, j){
                    s.style.visibility='hidden';
                  });
                },o);
              });
            }

        //REMOVE UNWANTED SELECTORS FROM RENDER TREE
            if ( scenario.hasOwnProperty('removeSelectors') ) {
              scenario.removeSelectors.forEach(function(o,i,a){
                casper.evaluate(function(o){
                  Array.prototype.forEach.call(document.querySelectorAll(o), function(s, j){
                    s.style.display='none';
                  });
                },o);
              });
            }

        //CREATE SCREEN SHOTS AND TEST COMPARE CONFIGURATION (CONFIG FILE WILL BE SAVED WHEN THIS PROCESS RETURNS)
            // If no selectors are provided then set the default 'body'
            if ( !scenario.hasOwnProperty('selectors') ) {
              scenario.selectors = [ 'body' ];
            }
        scenario.selectors.forEach(function(o,i,a){
          var cleanedSelectorName = o.replace(/[^a-z0-9_\-]/gi,'');//remove anything that's not a letter or a number
          //var cleanedUrl = scenario.url.replace(/[^a-zA-Z\d]/,'');//remove anything that's not a letter or a number
          var fileName = scenario_index + '_' + i + '_' + cleanedSelectorName + '_' + viewport_index + '_' + vp.name + '.png';;

          var reference_FP  = bitmaps_reference + '/' + fileName;
          var test_FP       = bitmaps_test + '/' + screenshotDateTime + '/' + fileName;

          var filePath      = (isReference)?reference_FP:test_FP;

          if(o === "body:noclip" || o === "document") {
            casper.capture(filePath);
          } else if (casper.exists(o)) {
            if (casper.visible(o)) {
              casper.captureSelector(filePath, o);
            } else {
              var assetData = fs.read(hiddenSelectorPath, 'b');
              fs.write(filePath, assetData, 'b');
            }
          } else {
            var assetData = fs.read(selectorNotFoundPath, 'b');
            fs.write(filePath, assetData, 'b');
          }

          if (!isReference) {
            compareConfig.testPairs.push({
              reference:reference_FP,
              test:test_FP,
              selector:o,
              fileName:fileName,
              label:scenario.label,
              misMatchThreshold: scenario.misMatchThreshold || config.misMatchThreshold
            });
          }
          //casper.echo('remote capture to > '+filePath,'info');

        });//end topLevelModules.forEach

      });

    });//end casper.each viewports

  });//end casper.each scenario

}

//========================
//this query should be moved to the prior process
//`isReference` could be better passed as env parameter
var exists = fs.exists(bitmaps_reference);
var isReference = false;
if(!exists){isReference=true; console.log('CREATING NEW REFERENCE FILES')}
//========================

capturePageSelectors(
  'index.html'
  ,scenarios
  ,viewports
  ,bitmaps_reference
  ,bitmaps_test
  ,isReference
);

casper.run(function(){
  complete();
  this.exit();
});

function complete(){
  fs.touch(compareConfigFileName);
  var compareConfigFile = fs.read(compareConfigFileName);
  var compareConfigJSON = JSON.parse(compareConfigFile || '{}');
  compareConfigJSON.compareConfig = compareConfig;
  fs.write(compareConfigFileName, JSON.stringify(compareConfigJSON,null,2), 'w');
  console.log(
    'Comparison config file updated.'
    //,configData
  );
}

function pad(number) {
  var r = String(number);
  if ( r.length === 1 ) {
    r = '0' + r;
  }
  return r;
}

function getScriptPath(scriptFilePath) {
  var script_path = ensureFileSuffix(scriptFilePath, 'js');

  if (casper_scripts) {
    script_path = glueStringsWithSlash(casper_scripts, script_path);
  }

  // make sure it's there...
  if (!fs.isFile(script_path)) {
    casper.echo(script_path + ' was not found.', 'ERROR');
    return;
  }

  return shimRelativePath(script_path);
}

function ensureFileSuffix(filename, suffix) {
  var re = new RegExp('\.' + suffix + '$', '');

  return filename.replace(re, '') + '.' + suffix;
}

// merge both strings while soft-enforcing a single slash between them
function glueStringsWithSlash(stringA, stringB) {
  return stringA.replace(/\/$/, '') + '/' + stringB.replace(/^\//, '');
}

// require() calls are relative to this file `genBitmaps.js` (not CWD) -- therefore relative paths need shimmimg
function shimRelativePath(path) {
  return path.replace(/^\.\.\//, '../../../').replace(/^\.\//, '../../');
}
<|endoftext|>


<commit_before>
export { NeuralNet_ParamsBase as ParamsBase } ;

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as Embedding from "../Embedding.js";
import * as Stage from "../Stage.js";
import * as Block from "../Block.js";
import { InferencedParams } from "./NeuralNet_InferencedParams.js";

//!!! ...unfinished... (2022/08/02)
// Perhaps, add parameter bCastToInt32 for controlling whether needs cast input to integer.
// Perhaps, add .blockCountOfStageLast, so that the final stage could have more blocks.

/**
 * NeuralNet parameters base class.
 *
 *
 * @member {number} input_height
 *   The input image's height.
 *
 * @member {number} input_width
 *   The input image's width.
 *
 * @member {number} input_channelCount
 *   The input image's channel count.
 *
 * @member {number} vocabularyChannelCount
 *   In the embedding layer, every vocabulary will have how many embedding channels.
 * Every input channel will be expanded into so many embedding channels. It could
 * be viewed as embeddingChannelCountPerInputChannel. It must be ( >= 2 ) because
 * it always has ( bEmbedVocabularyId == true ).
 *
 * @member {number} vocabularyCountPerInputChannel
 *   In the embedding layer, every input channel will have how many vocabularies.
 * This is also vocabulary count per vocabulary table (because every input channel
 * has a vocabulary table). For an image data (R-G-B-A four channels), there will
 * be 256 vocabularies per input channel because every channel is represented by
 * one byte (8 bits) which has 2^8 = 256 kinds of possible values.
 *
 * @member {number} nConvStageTypeId
 *   The type (ValueDesc.ConvStageType.Singleton.Ids.Xxx) of every convolution stage.
 *
 * @member {number} blockCountTotalRequested
 *   How many blocks of the whole neural network are wanted. It will be spreaded to
 * every stage. Note that every stage will have at least 2 blocks.
 *
 * @member {number} output_channelCount
 *   The output tensor's channel count.
 *
 * @member {boolean} bKeepInputTensor
 *   If true, apply() will not dispose inputTensor (i.e. will be kept).
 *
 * @member {InferencedParams} inferencedParams
 *   The inferenced parameters of this neural network parameters.
 *
 */
class NeuralNet_ParamsBase extends Recyclable.Root {

  /**
   * Used as default NeuralNet.ParamsBase provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "NeuralNet.ParamsBase.Pool",
    NeuralNet_ParamsBase, NeuralNet_ParamsBase.setAsConstructor );

  /**
   */
  constructor(
    input_height, input_width, input_channelCount,
    vocabularyChannelCount, vocabularyCountPerInputChannel,
    nConvStageTypeId,
    blockCountTotalRequested,
    output_channelCount,
    bKeepInputTensor
  ) {
    super();
    NeuralNet_ParamsBase.setAsConstructor_self.call( this,
      input_height, input_width, input_channelCount,
      vocabularyChannelCount, vocabularyCountPerInputChannel,
      nConvStageTypeId,
      blockCountTotalRequested,
      output_channelCount,
      bKeepInputTensor
    );
  }

  /** @override */
  static setAsConstructor(
    input_height, input_width, input_channelCount,
    vocabularyChannelCount, vocabularyCountPerInputChannel,
    nConvStageTypeId,
    blockCountTotalRequested,
    output_channelCount,
    bKeepInputTensor
  ) {
    super.setAsConstructor();
    NeuralNet_ParamsBase.setAsConstructor_self.call( this,
      input_height, input_width, input_channelCount,
      vocabularyChannelCount, vocabularyCountPerInputChannel,
      nConvStageTypeId,
      blockCountTotalRequested,
      output_channelCount,
      bKeepInputTensor
    );
    return this;
  }

  /** @override */
  static setAsConstructor_self(
    input_height, input_width, input_channelCount,
    vocabularyChannelCount, vocabularyCountPerInputChannel,
    nConvStageTypeId,
    blockCountTotalRequested,
    output_channelCount,
    bKeepInputTensor
  ) {
    this.input_height = input_height;
    this.input_width = input_width;
    this.input_channelCount = input_channelCount;
    this.vocabularyChannelCount = vocabularyChannelCount;
    this.vocabularyCountPerInputChannel = vocabularyCountPerInputChannel;
    this.nConvStageTypeId = nConvStageTypeId;
    this.blockCountTotalRequested = blockCountTotalRequested;
    this.output_channelCount = output_channelCount;
    this.bKeepInputTensor = bKeepInputTensor;
  }

  /** @override */
  disposeResources() {
    this.inferencedParams_dispose();

    this.bKeepInputTensor = undefined;
    this.output_channelCount = undefined;
    this.blockCountTotalRequested = undefined;
    this.nConvStageTypeId = undefined;
    this.vocabularyCountPerInputChannel = undefined;
    this.vocabularyChannelCount = undefined;
    this.input_channelCount = undefined;
    this.input_width = undefined;
    this.input_height = undefined;

    super.disposeResources();
  }

  /**
   * Get or create (from pool) NeuralNet.ParamsBase according to this NeuralNet.ParamsBase.
   */
  clone() {
    let another = ParamsBase.Pool.get_or_create_by(
      this.input_height,
      this.input_width,
      this.input_channelCount,
      this.vocabularyChannelCount,
      this.vocabularyCountPerInputChannel,
      this.nConvStageTypeId,
      this.blockCountTotalRequested,
      this.output_channelCount,
      this.bKeepInputTensor
    );
    return another;
  }

  /** Release .inferencedParams */
  inferencedParams_dispose() {
    if ( this.inferencedParams ) {
      this.inferencedParams.disposeResources_and_recycleToPool();
      this.inferencedParams = null;
    }
  }

  /**  */
  inferencedParams_create() {
    this.inferencedParams_dispose();
    this.inferencedParams = InferencedParams.Pool.get_or_create_by( this );
  }

  /**
   * @return {boolean}
   *   Return true, if .inferencedParams will create .embeddingParams and .stageParamsArray
   */
  inferencedParams_embeddingParams_stageParamsArray_needed() {
    return true;
  }

  /**
   * @return {Embedding.ParamsBase|Embedding.Params}
   *   Return which embedding parameter class should be used by InferencedParams.
   */
  EmbeddingParamsClass_get() {
    return Embedding.ParamsBase;
  }

  /**
   * @return {Stage.ParamsBase|Stage.Params}
   *   Return which stage parameter class should be used by InferencedParams.
   */
  StageParamsClass_get() {
    return Stage.ParamsBase;
  }

  /**
   * @return {Block.ParamsBase|Block.Params}
   *   Return which block parameter class should be used by InferencedParams.
   */
  BlockParamsClass_get() {
    return Block.ParamsBase;
  }

  get nConvStageTypeName() {
    return ValueDesc.ConvStageType.Singleton.getName_byId( this.nConvStageTypeId );
  }

  /** @override */
  toString() {
    let str = ``
      + `input_height=${this.input_height}, `
      + `input_width=${this.input_width}, `
      + `input_channelCount=${this.input_channelCount}, `
      + `vocabularyChannelCount=${this.vocabularyChannelCount}, `
      + `vocabularyCountPerInputChannel=${this.vocabularyCountPerInputChannel}, `

      + `nConvStageTypeName=${this.nConvStageTypeName}(${this.nConvStageTypeId}), `

      + `blockCountTotalRequested=${this.blockCountTotalRequested}, `

      + `output_channelCount=${this.output_channelCount}, `

      + `bKeepInputTensor=${this.bKeepInputTensor}, `
      + `${this.inferencedParams}`
    ;
    return str;
  }

}

<commit_msg>NeuralNet_ParamsBase<commit_after>
export { NeuralNet_ParamsBase as ParamsBase } ;

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as Embedding from "../Embedding.js";
import * as Stage from "../Stage.js";
import * as Block from "../Block.js";
import { InferencedParams } from "./NeuralNet_InferencedParams.js";

//!!! ...unfinished... (2022/08/02)
// Perhaps, add parameter bCastToInt32 for controlling whether needs cast input to integer.
// Perhaps, add .blockCountOfStageLast, so that the final stage could have more blocks.

/**
 * NeuralNet parameters base class.
 *
 *
 * @member {number} input_height
 *   The input image's height.
 *
 * @member {number} input_width
 *   The input image's width.
 *
 * @member {number} input_channelCount
 *   The input image's channel count.
 *
 * @member {number} vocabularyChannelCount
 *   In the embedding layer, every vocabulary will have how many embedding channels.
 * Every input channel will be expanded into so many embedding channels. It could
 * be viewed as embeddingChannelCountPerInputChannel. It must be ( >= 2 ) because
 * it always has ( bEmbedVocabularyId == true ).
 *
 * @member {number} vocabularyCountPerInputChannel
 *   In the embedding layer, every input channel will have how many vocabularies.
 * This is also vocabulary count per vocabulary table (because every input channel
 * has a vocabulary table). For an image data (R-G-B-A four channels), there will
 * be 256 vocabularies per input channel because every channel is represented by
 * one byte (8 bits) which has 2^8 = 256 kinds of possible values.
 *
 * @member {number} nConvStageTypeId
 *   The type (ValueDesc.ConvStageType.Singleton.Ids.Xxx) of every convolution stage.
 *
 * @member {number} blockCountTotalRequested
 *   How many blocks of the whole neural network are wanted. It will be spreaded to
 * every stage. Note that every stage will have at least 2 blocks.
 *
 * @member {number} output_channelCount
 *   The output tensor's channel count.
 *
 * @member {boolean} bKeepInputTensor
 *   If true, apply() will not dispose inputTensor (i.e. will be kept).
 *
 * @member {InferencedParams} inferencedParams
 *   The inferenced parameters of this neural network parameters.
 *
 */
class NeuralNet_ParamsBase extends Recyclable.Root {

  /**
   * Used as default NeuralNet.ParamsBase provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "NeuralNet.ParamsBase.Pool",
    NeuralNet_ParamsBase, NeuralNet_ParamsBase.setAsConstructor );

  /**
   */
  constructor(
    input_height, input_width, input_channelCount,
    vocabularyChannelCount, vocabularyCountPerInputChannel,
    nConvStageTypeId,
    blockCountTotalRequested,
    output_channelCount,
    bKeepInputTensor
  ) {
    super();
    NeuralNet_ParamsBase.setAsConstructor_self.call( this,
      input_height, input_width, input_channelCount,
      vocabularyChannelCount, vocabularyCountPerInputChannel,
      nConvStageTypeId,
      blockCountTotalRequested,
      output_channelCount,
      bKeepInputTensor
    );
  }

  /** @override */
  static setAsConstructor(
    input_height, input_width, input_channelCount,
    vocabularyChannelCount, vocabularyCountPerInputChannel,
    nConvStageTypeId,
    blockCountTotalRequested,
    output_channelCount,
    bKeepInputTensor
  ) {
    super.setAsConstructor();
    NeuralNet_ParamsBase.setAsConstructor_self.call( this,
      input_height, input_width, input_channelCount,
      vocabularyChannelCount, vocabularyCountPerInputChannel,
      nConvStageTypeId,
      blockCountTotalRequested,
      output_channelCount,
      bKeepInputTensor
    );
    return this;
  }

  /** @override */
  static setAsConstructor_self(
    input_height, input_width, input_channelCount,
    vocabularyChannelCount, vocabularyCountPerInputChannel,
    nConvStageTypeId,
    blockCountTotalRequested,
    output_channelCount,
    bKeepInputTensor
  ) {
    this.input_height = input_height;
    this.input_width = input_width;
    this.input_channelCount = input_channelCount;
    this.vocabularyChannelCount = vocabularyChannelCount;
    this.vocabularyCountPerInputChannel = vocabularyCountPerInputChannel;
    this.nConvStageTypeId = nConvStageTypeId;
    this.blockCountTotalRequested = blockCountTotalRequested;
    this.output_channelCount = output_channelCount;
    this.bKeepInputTensor = bKeepInputTensor;
  }

  /** @override */
  disposeResources() {
    this.inferencedParams_dispose();

    this.bKeepInputTensor = undefined;
    this.output_channelCount = undefined;
    this.blockCountTotalRequested = undefined;
    this.nConvStageTypeId = undefined;
    this.vocabularyCountPerInputChannel = undefined;
    this.vocabularyChannelCount = undefined;
    this.input_channelCount = undefined;
    this.input_width = undefined;
    this.input_height = undefined;

    super.disposeResources();
  }

  /**
   * Get or create (from pool) NeuralNet.ParamsBase according to this NeuralNet.ParamsBase.
   */
  clone() {
    let another = NeuralNet_ParamsBase.Pool.get_or_create_by(
      this.input_height,
      this.input_width,
      this.input_channelCount,
      this.vocabularyChannelCount,
      this.vocabularyCountPerInputChannel,
      this.nConvStageTypeId,
      this.blockCountTotalRequested,
      this.output_channelCount,
      this.bKeepInputTensor
    );
    return another;
  }

  /** Release .inferencedParams */
  inferencedParams_dispose() {
    if ( this.inferencedParams ) {
      this.inferencedParams.disposeResources_and_recycleToPool();
      this.inferencedParams = null;
    }
  }

  /**  */
  inferencedParams_create() {
    this.inferencedParams_dispose();
    this.inferencedParams = InferencedParams.Pool.get_or_create_by( this );
  }

  /**
   * @return {boolean}
   *   Return true, if .inferencedParams will create .embeddingParams and .stageParamsArray
   */
  inferencedParams_embeddingParams_stageParamsArray_needed() {
    return true;
  }

  /**
   * @return {Embedding.ParamsBase|Embedding.Params}
   *   Return which embedding parameter class should be used by InferencedParams.
   */
  EmbeddingParamsClass_get() {
    return Embedding.ParamsBase;
  }

  /**
   * @return {Stage.ParamsBase|Stage.Params}
   *   Return which stage parameter class should be used by InferencedParams.
   */
  StageParamsClass_get() {
    return Stage.ParamsBase;
  }

  /**
   * @return {Block.ParamsBase|Block.Params}
   *   Return which block parameter class should be used by InferencedParams.
   */
  BlockParamsClass_get() {
    return Block.ParamsBase;
  }

  get nConvStageTypeName() {
    return ValueDesc.ConvStageType.Singleton.getName_byId( this.nConvStageTypeId );
  }

  /** @override */
  toString() {
    let str = ``
      + `input_height=${this.input_height}, `
      + `input_width=${this.input_width}, `
      + `input_channelCount=${this.input_channelCount}, `
      + `vocabularyChannelCount=${this.vocabularyChannelCount}, `
      + `vocabularyCountPerInputChannel=${this.vocabularyCountPerInputChannel}, `

      + `nConvStageTypeName=${this.nConvStageTypeName}(${this.nConvStageTypeId}), `

      + `blockCountTotalRequested=${this.blockCountTotalRequested}, `

      + `output_channelCount=${this.output_channelCount}, `

      + `bKeepInputTensor=${this.bKeepInputTensor}, `
      + `${this.inferencedParams}`
    ;
    return str;
  }

}

<|endoftext|>


<commit_before>/**
 * Generic postback control.
 */
Prado.WebUI.CallbackControl = jQuery.klass(Prado.WebUI.PostBackControl,
{
	onPostBack : function(options, event)
	{
		var request = new Prado.CallbackRequest(options.EventTarget, options);
		request.dispatch();
		event.preventDefault();
	}
});

/**
 * TActiveButton control.
 */
Prado.WebUI.TActiveButton = jQuery.klass(Prado.WebUI.CallbackControl);
/**
 * TActiveLinkButton control.
 */
Prado.WebUI.TActiveLinkButton = jQuery.klass(Prado.WebUI.CallbackControl);

Prado.WebUI.TActiveImageButton = jQuery.klass(Prado.WebUI.TImageButton,
{
	onPostBack : function(options, event)
	{
		this.addXYInput(options, event);
		var request = new Prado.CallbackRequest(options.EventTarget, options);
		request.dispatch();
		event.preventDefault();
		this.removeXYInput(options, event);
	}
});
/**
 * Active check box.
 */
Prado.WebUI.TActiveCheckBox = jQuery.klass(Prado.WebUI.CallbackControl,
{
	onPostBack : function(options, event)
	{
		var request = new Prado.CallbackRequest(options.EventTarget, options);
		if(request.dispatch()==false)
			event.preventDefault();
	}
});

/**
 * TActiveRadioButton control.
 */
Prado.WebUI.TActiveRadioButton = jQuery.klass(Prado.WebUI.TActiveCheckBox);

Prado.WebUI.TActiveCheckBoxList = jQuery.klass(Prado.WebUI.Control,
{
	onInit : function(options)
	{
		for(var i = 0; i<options.ItemCount; i++)
		{
			var checkBoxOptions = jQuery.extend({}, options,
			{
				ID : options.ID+"_c"+i,
				EventTarget : options.ListName+"$c"+i
			});
			new Prado.WebUI.TActiveCheckBox(checkBoxOptions);
		}
	}
});

Prado.WebUI.TActiveRadioButtonList = Prado.WebUI.TActiveCheckBoxList;

/**
 * TActiveTextBox control, handles onchange event.
 */
Prado.WebUI.TActiveTextBox = jQuery.klass(Prado.WebUI.TTextBox,
{
	onInit : function(options)
	{
		this.options=options;
		if(options['TextMode'] != 'MultiLine')
			this.observe(this.element, "keydown", this.handleReturnKey.bind(this));
		if(this.options['AutoPostBack']==true)
			this.observe(this.element, "change", jQuery.proxy(this.doCallback,this,options));
	},

	doCallback : function(options, event)
	{
		var request = new Prado.CallbackRequest(options.EventTarget, options);
		request.dispatch();
	    event.preventDefault();
	}
});

/**
 * TJuiAutoComplete control.
 */

Prado.WebUI.TJuiAutoComplete = jQuery.klass(Prado.WebUI.TActiveTextBox,
{
	initialize : function(options)
	{
		this.options = options;
		this.observers = new Array();
		this.hasResults = false;
		jQuery.extend(this.options, {
			source: this.getUpdatedChoices.bind(this),
			select: this.selectEntry.bind(this),
			focus: function () {
				return false;
			},
			minLength: this.options.minLength,
			frequency: this.options.frequency
		});
		jQuery('#'+options.ID).autocomplete(this.options)
		.data( "ui-autocomplete")._renderItem = function( ul, item ) {
			return jQuery( "<li>" )
			.attr( "data-value", item.value )
			.append( jQuery( "<a>" ).html( item.label ) )
			.appendTo( ul );
		};

		if(options.AutoPostBack)
			this.onInit(options);

		Prado.Registry[options.ID] = this;
	},

	doCallback : function(event, options)
	{
		if(!this.active)
		{
			var request = new Prado.CallbackRequest(this.options.EventTarget, options);
			request.dispatch();
			event.stopPropagation();
		}
	},

	getUpdatedChoices : function(request, callback)
	{
        var lastTerm = this.extractLastTerm(request.term);
		var params = new Array(lastTerm, "__TJuiAutoComplete_onSuggest__");
		var options = jQuery.extend(this.options, {
			'autocompleteCallback' : callback
		});
		Prado.Callback(this.options.EventTarget, params, this.onComplete.bind(this), this.options);
	},

	extractLastTerm: function(string)
	{
		var re = new RegExp("[" + this.options.Separators + "]");
		return string.split(re).pop().trim();
	},

	/**
	 * Overrides parent implements, don't update if no results.
	 */
	selectEntry: function(event, ui) {
		var value = event.target.value;
		var lastTerm = this.extractLastTerm(value);

		// strip (possibly) incomplete last part
		var previousTerms = value.substr(0, value.length - lastTerm.length);
		// and append selected value
		ui.item.value = previousTerms + ui.item.value;

		//ui.item.value = event.target.value;
		var options = [ui.item.id, "__TJuiAutoComplete_onSuggestionSelected__"];
		Prado.Callback(this.options.EventTarget, options, null, this.options);
	},

	onComplete : function(request, result)
  	{
  		var that = this;
  		if(that.options.textCssClass===undefined)
  		{
			jQuery.each(result, function(idx, item) {
				result[idx]['value']=jQuery.trim(jQuery(item['label']).text());
			});
  		} else {
			jQuery.each(result, function(idx, item) {
				result[idx]['value']=jQuery.trim(jQuery(item['label']).find('.'+that.options.textCssClass).text());
			});
  		}

		request.options.autocompleteCallback(result);
	}
});

/**
 * Time Triggered Callback class.
 */
Prado.WebUI.TTimeTriggeredCallback = jQuery.klass(Prado.WebUI.Control,
{
	onInit : function(options)
	{
		this.options = jQuery.extend({ Interval : 1	}, options || {});
		Prado.WebUI.TTimeTriggeredCallback.registerTimer(this);
	},

	startTimer : function()
	{
		if(typeof(this.timer) == 'undefined' || this.timer == null)
			this.timer = this.setInterval(this.onTimerEvent.bind(this),this.options.Interval*1000);
	},

	stopTimer : function()
	{
		if(typeof(this.timer) != 'undefined')
		{
			this.clearInterval(this.timer);
			this.timer = null;
		}
	},

	resetTimer : function()
	{
		if(typeof(this.timer) != 'undefined')
		{
			this.clearInterval(this.timer);
			this.timer = null;
			this.timer = this.setInterval(this.onTimerEvent.bind(this),this.options.Interval*1000);
		}
	},

	onTimerEvent : function()
	{
		var request = new Prado.CallbackRequest(this.options.EventTarget, this.options);
		request.dispatch();
	},

	setTimerInterval : function(value)
	{
		if (this.options.Interval != value){
			this.options.Interval = value;
			this.resetTimer();
		}
	},

	onDone: function()
	{
		this.stopTimer();
	}
});

jQuery.extend(Prado.WebUI.TTimeTriggeredCallback,
{

	//class methods

	timers : {},

	registerTimer : function(timer)
	{
		Prado.WebUI.TTimeTriggeredCallback.timers[timer.options.ID] = timer;
	},

	start : function(id)
	{
		if(Prado.WebUI.TTimeTriggeredCallback.timers[id])
			Prado.WebUI.TTimeTriggeredCallback.timers[id].startTimer();
	},

	stop : function(id)
	{
		if(Prado.WebUI.TTimeTriggeredCallback.timers[id])
			Prado.WebUI.TTimeTriggeredCallback.timers[id].stopTimer();
	},

	setTimerInterval : function (id,value)
	{
		if(Prado.WebUI.TTimeTriggeredCallback.timers[id])
			Prado.WebUI.TTimeTriggeredCallback.timers[id].setTimerInterval(value);
	}
});

Prado.WebUI.ActiveListControl = jQuery.klass(Prado.WebUI.Control,
{
	onInit : function(options)
	{
		if(this.element)
		{
			this.options = options;
			this.observe(this.element, "change", this.doCallback.bind(this));
		}
	},

	doCallback : function(event)
	{
		var request = new Prado.CallbackRequest(this.options.EventTarget, this.options);
		request.dispatch();
		event.preventDefault();
	}
});

Prado.WebUI.TActiveDropDownList = jQuery.klass(Prado.WebUI.ActiveListControl);
Prado.WebUI.TActiveListBox = jQuery.klass(Prado.WebUI.ActiveListControl);

/**
 * Observe event of a particular control to trigger a callback request.
 */
Prado.WebUI.TEventTriggeredCallback = jQuery.klass(Prado.WebUI.Control,
{
	onInit : function(options)
	{
		this.options = options || {} ;
		var element = jQuery('#'+options['ControlID']).get(0);
		if(element)
			this.observe(element, this.getEventName(element), this.doCallback.bind(this));
	},

	getEventName : function(element)
	{
		var name = this.options.EventName;
   		if(typeof(name) == "undefined" && element.type)
		{
      		switch (element.type.toLowerCase())
			{
          		case 'password':
		        case 'text':
		        case 'textarea':
		        case 'select-one':
		        case 'select-multiple':
          			return 'change';
      		}
		}
		return typeof(name) == "undefined"  || name == "undefined" ? 'click' : name;
    },

	doCallback : function(event)
	{
		var request = new Prado.CallbackRequest(this.options.EventTarget, this.options);
		request.dispatch();
		if(this.options.StopEvent == true)
			event.preventDefault();
	}
});

/**
 * Observe changes to a property of a particular control to trigger a callback.
 */
Prado.WebUI.TValueTriggeredCallback = jQuery.klass(Prado.WebUI.Control,
{
	count : 1,

	observing : true,

	onInit : function(options)
	{
		this.options = options || {} ;
		this.options.PropertyName = this.options.PropertyName || 'value';
		var element = jQuery('#'+options['ControlID']).get(0);
		this.value = element ? element[this.options.PropertyName] : undefined;
		Prado.WebUI.TValueTriggeredCallback.register(this);
		this.startObserving();
	},

	stopObserving : function()
	{
		this.clearTimeout(this.timer);
		this.observing = false;
	},

	startObserving : function()
	{
		this.timer = this.setTimeout(this.checkChanges.bind(this), this.options.Interval*1000);
	},

	checkChanges : function()
	{
		var element = jQuery('#'+this.options.ControlID).get(0);
		if(element)
		{
			var value = element[this.options.PropertyName];
			if(this.value != value)
			{
				this.doCallback(this.value, value);
				this.value = value;
				this.count=1;
			}
			else
				this.count = this.count + this.options.Decay;
			if(this.observing)
				this.time = this.setTimeout(this.checkChanges.bind(this),
					parseInt(this.options.Interval*1000*this.count));
		}
	},

	doCallback : function(oldValue, newValue)
	{
		var request = new Prado.CallbackRequest(this.options.EventTarget, this.options);
		var param = {'OldValue' : oldValue, 'NewValue' : newValue};
		request.setCallbackParameter(param);
		request.dispatch();
	},

	onDone : function()
	{
		if (this.observing)
			this.stopObserving();
	}
});

jQuery.extend(Prado.WebUI.TValueTriggeredCallback,
{
	//class methods

	timers : {},

	register : function(timer)
	{
		Prado.WebUI.TValueTriggeredCallback.timers[timer.options.ID] = timer;
	},

	stop : function(id)
	{
		Prado.WebUI.TValueTriggeredCallback.timers[id].stopObserving();
	}
});

Prado.WebUI.TActiveTableCell = jQuery.klass(Prado.WebUI.CallbackControl);
Prado.WebUI.TActiveTableRow = jQuery.klass(Prado.WebUI.CallbackControl);
<commit_msg>undefined separator for TJuiAutoComplete multiselection gives wrong token<commit_after>/**
 * Generic postback control.
 */
Prado.WebUI.CallbackControl = jQuery.klass(Prado.WebUI.PostBackControl,
{
	onPostBack : function(options, event)
	{
		var request = new Prado.CallbackRequest(options.EventTarget, options);
		request.dispatch();
		event.preventDefault();
	}
});

/**
 * TActiveButton control.
 */
Prado.WebUI.TActiveButton = jQuery.klass(Prado.WebUI.CallbackControl);
/**
 * TActiveLinkButton control.
 */
Prado.WebUI.TActiveLinkButton = jQuery.klass(Prado.WebUI.CallbackControl);

Prado.WebUI.TActiveImageButton = jQuery.klass(Prado.WebUI.TImageButton,
{
	onPostBack : function(options, event)
	{
		this.addXYInput(options, event);
		var request = new Prado.CallbackRequest(options.EventTarget, options);
		request.dispatch();
		event.preventDefault();
		this.removeXYInput(options, event);
	}
});
/**
 * Active check box.
 */
Prado.WebUI.TActiveCheckBox = jQuery.klass(Prado.WebUI.CallbackControl,
{
	onPostBack : function(options, event)
	{
		var request = new Prado.CallbackRequest(options.EventTarget, options);
		if(request.dispatch()==false)
			event.preventDefault();
	}
});

/**
 * TActiveRadioButton control.
 */
Prado.WebUI.TActiveRadioButton = jQuery.klass(Prado.WebUI.TActiveCheckBox);

Prado.WebUI.TActiveCheckBoxList = jQuery.klass(Prado.WebUI.Control,
{
	onInit : function(options)
	{
		for(var i = 0; i<options.ItemCount; i++)
		{
			var checkBoxOptions = jQuery.extend({}, options,
			{
				ID : options.ID+"_c"+i,
				EventTarget : options.ListName+"$c"+i
			});
			new Prado.WebUI.TActiveCheckBox(checkBoxOptions);
		}
	}
});

Prado.WebUI.TActiveRadioButtonList = Prado.WebUI.TActiveCheckBoxList;

/**
 * TActiveTextBox control, handles onchange event.
 */
Prado.WebUI.TActiveTextBox = jQuery.klass(Prado.WebUI.TTextBox,
{
	onInit : function(options)
	{
		this.options=options;
		if(options['TextMode'] != 'MultiLine')
			this.observe(this.element, "keydown", this.handleReturnKey.bind(this));
		if(this.options['AutoPostBack']==true)
			this.observe(this.element, "change", jQuery.proxy(this.doCallback,this,options));
	},

	doCallback : function(options, event)
	{
		var request = new Prado.CallbackRequest(options.EventTarget, options);
		request.dispatch();
	    event.preventDefault();
	}
});

/**
 * TJuiAutoComplete control.
 */

Prado.WebUI.TJuiAutoComplete = jQuery.klass(Prado.WebUI.TActiveTextBox,
{
	initialize : function(options)
	{
		this.options = options;
		this.observers = new Array();
		this.hasResults = false;
		jQuery.extend(this.options, {
			source: this.getUpdatedChoices.bind(this),
			select: this.selectEntry.bind(this),
			focus: function () {
				return false;
			},
			minLength: this.options.minLength,
			frequency: this.options.frequency
		});
		jQuery('#'+options.ID).autocomplete(this.options)
		.data( "ui-autocomplete")._renderItem = function( ul, item ) {
			return jQuery( "<li>" )
			.attr( "data-value", item.value )
			.append( jQuery( "<a>" ).html( item.label ) )
			.appendTo( ul );
		};

		if(options.AutoPostBack)
			this.onInit(options);

		Prado.Registry[options.ID] = this;
	},

	doCallback : function(event, options)
	{
		if(!this.active)
		{
			var request = new Prado.CallbackRequest(this.options.EventTarget, options);
			request.dispatch();
			event.stopPropagation();
		}
	},

	getUpdatedChoices : function(request, callback)
	{
        var lastTerm = this.extractLastTerm(request.term);
		var params = new Array(lastTerm, "__TJuiAutoComplete_onSuggest__");
		var options = jQuery.extend(this.options, {
			'autocompleteCallback' : callback
		});
		Prado.Callback(this.options.EventTarget, params, this.onComplete.bind(this), this.options);
	},

	extractLastTerm: function(string)
	{
		var re = new RegExp("[" + (this.options.Separators || '') + "]");
		return string.split(re).pop().trim();
	},

	/**
	 * Overrides parent implements, don't update if no results.
	 */
	selectEntry: function(event, ui) {
		var value = event.target.value;
		var lastTerm = this.extractLastTerm(value);

		// strip (possibly) incomplete last part
		var previousTerms = value.substr(0, value.length - lastTerm.length);
		// and append selected value
		ui.item.value = previousTerms + ui.item.value;

		//ui.item.value = event.target.value;
		var options = [ui.item.id, "__TJuiAutoComplete_onSuggestionSelected__"];
		Prado.Callback(this.options.EventTarget, options, null, this.options);
	},

	onComplete : function(request, result)
  	{
  		var that = this;
  		if(that.options.textCssClass===undefined)
  		{
			jQuery.each(result, function(idx, item) {
				result[idx]['value']=jQuery.trim(jQuery(item['label']).text());
			});
  		} else {
			jQuery.each(result, function(idx, item) {
				result[idx]['value']=jQuery.trim(jQuery(item['label']).find('.'+that.options.textCssClass).text());
			});
  		}

		request.options.autocompleteCallback(result);
	}
});

/**
 * Time Triggered Callback class.
 */
Prado.WebUI.TTimeTriggeredCallback = jQuery.klass(Prado.WebUI.Control,
{
	onInit : function(options)
	{
		this.options = jQuery.extend({ Interval : 1	}, options || {});
		Prado.WebUI.TTimeTriggeredCallback.registerTimer(this);
	},

	startTimer : function()
	{
		if(typeof(this.timer) == 'undefined' || this.timer == null)
			this.timer = this.setInterval(this.onTimerEvent.bind(this),this.options.Interval*1000);
	},

	stopTimer : function()
	{
		if(typeof(this.timer) != 'undefined')
		{
			this.clearInterval(this.timer);
			this.timer = null;
		}
	},

	resetTimer : function()
	{
		if(typeof(this.timer) != 'undefined')
		{
			this.clearInterval(this.timer);
			this.timer = null;
			this.timer = this.setInterval(this.onTimerEvent.bind(this),this.options.Interval*1000);
		}
	},

	onTimerEvent : function()
	{
		var request = new Prado.CallbackRequest(this.options.EventTarget, this.options);
		request.dispatch();
	},

	setTimerInterval : function(value)
	{
		if (this.options.Interval != value){
			this.options.Interval = value;
			this.resetTimer();
		}
	},

	onDone: function()
	{
		this.stopTimer();
	}
});

jQuery.extend(Prado.WebUI.TTimeTriggeredCallback,
{

	//class methods

	timers : {},

	registerTimer : function(timer)
	{
		Prado.WebUI.TTimeTriggeredCallback.timers[timer.options.ID] = timer;
	},

	start : function(id)
	{
		if(Prado.WebUI.TTimeTriggeredCallback.timers[id])
			Prado.WebUI.TTimeTriggeredCallback.timers[id].startTimer();
	},

	stop : function(id)
	{
		if(Prado.WebUI.TTimeTriggeredCallback.timers[id])
			Prado.WebUI.TTimeTriggeredCallback.timers[id].stopTimer();
	},

	setTimerInterval : function (id,value)
	{
		if(Prado.WebUI.TTimeTriggeredCallback.timers[id])
			Prado.WebUI.TTimeTriggeredCallback.timers[id].setTimerInterval(value);
	}
});

Prado.WebUI.ActiveListControl = jQuery.klass(Prado.WebUI.Control,
{
	onInit : function(options)
	{
		if(this.element)
		{
			this.options = options;
			this.observe(this.element, "change", this.doCallback.bind(this));
		}
	},

	doCallback : function(event)
	{
		var request = new Prado.CallbackRequest(this.options.EventTarget, this.options);
		request.dispatch();
		event.preventDefault();
	}
});

Prado.WebUI.TActiveDropDownList = jQuery.klass(Prado.WebUI.ActiveListControl);
Prado.WebUI.TActiveListBox = jQuery.klass(Prado.WebUI.ActiveListControl);

/**
 * Observe event of a particular control to trigger a callback request.
 */
Prado.WebUI.TEventTriggeredCallback = jQuery.klass(Prado.WebUI.Control,
{
	onInit : function(options)
	{
		this.options = options || {} ;
		var element = jQuery('#'+options['ControlID']).get(0);
		if(element)
			this.observe(element, this.getEventName(element), this.doCallback.bind(this));
	},

	getEventName : function(element)
	{
		var name = this.options.EventName;
   		if(typeof(name) == "undefined" && element.type)
		{
      		switch (element.type.toLowerCase())
			{
          		case 'password':
		        case 'text':
		        case 'textarea':
		        case 'select-one':
		        case 'select-multiple':
          			return 'change';
      		}
		}
		return typeof(name) == "undefined"  || name == "undefined" ? 'click' : name;
    },

	doCallback : function(event)
	{
		var request = new Prado.CallbackRequest(this.options.EventTarget, this.options);
		request.dispatch();
		if(this.options.StopEvent == true)
			event.preventDefault();
	}
});

/**
 * Observe changes to a property of a particular control to trigger a callback.
 */
Prado.WebUI.TValueTriggeredCallback = jQuery.klass(Prado.WebUI.Control,
{
	count : 1,

	observing : true,

	onInit : function(options)
	{
		this.options = options || {} ;
		this.options.PropertyName = this.options.PropertyName || 'value';
		var element = jQuery('#'+options['ControlID']).get(0);
		this.value = element ? element[this.options.PropertyName] : undefined;
		Prado.WebUI.TValueTriggeredCallback.register(this);
		this.startObserving();
	},

	stopObserving : function()
	{
		this.clearTimeout(this.timer);
		this.observing = false;
	},

	startObserving : function()
	{
		this.timer = this.setTimeout(this.checkChanges.bind(this), this.options.Interval*1000);
	},

	checkChanges : function()
	{
		var element = jQuery('#'+this.options.ControlID).get(0);
		if(element)
		{
			var value = element[this.options.PropertyName];
			if(this.value != value)
			{
				this.doCallback(this.value, value);
				this.value = value;
				this.count=1;
			}
			else
				this.count = this.count + this.options.Decay;
			if(this.observing)
				this.time = this.setTimeout(this.checkChanges.bind(this),
					parseInt(this.options.Interval*1000*this.count));
		}
	},

	doCallback : function(oldValue, newValue)
	{
		var request = new Prado.CallbackRequest(this.options.EventTarget, this.options);
		var param = {'OldValue' : oldValue, 'NewValue' : newValue};
		request.setCallbackParameter(param);
		request.dispatch();
	},

	onDone : function()
	{
		if (this.observing)
			this.stopObserving();
	}
});

jQuery.extend(Prado.WebUI.TValueTriggeredCallback,
{
	//class methods

	timers : {},

	register : function(timer)
	{
		Prado.WebUI.TValueTriggeredCallback.timers[timer.options.ID] = timer;
	},

	stop : function(id)
	{
		Prado.WebUI.TValueTriggeredCallback.timers[id].stopObserving();
	}
});

Prado.WebUI.TActiveTableCell = jQuery.klass(Prado.WebUI.CallbackControl);
Prado.WebUI.TActiveTableRow = jQuery.klass(Prado.WebUI.CallbackControl);
<|endoftext|>


<commit_before>'use strict';
const assert = require('chai').assert;
const config = require('../api/config.js');
const http = require('http');
const createRetryJsonStream = require('../lib/tolerant-json-stream.js');

describe('node-connection', () => {

  describe('when connected to another node', () => {
    let response, server, stream;
    const url = `http://localhost:${config.port}/sets/a,b`;

    beforeEach(done => {
      server = http.createServer();
      server.once('request', (req, res) => {
        response = res;
        done();
      });
      server.listen(config.port, () => {
        stream = createRetryJsonStream(url);
      });
    });

    afterEach(done => {
      stream.stop();
      server.close(done); // waits until retry json has dropped connection
    });

    it('emits connect event', done => {
      response.flushHeaders();
      stream.once('connect', () => done());
    });

    it('emits initial object received from the stream', done => {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', data => {
        assert.equal(data.a, 1);
        done();
      });
    });

    it('emits subsequent objects received from the stream', done => {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', () => {
        response.write(JSON.stringify({ a: 2 }) + '\r\n');
        stream.once('data', data => {
          assert.equal(data.a, 2);
          done();
        });
      });
    });

    describe('when the server ends the current request', () => {
      it('reconnects and receives new data', done => {
        testReconnect(() => response.end(), done);
      });

      it('emits connectionError event', done => {
        response.end();
        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'server ended request');
          done();
        });
      });
    });

    describe('when the server destroys the current request', () => {
      it('reconnects and receives new data', done => {
        testReconnect(() => response.destroy(), done);
      });

      it('emits connectionError event', done => {
        response.end();
        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'server ended request');
          done();
        });
      });
    });

    describe('when the server dies', () => {
      it('emits connectionError event', done => {
        response.end();
        server.close();
        server.close = (cb) => cb(); // stub so beforeEach doesn't break

        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'server ended request');
          done();
        });
      });

      it('emits connectionError for subsequent reconnection failure', done => {
        response.end();
        server.close();
        server.close = (cb) => cb(); // stub so beforeEach doesn't break

        stream.once('connectionError', () => {
          stream.once('connectionError', err => {
            assert.instanceOf(err, Error);
            assert.match(err.message, /ECONNREFUSED/);
            done();
          });
        });
      });

      it('reconnection attempts back off');
    });

    describe('when the server is slow to respond', () => {
      it('should timeout request and try again');
      it('should backoff on retries on timeouts');
    });

    function testReconnect(terminate, done) {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', () => {
        let connected = false;

        // terminate the initial request to kick things off
        terminate();

        // wait for next request to server
        server.once('request', (req, secondResponse) => {
          secondResponse.write(JSON.stringify({ a: 2 }) + '\r\n');
        });

        stream.once('connect', () => connected = true);

        // assert state is emitted
        stream.once('data', data => {
          assert.isTrue(connected);
          assert.equal(data.a, 2);
          done();
        });
      });
    }
  });

  describe('error handling', () => {
    it('expects a node url', () => {
      assert.throws(() => {
        createRetryJsonStream(null, ['a','b']);
      }, 'url is required');
    });

    it('handles bad json data');
  });
});
<commit_msg>tolerant-json-stream: correct test context name.<commit_after>'use strict';
const assert = require('chai').assert;
const config = require('../api/config.js');
const http = require('http');
const createRetryJsonStream = require('../lib/tolerant-json-stream.js');

describe('tolerant-json-stream', () => {

  describe('when connected to another node', () => {
    let response, server, stream;
    const url = `http://localhost:${config.port}/sets/a,b`;

    beforeEach(done => {
      server = http.createServer();
      server.once('request', (req, res) => {
        response = res;
        done();
      });
      server.listen(config.port, () => {
        stream = createRetryJsonStream(url);
      });
    });

    afterEach(done => {
      stream.stop();
      server.close(done); // waits until retry json has dropped connection
    });

    it('emits connect event', done => {
      response.flushHeaders();
      stream.once('connect', () => done());
    });

    it('emits initial object received from the stream', done => {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', data => {
        assert.equal(data.a, 1);
        done();
      });
    });

    it('emits subsequent objects received from the stream', done => {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', () => {
        response.write(JSON.stringify({ a: 2 }) + '\r\n');
        stream.once('data', data => {
          assert.equal(data.a, 2);
          done();
        });
      });
    });

    describe('when the server ends the current request', () => {
      it('reconnects and receives new data', done => {
        testReconnect(() => response.end(), done);
      });

      it('emits connectionError event', done => {
        response.end();
        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'server ended request');
          done();
        });
      });
    });

    describe('when the server destroys the current request', () => {
      it('reconnects and receives new data', done => {
        testReconnect(() => response.destroy(), done);
      });

      it('emits connectionError event', done => {
        response.end();
        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'server ended request');
          done();
        });
      });
    });

    describe('when the server dies', () => {
      it('emits connectionError event', done => {
        response.end();
        server.close();
        server.close = (cb) => cb(); // stub so beforeEach doesn't break

        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'server ended request');
          done();
        });
      });

      it('emits connectionError for subsequent reconnection failure', done => {
        response.end();
        server.close();
        server.close = (cb) => cb(); // stub so beforeEach doesn't break

        stream.once('connectionError', () => {
          stream.once('connectionError', err => {
            assert.instanceOf(err, Error);
            assert.match(err.message, /ECONNREFUSED/);
            done();
          });
        });
      });

      it('reconnection attempts back off');
    });

    describe('when the server is slow to respond', () => {
      it('should timeout request and try again');
      it('should backoff on retries on timeouts');
    });

    function testReconnect(terminate, done) {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', () => {
        let connected = false;

        // terminate the initial request to kick things off
        terminate();

        // wait for next request to server
        server.once('request', (req, secondResponse) => {
          secondResponse.write(JSON.stringify({ a: 2 }) + '\r\n');
        });

        stream.once('connect', () => connected = true);

        // assert state is emitted
        stream.once('data', data => {
          assert.isTrue(connected);
          assert.equal(data.a, 2);
          done();
        });
      });
    }
  });

  describe('error handling', () => {
    it('expects a node url', () => {
      assert.throws(() => {
        createRetryJsonStream(null, ['a','b']);
      }, 'url is required');
    });

    it('handles bad json data');
  });
});
<|endoftext|>