<commit_before>'use strict';

/**
 * @ngdoc function
 * @name grafterizerApp.controller:TransformationnewCtrl
 * @description
 * # TransformationnewCtrl
 * Controller of the grafterizerApp
 */
angular.module('grafterizerApp')
  .controller('TransformationNewCtrl', function(
    $scope,
    $stateParams,
    ontotextAPI,
    uploadFile,
    $rootScope,
    $state,
    $mdToast,
    $mdDialog,
    transformationDataModel,
    generateClojure) {

    // $scope.readonlymode = true;

    $scope.document = {
      title: 'New transformation',
      description: '',
      keywords: []
    };

    var customfunctions = [
          new transformationDataModel.CustomFunctionDeclaration('replace-varible-string',
        '(defn replace-varible-string [cell]   (-> cell  (clojure.string/replace (read-string "#\\".* #\\"") "number") (clojure.string/replace (read-string "#\\"[0-9]{4} \\"") "") ))',
        'SERVICE', ''),
          new transformationDataModel.CustomFunctionDeclaration('add-filename-to-column',
        '(defn add-filename-to-column [ds destination-column] (let [fname (:grafter.tabular/data-source (meta ds))] (add-column ds destination-column fname)))     ',
        'SERVICE', ''),
          new transformationDataModel.CustomFunctionDeclaration('remove-columns',
        '(defn remove-columns [ds cols] (columns ds (remove (fn [item] (some (fn [a] (= item a)) cols )) (column-names ds)))) ',
        'SERVICE', 'Given a dataset and collection of column names narrows dataset to all but specified columns'),
          new transformationDataModel.CustomFunctionDeclaration('organize-date',
        '(defn organize-date "Transform date dd/mm/yyyy ~> yyyy-mm-dd" [date] (when (seq date)  (let [[d m y] (clojure.string/split date  (read-string "#\\"/\\""))]  (apply str (interpose "-" [y m d])))))',
        'DATE FUNCTIONS', 'Transform date dd/mm/yyyy ~> yyyy-mm-dd'),
          new transformationDataModel.CustomFunctionDeclaration('double-literal',
        '(defn double-literal [s] (Double/parseDouble s))', 'CONVERT DATATYPE', 'Coerce to integer'),
          new transformationDataModel.CustomFunctionDeclaration('integer-literal',
        '(defn integer-literal [s] (Integer/parseInt s))', 'CONVERT DATATYPE', 'Coerce to integer'),
          new transformationDataModel.CustomFunctionDeclaration('fill-when', '(defn fill-when [col] (grafter.sequences/fill-when col))', 'SERVICE',
        'Takes a sequence of values and copies a value through the sequence depending on the supplied predicate function'
      ),
          new transformationDataModel.CustomFunctionDeclaration('sort-dataset', '(defn sort-dataset  [ds col] (-> (make-dataset (sort-by col (:rows ds)) (column-names ds)) (with-meta (meta ds))))', 'SERVICE',
                         'Sorts a dataset by given column'
                              ),
              new transformationDataModel.CustomFunctionDeclaration('transform-gender',
        '(def transform-gender {"f" (s "female") "m" (s "male")})', 'UTILITY',
        'Maps "f" to "female" and "m" to "male"'),
          new transformationDataModel.CustomFunctionDeclaration('stringToNumeric',
        '(defn stringToNumeric    [x] (if (= "" x) nil  (if (.contains x ".") (Double/parseDouble x)(Integer/parseInt x))))',
        'CONVERT DATATYPE', 'Convert string to numeric'),
          new transformationDataModel.CustomFunctionDeclaration('string-literal', '(def string-literal s)',
        'CONVERT DATATYPE', 'Coerce to string'),
          new transformationDataModel.CustomFunctionDeclaration('boolean', '', 'CONVERT DATATYPE', 'Coerce to boolean'),
          new transformationDataModel.CustomFunctionDeclaration('count', '', 'COLLECTION',
        'Returns the number of items in the collection'),
          new transformationDataModel.CustomFunctionDeclaration('cast', '', 'CONVERT DATATYPE',
        ' Throws a ClassCastException if x is not a c, else returns x'),
          new transformationDataModel.CustomFunctionDeclaration('capitalize',
        '', 'STRING', 'Converts first character of the string to upper-case, all other characters to lower-case.'),
          new transformationDataModel.CustomFunctionDeclaration('dec', '', 'NUMBER',
        'Returns a number one less than num'),
          new transformationDataModel.CustomFunctionDeclaration('double', '', 'CONVERT DATATYPE', 'Coerce to double'),
          new transformationDataModel.CustomFunctionDeclaration('first', '', 'COLLECTION',
        'Returns the first item in the collection'),
          new transformationDataModel.CustomFunctionDeclaration('float', '', 'CONVERT DATATYPE', 'Coerce to float'),
          new transformationDataModel.CustomFunctionDeclaration('inc', '', 'NUMBER',
        'Returns a number one greater than num'),
          new transformationDataModel.CustomFunctionDeclaration('keyword', '', 'CONVERT DATATYPE',
        'Returns a Keyword with the given namespace and name. '),
          new transformationDataModel.CustomFunctionDeclaration('last', '', 'COLLECTION',
        'Return the last item in the collection'),
          new transformationDataModel.CustomFunctionDeclaration('long', '', 'CONVERT DATATYPE', 'Coerce to long'),
          new transformationDataModel.CustomFunctionDeclaration('name', '', 'CONVERT DATATYPE',
        'Returns the name String of a string, symbol or keyword'),
          new transformationDataModel.CustomFunctionDeclaration('second', '', 'COLLECTION',
        'Returns the second item in the collection'),
          new transformationDataModel.CustomFunctionDeclaration('short', '', 'CONVERT DATATYPE', 'Coerce to short'),
          new transformationDataModel.CustomFunctionDeclaration('join',
        '(defn join [& strings] (clojure.string/join " " strings))', 'STRING',
        'Returns a string of all elements in the collection separated by space.'),
          new transformationDataModel.CustomFunctionDeclaration('join-with',
        '(defn join-with [sep] ( fn [& strings] (clojure.string/join sep strings)))', 'STRING',
        'Returns a string of all elements in the collection separated by custom separator.'),
          new transformationDataModel.CustomFunctionDeclaration('lower-case',
        '', 'STRING', 'Converts string to all lower-case'),
          new transformationDataModel.CustomFunctionDeclaration('upper-case',
        '', 'STRING', 'Converts string to all upper-case'),
          new transformationDataModel.CustomFunctionDeclaration('reverse', '', 'STRING', 'Returns given string with its characters reversed'),
          new transformationDataModel.CustomFunctionDeclaration('string-as-keyword', '(defn string-as-keyword [s] ( when (seq s) (->   (str s) clojure.string/trim   (clojure.string/replace "(" "-") (clojure.string/replace ")" "") (clojure.string/replace " " "_") (clojure.string/replace "," "-") (clojure.string/replace "." "") (clojure.string/replace "/" "-") (clojure.string/replace "---" "-") (clojure.string/replace "--" "-") (clojure.string/replace ":" "") (clojure.string/replace "\\"" "") )))','STRING','Removes blanks and special symbols from a string thus making it possible to use it as a keyword'),
          new transformationDataModel.CustomFunctionDeclaration('remove-blanks', '(defn remove-blanks [s]  (when (seq s)  (clojure.string/replace s " " "")))','STRING','Removes blanks in a string'),
          new transformationDataModel.CustomFunctionDeclaration('titleize', '(defn titleize [st] (when (seq st) (let [a (clojure.string/split st (read-string "#\\" \\"")) c (map clojure.string/capitalize a)]  (->> c (interpose " ") (apply str) trim))))','STRING','Capitalizes each word in a string'),
          new transformationDataModel.CustomFunctionDeclaration('trim', '', 'STRING', 'Removes whitespace from both ends of string'),
          new transformationDataModel.CustomFunctionDeclaration('trim-newline',
        '', 'STRING', 'Removes all trailing newline \n or return \r characters from string'),
          new transformationDataModel.CustomFunctionDeclaration('triml', '', 'STRING',
        'Removes whitespace from the left side of string'),
          new transformationDataModel.CustomFunctionDeclaration('trimr', '', 'STRING',
        'Removes whitespace from the right side of string'),
          new transformationDataModel.CustomFunctionDeclaration('str', '', 'STRING',
        'With one arg x, returns x.toString(). (str nil) returns the empty string. With more than one arg, returns the concatenation of the str values of the args.'),
          new transformationDataModel.CustomFunctionDeclaration('rem', '', 'NUMBER',
        'Returns remainder of dividing numerator by denominator')];
    customfunctions.sort(function(a, b) {
      if (a.name > b.name) {
        return 1;

      } else {
        return -1;
      }

    });

    var predicatefunctions = [new transformationDataModel.CustomFunctionDeclaration(
        'empty?', '', 'PREDICATE', 'Returns true if given collection has no items'), new transformationDataModel.CustomFunctionDeclaration(
        'every?', '', 'PREDICATE',
        'Returns true if first argument predicate is logical true for every x in collection, else false'), new transformationDataModel
      .CustomFunctionDeclaration(
        'false?', '', 'PREDICATE', 'Returns true if given value is the value false, false otherwise'), new transformationDataModel
      .CustomFunctionDeclaration(
        'float?', '', 'PREDICATE', 'Returns true if given value is a floating point number'), new transformationDataModel
      .CustomFunctionDeclaration(
        'keyword?', '', 'PREDICATE', 'Return true if given argument is a Keyword'), new transformationDataModel.CustomFunctionDeclaration(
        'neg?', '', 'PREDICATE', 'Returns true if argument is less than zero, else false'), new transformationDataModel
      .CustomFunctionDeclaration(
        'nil?', '', 'PREDICATE', 'Returns true if argument is nil, false otherwise'), new transformationDataModel.CustomFunctionDeclaration(
        'number?', '', 'PREDICATE', 'Returns true if argument is a Number'), new transformationDataModel.CustomFunctionDeclaration(
        'odd?', '', 'PREDICATE', 'Returns true if argument is odd, throws an exception if it is not an integer'), new transformationDataModel
      .CustomFunctionDeclaration(
        'pos?', '', 'PREDICATE', 'Returns true if argument is greater than zero, else false'), new transformationDataModel
      .CustomFunctionDeclaration(
        'ratio?', '', 'PREDICATE', 'Returns true if argument is a Ratio'), new transformationDataModel.CustomFunctionDeclaration(
        'rational?', '', 'PREDICATE', 'Returns true if argument is a rational number'), new transformationDataModel.CustomFunctionDeclaration(
        'string?', '', 'PREDICATE', 'Return true if argument is a String'), new transformationDataModel.CustomFunctionDeclaration(
        'true?', '', 'PREDICATE', 'Returns true if argument is the value true, false otherwise'), new transformationDataModel
      .CustomFunctionDeclaration(
        'zero?', '', 'PREDICATE', 'Returns true if argument is zero, else false')];

    var numericcustomfunctions = [new transformationDataModel.CustomFunctionDeclaration(
        '+', '', 'NUMBER', ''),
                                    new transformationDataModel.CustomFunctionDeclaration(
        '-', '', 'NUMBER', ''),
                                    new transformationDataModel.CustomFunctionDeclaration(
        '*', '', 'NUMBER', ''),
                                    new transformationDataModel.CustomFunctionDeclaration(
        '/', '', 'NUMBER', '')];

    var allcustomfunctions = customfunctions.concat(predicatefunctions.concat(numericcustomfunctions));
    $scope.clojure = '';

    //Initial functions: Make dataset with first row from header and rename columns as keywords to allow referring to them
    var j;
    for (j = 0; j < customfunctions.length; ++j)
      if (customfunctions[j].name === 'keyword') break;

    $scope.pipeline = new transformationDataModel.Pipeline([/*makeds,renamecols*/]);
    $scope.transformation = new transformationDataModel.Transformation(
      allcustomfunctions, [], [$scope.pipeline], []);
    $rootScope.transformation = $scope.transformation;

    $rootScope.actions = {
      save: function(distributionId) {
        var clojure = generateClojure.fromTransformation($scope.transformation);

        var transformationType = 'pipe';
        var transformationCommand = 'my-pipe';

        if ($scope.transformation.graphs &&
          $scope.transformation.graphs.length !== 0) {
          transformationType = 'graft';
          transformationCommand = 'my-graft';
        }

        ontotextAPI.newTransformation({
          '@context': ontotextAPI.getContextDeclaration(),
          '@type': 'dcat:Transformation',
          'dct:title': $scope.document.title,
          'dct:description': $scope.document.description,
          'dcat:public': $scope.document['dct:public'] ? 'true' : 'false',
          'dct:modified': moment().format('YYYY-MM-DD'),
          'dcat:transformationType': transformationType,
          'dcat:transformationCommand': transformationCommand,
          'dcat:keyword': $scope.document.keywords
        }, clojure, $scope.transformation)
          .success(function(data) {
            $mdToast.show(
              $mdToast.simple()
              .content('Transformation saved')
              .position('bottom left')
              .hideDelay(6000)
            );
            if (distributionId) {
              $state.go('transformations.transformation.preview', {
                id: data['@id'],
                distribution: distributionId
              });
            } else {
              $state.go('transformations.transformation', {
                id: data['@id']
              });
            }
          });
      }
    };

    $scope.editPrefixers = function() {
      $scope.originalPrefixers = [];
      angular.copy($scope.transformation.prefixers, $scope.originalPrefixers);
      $mdDialog.show({
        templateUrl: 'views/editprefixes.html',
        controller: 'EditprefixersCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      }).then(
        function() {},

        function() {
          angular.copy($scope.originalPrefixers, $scope.transformation.prefixers);
        });
    };

    $scope.editLibraries = function() {
      $scope.originalLibraries = [];
      angular.copy($scope.transformation.libraries, $scope.originalLibraries);
      $mdDialog.show({
        templateUrl: 'views/editlibraries.html',
        controller: 'EditlibrariesCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      }).then(
        function() {},

        function() {
          angular.copy($scope.originalLibraries, $scope.transformation.libraries);
        });
    };

    $scope.editRDFPrefixes = function() {
      $mdDialog.show({
        templateUrl: 'views/MappingPrefixManage.html',
        controller: 'MappingPrefixManageCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      });
    };

    $scope.validateMapping = function() {
      $mdDialog.show({
        templateUrl: 'views/validateMapping.html',
        controller: 'validateMappingCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      });
    };

    $scope.defineCustomFunctions = function() {
      $scope.originalCustomFunctionDeclarations = [];
      angular.copy($scope.transformation.customFunctionDeclarations, $scope
        .originalCustomFunctionDeclarations);

      $mdDialog.show({
        templateUrl: 'views/createcustomfunction.html',
        controller: 'CustomfunctionsdialogcontrollerCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      }).then(
        function() {},

        function() {
          angular.copy($scope.originalCustomFunctionDeclarations, $scope.transformation
            .customFunctionDeclarations);
        });
    };

    $scope.defineStringCustomFunctions = function() {
      $mdDialog.show({
        templateUrl: 'views/createstringcustomfunction.html',
        controller: 'CustomStringfunctionsdialogcontrollerCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      });
    };

    $scope.$watch('fileUpload', function() {
      if ($scope.fileUpload) {
        var file = $scope.fileUpload;

        uploadFile.upload(file, function(data) {
          $rootScope.actions.save(data['@id']);
        });
      }
    });

    $scope.loadDistribution = function() {
      $mdDialog.show({
        templateUrl: 'views/loaddistribution.html',
        controller: 'LoadDistributionCtrl',
        scope: $scope.$new(false),
        clickOutsideToClose: true
      }).then(function(distribution) {
        $rootScope.actions.save(distribution);
      });
    };

  });
<commit_msg>Fix #118<commit_after>'use strict';

/**
 * @ngdoc function
 * @name grafterizerApp.controller:TransformationnewCtrl
 * @description
 * # TransformationnewCtrl
 * Controller of the grafterizerApp
 */
angular.module('grafterizerApp')
  .controller('TransformationNewCtrl', function(
    $scope,
    $stateParams,
    ontotextAPI,
    uploadFile,
    $rootScope,
    $state,
    $mdToast,
    $mdDialog,
    transformationDataModel,
    generateClojure) {

    $scope.readonlymode = false;

    $scope.document = {
      title: 'New transformation',
      description: '',
      keywords: []
    };

    var customfunctions = [
          new transformationDataModel.CustomFunctionDeclaration('replace-varible-string',
        '(defn replace-varible-string [cell]   (-> cell  (clojure.string/replace (read-string "#\\".* #\\"") "number") (clojure.string/replace (read-string "#\\"[0-9]{4} \\"") "") ))',
        'SERVICE', ''),
          new transformationDataModel.CustomFunctionDeclaration('add-filename-to-column',
        '(defn add-filename-to-column [ds destination-column] (let [fname (:grafter.tabular/data-source (meta ds))] (add-column ds destination-column fname)))     ',
        'SERVICE', ''),
          new transformationDataModel.CustomFunctionDeclaration('remove-columns',
        '(defn remove-columns [ds cols] (columns ds (remove (fn [item] (some (fn [a] (= item a)) cols )) (column-names ds)))) ',
        'SERVICE', 'Given a dataset and collection of column names narrows dataset to all but specified columns'),
          new transformationDataModel.CustomFunctionDeclaration('organize-date',
        '(defn organize-date "Transform date dd/mm/yyyy ~> yyyy-mm-dd" [date] (when (seq date)  (let [[d m y] (clojure.string/split date  (read-string "#\\"/\\""))]  (apply str (interpose "-" [y m d])))))',
        'DATE FUNCTIONS', 'Transform date dd/mm/yyyy ~> yyyy-mm-dd'),
          new transformationDataModel.CustomFunctionDeclaration('double-literal',
        '(defn double-literal [s] (Double/parseDouble s))', 'CONVERT DATATYPE', 'Coerce to integer'),
          new transformationDataModel.CustomFunctionDeclaration('integer-literal',
        '(defn integer-literal [s] (Integer/parseInt s))', 'CONVERT DATATYPE', 'Coerce to integer'),
          new transformationDataModel.CustomFunctionDeclaration('fill-when', '(defn fill-when [col] (grafter.sequences/fill-when col))', 'SERVICE',
        'Takes a sequence of values and copies a value through the sequence depending on the supplied predicate function'
      ),
          new transformationDataModel.CustomFunctionDeclaration('sort-dataset', '(defn sort-dataset  [ds col] (-> (make-dataset (sort-by col (:rows ds)) (column-names ds)) (with-meta (meta ds))))', 'SERVICE',
                         'Sorts a dataset by given column'
                              ),
              new transformationDataModel.CustomFunctionDeclaration('transform-gender',
        '(def transform-gender {"f" (s "female") "m" (s "male")})', 'UTILITY',
        'Maps "f" to "female" and "m" to "male"'),
          new transformationDataModel.CustomFunctionDeclaration('stringToNumeric',
        '(defn stringToNumeric    [x] (if (= "" x) nil  (if (.contains x ".") (Double/parseDouble x)(Integer/parseInt x))))',
        'CONVERT DATATYPE', 'Convert string to numeric'),
          new transformationDataModel.CustomFunctionDeclaration('string-literal', '(def string-literal s)',
        'CONVERT DATATYPE', 'Coerce to string'),
          new transformationDataModel.CustomFunctionDeclaration('boolean', '', 'CONVERT DATATYPE', 'Coerce to boolean'),
          new transformationDataModel.CustomFunctionDeclaration('count', '', 'COLLECTION',
        'Returns the number of items in the collection'),
          new transformationDataModel.CustomFunctionDeclaration('cast', '', 'CONVERT DATATYPE',
        ' Throws a ClassCastException if x is not a c, else returns x'),
          new transformationDataModel.CustomFunctionDeclaration('capitalize',
        '', 'STRING', 'Converts first character of the string to upper-case, all other characters to lower-case.'),
          new transformationDataModel.CustomFunctionDeclaration('dec', '', 'NUMBER',
        'Returns a number one less than num'),
          new transformationDataModel.CustomFunctionDeclaration('double', '', 'CONVERT DATATYPE', 'Coerce to double'),
          new transformationDataModel.CustomFunctionDeclaration('first', '', 'COLLECTION',
        'Returns the first item in the collection'),
          new transformationDataModel.CustomFunctionDeclaration('float', '', 'CONVERT DATATYPE', 'Coerce to float'),
          new transformationDataModel.CustomFunctionDeclaration('inc', '', 'NUMBER',
        'Returns a number one greater than num'),
          new transformationDataModel.CustomFunctionDeclaration('keyword', '', 'CONVERT DATATYPE',
        'Returns a Keyword with the given namespace and name. '),
          new transformationDataModel.CustomFunctionDeclaration('last', '', 'COLLECTION',
        'Return the last item in the collection'),
          new transformationDataModel.CustomFunctionDeclaration('long', '', 'CONVERT DATATYPE', 'Coerce to long'),
          new transformationDataModel.CustomFunctionDeclaration('name', '', 'CONVERT DATATYPE',
        'Returns the name String of a string, symbol or keyword'),
          new transformationDataModel.CustomFunctionDeclaration('second', '', 'COLLECTION',
        'Returns the second item in the collection'),
          new transformationDataModel.CustomFunctionDeclaration('short', '', 'CONVERT DATATYPE', 'Coerce to short'),
          new transformationDataModel.CustomFunctionDeclaration('join',
        '(defn join [& strings] (clojure.string/join " " strings))', 'STRING',
        'Returns a string of all elements in the collection separated by space.'),
          new transformationDataModel.CustomFunctionDeclaration('join-with',
        '(defn join-with [sep] ( fn [& strings] (clojure.string/join sep strings)))', 'STRING',
        'Returns a string of all elements in the collection separated by custom separator.'),
          new transformationDataModel.CustomFunctionDeclaration('lower-case',
        '', 'STRING', 'Converts string to all lower-case'),
          new transformationDataModel.CustomFunctionDeclaration('upper-case',
        '', 'STRING', 'Converts string to all upper-case'),
          new transformationDataModel.CustomFunctionDeclaration('reverse', '', 'STRING', 'Returns given string with its characters reversed'),
          new transformationDataModel.CustomFunctionDeclaration('string-as-keyword', '(defn string-as-keyword [s] ( when (seq s) (->   (str s) clojure.string/trim   (clojure.string/replace "(" "-") (clojure.string/replace ")" "") (clojure.string/replace " " "_") (clojure.string/replace "," "-") (clojure.string/replace "." "") (clojure.string/replace "/" "-") (clojure.string/replace "---" "-") (clojure.string/replace "--" "-") (clojure.string/replace ":" "") (clojure.string/replace "\\"" "") )))','STRING','Removes blanks and special symbols from a string thus making it possible to use it as a keyword'),
          new transformationDataModel.CustomFunctionDeclaration('remove-blanks', '(defn remove-blanks [s]  (when (seq s)  (clojure.string/replace s " " "")))','STRING','Removes blanks in a string'),
          new transformationDataModel.CustomFunctionDeclaration('titleize', '(defn titleize [st] (when (seq st) (let [a (clojure.string/split st (read-string "#\\" \\"")) c (map clojure.string/capitalize a)]  (->> c (interpose " ") (apply str) trim))))','STRING','Capitalizes each word in a string'),
          new transformationDataModel.CustomFunctionDeclaration('trim', '', 'STRING', 'Removes whitespace from both ends of string'),
          new transformationDataModel.CustomFunctionDeclaration('trim-newline',
        '', 'STRING', 'Removes all trailing newline \n or return \r characters from string'),
          new transformationDataModel.CustomFunctionDeclaration('triml', '', 'STRING',
        'Removes whitespace from the left side of string'),
          new transformationDataModel.CustomFunctionDeclaration('trimr', '', 'STRING',
        'Removes whitespace from the right side of string'),
          new transformationDataModel.CustomFunctionDeclaration('str', '', 'STRING',
        'With one arg x, returns x.toString(). (str nil) returns the empty string. With more than one arg, returns the concatenation of the str values of the args.'),
          new transformationDataModel.CustomFunctionDeclaration('rem', '', 'NUMBER',
        'Returns remainder of dividing numerator by denominator')];
    customfunctions.sort(function(a, b) {
      if (a.name > b.name) {
        return 1;

      } else {
        return -1;
      }

    });

    var predicatefunctions = [new transformationDataModel.CustomFunctionDeclaration(
        'empty?', '', 'PREDICATE', 'Returns true if given collection has no items'), new transformationDataModel.CustomFunctionDeclaration(
        'every?', '', 'PREDICATE',
        'Returns true if first argument predicate is logical true for every x in collection, else false'), new transformationDataModel
      .CustomFunctionDeclaration(
        'false?', '', 'PREDICATE', 'Returns true if given value is the value false, false otherwise'), new transformationDataModel
      .CustomFunctionDeclaration(
        'float?', '', 'PREDICATE', 'Returns true if given value is a floating point number'), new transformationDataModel
      .CustomFunctionDeclaration(
        'keyword?', '', 'PREDICATE', 'Return true if given argument is a Keyword'), new transformationDataModel.CustomFunctionDeclaration(
        'neg?', '', 'PREDICATE', 'Returns true if argument is less than zero, else false'), new transformationDataModel
      .CustomFunctionDeclaration(
        'nil?', '', 'PREDICATE', 'Returns true if argument is nil, false otherwise'), new transformationDataModel.CustomFunctionDeclaration(
        'number?', '', 'PREDICATE', 'Returns true if argument is a Number'), new transformationDataModel.CustomFunctionDeclaration(
        'odd?', '', 'PREDICATE', 'Returns true if argument is odd, throws an exception if it is not an integer'), new transformationDataModel
      .CustomFunctionDeclaration(
        'pos?', '', 'PREDICATE', 'Returns true if argument is greater than zero, else false'), new transformationDataModel
      .CustomFunctionDeclaration(
        'ratio?', '', 'PREDICATE', 'Returns true if argument is a Ratio'), new transformationDataModel.CustomFunctionDeclaration(
        'rational?', '', 'PREDICATE', 'Returns true if argument is a rational number'), new transformationDataModel.CustomFunctionDeclaration(
        'string?', '', 'PREDICATE', 'Return true if argument is a String'), new transformationDataModel.CustomFunctionDeclaration(
        'true?', '', 'PREDICATE', 'Returns true if argument is the value true, false otherwise'), new transformationDataModel
      .CustomFunctionDeclaration(
        'zero?', '', 'PREDICATE', 'Returns true if argument is zero, else false')];

    var numericcustomfunctions = [new transformationDataModel.CustomFunctionDeclaration(
        '+', '', 'NUMBER', ''),
                                    new transformationDataModel.CustomFunctionDeclaration(
        '-', '', 'NUMBER', ''),
                                    new transformationDataModel.CustomFunctionDeclaration(
        '*', '', 'NUMBER', ''),
                                    new transformationDataModel.CustomFunctionDeclaration(
        '/', '', 'NUMBER', '')];

    var allcustomfunctions = customfunctions.concat(predicatefunctions.concat(numericcustomfunctions));
    $scope.clojure = '';

    //Initial functions: Make dataset with first row from header and rename columns as keywords to allow referring to them
    var j;
    for (j = 0; j < customfunctions.length; ++j)
      if (customfunctions[j].name === 'keyword') break;

    $scope.pipeline = new transformationDataModel.Pipeline([/*makeds,renamecols*/]);
    $scope.transformation = new transformationDataModel.Transformation(
      allcustomfunctions, [], [$scope.pipeline], []);
    $rootScope.transformation = $scope.transformation;

    $rootScope.actions = {
      save: function(distributionId) {
        var clojure = generateClojure.fromTransformation($scope.transformation);

        var transformationType = 'pipe';
        var transformationCommand = 'my-pipe';

        if ($scope.transformation.graphs &&
          $scope.transformation.graphs.length !== 0) {
          transformationType = 'graft';
          transformationCommand = 'my-graft';
        }

        ontotextAPI.newTransformation({
          '@context': ontotextAPI.getContextDeclaration(),
          '@type': 'dcat:Transformation',
          'dct:title': $scope.document.title,
          'dct:description': $scope.document.description,
          'dcat:public': $scope.document['dct:public'] ? 'true' : 'false',
          'dct:modified': moment().format('YYYY-MM-DD'),
          'dcat:transformationType': transformationType,
          'dcat:transformationCommand': transformationCommand,
          'dcat:keyword': $scope.document.keywords
        }, clojure, $scope.transformation)
          .success(function(data) {
            $mdToast.show(
              $mdToast.simple()
              .content('Transformation saved')
              .position('bottom left')
              .hideDelay(6000)
            );
            if (distributionId) {
              $state.go('transformations.transformation.preview', {
                id: data['@id'],
                distribution: distributionId
              });
            } else {
              $state.go('transformations.transformation', {
                id: data['@id']
              });
            }
          });
      }
    };

    $scope.editPrefixers = function() {
      $scope.originalPrefixers = [];
      angular.copy($scope.transformation.prefixers, $scope.originalPrefixers);
      $mdDialog.show({
        templateUrl: 'views/editprefixes.html',
        controller: 'EditprefixersCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      }).then(
        function() {},

        function() {
          angular.copy($scope.originalPrefixers, $scope.transformation.prefixers);
        });
    };

    $scope.editLibraries = function() {
      $scope.originalLibraries = [];
      angular.copy($scope.transformation.libraries, $scope.originalLibraries);
      $mdDialog.show({
        templateUrl: 'views/editlibraries.html',
        controller: 'EditlibrariesCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      }).then(
        function() {},

        function() {
          angular.copy($scope.originalLibraries, $scope.transformation.libraries);
        });
    };

    $scope.editRDFPrefixes = function() {
      $mdDialog.show({
        templateUrl: 'views/MappingPrefixManage.html',
        controller: 'MappingPrefixManageCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      });
    };

    $scope.validateMapping = function() {
      $mdDialog.show({
        templateUrl: 'views/validateMapping.html',
        controller: 'validateMappingCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      });
    };

    $scope.defineCustomFunctions = function() {
      $scope.originalCustomFunctionDeclarations = [];
      angular.copy($scope.transformation.customFunctionDeclarations, $scope
        .originalCustomFunctionDeclarations);

      $mdDialog.show({
        templateUrl: 'views/createcustomfunction.html',
        controller: 'CustomfunctionsdialogcontrollerCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      }).then(
        function() {},

        function() {
          angular.copy($scope.originalCustomFunctionDeclarations, $scope.transformation
            .customFunctionDeclarations);
        });
    };

    $scope.defineStringCustomFunctions = function() {
      $mdDialog.show({
        templateUrl: 'views/createstringcustomfunction.html',
        controller: 'CustomStringfunctionsdialogcontrollerCtrl',
        scope: $scope.$new(false, $scope),
        clickOutsideToClose: true
      });
    };

    $scope.$watch('fileUpload', function() {
      if ($scope.fileUpload) {
        var file = $scope.fileUpload;

        uploadFile.upload(file, function(data) {
          $rootScope.actions.save(data['@id']);
        });
      }
    });

    $scope.loadDistribution = function() {
      $mdDialog.show({
        templateUrl: 'views/loaddistribution.html',
        controller: 'LoadDistributionCtrl',
        scope: $scope.$new(false),
        clickOutsideToClose: true
      }).then(function(distribution) {
        $rootScope.actions.save(distribution);
      });
    };

  });
<|endoftext|>


<commit_before>// Constants.
var noteDuration = 1.0;
var noteVolume = 1.0;
var defaultOctave = 5;

// Octave of the previous note.
var previousOctave = defaultOctave;

// Audio context for playing notes.
var audio = new (window.AudioContext || window.webkitAudioContext)()

function playNote(frequency, volume, duration)
{
    var halfPeriod = 1 / frequency / 2;
    if (duration > halfPeriod) {
        duration -= duration % halfPeriod;
    } else {
        duration = halfPeriod;
    }

    var g = audio.createGain();
    var o = audio.createOscillator();
    o.connect(g);
    g.connect(audio.destination);

    o.frequency.value = frequency;
    g.gain.value = volume;
    o.start(0);
    o.stop(audio.currentTime + duration);
}

// Returns true if the note is valid.
function validateNote(note) {
	if(note.length > 2 || note.length == 0) {
		return false;
	}

	if (note[0] >= "a" && note[0] <= "z") {
		note[0] = note[0] + ("a" - "A");
	}

	if(note[0] < "A" || note[0] > "G") {
		return false;
	}

	if(note.length ==2 && (note[1] < "0" || note[1] > "8" )) {
		return false;
	}
	else return true;
}

// Returns 0 for C, 1 for D, ..., 5 for A, 6 for B.
function letterToPitchIndex(letter) {
	if (letter >= "A" && letter <= "B") {
		return letter - "A" + 5;
	}
	else return letter - "C";
}

// Converts the note to a frequency. Assumes letter is uppercase.
function noteToFrequency(note) {
	var pitchIndex = letterToPitchIndex(note[0]);
	var octave = (note.length == 2) ? note[1] - "0" : previousOctave;
	previousOctave = octave;
	var i = 7*octave + pitchIndex;
	return 16.35 * Math.pow (2, i/7);

}

function play() {
	var melody = document.getElementById("melody").value;
	var notes = melody.split(" ");

	// Validate all the notes.
	for (var i = 0; i < notes.length; i++) {
		if (!validateNote(notes[i])) {
			alert("Invalid note " + notes[i] + ". Try again!");
			return;
		}
	}

	// Play the notes.
	for (var i = 0; i < notes.length; i++) {
		playNote(noteToFrequency(notes[i]), noteVolume, noteDuration);
	}
}

function playWithHarmony() {
	alert("This should play with harmony.");
}<commit_msg>It's working :)<commit_after>// Constants.
var noteDuration = 1.0;
var noteVolume = 1.0;
var defaultOctave = 5;

// Octave of the previous note.
var previousOctave;

// Audio context for playing notes.
var audio = new (window.AudioContext || window.webkitAudioContext)();

function playNote(frequency, volume, duration)
{
    var halfPeriod = 1 / frequency / 2;
    if (duration > halfPeriod) {
        duration -= duration % halfPeriod;
    } else {
        duration = halfPeriod;
    }

    var g = audio.createGain();
    var o = audio.createOscillator();
    o.connect(g);
    g.connect(audio.destination);

    o.frequency.value = frequency;
    g.gain.value = volume;
    o.start(0);
    o.stop(audio.currentTime + duration);
}

// Returns true if the note is valid.
function validateNote(note) {
	if(note.length > 2 || note.length == 0) {
		return false;
	}

	if(note[0] < "A" || note[0] > "G") {
		return false;
	}

	if(note.length ==2 && (note[1] < "0" || note[1] > "8" )) {
		return false;
	}
	else return true;
}

// Returns 0 for C, 1 for D, ..., 5 for A, 6 for B.
function letterToPitchIndex(letter) {
	if (letter >= "A" && letter <= "B") {
		return letter.charCodeAt(0) - "A".charCodeAt(0) + 5;
	}
	else return letter.charCodeAt(0) - "C".charCodeAt(0);
}

// Converts the note to a frequency. Assumes letter is uppercase.
function noteToFrequency(note) {
	var pitchIndex = letterToPitchIndex(note[0]);
	var octave = (note.length == 2) ? note[1] - "0" : previousOctave;
	previousOctave = octave;
	var i = 7*octave + pitchIndex;
	return 16.35 * Math.pow (2, i/7);

}

function play() {
	previousOctave = defaultOctave;
	var melody = document.getElementById("melody").value;
	var notes = melody.split(" ");

	// Validate all the notes.
	for (var i = 0; i < notes.length; i++) {
		notes[i] = notes[i].toUpperCase();
		if (!validateNote(notes[i])) {
			alert("Invalid note " + notes[i] + ". Try again!");
			return;
		}
	}

	// Play the notes.
	var i = 0;
	var playNext = function() {
		playNote(noteToFrequency(notes[i]), noteVolume, noteDuration);
		i++;
		if (i < notes.length) {
			setTimeout(playNext, noteDuration * 1000);
		}
	}
	playNext();
}

function playWithHarmony() {
	alert("This should play with harmony.");
}<|endoftext|>


<commit_before>$(function () {

    $(".cartNavInner").each(function () {
        appendDiscontinued(this);
    });

    $(".stockOpen").each(function () {
        var stockLink = "http://www.yodobashi.com/" + $(this).attr('rel');
        getStock(stockLink, this);
    });
});
function getStock(stockUrl, target)
{
    var myStoreName = "";
    chrome.runtime.sendMessage({action: "getLocalStorage"}, function(response) {
      if (response["store_name"]) {
        myStoreName = response["store_name"];
      }
    });

    $.ajax({
        url : stockUrl,
    }).done(function (data)
    {
        var stock = "在庫なし";
        $(data).find(".storeInfoUnit").each(function () {
            var storeName = $(this).find(".storeName").text();
            if (storeName == myStoreName) {
                stock = $(this).find(".uiIconTxtS").text();
            }
        });
        $(target).html(myStoreName + ":" + stock);
    }).fail(function (data) {
    });
}

function appendDiscontinued(target) {
    var newInput = $(target).html() + "<input type='hidden' name='discontinued' value='false'>";
    $(target).html(newInput);
}
<commit_msg>Format code<commit_after>$(function () {

    $(".cartNavInner").each(function () {
        appendDiscontinued(this);
    });

    $(".stockOpen").each(function () {
        var stockLink = "http://www.yodobashi.com/" + $(this).attr('rel');
        getStock(stockLink, this);
    });
});

function getStock(stockUrl, target) {
    var myStoreName = "";
    chrome.runtime.sendMessage({action: "getLocalStorage"}, function (response) {
        if (response["store_name"]) {
            myStoreName = response["store_name"];
        }
    });

    $.ajax({
        url: stockUrl,
    }).done(function (data) {
        var stock = "在庫なし";
        $(data).find(".storeInfoUnit").each(function () {
            var storeName = $(this).find(".storeName").text();
            if (storeName == myStoreName) {
                stock = $(this).find(".uiIconTxtS").text();
            }
        });
        $(target).html(myStoreName + ":" + stock);
    }).fail(function (data) {
    });
}

function appendDiscontinued(target) {
    var newInput = $(target).html() + "<input type='hidden' name='discontinued' value='false'>";
    $(target).html(newInput);
}
<|endoftext|>


<commit_before>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
//prompt: (bot) => bot.say('...'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}, waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
        .then(() => 'selecteerHypotheek');
    }
},

selecteerHypotheek: {
    receive: (bot, message) => {

      switch(message.text) {
        case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => '')
        case 'hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => '')
        case 'Starters hypotheek':
          return bot.say(`Daar help ik je graag bij. Weet je al wat voor soort woning?`)
          .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
            .then(() => bot.say(`%[Appartement](postback:hypotheekkeuze_appartement) %[Tussenwoning](postback:hypotheekkeuze_tussenwoning) %[Vrijstaand](postback:hypotheekkeuze_vrijstaand)`))
            .then(() => 'askName')
          break;
        case 'Nieuwe hypotheek':
          return bot.say(`Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`))
            .then(() => 'processing')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`Sorry. Momenteel biedt Independer alleen hypotheken aan voor Starters.`)
            .then(() => 'bye')
          break;
        default:
          return bot.say(`...`)
            .then(() => 'processing')
          break;
      }
    }
},
hypotheekkeuze_appartement: {
  //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    //receive: () => 'processing'
      receive: () => 'vervolgVragen'
},
hypotheekkeuze_tussenwoning: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    //receive: () => 'processing'
      receive: () => 'vervolgVragen'
},
hypotheekkeuze_vrijstaand: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    //receive: () => 'processing'
      receive: () => 'vervolgVragen'
},
hypotheektype_nieuw: {
//    prompt: (bot) => bot.say(`Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`),
    receive: () => 'bye'
},

vervolgVragen: {
  receive: (bot, message) => {
    switch(message.text) {
        case 'Appartement':
          return bot.say(`Top!`)
          .then(() => 'askName')
        break;
      default:
        return bot.say(`...`)
          .then(() => 'processing')
        break;
    }
    }
},

askName: {
    prompt: (bot) => bot.say('Top - maar met wie heb ik het genoegen?'),
    receive: (bot, message) => {
        const name = message.text;
        return bot.setProp('name', name)
            .then(() => bot.say(`Hoi ${name}. ik heb nog wat vragen voor je om verder te kunnen.`))
            .then(() => 'vervolgVragen');
    }
},

bye: {
    prompt: (bot) => bot.say('Bedankt voor je tijd'),
    receive: () => 'processing'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => ''
// },

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<commit_msg>script<commit_after>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
//prompt: (bot) => bot.say('...'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}, waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
        .then(() => 'selecteerHypotheek');
    }
},

selecteerHypotheek: {
    receive: (bot, message) => {

      switch(message.text) {
        case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => '')
        case 'hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => '')
        case 'Starters hypotheek':
          return bot.say(`Daar help ik je graag bij. Weet je al wat voor soort woning?`)
          .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
            .then(() => bot.say(`%[Appartement](postback:hypotheekkeuze_appartement) %[Tussenwoning](postback:hypotheekkeuze_tussenwoning) %[Vrijstaand](postback:hypotheekkeuze_vrijstaand)`))
            .then(() => 'askName')
          break;
        case 'Nieuwe hypotheek':
          return bot.say(`Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`))
            .then(() => 'processing')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`Sorry. Momenteel biedt Independer alleen hypotheken aan voor Starters.`)
            .then(() => 'bye')
          break;
        default:
          return bot.say(`...`)
            .then(() => 'processing')
          break;
      }
    }
},
hypotheekkeuze_appartement: {
  //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'processing'
},
hypotheekkeuze_tussenwoning: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'processing'
},
hypotheekkeuze_vrijstaand: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'processing'
},
hypotheektype_nieuw: {
//    prompt: (bot) => bot.say(`Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`),
    receive: () => 'bye'
},

vervolgVragen: {
  receive: (bot, message) => {
    switch(message.text) {
        case 'Appartement':
          return bot.say(`Top!`)
          .then(() => 'askName')
        break;
      default:
        return bot.say(`...`)
          .then(() => 'processing')
        break;
    }
    }
},

askName: {
    prompt: (bot) => bot.say('Top - maar met wie heb ik het genoegen?'),
    receive: (bot, message) => {
        const name = message.text;
        return bot.setProp('name', name)
            .then(() => bot.say(`Hoi ${name}. ik heb nog wat vragen voor je om verder te kunnen.`))
            .then(() => 'vervolgVragen');
    }
},

bye: {
    prompt: (bot) => bot.say('Bedankt voor je tijd'),
    receive: () => 'processing'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => ''
// },

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<|endoftext|>


<commit_before>(function() {
    'use strict';

    // Variables with names starting with '$' are DOM-elements.
    // Function and variables with names starting with 'g' are global.
    // Variables with names starting with 'a' are parameters.

    var $buttonsContainer = document.getElementById('buttons_container'),
        $canvas = document.getElementById('canvas'),
        gCtx = $canvas.getContext('2d'),
        gCanvasMetrics = {
            DEFAULT_WIDTH: 640,
            DEFAULT_HEIGHT: 480,
            width: null,
            height: null,
            scaleFactor: null,
            offsetX: null,
            offsetY: null,
        },
        gImagesPaths = ['img/card1.png', 'img/card2.png', 'img/card3.png'],
        gImages = {};

    gInitCanvasResizing();
    gStartImagesLoading();

    function gInitCanvasResizing() {
        var debounceTmt = null;

        //initial canvas size setting
        setCanvasSize();

        window.onresize = function() {
            clearTimeout(debounceTmt);
            debounceTmt = setTimeout(setCanvasSize, 100);
        };

        function setCanvasSize() {
            gCanvasMetrics.width = window.innerWidth;
            gCanvasMetrics.height = window.innerHeight;

            $canvas.width = gCanvasMetrics.width;
            $canvas.height = gCanvasMetrics.height;
            console.log('Canvas size is set to ' + gCanvasMetrics.width + 'x' + gCanvasMetrics.height);

            gCanvasMetrics.scaleFactor = Math.min(gCanvasMetrics.width/gCanvasMetrics.DEFAULT_WIDTH,
                                                 gCanvasMetrics.height/gCanvasMetrics.DEFAULT_HEIGHT);
            console.log('Scale factor is set to ' + gCanvasMetrics.scaleFactor);

            gCanvasMetrics.offsetX = Math.floor((gCanvasMetrics.width - gCanvasMetrics.DEFAULT_WIDTH*gCanvasMetrics.scaleFactor)/2);
            gCanvasMetrics.offsetY = Math.floor((gCanvasMetrics.height - gCanvasMetrics.DEFAULT_HEIGHT*gCanvasMetrics.scaleFactor)/2);
            console.log('Offsets: x=' + gCanvasMetrics.offsetX + ', y=' + gCanvasMetrics.offsetY);
        }
    }

    function gStartImagesLoading() {
        for (var i = 0, len = gImagesPaths.length; i < len; i++) {
            gImages[i] = new Image();
            gImages[i].onload = addButtonForImage.bind(null, i, len - 1);
            gImages[i].src = gImagesPaths[i];
        }

        function addButtonForImage(aNumber, aTotal) {
            console.log('Image ' + aNumber + ' is loaded.');

            var $button = document.createElement('button');
            $button.className = 'image_button';
            $button.textContent = 'Image ' + aNumber;
            $button.style.top = gCanvasMetrics.height*0.8 + 'px';
            $button.style.left = (gCanvasMetrics.offsetX + gCanvasMetrics.scaleFactor*gCanvasMetrics.DEFAULT_WIDTH*(0.1 + 0.8*aNumber/aTotal)) + 'px';
            $buttonsContainer.insertBefore($button, null);
        }
    }
})();<commit_msg>Add buttons repositioning on window resize<commit_after>(function() {
    'use strict';

    // Variables with names starting with '$' are DOM-elements.
    // Function and variables with names starting with 'g' are global.
    // Variables with names starting with 'a' are parameters.

    var $buttonsContainer = document.getElementById('buttons_container'),
        $canvas = document.getElementById('canvas'),
        gCtx = $canvas.getContext('2d'),
        gCanvasMetrics = {
            DEFAULT_WIDTH: 640,
            DEFAULT_HEIGHT: 480,
            width: null,
            height: null,
            scaleFactor: null,
            offsetX: null,
            offsetY: null,
        },
        gImagesPaths = ['img/card1.png', 'img/card2.png', 'img/card3.png'],
        gImages = {},
        gButtons = [];

    gInitCanvasAndButtonsResizing();
    gStartImagesLoading();

    function gInitCanvasAndButtonsResizing() {
        var debounceTmt = null;

        //initial canvas size setting
        setCanvasSize();

        window.onresize = function() {
            clearTimeout(debounceTmt);
            debounceTmt = setTimeout(function() {
                setCanvasSize();
                setButtonsPosition();
            }, 100);
        };

        function setCanvasSize() {
            gCanvasMetrics.width = window.innerWidth;
            gCanvasMetrics.height = window.innerHeight;

            $canvas.width = gCanvasMetrics.width;
            $canvas.height = gCanvasMetrics.height;
            console.log('Canvas size is set to ' + gCanvasMetrics.width + 'x' + gCanvasMetrics.height);

            gCanvasMetrics.scaleFactor = Math.min(gCanvasMetrics.width/gCanvasMetrics.DEFAULT_WIDTH,
                                                 gCanvasMetrics.height/gCanvasMetrics.DEFAULT_HEIGHT);
            console.log('Scale factor is set to ' + gCanvasMetrics.scaleFactor);

            gCanvasMetrics.offsetX = Math.floor((gCanvasMetrics.width - gCanvasMetrics.DEFAULT_WIDTH*gCanvasMetrics.scaleFactor)/2);
            gCanvasMetrics.offsetY = Math.floor((gCanvasMetrics.height - gCanvasMetrics.DEFAULT_HEIGHT*gCanvasMetrics.scaleFactor)/2);
            console.log('Offsets: x=' + gCanvasMetrics.offsetX + ', y=' + gCanvasMetrics.offsetY);
        }

        function setButtonsPosition() {
            for (var i = 0, len = gButtons.length; i < len; i++) {
                gSetButtonPosition(gButtons[i]);
            }
        }
    }

    function gSetButtonPosition(aButton) {
        aButton.style.top = gCanvasMetrics.height*0.8 + 'px';
        aButton.style.left = (gCanvasMetrics.offsetX + gCanvasMetrics.scaleFactor*gCanvasMetrics.DEFAULT_WIDTH*(0.1 + 0.8*aButton.number/(gImagesPaths.length - 1))) + 'px';
    }

    function gStartImagesLoading() {
        for (var i = 0, len = gImagesPaths.length; i < len; i++) {
            gImages[i] = new Image();
            gImages[i].onload = addButtonForImage.bind(null, i);
            gImages[i].src = gImagesPaths[i];
        }

        function addButtonForImage(aNumber) {
            console.log('Image ' + aNumber + ' is loaded.');

            var $button = document.createElement('button');
            $button.className = 'image_button';
            $button.textContent = 'Image ' + (aNumber + 1);
            $button.number = aNumber;

            gSetButtonPosition($button);

            $buttonsContainer.insertBefore($button, null);

            gButtons.push($button);

            $button.onclick = function() {
            };
        }
    }
})();<|endoftext|>


<commit_before>// Edit the initial year
var year = "1910";

// Edit the center point and zoom level
var map = L.map('map', {
  center: [41.79, -72.6],
  zoom: 10,
  scrollWheelZoom: false
});

// Edit links to your GitHub repo and data source credit
map.attributionControl
.setPrefix('View data and code on GitHub, created with Leaflet; design by CT Mirror');

// basemap layer
new L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors, © CartoDB'
}).addTo(map);

 // Edit the getColor property to match data column header in your GeoJson file
 function style(feature) {
   return {
     fillColor: getColor(feature.properties["index" + year]),
     weight: 1,
     opacity: 1,
     color: 'black',
     fillOpacity: 0.7,
   };
 }

// Edit to upload GeoJSON data file from your local directory; removed var = geoJsonLayer since this is declared above
$.getJSON("towns-index.geojson", function (data) {
  geoJsonLayer = L.geoJson(data, {
    style: style,
    onEachFeature: onEachFeature
  }).addTo(map);
});

// this highlights the layer on hover
function highlightFeature(e) {
  var layer = e.target;

  layer.setStyle({
    weight: 4,
    color: 'black',
    fillOpacity: 0.7
  });

  info.update(layer.feature.properties);
}

// this resets the highlight after hover moves away; revised
function resetHighlight(e) {
  geoJsonLayer.setStyle(style);
  info.update();
}

function onEachFeature(feature, layer) {
  layer.on({
    mouseover: highlightFeature,
    mouseout: resetHighlight,
    click: highlightFeature
  });
}

// Edit ranges and colors to match your data; see http://colorbrewer.org
function getColor(d) {
  return d > 2 ? '#800026' :
         d > 1.5 ? '#BD0026' :
         d > 1  ? '#E31A1C' :
         d > 0.5  ? '#FC4E2A' :
         d > 0  ? '#FD8D3C' :
                    '#ffffff';
}

var info = L.control();

info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
    this.update();
    return this._div;
  };

// method that we will use to update the control based on feature properties passed
info.update = function (props) {
  var winName =
  this._div.innerHTML = (props ?
    '
' + props.town.toProperCase() + '
' : '
Hover over towns
') + '

Home Value Index
' +(props ? '' + (checkNull(props["index" + year])) : '--') + '
';
};

info.addTo(map);

// Check this
$(".tabItem").click(function() {
  $(".tabItem").removeClass("selected");
  $(this).addClass("selected");
  // year = $(this).html().split("-")[1];  /* for school years */
  year = $(this).html();
  geoJsonLayer.setStyle(style);
});

String.prototype.toProperCase = function () {
  return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

function checkNull(val) {
  if (val != null || val == "NaN") {
    return comma(val);
  } else {
    return "--";
  }
}

function checkThePct(a,b) {
  if (a != null && b != null) {
    return Math.round(a/b*1000)/10 + "%";
  } else {
    return "--";
  }
}

function comma(val){
  while (/(\d+)(\d{3})/.test(val.toString())){
    val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
  }
  return val;
}

// });
<commit_msg>new fill color<commit_after>// Edit the initial year
var year = "1910";

// Edit the center point and zoom level
var map = L.map('map', {
  center: [41.79, -72.6],
  zoom: 10,
  scrollWheelZoom: false
});

// Edit links to your GitHub repo and data source credit
map.attributionControl
.setPrefix('View data and code on GitHub, created with Leaflet; design by CT Mirror');

// basemap layer
new L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors, © CartoDB'
}).addTo(map);

 // Edit the getColor property to match data column header in your GeoJson file
function style(feature) {
  return {
    fillColor: getColor(feature.properties["index" + year]),
    weight: 1,
    opacity: 1,
    color: 'black',
    fillOpacity: 0.8,
  };
}

// Edit to upload GeoJSON data file from your local directory; removed var = geoJsonLayer since this is declared above
$.getJSON("towns-index.geojson", function (data) {
  geoJsonLayer = L.geoJson(data, {
    style: style,
    onEachFeature: onEachFeature
  }).addTo(map);
});

// this highlights the layer on hover
function highlightFeature(e) {
  var layer = e.target;

  layer.setStyle({
    weight: 4,
    color: 'black',
    fillOpacity: 0.7
  });

  info.update(layer.feature.properties);
}

// this resets the highlight after hover moves away; revised
function resetHighlight(e) {
  geoJsonLayer.setStyle(style);
  info.update();
}

function onEachFeature(feature, layer) {
  layer.on({
    mouseover: highlightFeature,
    mouseout: resetHighlight,
    click: highlightFeature
  });
}

// Edit ranges and colors to match your data; see http://colorbrewer.org
function getColor(d) {
  return d > 2.0 ? '#006d2c' :
         d > 1.5 ? '#2ca25f' :
         d > 1.0 ? '#66c2a4' :
         d > 0.5 ? '#b2e2e2' :
         d > 0.1 ? '#edf8fb' :
                   '#ffffff' ;
}

var info = L.control();

info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
    this.update();
    return this._div;
  };

// method that we will use to update the control based on feature properties passed
info.update = function (props) {
  var winName =
  this._div.innerHTML = (props ?
    '
' + props.town.toProperCase() + '
' : '
Hover over towns
') + '

Home Value Index
' +(props ? '' + (checkNull(props["index" + year])) : '--') + '
';
};

info.addTo(map);

// Check this
$(".tabItem").click(function() {
  $(".tabItem").removeClass("selected");
  $(this).addClass("selected");
  // year = $(this).html().split("-")[1];  /* for school years */
  year = $(this).html();
  geoJsonLayer.setStyle(style);
});

String.prototype.toProperCase = function () {
  return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

function checkNull(val) {
  if (val != null || val == "NaN") {
    return comma(val);
  } else {
    return "--";
  }
}

function checkThePct(a,b) {
  if (a != null && b != null) {
    return Math.round(a/b*1000)/10 + "%";
  } else {
    return "--";
  }
}

function comma(val){
  while (/(\d+)(\d{3})/.test(val.toString())){
    val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
  }
  return val;
}

// });
<|endoftext|>


<commit_before>const faceColor = '#272B2A',
      borderColor = '#569E92',
      handColor = '#526A5D',
      numbersColor = '#FFFDB6',
      markersColor = '#9FFE00',
      numbersFont = 'px Cinzel',
      titleText = 'MilliClock',
      titleFont = 'px Tangerine',
      textAM = 'AM',
      textPM = 'PM',
      periodFont = 'px "Expletus Sans"',
      canvas = document.getElementById('canvas'),
      ctx = canvas.getContext('2d'),
      fps = 60;
      ms = 1000 / fps;
      circle = 2 * Math.PI,
      piPer6 = Math.PI / 6,
      piPer30 = Math.PI / 30,
      piPer360 = Math.PI / 360,
      piPer500 = Math.PI / 500,
      piPer1800 = Math.PI / 1800,
      piPer21600 = Math.PI / 21600,
      piPer30000 = Math.PI / 30000,
      piPer1800000 = Math.PI / 1800000,
      piPer21600000 = Math.PI / 21600000;

let resizeTimeout = null,
    radius = 0,
    grad = {},
    x = 0,
    y = 0,
    now = {},
    hour = 0,
    minute = 0,
    second = 0,
    millisecond = 0,
    ang = 0;
    text = '',
    gradRadius0 = 0,
    gradRadius1 = 0,
    size01 = 0,
    numTranslate = 0,
    titleSize = 0,
    textTranslate = 0,
    markersTranslate = 0,
    markersSmall = 0,
    markersBig = 0,
    hourSize = 0,
    minuteSize = 0,
    secondSize = 0,
    millisecondSize = 0,
    hourSize2 = 0,
    minuteSize2 = 0,
    secondSize2 = 0,
    millisecondSize2 = 0,
    hourWidth = 0,
    minuteWidth = 0,
    secondWidth = 0,
    millisecondWidth = 0;

(function() {
  resizeAndDraw();
  window.addEventListener('resize', resizeThrottler, false);
}());

function resizeThrottler() {
  if (!resizeTimeout) {
    resizeTimeout = setTimeout(function() {
      resizeTimeout = null;
      resizeAndDraw();
    }, ms);
  }
}

function resizeAndDraw() {
  // handle the resize event
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  radius = 0.9 * Math.min(canvas.width, canvas.height) / 2;
  setSizes(radius);
  x = canvas.width / 2;
  y = canvas.height / 2;
  ctx.translate(x, y);
  grad = ctx.createRadialGradient(0, 0, gradRadius0, 0, 0, gradRadius1);
  grad.addColorStop(0, faceColor);
  grad.addColorStop(0.5, borderColor);
  grad.addColorStop(1, handColor);
  setInterval(drawClock, 1);
}

function setSizes(radius) {
  gradRadius0 = radius * 0.97;
  gradRadius1 = radius * 1.03;
  size01 = radius * 0.1;
  numTranslate = radius * 0.85;
  titleSize = radius * 0.12;
  textTranslate = radius / 2.4;
  markersTranslate = radius * 0.94;
  markersSmall = radius * 0.005;
  markersBig = radius * 0.008;
  hourSize = radius * 0.5;
  minuteSize = radius * 0.7;
  secondSize = radius * 0.9;
  millisecondSize = radius * 0.06;
  hourSize2 = hourSize * 0.1;
  minuteSize2 = minuteSize * 0.1;
  secondSize2 = secondSize * 0.1;
  millisecondSize2 = millisecondSize * 0.1;
  hourWidth = radius * 0.03;
  minuteWidth = radius * 0.02;
  secondWidth = radius * 0.01;
  millisecondWidth = radius * 0.007;
}

function drawClock() {
  now = new Date();
  hour = now.getHours();
  minute = now.getMinutes();
  second = now.getSeconds();
  millisecond = now.getMilliseconds();
  text = hour < 12 ? textAM : textPM;
  drawFace();
  drawMarkers();
  drawNumbers();
  drawText();
  drawTime();
}

function drawFace() {
  ctx.beginPath();
  ctx.arc(0, 0, radius, 0, circle);
  ctx.fillStyle = faceColor;
  ctx.fill();
  ctx.strokeStyle = grad;
  ctx.lineWidth = size01;
  ctx.stroke();
}

function drawMarkers() {
  for (let n = 1; n < 61; n++) {
    ang = n * piPer30;
    ctx.rotate(ang);
    ctx.translate(0, -markersTranslate);
    ctx.beginPath();
    if(n % 5) {
      ctx.arc(0, 0, markersSmall, 0, circle);
    } else {
      ctx.arc(0, 0, markersBig, 0, circle);
    }
    ctx.fillStyle = markersColor;
    ctx.fill();
    ctx.translate(0, markersTranslate);
    ctx.rotate(-ang);
  }
}

function drawNumbers() {
  ctx.font = size01 + numbersFont;
  ctx.fillStyle = numbersColor;
  ctx.textBaseline = 'middle';
  ctx.textAlign = 'center';
  for (let n = 1; n < 13; n++) {
    if(!(n % 3)) {
      ang = n * piPer6;
      ctx.rotate(ang);
      ctx.translate(0, -numTranslate);
      ctx.rotate(-ang);
      ctx.fillText(romanize(n), 0, 0);
      ctx.rotate(ang);
      ctx.translate(0, numTranslate);
      ctx.rotate(-ang);
    }
  }
}

function romanize(num) {
  switch(num) {
    case  1: return 'I';
    case  2: return 'II';
    case  3: return 'III';
    case  4: return 'IV';
    case  5: return 'V';
    case  6: return 'VI';
    case  7: return 'VII';
    case  8: return 'VIII';
    case  9: return 'IX';
    case 10: return 'X';
    case 11: return 'XI';
    case 12: return 'XII';
  }
}

function drawText() {
  ctx.textBaseline = 'middle';
  ctx.textAlign = 'center';
  ctx.fillStyle = numbersColor;
  ctx.font = titleSize + titleFont;
  ctx.fillText(titleText, 0, -textTranslate);
  ctx.font = size01 + periodFont;
  // ctx.fillText('©2016', 0, radius / 2.6);
  // ctx.fillText('by Lucas César', 0, radius / 2.2);
  ctx.fillText(text, 0, textTranslate);
}

function drawTime() {
  // Hour
  hour = hour % 12;
  hour = hour * piPer6 + minute * piPer360 + second * piPer21600 + millisecond * piPer21600000;

  // Minute
  minute = minute * piPer30 + second * piPer1800 + millisecond * piPer1800000;

  // Second
  second = second * piPer30 + millisecond * piPer30000;

  // Millisecond
  millisecond = millisecond * piPer500;

  drawHand(ctx, hour, hourSize, hourSize2, hourWidth);
  drawHand(ctx, minute, minuteSize, minuteSize2, minuteWidth);
  drawHand(ctx, second, secondSize, secondSize2, secondWidth, markersColor);
  drawHand(ctx, millisecond, millisecondSize, millisecondSize2, millisecondWidth, markersColor);
}

function drawHand(ctx, ang, length, length2, width, color) {
  ctx.beginPath();
  ctx.strokeStyle = typeof color !== 'undefined' ? color : handColor;
  ctx.lineWidth = width;
  ctx.lineCap = 'round';
  ctx.moveTo(0, 0);
  ctx.rotate(ang);
  ctx.lineTo(0, -length);
  ctx.stroke();
  ctx.lineTo(0, length2);
  ctx.stroke();
  ctx.rotate(-ang);
}
<commit_msg>Fixed wrong semicolon placement instead of comma.<commit_after>const faceColor = '#272B2A',
      borderColor = '#569E92',
      handColor = '#526A5D',
      numbersColor = '#FFFDB6',
      markersColor = '#9FFE00',
      numbersFont = 'px Cinzel',
      titleText = 'MilliClock',
      titleFont = 'px Tangerine',
      textAM = 'AM',
      textPM = 'PM',
      periodFont = 'px "Expletus Sans"',
      canvas = document.getElementById('canvas'),
      ctx = canvas.getContext('2d'),
      fps = 60,
      ms = 1000 / fps,
      circle = 2 * Math.PI,
      piPer6 = Math.PI / 6,
      piPer30 = Math.PI / 30,
      piPer360 = Math.PI / 360,
      piPer500 = Math.PI / 500,
      piPer1800 = Math.PI / 1800,
      piPer21600 = Math.PI / 21600,
      piPer30000 = Math.PI / 30000,
      piPer1800000 = Math.PI / 1800000,
      piPer21600000 = Math.PI / 21600000;

let resizeTimeout = null,
    radius = 0,
    grad = {},
    x = 0,
    y = 0,
    now = {},
    hour = 0,
    minute = 0,
    second = 0,
    millisecond = 0,
    ang = 0,
    text = '',
    gradRadius0 = 0,
    gradRadius1 = 0,
    size01 = 0,
    numTranslate = 0,
    titleSize = 0,
    textTranslate = 0,
    markersTranslate = 0,
    markersSmall = 0,
    markersBig = 0,
    hourSize = 0,
    minuteSize = 0,
    secondSize = 0,
    millisecondSize = 0,
    hourSize2 = 0,
    minuteSize2 = 0,
    secondSize2 = 0,
    millisecondSize2 = 0,
    hourWidth = 0,
    minuteWidth = 0,
    secondWidth = 0,
    millisecondWidth = 0;

(function() {
  resizeAndDraw();
  window.addEventListener('resize', resizeThrottler, false);
}());

function resizeThrottler() {
  if (!resizeTimeout) {
    resizeTimeout = setTimeout(function() {
      resizeTimeout = null;
      resizeAndDraw();
    }, ms);
  }
}

function resizeAndDraw() {
  // handle the resize event
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  radius = 0.9 * Math.min(canvas.width, canvas.height) / 2;
  setSizes(radius);
  x = canvas.width / 2;
  y = canvas.height / 2;
  ctx.translate(x, y);
  grad = ctx.createRadialGradient(0, 0, gradRadius0, 0, 0, gradRadius1);
  grad.addColorStop(0, faceColor);
  grad.addColorStop(0.5, borderColor);
  grad.addColorStop(1, handColor);
  setInterval(drawClock, 1);
}

function setSizes(radius) {
  gradRadius0 = radius * 0.97;
  gradRadius1 = radius * 1.03;
  size01 = radius * 0.1;
  numTranslate = radius * 0.85;
  titleSize = radius * 0.12;
  textTranslate = radius / 2.4;
  markersTranslate = radius * 0.94;
  markersSmall = radius * 0.005;
  markersBig = radius * 0.008;
  hourSize = radius * 0.5;
  minuteSize = radius * 0.7;
  secondSize = radius * 0.9;
  millisecondSize = radius * 0.06;
  hourSize2 = hourSize * 0.1;
  minuteSize2 = minuteSize * 0.1;
  secondSize2 = secondSize * 0.1;
  millisecondSize2 = millisecondSize * 0.1;
  hourWidth = radius * 0.03;
  minuteWidth = radius * 0.02;
  secondWidth = radius * 0.01;
  millisecondWidth = radius * 0.007;
}

function drawClock() {
  now = new Date();
  hour = now.getHours();
  minute = now.getMinutes();
  second = now.getSeconds();
  millisecond = now.getMilliseconds();
  text = hour < 12 ? textAM : textPM;
  drawFace();
  drawMarkers();
  drawNumbers();
  drawText();
  drawTime();
}

function drawFace() {
  ctx.beginPath();
  ctx.arc(0, 0, radius, 0, circle);
  ctx.fillStyle = faceColor;
  ctx.fill();
  ctx.strokeStyle = grad;
  ctx.lineWidth = size01;
  ctx.stroke();
}

function drawMarkers() {
  for (let n = 1; n < 61; n++) {
    ang = n * piPer30;
    ctx.rotate(ang);
    ctx.translate(0, -markersTranslate);
    ctx.beginPath();
    if(n % 5) {
      ctx.arc(0, 0, markersSmall, 0, circle);
    } else {
      ctx.arc(0, 0, markersBig, 0, circle);
    }
    ctx.fillStyle = markersColor;
    ctx.fill();
    ctx.translate(0, markersTranslate);
    ctx.rotate(-ang);
  }
}

function drawNumbers() {
  ctx.font = size01 + numbersFont;
  ctx.fillStyle = numbersColor;
  ctx.textBaseline = 'middle';
  ctx.textAlign = 'center';
  for (let n = 1; n < 13; n++) {
    if(!(n % 3)) {
      ang = n * piPer6;
      ctx.rotate(ang);
      ctx.translate(0, -numTranslate);
      ctx.rotate(-ang);
      ctx.fillText(romanize(n), 0, 0);
      ctx.rotate(ang);
      ctx.translate(0, numTranslate);
      ctx.rotate(-ang);
    }
  }
}

function romanize(num) {
  switch(num) {
    case  1: return 'I';
    case  2: return 'II';
    case  3: return 'III';
    case  4: return 'IV';
    case  5: return 'V';
    case  6: return 'VI';
    case  7: return 'VII';
    case  8: return 'VIII';
    case  9: return 'IX';
    case 10: return 'X';
    case 11: return 'XI';
    case 12: return 'XII';
  }
}

function drawText() {
  ctx.textBaseline = 'middle';
  ctx.textAlign = 'center';
  ctx.fillStyle = numbersColor;
  ctx.font = titleSize + titleFont;
  ctx.fillText(titleText, 0, -textTranslate);
  ctx.font = size01 + periodFont;
  // ctx.fillText('©2016', 0, radius / 2.6);
  // ctx.fillText('by Lucas César', 0, radius / 2.2);
  ctx.fillText(text, 0, textTranslate);
}

function drawTime() {
  // Hour
  hour = hour % 12;
  hour = hour * piPer6 + minute * piPer360 + second * piPer21600 + millisecond * piPer21600000;

  // Minute
  minute = minute * piPer30 + second * piPer1800 + millisecond * piPer1800000;

  // Second
  second = second * piPer30 + millisecond * piPer30000;

  // Millisecond
  millisecond = millisecond * piPer500;

  drawHand(ctx, hour, hourSize, hourSize2, hourWidth);
  drawHand(ctx, minute, minuteSize, minuteSize2, minuteWidth);
  drawHand(ctx, second, secondSize, secondSize2, secondWidth, markersColor);
  drawHand(ctx, millisecond, millisecondSize, millisecondSize2, millisecondWidth, markersColor);
}

function drawHand(ctx, ang, length, length2, width, color) {
  ctx.beginPath();
  ctx.strokeStyle = typeof color !== 'undefined' ? color : handColor;
  ctx.lineWidth = width;
  ctx.lineCap = 'round';
  ctx.moveTo(0, 0);
  ctx.rotate(ang);
  ctx.lineTo(0, -length);
  ctx.stroke();
  ctx.lineTo(0, length2);
  ctx.stroke();
  ctx.rotate(-ang);
}
<|endoftext|>


<commit_before>
// Function to check if location is hacker news.
function checkLocation() {
	var hackerNewsHost;

	hackerNewsHost = "news.ycombinator.com";

	// return true or false.
	if ( location.host == hackerNewsHost ) {
		return true;
	} else {
		return false;
	}
}

// This is where the magic happens.
function main() {

}

// check if the page is hacker news and run main if so.
var locationIsHackerNews;

locationIsHackerNews = checkLocation();

if ( locationIsHackerNews ) main();<commit_msg>Changed name of main function.<commit_after>
// Function to check if location is hacker news.
function checkLocation() {
	var hackerNewsHost;

	hackerNewsHost = "news.ycombinator.com";

	// return true or false.
	if ( location.host == hackerNewsHost ) {
		return true;
	} else {
		return false;
	}
}

// Main function for when on hacker news.
function onHackerNews() {

}

// check if the page is hacker news and run onHackerNews if so.
var locationIsHackerNews;

locationIsHackerNews = checkLocation();

if ( locationIsHackerNews ) onHackerNews();<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;
const smoochBot = require('smooch-bot');
const MemoryStore = smoochBot.MemoryStore;
const MemoryLock = smoochBot.MemoryLock;
const Bot = smoochBot.Bot;
// const Script = smoochBot.Script;
const StateMachine = smoochBot.StateMachine;

var storage = require("node-persist");
var getQuotesFromStorage = require('./helper.js');
storage.initSync();

class HerokuBot extends Bot {
    constructor(options) {
        super(options);
    }

    say(text) {
        return new Promise((resolve) => {
            console.log(text);
            resolve();
        });
    }

    getQ() {
        getQuotesFromStorage(function(quote){
            console.log(quote);
            return quote;
        });
    }
}

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Smooch Bot!')
                .then(() => 'askName');
        }
    },

    getQuotes : {
      prompt: (bot) => bot.say(),
      receive: (bot) => {
          return bot.say('Have a good day')
            .then(() => 'finish');
      }
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}
Is that OK? %[Yes](postback:yes) %[No](postback:no)`))
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my crear didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});

const userId = 'testUserId';
const store = new MemoryStore();
const lock = new MemoryLock();
const bot = new HerokuBot({
    store,
    lock,
    userId
});

const stateMachine = new StateMachine({
    bot,
    userId
});

process.stdin.on('data', function(data) {
    stateMachine.receiveMessage({
        text: data.toString().trim()
    })
        .catch((err) => {
            console.error(err);
            console.error(err.stack);
        });
});<commit_msg>script.js updated<commit_after>'use strict';

const Script = require('smooch-bot').Script;
const smoochBot = require('smooch-bot');
// const MemoryStore = smoochBot.MemoryStore;
// const MemoryLock = smoochBot.MemoryLock;
// const Bot = smoochBot.Bot;
// // const Script = smoochBot.Script;
// const StateMachine = smoochBot.StateMachine;

var storage = require("node-persist");
var getQuotesFromStorage = require('./helper.js');
storage.initSync();

// class HerokuBot extends Bot {
//     constructor(options) {
//         super(options);
//     }

//     say(text) {
//         return new Promise((resolve) => {
//             console.log(text);
//             resolve();
//         });
//     }

//     getQ() {
//         getQuotesFromStorage(function(quote){
//             console.log(quote);
//             return quote;
//         });
//     }
// }

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Smooch Bot!')
                .then(() => 'askName');
        }
    },

    getQuotes : {
      prompt: (bot) => bot.say(),
      receive: (bot) => {
          return bot.say('Have a good day')
            .then(() => 'finish');
      }
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}
Is that OK? %[Yes](postback:yes) %[No](postback:no)`))
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my crear didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});

<|endoftext|>


<commit_before>/***
 * Setup a webcam and fetch data from it
 **/
var webcam = (function() {
  var video, snapshot, context, stream;

  this.init = function(onComplete) {
    snapshot = document.getElementById('snapshot');
    video = document.getElementById('video');
    context = snapshot.getContext('2d');

    var getUserMedia =
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia;

    var URL = (window.URL || window.webkitURL);

    var errback = function() {
      alert('Failed to setup camera. Perhaps try a different browser with getUserMedia support.');
    };

    if (!getUserMedia) errback();
    else{
      getUserMedia.call(navigator, {video:true}, function (stream) {
        video.src = URL.createObjectURL(stream);

        var interval = setInterval(function() {
          if (video.videoWidth > 0) {
            clearInterval(interval);

            onComplete(video.videoWidth, video.videoHeight);
          }
        }, 100);

      }, errback);
    }

  };

  this.fetch = function() {
    context.drawImage(video, 0, 0);

    return context.getImageData(0, 0, video.videoWidth, video.videoHeight).data;
  };

  return this;
}).call({});

$(function() {

  var drawCanvas = document.getElementById('draw'),
      video = document.getElementById('video'),
      outputCanvas = document.getElementById('output'),
      snapshotCanvas = document.getElementById('snapshot'),
      videoStream = null;

  var width = drawCanvas.width,
      height = drawCanvas.height;

  var drawContext = drawCanvas.getContext("2d"),
      outputContext = outputCanvas.getContext("2d"),
      snapshotContext = snapshotCanvas.getContext("2d"),
      outputImage = null, outputData = null;

  var frames = [],
      times = [];

  var frameInterval,
      frameNumber = 0;

  // Write an initial message to the outputCanvas
  outputContext.fillStyle = "red";
  outputContext.font = "bold 16px Arial";
  outputContext.fillText("Waiting for webcam feed...", 20, 28);

  webcam.init(function(videoWidth, videoHeight) {
    width = videoWidth;
    height = videoHeight;

    _.each([snapshotCanvas, outputCanvas, drawCanvas], function(canvas) {
      canvas.width = width;
      canvas.height = height;
    });

    // Create output image and fill alpha channel
    outputImage = outputContext.getImageData(0, 0, width, height);
    outputData = outputImage.data;
    for(var i = 0; i < outputData.length; i += 4) {
      outputData[i+3] = 255;
    }

    // Setup the drawing canvas, and the frame interval
    setupDrawCanvas($('#draw'));
    frameInterval = setInterval(frame, 30);
  });

  function frame() {
    var data = webcam.fetch();
    var count = $('#frames').val();
    var now = new Date().getTime() / 1000.0;

    times.push(now);
    frames.push(data);
    while (frames.length > count) {
      times.shift();
      frames.shift();
    }

    // quickly iterate over all pixels
    var drawData = drawContext.getImageData(0, 0, width, height).data;

    var dataLength = drawData.length;
    var lineLength = dataLength / height;

    var delay, outputPos, inputPos;

    var drawScale = (frames.length-1) / 255.0;

    // Render the entire image line by line
    for (var linePosition = 0; linePosition < dataLength; linePosition += lineLength) {
      for(var i = 0; i < lineLength; i += 4) {

        // Flip the output for a mirror-like effect
        outputPos = linePosition+lineLength-i-4;
        inputPos  = linePosition+i;
        delay = parseInt(drawData[outputPos] * drawScale, 10);

        // Draw out all of the frames
        outputData[outputPos]   = frames[delay][inputPos];
        outputData[outputPos+1] = frames[delay][inputPos+1];
        outputData[outputPos+2] = frames[delay][inputPos+2];
      }
    }

    outputContext.putImageData(outputImage, 0, 0);

    // Update the status bar
    frameNumber += 1;
    $('#status').text(
        "Frame: "+frameNumber+"\n"+
        "Frames loaded: "+frames.length+"\n"+
        "Total delay: "+(now-times[0]).toFixed(1)
      );
  }

  // Set up all the drawer
  function setupDrawCanvas($canvas) {
    $('#defaults').change();
  }

  (function() {
    var ctx = drawContext;

    var addDefault = function(caption, cb) {
      $('#defaults').append(
        $('<option>').prop('value', caption)
                    .text(caption)
                    .data('callback', cb)
      );
    };

    var background = function(color) {
      ctx.fillStyle = color;
      ctx.fillRect(0, 0, width, height);
    };

    var linearGradient = function(x,y,x2,y2, start, stop) {
      var gradient = ctx.createLinearGradient(x,y,x2,y2);
      gradient.addColorStop(0, start);
      gradient.addColorStop(1, stop);
      background(gradient);
    };

    var radialGradient = function(x,y,r,x2,y2,r2, start, stop) {
      var gradient = ctx.createRadialGradient(x,y,r,x2,y2,r2);
      gradient.addColorStop(0, start);
      gradient.addColorStop(1, stop);
      background(gradient);
    };

    var gradientWaves = function(x, y, x2, y2, stops) {
      var gradient = ctx.createLinearGradient(x, y, x2, y2);
      for (var k = 0; k <= stops; k++) {
        gradient.addColorStop(k / stops, k%2 == 0 ? '#fff' : '#000');
        console.log(k);
      }
      background(gradient);
    };

    addDefault('top-bottom', function() {
      linearGradient(0, 0, 0, height, '#fff', '#000');
    });

    addDefault('bottom-top', function() {
      linearGradient(0, 0, 0, height, '#000', '#fff');
    });

    addDefault('diagonal', function() {
      linearGradient(0, 0, width, height, '#fff', '#000');
    });

    addDefault('tunnel', function() {
      linearGradient(0, 0, width, height, '#fff', '#000');
      radialGradient(0, 0, 0, width, height, Math.max(width,height)/2, '#fff', '#000');
    });

    addDefault('radial-in', function() {
      background('#fff');
      radialGradient(width/2, height/2, 0, width/2, height/2, Math.max(width,height), '#000', '#fff');
    });

    addDefault('radial-out', function() {
      radialGradient(width/2, height/2, 0, width/2, height/2, Math.max(width,height), '#fff', '#000');
    });

    addDefault('horizontal-waves', function() {
      gradientWaves(0, 0, width, 0, 5);
    });

    addDefault('vertical-waves', function() {
      gradientWaves(0, 0, 0, height, 5);
    });

    addDefault('diagonal-waves', function() {
      gradientWaves(0, 0, width, height, 5);
    });

    addDefault('blank', function() {
      background('#fff');
    });

  })();

  $('#defaults').change(function() {
    $(this).find('option:selected').data('callback')();
  }).keyup(function() { $(this).change(); }).change();

});

<commit_msg>Add code for drawing on the canvas<commit_after>/***
 * Setup a webcam and fetch data from it
 **/
var webcam = (function() {
  var video, snapshot, context, stream;

  this.init = function(onComplete) {
    snapshot = document.getElementById('snapshot');
    video = document.getElementById('video');
    context = snapshot.getContext('2d');

    var getUserMedia =
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia;

    var URL = (window.URL || window.webkitURL);

    var errback = function() {
      alert('Failed to setup camera. Perhaps try a different browser with getUserMedia support.');
    };

    if (!getUserMedia) errback();
    else{
      getUserMedia.call(navigator, {video:true}, function (stream) {
        video.src = URL.createObjectURL(stream);

        var interval = setInterval(function() {
          if (video.videoWidth > 0) {
            clearInterval(interval);

            onComplete(video.videoWidth, video.videoHeight);
          }
        }, 100);

      }, errback);
    }

  };

  this.fetch = function() {
    context.drawImage(video, 0, 0);

    return context.getImageData(0, 0, video.videoWidth, video.videoHeight).data;
  };

  return this;
}).call({});

var draw = (function() {

  return this;
}).call({});

$(function() {

  var drawCanvas = document.getElementById('draw'),
      video = document.getElementById('video'),
      outputCanvas = document.getElementById('output'),
      snapshotCanvas = document.getElementById('snapshot'),
      videoStream = null;

  var width = drawCanvas.width,
      height = drawCanvas.height;

  var drawContext = drawCanvas.getContext("2d"),
      outputContext = outputCanvas.getContext("2d"),
      snapshotContext = snapshotCanvas.getContext("2d"),
      outputImage = null, outputData = null;

  var frames = [],
      times = [];

  var frameInterval,
      frameNumber = 0;

  // Write an initial message to the outputCanvas
  outputContext.fillStyle = "red";
  outputContext.font = "bold 16px Arial";
  outputContext.fillText("Waiting for webcam feed...", 20, 28);

  webcam.init(function(videoWidth, videoHeight) {
    width = videoWidth;
    height = videoHeight;

    _.each([snapshotCanvas, outputCanvas], function(canvas) {
      canvas.width = width;
      canvas.height = height;
    });

    if (drawCanvas.width != width || drawCanvas.height != height) {
      drawCanvas.width = width;
      drawCanvas.height = height;
      $('#defaults').change();
    }

    // Create output image and fill alpha channel
    outputImage = outputContext.getImageData(0, 0, width, height);
    outputData = outputImage.data;
    for(var i = 0; i < outputData.length; i += 4) {
      outputData[i+3] = 255;
    }

    // Setup the drawing canvas, and the frame interval
    frameInterval = setInterval(frame, 30);
  });

  function frame() {
    var data = webcam.fetch();
    var count = $('#frames').val();
    var now = new Date().getTime() / 1000.0;

    times.push(now);
    frames.push(data);
    while (frames.length > count) {
      times.shift();
      frames.shift();
    }

    // quickly iterate over all pixels
    var drawData = drawContext.getImageData(0, 0, width, height).data;

    var dataLength = drawData.length;
    var lineLength = dataLength / height;

    var delay, outputPos, inputPos;

    var drawScale = (frames.length-1) / 255.0;

    // Render the entire image line by line
    for (var linePosition = 0; linePosition < dataLength; linePosition += lineLength) {
      for(var i = 0; i < lineLength; i += 4) {

        // Flip the output for a mirror-like effect
        outputPos = linePosition+lineLength-i-4;
        inputPos  = linePosition+i;
        delay = parseInt(drawData[outputPos] * drawScale, 10);

        // Draw out all of the frames
        outputData[outputPos]   = frames[delay][inputPos];
        outputData[outputPos+1] = frames[delay][inputPos+1];
        outputData[outputPos+2] = frames[delay][inputPos+2];
      }
    }

    outputContext.putImageData(outputImage, 0, 0);

    // Update the status bar
    frameNumber += 1;
    $('#status').text(
        "Frame: "+frameNumber+"\n"+
        "Frames loaded: "+frames.length+"\n"+
        "Total delay: "+(now-times[0]).toFixed(1)
      );
  }

  (function() {
    var brush = new Image();
    brush.src = 'brush.png';

    var started = false;

    var $draw = $('#draw');
    $draw.mousedown(function() { started = true; });
    $draw.mouseup(function() { started = false; });
    $draw.mousemove(function(ev) {
      if (started) {
        var off = $draw.offset();
        drawContext.drawImage(brush,
          ev.pageX - off.left - brush.width/2,
          ev.pageY - off.top - brush.height/2
        );
      }
    });
  })();

  (function() {
    var ctx = drawContext;

    var addDefault = function(caption, cb) {
      $('#defaults').append(
        $('<option>').prop('value', caption)
                    .text(caption)
                    .data('callback', cb)
      );
    };

    var background = function(color) {
      ctx.fillStyle = color;
      ctx.fillRect(0, 0, width, height);
    };

    var linearGradient = function(x,y,x2,y2, start, stop) {
      var gradient = ctx.createLinearGradient(x,y,x2,y2);
      gradient.addColorStop(0, start);
      gradient.addColorStop(1, stop);
      background(gradient);
    };

    var radialGradient = function(x,y,r,x2,y2,r2, start, stop) {
      var gradient = ctx.createRadialGradient(x,y,r,x2,y2,r2);
      gradient.addColorStop(0, start);
      gradient.addColorStop(1, stop);
      background(gradient);
    };

    var gradientWaves = function(x, y, x2, y2, stops) {
      var gradient = ctx.createLinearGradient(x, y, x2, y2);
      for (var k = 0; k <= stops; k++) {
        gradient.addColorStop(k / stops, k%2 == 0 ? '#fff' : '#000');
        console.log(k);
      }
      background(gradient);
    };

    addDefault('top-bottom', function() {
      linearGradient(0, 0, 0, height, '#fff', '#000');
    });

    addDefault('bottom-top', function() {
      linearGradient(0, 0, 0, height, '#000', '#fff');
    });

    addDefault('diagonal', function() {
      linearGradient(0, 0, width, height, '#fff', '#000');
    });

    addDefault('tunnel', function() {
      linearGradient(0, 0, width, height, '#fff', '#000');
      radialGradient(0, 0, 0, width, height, Math.max(width,height)/2, '#fff', '#000');
    });

    addDefault('radial-in', function() {
      background('#fff');
      radialGradient(width/2, height/2, 0, width/2, height/2, Math.max(width,height), '#000', '#fff');
    });

    addDefault('radial-out', function() {
      radialGradient(width/2, height/2, 0, width/2, height/2, Math.max(width,height), '#fff', '#000');
    });

    addDefault('horizontal-waves', function() {
      gradientWaves(0, 0, width, 0, 5);
    });

    addDefault('vertical-waves', function() {
      gradientWaves(0, 0, 0, height, 5);
    });

    addDefault('diagonal-waves', function() {
      gradientWaves(0, 0, width, height, 5);
    });

    addDefault('blank', function() {
      background('#fff');
    });

  })();

  $('#defaults').change(function() {
    $(this).find('option:selected').data('callback')();
  }).keyup(function() { $(this).change(); }).change();

});

<|endoftext|>