<commit_before>"use strict";

module.exports = function({ types: t }) {
  return {
    name: "transform-regexp-constructors",
    visitor: {
      NewExpression(path) {
        if (!t.isIdentifier(path.node.callee, {name: "RegExp"})) {
          return;
        }
        const evaluatedArgs = path.get("arguments")
                                  .map((a) => a.evaluate());
        if (!evaluatedArgs.every((a) => a.confident === true &&
            typeof a.value === "string")) {
          return;
        }
        let pattern = (evaluatedArgs.length >= 1 &&
                          evaluatedArgs[0].value !== "") ?
                        evaluatedArgs[0].value :
                        "(?:)";
        const flags = evaluatedArgs.length >= 2 ?
                      evaluatedArgs[1].value :
                      "";

        pattern = pattern
          .replace(/\n/g, '\\n')
          .replace(/\r/g, '\\r')
          .replace(/\//g, '\\/');

        path.replaceWith(t.regExpLiteral(pattern, flags));
      }
    },
  };
};
<commit_msg>Fix lint<commit_after>"use strict";

module.exports = function({ types: t }) {
  return {
    name: "transform-regexp-constructors",
    visitor: {
      NewExpression(path) {
        if (!t.isIdentifier(path.node.callee, {name: "RegExp"})) {
          return;
        }
        const evaluatedArgs = path.get("arguments")
                                  .map((a) => a.evaluate());
        if (!evaluatedArgs.every((a) => a.confident === true &&
            typeof a.value === "string")) {
          return;
        }
        let pattern = (evaluatedArgs.length >= 1 &&
                          evaluatedArgs[0].value !== "") ?
                        evaluatedArgs[0].value :
                        "(?:)";
        const flags = evaluatedArgs.length >= 2 ?
                      evaluatedArgs[1].value :
                      "";

        pattern = pattern
          .replace(/\n/g, "\\n")
          .replace(/\r/g, "\\r")
          .replace(/\//g, "\\/");

        path.replaceWith(t.regExpLiteral(pattern, flags));
      }
    },
  };
};
<|endoftext|>


<commit_before>(function ($, Prism) {
    'use strict';

    // My plugin default options
    var defaultOptions = {};

    function highlightIt(text, language) {
        return [
            '
',
            '' + Prism.highlight(text, Prism.languages[language]) + '',
            '
',
            '

'
        ].join('');
    }

    // If my plugin is a button
    function buildButtonDef(trumbowyg) {
        return {
            fn: function () {
                var $modal = trumbowyg.openModal('Code', [
                        '
',
                        '   <select class="form-control" id="language">',
                        (function () {
                            var options = '';

                            for (var lang in Prism.languages) {
                                if (Prism.languages[lang].comment) options += '<option value="' + lang + '">' + lang + '</option>';
                            }

                            return options;
                        })(),
                        '   </select>',
                        '
',
                        '
',
                        '   <textarea class="form-control" id="code"></textarea>',
                        '
',
                    ].join('\n')),
                    $language = $modal.find('#language'),
                    $code = $modal.find('#code');

                // Listen clicks on modal box buttons
                $modal.on('tbwconfirm', function (e) {
                    trumbowyg.range.deleteContents();
                    trumbowyg.range.insertNode($(highlightIt($code.val(), $language.val()))[0]);
                    trumbowyg.closeModal();
                });

                $modal.on('tbwcancel', function (e) {
                    trumbowyg.closeModal();
                });
            }
        }
    }

    $.extend(true, $.trumbowyg, {
        // Add some translations
        langs: {
            en: {
                highlight: 'Code syntax highlight'
            }
        },
        // Add our plugin to Trumbowyg registred plugins
        plugins: {
            highlight: {
                init: function (trumbowyg) {
                    // Fill current Trumbowyg instance with my plugin default options
                    trumbowyg.o.plugins.highlight = $.extend(true, {},
                        defaultOptions,
                        trumbowyg.o.plugins.highlight || {}
                    );

                    // If my plugin is a button
                    trumbowyg.addBtnDef('highlight', buildButtonDef(trumbowyg));
                }
            }
        }
    })
})(jQuery, Prism);<commit_msg>fix insert html code<commit_after>(function ($, Prism) {
    'use strict';

    // My plugin default options
    var defaultOptions = {};

    function highlightIt(text, language) {
        return [
            '
',
            '' + Prism.highlight(text, Prism.languages[language]) + '',
            '
'
        ].join('');
    }

    // If my plugin is a button
    function buildButtonDef(trumbowyg) {
        return {
            fn: function () {
                var $modal = trumbowyg.openModal('Code', [
                        '
',
                        '   <select class="form-control language">',
                        (function () {
                            var options = '';

                            for (var lang in Prism.languages) {
                                if (Prism.languages[lang].comment) options += '<option value="' + lang + '">' + lang + '</option>';
                            }

                            return options;
                        })(),
                        '   </select>',
                        '
',
                        '
',
                        '   <textarea class="form-control code"></textarea>',
                        '
',
                    ].join('\n')),
                    $language = $modal.find('.language'),
                    $code = $modal.find('.code');

                // Listen clicks on modal box buttons
                $modal.on('tbwconfirm', function (e) {
                    trumbowyg.restoreRange();
                    trumbowyg.execCmd('insertHTML', highlightIt($code.val(), $language.val()));
                    trumbowyg.execCmd('insertHTML', '

');

                    trumbowyg.closeModal();
                });

                $modal.on('tbwcancel', function (e) {
                    trumbowyg.closeModal();
                });
            }
        }
    }

    $.extend(true, $.trumbowyg, {
        // Add some translations
        langs: {
            en: {
                highlight: 'Code syntax highlight'
            }
        },
        // Add our plugin to Trumbowyg registred plugins
        plugins: {
            highlight: {
                init: function (trumbowyg) {
                    // Fill current Trumbowyg instance with my plugin default options
                    trumbowyg.o.plugins.highlight = $.extend(true, {},
                        defaultOptions,
                        trumbowyg.o.plugins.highlight || {}
                    );

                    // If my plugin is a button
                    trumbowyg.addBtnDef('highlight', buildButtonDef(trumbowyg));
                }
            }
        }
    })
})(jQuery, Prism);<|endoftext|>


<commit_before><commit_msg>Fix changelly error<commit_after><|endoftext|>


<commit_before>'use strict';

/**
 * @module computation-service
 */
const common = require('coinstac-common');
const Computation = common.models.computation.Computation;
const crypto = require('crypto');
const ModelService = require('../model-service');
const RemoteComputationResult = common.models.computation.RemoteComputationResult;

/**
 * @extends ModelService
 */
class ComputationService extends ModelService {
  modelServiceHooks() {
    return {
      dbName: 'computations',
      ModelType: Computation,
    };
  }

  /**
   * Kick off a remote computation result.
   *
   * @param {Object} options
   * @param {string} options.consortiumId
   * @param {string} options.projectId
   * @returns {Promise}
   */
  kickoff({ consortiumId, projectId }) {
    const client = this.client;

    return Promise.all([
      client.consortia.db.get(consortiumId),
      client.projects.db.get(projectId),
    ]).then(([consortium, project]) => {
      if (!consortium.activeComputationId) {
        throw new Error(
          `Consortium "${consortium.label}" doesn't have an active computation`
        );
      }
      const activeComputationId = consortium.activeComputationId;

      return client.dbRegistry.get(`remote-consortium-${consortiumId}`)
        .find({
          selector: {
            complete: { '$eq': false },
          },
        })
        .then(docs => {
          if (!docs || !docs.length) {
            return crypto
              .createHash('md5')
              .update(`${consortiumId}${activeComputationId}${Date.now()}`)
              .digest('hex');
          }

          return docs[0]._id;
        })
        .then(runId => {
          const result = new RemoteComputationResult({
            _id: runId,
            computationId: activeComputationId,
            consortiumId,
          });
          return client.pool.triggerRunner(result, project);
        });
    });
  }
}

module.exports = ComputationService;
<commit_msg>Fix query selector.<commit_after>'use strict';

/**
 * @module computation-service
 */
const common = require('coinstac-common');
const Computation = common.models.computation.Computation;
const crypto = require('crypto');
const ModelService = require('../model-service');
const RemoteComputationResult = common.models.computation.RemoteComputationResult;

/**
 * @extends ModelService
 */
class ComputationService extends ModelService {
  modelServiceHooks() {
    return {
      dbName: 'computations',
      ModelType: Computation,
    };
  }

  /**
   * Kick off a remote computation result.
   *
   * @param {Object} options
   * @param {string} options.consortiumId
   * @param {string} options.projectId
   * @returns {Promise}
   */
  kickoff({ consortiumId, projectId }) {
    const client = this.client;

    return Promise.all([
      client.consortia.db.get(consortiumId),
      client.projects.db.get(projectId),
    ]).then(([consortium, project]) => {
      if (!consortium.activeComputationId) {
        throw new Error(
          `Consortium "${consortium.label}" doesn't have an active computation`
        );
      }
      const activeComputationId = consortium.activeComputationId;

      return client.dbRegistry.get(`remote-consortium-${consortiumId}`)
        .find({
          selector: {
            'data.complete': false,
          },
        })
        .then(docs => {
          if (!docs || !docs.length) {
            return crypto
              .createHash('md5')
              .update(`${consortiumId}${activeComputationId}${Date.now()}`)
              .digest('hex');
          }

          return docs[0]._id;
        })
        .then(runId => {
          const result = new RemoteComputationResult({
            _id: runId,
            computationId: activeComputationId,
            consortiumId,
          });
          return client.pool.triggerRunner(result, project);
        });
    });
  }
}

module.exports = ComputationService;
<|endoftext|>


<commit_before>let currentBrowser;

module.exports = {
  tags: ['component', 'carousel'],
  'Bolt Carousel E2E': function(browser) {
    const { testingUrl } = browser.globals;
    console.log(`global browser url: ${testingUrl}`);
    currentBrowser = '--' + browser.currentEnv || 'chrome';
    let testName = 'bolt-carousel-basic';

    browser
      .url(
        `${testingUrl}/pattern-lab/patterns/02-components-carousel-variations-basic--01-basic-carousel/02-components-carousel-variations-basic--01-basic-carousel.html`,
      )
      .waitForElementVisible('bolt-carousel', 1000)
      .assert.elementPresent('.c-bolt-carousel__wrapper')
      .saveScreenshot(
        `screenshots/bolt-carousel/${testName}--${currentBrowser}.png`,
      )
      .end();
  },
};
<commit_msg>fix: update Nightwatch e2e test url<commit_after>let currentBrowser;

module.exports = {
  tags: ['component', 'carousel'],
  'Bolt Carousel E2E': function(browser) {
    const { testingUrl } = browser.globals;
    console.log(`global browser url: ${testingUrl}`);
    currentBrowser = '--' + browser.currentEnv || 'chrome';
    let testName = 'bolt-carousel-basic';

    browser
      .url(
        `${testingUrl}/pattern-lab/patterns/02-components-carousel--01-basic-carousel/02-components-carousel--01-basic-carousel.html`,
      )
      .waitForElementVisible('bolt-carousel', 1000)
      .assert.elementPresent('.c-bolt-carousel__wrapper')
      .saveScreenshot(
        `screenshots/bolt-carousel/${testName}--${currentBrowser}.png`,
      )
      .end();
  },
};
<|endoftext|>


<commit_before>'use strict';

function FolderListController($scope, $state, folders, FoldersService, context, $stateParams, OfficesService) {

    $scope.items = folders.data || folders;

    $scope.entityName = 'folders';
    $scope.entityRowTpl = '/icu/components/folder-list/folder-row.html';

    var creatingStatuses = {
        NotCreated: 0,
        Creating: 1,
        Created: 2
    };

    $scope.update = function(item) {
        return FoldersService.update(item);
    };

    $scope.create = function(parent) {
        var newItem = {
            title: '',
            color: '0097A7',
            watchers: [],
            __state: creatingStatuses.NotCreated,
            __autocomplete: true
        };
        if(parent){
            newItem.office = parent.id;
        }
        return FoldersService.create(newItem).then(function(result) {
            $scope.items.push(result);
            FoldersService.data.push(result);
            return result;
        });
    }

    $scope.loadMore = function(start, LIMIT, sort) {
        return FoldersService.getAll(start, LIMIT, sort).then(function(docs) {
            $scope.items = $scope.items.concat(docs.data);
            return $scope.items;
        });
    }
}

angular.module('mean.icu.ui.folderlist', []).controller('FolderListController', FolderListController);
<commit_msg>resolved issue with none-saving folders below the 25-th<commit_after>'use strict';

function FolderListController($scope, $state, folders, FoldersService, context, $stateParams, OfficesService) {

    $scope.items = folders.data || folders;

    $scope.entityName = 'folders';
    $scope.entityRowTpl = '/icu/components/folder-list/folder-row.html';

    $scope.loadNext = folders.next;
    $scope.loadPrev = folders.prev;

    var creatingStatuses = {
        NotCreated: 0,
        Creating: 1,
        Created: 2
    };

    $scope.update = function(item) {
        return FoldersService.update(item);
    };

    $scope.create = function(parent) {
        var newItem = {
            title: '',
            color: '0097A7',
            watchers: [],
            __state: creatingStatuses.NotCreated,
            __autocomplete: true
        };
        if(parent){
            newItem.office = parent.id;
        }
        return FoldersService.create(newItem).then(function(result) {
            $scope.items.push(result);
            FoldersService.data.push(result);
            return result;
        });
    }

    $scope.loadMore = function(start, LIMIT, sort) {
        if (!$scope.isLoading && $scope.loadNext) {
            $scope.isLoading = true;
            $scope.loadNext().then(function(items) {

                _(items.data).each(function(p) {
                    p.__state = creatingStatuses.Created;
                });

                var offset = $scope.displayOnly ? 0 : 1;

                if (items.data.length) {
                    var index = $scope.items.length - offset;
                    var args = [index, 0].concat(items.data);

                    [].splice.apply($scope.items, args);
                }

                $scope.loadNext = items.next;
                $scope.loadPrev = items.prev;
                $scope.isLoading = false;
            });
        }
    }
}

angular.module('mean.icu.ui.folderlist', []).controller('FolderListController', FolderListController);
<|endoftext|>


<commit_before><commit_msg>feat(gatsby-source-filesystem): env flag to placeholder remote assets (#27663)<commit_after><|endoftext|>


<commit_before>'use strict'

import BaseTransport from './rpc'

class DesktopTransport extends BaseTransport {
  constructor (incomingRPCCallback) {
    const paths = [
      // Hardcoded for now!
      process.env.HOME + '/Library/Caches/KeybaseDevel/keybased.sock',
      process.env.XDG_RUNTIME_DIR + '/keybase.devel/keybased.sock'
    ]
    let sockfile = null
    paths.map(path => {
      // Can't use ES2015 import because it'll hoist and crash mobile.
      let fs = require('fs')
      let exists = fs.existsSync(path)
      if (exists) {
        console.log('Found keybased socket file at ' + path)
        sockfile = path
      }
    })
    if (!sockfile) {
      console.error('No keybased socket file found!')
    }
    super(
      { path: sockfile, robust: true },
      null,
      incomingRPCCallback
    )
    this.connect = true
    this.base64 = false
  }
}

export default DesktopTransport
<commit_msg>Don't need engine.desktop.js anymore<commit_after><|endoftext|>


<commit_before>const librariesMissing = libraryNames =>
  libraryNames.length
    ? `You have to install these libraries first: ${libraryNames}`
    : null;
const librariesInstalled = libraryNames =>
  libraryNames.length ? `Libraries ${libraryNames} installed` : null;

const packagesMissing = packageNames =>
  packageNames.length
    ? `You have to install these packages first: ${packageNames}`
    : null;
const packagesInstalled = packageNames =>
  packageNames.length ? `Packages ${packageNames} installed` : null;

export default {
  ARDUINO_DEPENDENCIES_MISSING: ({
    libraries,
    libraryNames,
    packages,
    packageNames,
  }) => ({
    title: 'Arduino dependencies missing',
    solution: [librariesMissing(libraryNames), packagesMissing(packageNames)]
      .filter(a => !!a)
      .join('\r\n'),
    button: 'Download & Install',
    data: { libraries, packages, packageNames },
  }),
  ARDUINO_DEPENDENCIES_INSTALLED: ({ libraryNames, packageNames }) => ({
    title: 'Arduino dependencies installed',
    note: [librariesInstalled(libraryNames), packagesInstalled(packageNames)]
      .filter(a => !!a)
      .join('\r\n'),
    persistent: true,
  }),
};
<commit_msg>chore(xod-client-electron): change messages about successful installation of arduino dependencies<commit_after>const librariesMissing = libraryNames =>
  libraryNames.length
    ? `You have to install these libraries first: ${libraryNames}`
    : null;
const librariesInstalled = libraryNames =>
  libraryNames.length
    ? `Libraries ${libraryNames} installed successfully`
    : null;

const packagesMissing = packageNames =>
  packageNames.length
    ? `You have to install these packages first: ${packageNames}`
    : null;
const packagesInstalled = packageNames =>
  packageNames.length
    ? `Package "${packageNames}" installed successfully`
    : null;

export default {
  ARDUINO_DEPENDENCIES_MISSING: ({
    libraries,
    libraryNames,
    packages,
    packageNames,
  }) => ({
    title: 'Arduino dependencies missing',
    solution: [librariesMissing(libraryNames), packagesMissing(packageNames)]
      .filter(a => !!a)
      .join('\r\n'),
    button: 'Download & Install',
    data: { libraries, packages, packageNames },
  }),
  ARDUINO_DEPENDENCIES_INSTALLED: ({ libraryNames, packageNames }) => ({
    title: 'Arduino dependencies installed',
    note: [librariesInstalled(libraryNames), packagesInstalled(packageNames)]
      .filter(a => !!a)
      .join('\r\n'),
    solution: 'Now you are able to upload the program',
    persistent: true,
  }),
};
<|endoftext|>


<commit_before>import React, {Component} from '../base-react'
import ipc from 'ipc'

function remoteDispatch (action) {
  if (action.constructor === Function) {
    throw new TypeError("Can't remoteDispatch on a function!")
  }

  // TODO serialize the action with transit so we can support more types
  ipc.send('dispatchAction', action)
}

export default function (mapStateToProps, mapDispatchToProps, mergeProps) {
  // TODO: implement some reasonable state input
  const stateProps = mapStateToProps && mapStateToProps({}) || {}
  const dispatchProps = mapDispatchToProps && mapDispatchToProps(remoteDispatch) || {}

  return ConnectedComponent => {
    class RemoteConnectedComponent extends Component {
      render () {
        const ownProps = this.props
        const props = mergeProps && mergeProps(stateProps, dispatchProps, ownProps) || {
          ...stateProps,
          ...dispatchProps,
          ...ownProps
        }

        console.log('props are: ', props)

        return <ConnectedComponent {...props} />
      }
    }

    return RemoteConnectedComponent
  }
}
<commit_msg>Remove unused remote connect<commit_after><|endoftext|>


<commit_before>
var new_browser = require('./browser').new_browser;

exports.check_title = function(test) {

    var browser = new_browser();

    test.expect(1);

    browser
        .waitForTextPresent('Welcome to PopIt')
        .assertTextPresent('Welcome to PopIt')
        .testComplete()
        .end(function (err) {
            if (err) throw err;
            test.ok(true);
            test.done();
        });

};

<commit_msg>Clear database before running tests<commit_after>// switch to testing mode
process.env.NODE_ENV = 'testing';

var utils       = require('../lib/utils'),
    new_browser = require('./browser').new_browser;

module.exports = {
    setUp: function (cb) {
        utils.delete_all_testing_databases(cb);
    },

    check_title: function(test) {

        var browser = new_browser();

        test.expect(1);

        browser
            .waitForTextPresent('Welcome to PopIt')
            .assertTextPresent('Welcome to PopIt')
            .testComplete()
            .end(function (err) {
                if (err) throw err;
                test.ok(true);
                test.done();
            });
    },
};

<|endoftext|>


<commit_before>const userLanguage = document.documentElement.lang;

module.exports = {

    props: {
        'action': {
            type: String,
            required: true
        },
        'default': {
            type: Object,
            default: function() {
                return {};
            }
        },
    },

    data: function() {
        return {
            form: this.default,
            datePickerConfig: {
                dateFormat: 'Y-m-d H:i:S',
                altInput: true,
                altFormat: 'd.m.Y',
                locale: userLanguage === 'en' ? null : require("flatpickr/dist/l10n/"+userLanguage+".js")[userLanguage]
            },
            timePickerConfig: {
                enableTime: true,
                noCalendar: true,
                time_24hr: true,
                enableSeconds: true,
                dateFormat: 'H:i:S',
                altInput: true,
                altFormat: 'H:i:S',
                locale: userLanguage === 'en' ? null : require("flatpickr/dist/l10n/"+userLanguage+".js")[userLanguage]
            },
            datetimePickerConfig: {
                enableTime: true,
                time_24hr: true,
                enableSeconds: true,
                dateFormat: 'Y-m-d H:i:S',
                altInput: true,
                altFormat: 'd.m.Y H:i:S',
                locale: userLanguage === 'en' ? null : require("flatpickr/dist/l10n/"+userLanguage+".js")[userLanguage]
            },
            wysiwygConfig: {
                placeholder: 'Type a text here',
                modules: {
                    toolbar: [
                        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                        ['bold', 'italic', 'underline', 'strike'],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'align': [] }],
                        ['clean']
                    ]
                }
            }
        }
    },

    methods: {
        onSubmit() {
            return this.$validator.validateAll()
                .then(result => {
                    if (!result) {
                        return false;
                    }
                    axios.post(this.action, this.form)
                        .then(response => this.onSuccess(response.data))
                        .catch(errors => this.onFail(errors.response.data))
                });
        },
        onSuccess(data) {
            window.location.replace(data.redirect)
        },
        onFail(errors) {
            Object.keys(errors).map(key => this.$validator.errorBag.add(key, errors[key][0]));
        }
    }
};
<commit_msg>Fixed default to data change<commit_after>const userLanguage = document.documentElement.lang;

module.exports = {

    props: {
        'action': {
            type: String,
            required: true
        },
        'data': {
            type: Object,
            default: function() {
                return {};
            }
        },
    },

    data: function() {
        return {
            form: this.data,
            datePickerConfig: {
                dateFormat: 'Y-m-d H:i:S',
                altInput: true,
                altFormat: 'd.m.Y',
                locale: userLanguage === 'en' ? null : require("flatpickr/dist/l10n/"+userLanguage+".js")[userLanguage]
            },
            timePickerConfig: {
                enableTime: true,
                noCalendar: true,
                time_24hr: true,
                enableSeconds: true,
                dateFormat: 'H:i:S',
                altInput: true,
                altFormat: 'H:i:S',
                locale: userLanguage === 'en' ? null : require("flatpickr/dist/l10n/"+userLanguage+".js")[userLanguage]
            },
            datetimePickerConfig: {
                enableTime: true,
                time_24hr: true,
                enableSeconds: true,
                dateFormat: 'Y-m-d H:i:S',
                altInput: true,
                altFormat: 'd.m.Y H:i:S',
                locale: userLanguage === 'en' ? null : require("flatpickr/dist/l10n/"+userLanguage+".js")[userLanguage]
            },
            wysiwygConfig: {
                placeholder: 'Type a text here',
                modules: {
                    toolbar: [
                        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                        ['bold', 'italic', 'underline', 'strike'],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'align': [] }],
                        ['clean']
                    ]
                }
            }
        }
    },

    methods: {
        onSubmit() {
            return this.$validator.validateAll()
                .then(result => {
                    if (!result) {
                        return false;
                    }
                    axios.post(this.action, this.form)
                        .then(response => this.onSuccess(response.data))
                        .catch(errors => this.onFail(errors.response.data))
                });
        },
        onSuccess(data) {
            window.location.replace(data.redirect)
        },
        onFail(errors) {
            Object.keys(errors).map(key => this.$validator.errorBag.add(key, errors[key][0]));
        }
    }
};
<|endoftext|>


<commit_before>'use strict';

goog.provide('Blockly.Blocks.appshare');

goog.require('Blockly.Blocks');

Blockly.Blocks['appshare_app'] = {
  init: function() {
    this.appendDummyInput().appendField("Appshare Application");
    this.setTooltip('');
    this.setHelpUrl('http://www.example.com/');
    this.setColour(230);
    this.appendDummyInput().appendField("");
    this.appendDummyInput().appendField("Add UI blocks here");
    this.appendStatementInput("main application element").setCheck("HtmlElement");

    this.setColour(230);
    this.appendDummyInput().appendField("Main Application Text")
        .appendField(new Blockly.FieldTextInput("Type text here"), "VALUE");

  }
};

Blockly.Blocks['appshare_ui_component'] = {
  init: function() {
    this.appendDummyInput().appendField("UI component");
    this.setColour(130);
    this.appendDummyInput().appendField("");
    this.appendDummyInput().appendField("Add Divs here");
    this.appendStatementInput("main div element").setCheck("HtmlElement");
    //this.setOutput(true, 'UiComponent')
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
  }
};

Blockly.Blocks['appshare_div'] = {
  init: function() {
    this.appendDummyInput().appendField("
");
    this.appendStatementInput("more elements").setCheck("HtmlElement");
    this.appendDummyInput().appendField("
");
    this.setInputsInline(true);

    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(130);
    this.setTooltip('');
    this.setHelpUrl('http://www.example.com/');
  }
};

Blockly.Blocks['appshare_no_attributes'] = {
  init: function() {
    this.appendDummyInput().appendField("no attributes");
    this.setInputsInline(true);

    this.setColour(150);
    this.setTooltip('');
    this.setOutput(true, 'HtmlElementAttribute')
    this.setHelpUrl('http://www.example.com/');
  }
};

Blockly.Blocks['appshare_element_attribute'] = {
  init: function() {
    this.appendDummyInput()
        .appendField(new Blockly.FieldTextInput("style"), "style")
        .appendField("=")
        .appendField(new Blockly.FieldTextInput("width=100%"), "value");

    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElementAttribute");
    this.setNextStatement(true, "HtmlElementAttribute");
    this.setOutput(true, 'HtmlElementAttribute')
    this.setColour(230);
    this.setTooltip('');
    this.setHelpUrl('http://www.example.com/');
  }

};

Blockly.Blocks['appshare_element_header'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Header text")
        .appendField(new Blockly.FieldTextInput("Header text"), "VALUE");

    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
    //this.setOutput(true, 'HtmlElement')
    this.setHelpUrl('http://www.example.com/');
  }
};

Blockly.Blocks['appshare_element_text'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("text")
        .appendField(new Blockly.FieldTextInput("Type text here"), "VALUE");

    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
    //this.setOutput(true, 'HtmlElement')
    this.setHelpUrl('http://www.example.com/');
  }
};

Blockly.Blocks['appshare_element_br'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Newline");
    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
  }
};

Blockly.Blocks['appshare_element_box'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Box");
    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
  }
};

Blockly.Blocks['appshare_element_left_padding'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Left Padding");
    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
  }
};

Blockly.Blocks['appshare_element_top_padding'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Top Padding");
    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
  }
};

Blockly.Blocks['appshare_custom_component'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Thing")
        .appendField(new Blockly.FieldTextInput("Component_Name"), "COMPONENT_NAME");
    this.setColour(230);
    this.appendDummyInput().appendField("");
    this.appendDummyInput().appendField("Add DIV blocks here");
    this.appendStatementInput("main div element").setCheck("HtmlElement");
  }
}

Blockly.Blocks['appshare_call_custom_component'] = {
  init: function() {

    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');

    var dropdown = new Blockly.FieldDropdown([['world', 'WORLD'], ['computer', 'CPU']]);
    this.appendDummyInput()
    .appendField("component name").appendField(dropdown, 'COMPONENT_NAME_VALUE');
    dropdown.setText(""); // set the actual text
    dropdown.setValue("");

    //this.setOutput(true, 'HtmlElement')
    this.setHelpUrl('http://www.example.com/');
  },

  onchange: function(event) {
    //var dropdown = new Blockly.FieldDropdown([['1', '1'], ['2', '2']]);
    //this.getInput("COMPONENT_NAME").appendField(dropdown, 'MODE');
    //this.removeInput('COMPONENT_NAME');
    //var dropdown = new Blockly.FieldDropdown([['1', '1'], ['2', '2']]);
    //this.appendValueInput("COMPONENT_NAME2").appendField(dropdown, 'MODE2');
    var dummyData = component_list;

    // setting the menuGenerator for your "variable_name"
    this.getField("COMPONENT_NAME_VALUE").menuGenerator_ = dummyData;
  }

};

Blockly.Blocks['appshare_db_component'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("DB")
        .appendField(new Blockly.FieldTextInput("table_name"), "VALUE");
    this.appendDummyInput()
        .appendField("Fields")
        .appendField(new Blockly.FieldTextInput(":id"), "DB_FIELDS");
    this.appendStatementInput("more elements").setCheck("HtmlElement");
    this.setColour(230);
    this.appendDummyInput().appendField("");
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
  }
}

Blockly.Blocks['appshare_db_field'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Field")
        .appendField(new Blockly.FieldTextInput("id"), "VALUE");
    this.setColour(230);
    this.appendDummyInput().appendField("");
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
  }
}

Blockly.Blocks['appshare_show_tables'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Show tables");
    this.setColour(230);
    this.appendDummyInput().appendField("");
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
  }
}

Blockly.Blocks['appshare_input_field'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Placeholder")
        .appendField(new Blockly.FieldTextInput("Some text"), "PLACEHOLDER");
    this.setColour(230);
    this.appendDummyInput().appendField("");
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
  }
}
<commit_msg>Allow input field to take in a callback function<commit_after>'use strict';

goog.provide('Blockly.Blocks.appshare');

goog.require('Blockly.Blocks');

Blockly.Blocks['appshare_app'] = {
  init: function() {
    this.appendDummyInput().appendField("Appshare Application");
    this.setTooltip('');
    this.setHelpUrl('http://www.example.com/');
    this.setColour(230);
    this.appendDummyInput().appendField("");
    this.appendDummyInput().appendField("Add UI blocks here");
    this.appendStatementInput("main application element").setCheck("HtmlElement");

    this.setColour(230);
    this.appendDummyInput().appendField("Main Application Text")
        .appendField(new Blockly.FieldTextInput("Type text here"), "VALUE");

  }
};

Blockly.Blocks['appshare_ui_component'] = {
  init: function() {
    this.appendDummyInput().appendField("UI component");
    this.setColour(130);
    this.appendDummyInput().appendField("");
    this.appendDummyInput().appendField("Add Divs here");
    this.appendStatementInput("main div element").setCheck("HtmlElement");
    //this.setOutput(true, 'UiComponent')
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
  }
};

Blockly.Blocks['appshare_div'] = {
  init: function() {
    this.appendDummyInput().appendField("
");
    this.appendStatementInput("more elements").setCheck("HtmlElement");
    this.appendDummyInput().appendField("
");
    this.setInputsInline(true);

    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(130);
    this.setTooltip('');
    this.setHelpUrl('http://www.example.com/');
  }
};

Blockly.Blocks['appshare_no_attributes'] = {
  init: function() {
    this.appendDummyInput().appendField("no attributes");
    this.setInputsInline(true);

    this.setColour(150);
    this.setTooltip('');
    this.setOutput(true, 'HtmlElementAttribute')
    this.setHelpUrl('http://www.example.com/');
  }
};

Blockly.Blocks['appshare_element_attribute'] = {
  init: function() {
    this.appendDummyInput()
        .appendField(new Blockly.FieldTextInput("style"), "style")
        .appendField("=")
        .appendField(new Blockly.FieldTextInput("width=100%"), "value");

    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElementAttribute");
    this.setNextStatement(true, "HtmlElementAttribute");
    this.setOutput(true, 'HtmlElementAttribute')
    this.setColour(230);
    this.setTooltip('');
    this.setHelpUrl('http://www.example.com/');
  }

};

Blockly.Blocks['appshare_element_header'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Header text")
        .appendField(new Blockly.FieldTextInput("Header text"), "VALUE");

    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
    //this.setOutput(true, 'HtmlElement')
    this.setHelpUrl('http://www.example.com/');
  }
};

Blockly.Blocks['appshare_element_text'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("text")
        .appendField(new Blockly.FieldTextInput("Type text here"), "VALUE");

    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
    //this.setOutput(true, 'HtmlElement')
    this.setHelpUrl('http://www.example.com/');
  }
};

Blockly.Blocks['appshare_element_br'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Newline");
    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
  }
};

Blockly.Blocks['appshare_element_box'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Box");
    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
  }
};

Blockly.Blocks['appshare_element_left_padding'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Left Padding");
    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
  }
};

Blockly.Blocks['appshare_element_top_padding'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Top Padding");
    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');
  }
};

Blockly.Blocks['appshare_custom_component'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Thing")
        .appendField(new Blockly.FieldTextInput("Component_Name"), "COMPONENT_NAME");
    this.setColour(230);
    this.appendDummyInput().appendField("");
    this.appendDummyInput().appendField("Add DIV blocks here");
    this.appendStatementInput("main div element").setCheck("HtmlElement");
  }
}

Blockly.Blocks['appshare_call_custom_component'] = {
  init: function() {

    this.appendDummyInput().setAlign(Blockly.ALIGN_RIGHT);
    this.setInputsInline(true);
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
    this.setColour(230);
    this.setTooltip('');

    var dropdown = new Blockly.FieldDropdown([['world', 'WORLD'], ['computer', 'CPU']]);
    this.appendDummyInput()
    .appendField("component name").appendField(dropdown, 'COMPONENT_NAME_VALUE');
    dropdown.setText(""); // set the actual text
    dropdown.setValue("");

    //this.setOutput(true, 'HtmlElement')
    this.setHelpUrl('http://www.example.com/');
  },

  onchange: function(event) {
    //var dropdown = new Blockly.FieldDropdown([['1', '1'], ['2', '2']]);
    //this.getInput("COMPONENT_NAME").appendField(dropdown, 'MODE');
    //this.removeInput('COMPONENT_NAME');
    //var dropdown = new Blockly.FieldDropdown([['1', '1'], ['2', '2']]);
    //this.appendValueInput("COMPONENT_NAME2").appendField(dropdown, 'MODE2');
    var dummyData = component_list;

    // setting the menuGenerator for your "variable_name"
    this.getField("COMPONENT_NAME_VALUE").menuGenerator_ = dummyData;
  }

};

Blockly.Blocks['appshare_db_component'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("DB")
        .appendField(new Blockly.FieldTextInput("table_name"), "VALUE");
    this.appendDummyInput()
        .appendField("Fields")
        .appendField(new Blockly.FieldTextInput(":id"), "DB_FIELDS");
    this.appendStatementInput("more elements").setCheck("HtmlElement");
    this.setColour(230);
    this.appendDummyInput().appendField("");
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
  }
}

Blockly.Blocks['appshare_db_field'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Field")
        .appendField(new Blockly.FieldTextInput("id"), "VALUE");
    this.setColour(230);
    this.appendDummyInput().appendField("");
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
  }
}

Blockly.Blocks['appshare_show_tables'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Show tables");
    this.setColour(230);
    this.appendDummyInput().appendField("");
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
  }
}

Blockly.Blocks['appshare_input_field'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Input field")
        .appendField();
    this.appendDummyInput()
        .appendField("Placeholder text")
        .appendField(new Blockly.FieldTextInput("Some text"), "PLACEHOLDER");
    this.setColour(230);
    this.appendDummyInput().appendField("");

    this.appendDummyInput().appendField("Add callback code here");
    this.appendStatementInput("main div element").setCheck("CodeElement");
    this.setPreviousStatement(true, "HtmlElement");
    this.setNextStatement(true, "HtmlElement");
  }
}
<|endoftext|>


<commit_before>define(function (require) {
  require("jquery");
  var Utils = require("core/Utils");
  var Locale = require("core/Locale");
  var Inherits = require("core/Inherits");
  var Class = require("core/Class");
  var Storage = require("core/Storage");
  var Dialog = require("core/Dialog");
  var Grid= require("core/Control/Grid");
  var List = require("core/Control/List");
  var DivButton = require("core/Control/DivButton");
  var Field = require("core/Control/Field/Field");

  function save_as_draft(self, list) {
    var data = {};
    list.data().forEach(function (item) {
      data[item.locale] = item.value;
    });
    self._draft = data;
  }

  function show_languages_dialog(self, locale, locales, columns) {
    if (!self._draft) {
      self._draft = self._value;
    }
    var items = Object.keys(self._draft).map(function(locale_id) { return { "id" : locale_id, "locale": locale_id, "value" : self._draft[locale_id] }; });
    var list = new List();
    var dialog = new Dialog();
    dialog.init(function(contents_id) {
      return list.init("#" + contents_id, { class_id : self.detail_id(), width : 300, height : 400});
    })
    .then(function () {
      list.data(items);
      list.edit(true);
      list.refresh();
    })
    .then(function () {
      dialog.title("Locales");
      dialog.buttons([
        { text: "OK",    click:function (event) { save_as_draft(self, list); dialog.close(); } },
        { text:"Cancel", click:function (event) { dialog.close(); }}
      ]);
      dialog.size(400, 300);
      dialog.open();
    });
  }

  function Text() {
    Field.call(this, "core/Control/Field", "Text");
    this._input = null;
    this._value = null;
    this._draft = null;
    this._properties = null;
    this._button = null;
  };
  Inherits(Text, Field);

  Text.prototype.template = function() {
    return '
<input style="color:black;"/>

';
  };

  Text.prototype.create_form = function(root, field_name) {
    this._input = root.find('input');
    this._input.attr("name", field_name);
    this._input.css("width", this._properties.width);
    this._input.w2field("text");
  };

  Text.DEFAULT_PROPERTIES = { "width" : 200, "is_require" : false, "default" : "", "multi_lingualization" : false };
  Text.prototype.default_properties = function() {
    return Text.DEFAULT_PROPERTIES;
  };

  Text.prototype.detail_id = function() {
    return Class.TEXT_MULTILINGUALIZATION_ID;
  };

  Text.prototype.init = function(selector, field) {
    var dfd = new $.Deferred;

    var root = $(selector);
    root.append(this.template());

    // properties
    this._properties = Utils.get_as_json(
      this.default_properties(),
      function() { return field.datatype.properties; },
      false);
    var self = this;

    // Label
    var label = root.find("label");
    var caption = Locale.translate(field.label);
    label.text(caption);

    // Input
    this.create_form(root, field.name);

    // If *NOT* multi-lingualize, don't create Button
    if (!self._properties.multi_lingualization) {
      dfd.resolve();
      return dfd.promise();
    }

    // Get Locale data
    var locale = null;
    var locales = null;
    var columns = null;
    Storage.read(Class.CLASS_ID, Class.LOCALE_ID)
    .then(function(data) {
      locale = data;
    })
    .then(function () {
      return Storage.read(Class.LOCALE_ID).then(function(objects) { locales = objects; })
    })
    .then(function () {
      return Grid.create_columns(locale).then(function (columns_) { columns = columns_; });
    })
    .then(function () {
      // Button
      var button_selector = selector + " > div > div[name='button']";
      self._button = new DivButton();
      return self._button.init(button_selector, '', function (event) {
        show_languages_dialog(self, locale, locales, columns);
      });
    })
    .then(function () {
      self._button.visible(false);
      dfd.resolve();
    });

    return dfd.promise();
  };

  Text.prototype.backuped = function() {
    return this._value;
  };

  Text.prototype.commit = function() {
    if (!this._properties.multi_lingualization) {
      this._value = this._input.val();
      return;
    }
    this._value = !this._draft ? {} : this._draft;
    this._value[""] = this._input.val();
  };

  Text.prototype.restore = function() {
    if (!this._properties.multi_lingualization) {
      this._input.val(this._value);
      return;
    }
    this._draft = this._value;
  };

  Text.prototype.edit = function(on) {
    this._input.attr("readonly", !on);
    if (!this._button) {
      return;
    }
    this._button.visible(on);
  };

  Text.prototype.data = function(value) {
  	var multi = this._properties.multi_lingualization;
    // getter
    if (arguments.length == 0) {
      if (!multi) {
        return this._input.val();
      } else {
        var v = !this._draft ? {} : this._draft;
        v[""] = this._input.val();
        return v;
      }
    }
    // setter
    if (!multi) {
      this._value = Utils.is_object(value) ? value[""] : value;
    } else {
      this._value = Utils.is_object(value) ? value : { "" : value };
    }
    this._input.val(!multi ? this._value : this._value[""]);
  };

  Text.generate_renderer = function(default_properties, field) {
    var props = Utils.get_as_json(default_properties, function() { return field.datatype.properties; });

    var dfd = new $.Deferred;
    var renderer = function(record, index, column_index) {
      var value = record[field.name];
      if (Utils.is_object(value) && props.multi_lingualization) {
        return Locale.translate(value);
      } else {
        return value;
      }
    };
    dfd.resolve(renderer);
    return dfd.promise();
  };

  Text.cell_render = function(field) {
    return Text.generate_renderer(Text.DEFAULT_PROPERTIES, field);
  };

  return Text;
});
<commit_msg>Fixed Text.js bug.<commit_after>define(function (require) {
  require("jquery");
  var Utils = require("core/Utils");
  var Locale = require("core/Locale");
  var Inherits = require("core/Inherits");
  var Class = require("core/Class");
  var Storage = require("core/Storage");
  var Dialog = require("core/Dialog");
  var Grid= require("core/Control/Grid");
  var List = require("core/Control/List");
  var DivButton = require("core/Control/DivButton");
  var Field = require("core/Control/Field/Field");

  function save_as_draft(self, list) {
    var data = {};
    list.data().forEach(function (item) {
      data[item.locale] = item.value;
    });
    self._draft = data;
  }

  function show_languages_dialog(self, locale, locales, columns) {
    if (!self._draft) {
      self._draft = self._value;
    }
    var items = Object.keys(self._draft).map(function(locale_id) { return { "id" : locale_id, "locale": locale_id, "value" : self._draft[locale_id] }; });
    var list = new List();
    var dialog = new Dialog();
    dialog.init(function(contents_id) {
      return list.init("#" + contents_id, { class_id : self.detail_id(), width : 300, height : 400});
    })
    .then(function () {
      list.data(items);
      list.edit(true);
      list.refresh();
    })
    .then(function () {
      dialog.title("Locales");
      dialog.buttons([
        { text: "OK",    click:function (event) { save_as_draft(self, list); dialog.close(); } },
        { text:"Cancel", click:function (event) { dialog.close(); }}
      ]);
      dialog.size(400, 300);
      dialog.open();
    });
  }

  function Text() {
    Field.call(this, "core/Control/Field", "Text");
    this._input = null;
    this._value = null;
    this._draft = null;
    this._properties = null;
    this._button = null;
  };
  Inherits(Text, Field);

  Text.prototype.template = function() {
    return '
<input style="color:black;"/>

';
  };

  Text.prototype.create_form = function(root, field_name) {
    this._input = root.find('input');
    this._input.attr("name", field_name);
    this._input.css("width", this._properties.width);
    this._input.w2field("text");
  };

  Text.DEFAULT_PROPERTIES = { "width" : 200, "is_require" : false, "default" : "", "multi_lingualization" : false };
  Text.prototype.default_properties = function() {
    return Text.DEFAULT_PROPERTIES;
  };

  Text.prototype.detail_id = function() {
    return Class.TEXT_MULTILINGUALIZATION_ID;
  };

  Text.prototype.init = function(selector, field) {
    var dfd = new $.Deferred;

    var root = $(selector);
    root.append(this.template());

    // properties
    this._properties = Utils.get_as_json(
      this.default_properties(),
      function() { return field.datatype.properties; },
      false);
    var self = this;

    // Label
    var label = root.find("label");
    var caption = Locale.translate(field.label);
    label.text(caption);

    // Input
    this.create_form(root, field.name);

    // If *NOT* multi-lingualize, don't create Button
    if (!self._properties.multi_lingualization) {
      dfd.resolve();
      return dfd.promise();
    }

    // Get Locale data
    var locale = null;
    var locales = null;
    var columns = null;
    Storage.read(Class.CLASS_ID, Class.LOCALE_ID)
    .then(function(data) {
      locale = data;
    })
    .then(function () {
      return Storage.read(Class.LOCALE_ID).then(function(objects) { locales = objects; })
    })
    .then(function () {
      return Grid.create_columns(locale).then(function (columns_) { columns = columns_; });
    })
    .then(function () {
      // Button
      var button_selector = selector + " > div > div[name='button']";
      self._button = new DivButton();
      return self._button.init(button_selector, '', function (event) {
        show_languages_dialog(self, locale, locales, columns);
      });
    })
    .then(function () {
      self._button.visible(false);
      dfd.resolve();
    });

    return dfd.promise();
  };

  Text.prototype.backuped = function() {
    return this._value;
  };

  Text.prototype.commit = function() {
    if (!this._properties.multi_lingualization) {
      this._value = this._input.val();
      return;
    }
    this._value = !this._draft ? {} : this._draft;
    this._value[""] = this._input.val();
  };

  Text.prototype.restore = function() {
    if (!this._properties.multi_lingualization) {
      this._input.val(this._value);
      return;
    }
    this._draft = this._value;
  };

  Text.prototype.edit = function(on) {
    this._input.attr("readonly", !on);
    if (!this._button) {
      return;
    }
    this._button.visible(on);
  };

  Text.prototype.data = function(value) {
  	var multi = this._properties.multi_lingualization;
    // getter
    if (arguments.length == 0) {
      if (!multi) {
        return this._input.val();
      } else {
        var v = !this._draft ? {} : this._draft;
        v[""] = this._input.val();
        return v;
      }
    }
    // setter
    if (!multi) {
      this._value = Utils.is_object(value) ? value[""] : value;
    } else {
      this._value = Utils.is_object(value) ? value : { "" : value };
    }
    this._draft = this._value;
    this._input.val(!multi ? this._value : this._value[""]);
  };

  Text.generate_renderer = function(default_properties, field) {
    var props = Utils.get_as_json(default_properties, function() { return field.datatype.properties; });

    var dfd = new $.Deferred;
    var renderer = function(record, index, column_index) {
      var value = record[field.name];
      if (Utils.is_object(value) && props.multi_lingualization) {
        return Locale.translate(value);
      } else {
        return value;
      }
    };
    dfd.resolve(renderer);
    return dfd.promise();
  };

  Text.cell_render = function(field) {
    return Text.generate_renderer(Text.DEFAULT_PROPERTIES, field);
  };

  return Text;
});
<|endoftext|>


<commit_before>load('tests/test-common.js');
var engine;

// feel free to add more here...
var classIds =
    [
        "DOID:14330", // PD
        "DOID_12358", // patulous eustachian tube
    ];

exports.testClassInfo = function() {
    classIds.forEach(
        function(id) {
            var resObj = engine.fetchClassInfo(id);
            console.log(JSON.stringify(resObj,' ',1));
            assert.isTrue(resObj.definition.length > 0);
            assert.isTrue(resObj.id.length > 0);
            assert.isTrue(resObj.label.length > 0);
            assert.isTrue(resObj.category == 'disease');
            // todo - check json
            //assert.isTrue(resObj.resultCount > 100);
            //assert.isTrue(resObj.results.length > 100);

        }
    );
}

if (require.main == module) {
    engine = new getTestEngine();

    var rtn = require("test").run(exports);
    print("Return code="+rtn);
    system.exit(rtn);
}
<commit_msg>fixed test to accept multiple definitions, as is now standard for SG<commit_after>load('tests/test-common.js');
var engine;

// feel free to add more here...
var classIds =
    [
        "DOID:14330", // PD
        "DOID_12358", // patulous eustachian tube
    ];

exports.testClassInfo = function() {
    classIds.forEach(
        function(id) {
            var resObj = engine.fetchClassInfo(id);
            console.log(JSON.stringify(resObj,' ',1));
            assert.isTrue(resObj.definitions.length > 0);
            assert.isTrue(resObj.id.length > 0);
            assert.isTrue(resObj.label.length > 0);
            assert.isTrue(resObj.category == 'disease');
            // todo - check json
            //assert.isTrue(resObj.resultCount > 100);
            //assert.isTrue(resObj.results.length > 100);

        }
    );
}

if (require.main == module) {
    engine = new getTestEngine();

    var rtn = require("test").run(exports);
    print("Return code="+rtn);
    system.exit(rtn);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";

const fs = require("fs");

global.v86util = {};

// copied from const.js
global.WASM_TABLE_SIZE = 0x10000;
// The space we need for misc internal state before the beginning of mem8; see global_pointers.h
global.INTERNAL_MEM_SIZE = 4096 + 0x100000 * 6;
global.WASM_PAGE_SIZE = 64 * 1024;

global.dbg_assert = x => console.assert(x);

require("../../src/browser/lib.js");

const Codegen = require("../../src/codegen.js");

const codegen_module_buffer = fs.readFileSync(__dirname + "/../../build/codegen-test.wasm");

const vals = {
    imm8: 1,
    imm8s: 1,
    imm16: 2,
    imm32s: 3,
    asize_32: false,
    reg16: 0,
    reg32s: 0,
    instruction_pointer: 0,
    previous_ip: 0,
    prefixes: 0,
};

const wasm_test_funcs = {
    env: {
        _read_imm8() { return vals.imm8; },
        _read_imm8s() { return vals.imm8s; },
        _read_imm16() { return vals.imm16; },
        _read_imm32s() { return vals.imm32s; },
        _is_asize_32() { return vals.asize_32; },
        _printf(...args) { console.log(...args); },
        ___assert_fail(...args) { console.error(...args); console.assert(false); },
        abort() { console.assert(false); },

        // static pointer imports
        g$_reg16() { return vals.reg16; },
        g$_reg32s() { return vals.reg32s; },
        g$_instruction_pointer() { return vals.instruction_pointer; },
        g$_previous_ip() { return vals.previous_ip; },
        g$_prefixes() { return vals.prefixes; },
    },
};

const memory_size = 256 * 1024 * 1024;

v86util.load_wasm(
    "build/codegen-test.wasm",
    wasm_test_funcs,
    memory_size + INTERNAL_MEM_SIZE,
    WASM_TABLE_SIZE,
    wm => {
        try {
            test(new Codegen(wm));
        } catch(er) {
            console.error(er);
            process.exit(1);
        }
    }
);

function test(gen)
{
    gen.reset();
    gen.fn0("fn0");
    gen.fn1("fn1", 0);
    gen.fn2("fn2", 0, 1);
    gen.increment_instruction_pointer(10);
    gen.set_previous_eip();
    gen.modrm_fn0("fn1r");
    gen.modrm_fn1("fn2r", 2);
    vals.asize_32 = !vals.asize_32;
    gen.modrm_fn0("fn1r");
    gen.modrm_fn1("fn2r", 2);
    gen.finish();

    let buf = gen.get_module_code();
    fs.writeFileSync(__dirname + "/../../build/codegen-test-output.wasm", buf);

    const module = new WebAssembly.Module(buf);

    const expected = [
        ["fn0"],
        ["fn1", 0],
        ["fn2", 0, 1],
        ["fn1r", 0],
        ["fn2r", 0, 0],
        ["fn1r", 0],
        ["fn2r", 0, 0],
    ];

    const store = [];

    const imports = {
        e: {
            fn0() { store.push(["fn0"]); },
            fn1(arg0) { store.push(["fn1", arg0]); },
            fn2(arg0, arg1) { store.push(["fn2", arg0, arg1]); },
            fn1r(arg0) { store.push(["fn1r", arg0]); },
            fn2r(arg0, arg1) { store.push(["fn2r", arg0, arg1]); },
            get_seg_prefix_ds() {},
            get_seg_prefix_ss() {},
            get_seg_prefix() {},
            m: new WebAssembly.Memory({ initial: memory_size / 64 / 1024 }),
        },
    };
    const o = new WebAssembly.Instance(module, imports);
    o.exports.f();
    const view = new Uint32Array(imports.e.m.buffer);
    console.log(store);
    console.assert(view[vals.instruction_pointer] === 10);
    console.assert(view[vals.previous_ip] === 10);
    console.assert(JSON.stringify(store) === JSON.stringify(expected));
}

<commit_msg>Fix codegen test<commit_after>#!/usr/bin/env node
"use strict";

const fs = require("fs");

global.v86util = {};

// copied from const.js
global.WASM_TABLE_SIZE = 0x10000;
// The space we need for misc internal state before the beginning of mem8; see global_pointers.h
global.INTERNAL_MEM_SIZE = 4096 + 0x100000 * 6;
global.WASM_PAGE_SIZE = 64 * 1024;

global.dbg_assert = x => console.assert(x);

require("../../src/browser/lib.js");

const Codegen = require("../../src/codegen.js");

const codegen_module_buffer = fs.readFileSync(__dirname + "/../../build/codegen-test.wasm");

const vals = {
    imm8: 1,
    imm8s: 1,
    imm16: 2,
    imm32s: 3,
    asize_32: false,
    reg16: 0,
    reg32s: 0,
    instruction_pointer: 0,
    previous_ip: 0,
    prefixes: 0,
    timestamp_counter: 0,
};

const wasm_test_funcs = {
    env: {
        _read_imm8() { return vals.imm8; },
        _read_imm8s() { return vals.imm8s; },
        _read_imm16() { return vals.imm16; },
        _read_imm32s() { return vals.imm32s; },
        _is_asize_32() { return vals.asize_32; },
        _printf(...args) { console.log(...args); },
        ___assert_fail(...args) { console.error(...args); console.assert(false); },
        abort() { console.assert(false); },

        // static pointer imports
        g$_reg16() { return vals.reg16; },
        g$_reg32s() { return vals.reg32s; },
        g$_instruction_pointer() { return vals.instruction_pointer; },
        g$_previous_ip() { return vals.previous_ip; },
        g$_prefixes() { return vals.prefixes; },
        g$_timestamp_counter() { return vals.timestamp_counter; },
    },
};

const memory_size = 256 * 1024 * 1024;

v86util.load_wasm(
    "build/codegen-test.wasm",
    wasm_test_funcs,
    memory_size + INTERNAL_MEM_SIZE,
    WASM_TABLE_SIZE,
    wm => {
        try {
            test(new Codegen(wm));
        } catch(er) {
            console.error(er);
            process.exit(1);
        }
    }
);

function test(gen)
{
    gen.reset();
    gen.fn0("fn0");
    gen.fn1("fn1", 0);
    gen.fn2("fn2", 0, 1);
    gen.increment_instruction_pointer(10);
    gen.set_previous_eip();
    gen.modrm_fn0("fn1r");
    gen.modrm_fn1("fn2r", 2);
    vals.asize_32 = !vals.asize_32;
    gen.modrm_fn0("fn1r");
    gen.modrm_fn1("fn2r", 2);
    gen.finish();

    let buf = gen.get_module_code();
    fs.writeFileSync(__dirname + "/../../build/codegen-test-output.wasm", buf);

    const module = new WebAssembly.Module(buf);

    const expected = [
        ["fn0"],
        ["fn1", 0],
        ["fn2", 0, 1],
        ["fn1r", 0],
        ["fn2r", 0, 0],
        ["fn1r", 0],
        ["fn2r", 0, 0],
    ];

    const store = [];

    const imports = {
        e: {
            fn0() { store.push(["fn0"]); },
            fn1(arg0) { store.push(["fn1", arg0]); },
            fn2(arg0, arg1) { store.push(["fn2", arg0, arg1]); },
            fn1r(arg0) { store.push(["fn1r", arg0]); },
            fn2r(arg0, arg1) { store.push(["fn2r", arg0, arg1]); },
            get_seg_prefix_ds() {},
            get_seg_prefix_ss() {},
            get_seg_prefix() {},
            m: new WebAssembly.Memory({ initial: memory_size / 64 / 1024 }),
        },
    };
    const o = new WebAssembly.Instance(module, imports);
    o.exports.f();
    const view = new Uint32Array(imports.e.m.buffer);
    console.log(store);
    console.assert(view[vals.instruction_pointer] === 10);
    console.assert(view[vals.previous_ip] === 10);
    console.assert(JSON.stringify(store) === JSON.stringify(expected));
}

<|endoftext|>


<commit_before>define([
        '../Core/defined',
        '../Core/DeveloperError',
    ], function(
        defined,
        DeveloperError) {
    'use strict';

    // Note that this fails if your string looks like
    // searchString[singleCharacter]searchString
    function replaceInSourceString(str, replacement, splitSource) {
        var regexStr = '(^|[^\\w])(' + str + ')($|[^\\w])';
        var regex = new RegExp(regexStr, 'g');

        for (var number = 0; number < splitSource.length; ++number) {
            var line = splitSource[number];
            splitSource[number] = line.replace(regex, '$1' + replacement + '$3');
        }
    }

    function replaceInSourceRegex(regex, replacement, splitSource) {
        for (var number = 0; number < splitSource.length; ++number) {
            var line = splitSource[number];
            splitSource[number] = line.replace(regex, replacement);
        }
    }

    function findInSource(str, splitSource) {
        var regexStr = '(^|[^\\w])(' + str + ')($|[^\\w])';
        var regex = new RegExp(regexStr, 'g');
        for (var number = 0; number < splitSource.length; ++number) {
            var line = splitSource[number];
            if (regex.test(line)) {
                return true;
            }
        }
        return false;
    }

    function compileSource(splitSource) {
        var wholeSource = '';
        for (var number = 0; number < splitSource.length; ++number) {
            wholeSource += splitSource[number] + '\n';
        }
        return wholeSource;
    }

    function setAdd(variable, set1) {
        if (set1.indexOf(variable) === -1) {
            set1.push(variable);
        }
    }

    function getVariablePreprocessorBranch(variablesThatWeCareAbout, splitSource) {
        var variableMap = {};

        var numVariablesWeCareAbout = variablesThatWeCareAbout.length;
        for (var a = 0; a < numVariablesWeCareAbout; ++a) {
            var variableThatWeCareAbout = variablesThatWeCareAbout[a];
            variableMap[variableThatWeCareAbout] = [null];
        }

        var stack = [];
        for (var i = 0; i < splitSource.length; ++i) {
            var line = splitSource[i];
            var hasIF = /(#ifdef|#if)/g.test(line);
            var hasELSE = /#else/g.test(line);
            var hasENDIF = /#endif/g.test(line);

            if (hasIF) {
                stack.push(line);
            } else if (hasELSE) {
                var top = stack[stack.length - 1];
                var op = top.replace('ifdef', 'ifndef');
                if (/if/g.test(op)) {
                    op = op.replace(/(#if\s+)(\S*)([^]*)/, '$1!($2)$3');
                }
                stack.pop();
                stack.push(op);
            } else if (hasENDIF) {
                stack.pop();
            } else if (!/layout/g.test(line)) {
                for (var varIndex = 0; varIndex < numVariablesWeCareAbout; ++varIndex) {
                    var varName = variablesThatWeCareAbout[varIndex];
                    if (line.indexOf(varName) !== -1) {
                        if (variableMap[varName].length === 1 && variableMap[varName][0] === null) {
                            variableMap[varName] = stack.slice();
                        } else {
                            variableMap[varName] = variableMap[varName].filter(function(x) {
                                return stack.indexOf(x) >= 0;
                            });
                        }
                    }
                }
            }
        }

        for (var care in variableMap) {
            if (variableMap.hasOwnProperty(care)) {
                if (variableMap.length === 1 && variableMap[0] === null) {
                    variableMap.splice(0, 1);
                }
            }
        }

        return variableMap;
    }

    function removeExtension(name, splitSource) {
        var regex = '#extension\\s+GL_' + name + '\\s+:\\s+[a-zA-Z0-9]+\\s*$';
        replaceInSourceRegex(new RegExp(regex, 'g'), '', splitSource);
    }

    /**
     * A function to port GLSL shaders from GLSL ES 1.00 to GLSL ES 3.00
     *
     * This function is nowhere near comprehensive or complete. It just
     * handles some common cases.
     *
     * Note that this function requires the presence of the
     * "#define OUTPUT_DECLARATION" line that is appended
     * by ShaderSource.
     *
     * @private
     */
    function modernizeShader(source, isFragmentShader) {
        var outputDeclarationRegex = /#define OUTPUT_DECLARATION/;
        var splitSource = source.split('\n');

        if (/#version 300 es/g.test(source)) {
            return source;
        }

        var outputDeclarationLine = -1;
        var number;
        for (number = 0; number < splitSource.length; ++number) {
            var line = splitSource[number];
            if (outputDeclarationRegex.exec(line)) {
                outputDeclarationLine = number;
                break;
            }
        }

        if (outputDeclarationLine === -1) {
            throw new DeveloperError('Could not find a #define OUTPUT_DECLARATION!');
        }

        var outputVariables = [];

        for (var i = 0; i < 10; i++) {
            var fragDataString = 'gl_FragData\\[' + i + '\\]';
            var newOutput = 'czm_out' + i;
            var regex = new RegExp(fragDataString, 'g');
            if (regex.test(source)) {
                setAdd(newOutput, outputVariables);
                replaceInSourceString(fragDataString, newOutput, splitSource);
                splitSource.splice(outputDeclarationLine, 0, 'layout(location = ' + i + ') out vec4 ' + newOutput + ';');
                outputDeclarationLine += 1;
            }
        }

        var czmFragColor = 'czm_fragColor';
        if (findInSource('gl_FragColor', splitSource)) {
            setAdd(czmFragColor, outputVariables);
            replaceInSourceString('gl_FragColor', czmFragColor, splitSource);
            splitSource.splice(outputDeclarationLine, 0, 'layout(location = 0) out vec4 czm_fragColor;');
            outputDeclarationLine += 1;
        }

        var variableMap = getVariablePreprocessorBranch(outputVariables, splitSource);
        var lineAdds = {};
        for (var c = 0; c < splitSource.length; c++) {
            var l = splitSource[c];
            for (var care in variableMap) {
                if (variableMap.hasOwnProperty(care)) {
                    var matchVar = new RegExp('(layout)[^]+(out)[^]+(' + care + ')[^]+', 'g');
                    if (matchVar.exec(l) !== null) {
                        lineAdds[l] = care;
                    }
                }
            }
        }

        for (var layoutDeclaration in lineAdds) {
            if (lineAdds.hasOwnProperty(layoutDeclaration)) {
                var variableName = lineAdds[layoutDeclaration];
                var lineNumber = splitSource.indexOf(layoutDeclaration);
                var entry = variableMap[variableName];
                var depth = entry.length;
                var d;
                for (d = 0; d < depth; d++) {
                    splitSource.splice(lineNumber, 0, entry[d]);
                }
                lineNumber += depth + 1;
                for (d = depth - 1; d >= 0; d--) {
                    splitSource.splice(lineNumber, 0, '#endif //' + entry[d]);
                }
            }
        }

        var versionThree = '#version 300 es';
        var foundVersion = false;
        for (number = 0; number < splitSource.length; number++) {
            if (/#version/.test(splitSource[number])) {
                splitSource[number] = versionThree;
                foundVersion = true;
            }
        }

        if (!foundVersion) {
            splitSource.splice(0, 0, versionThree);
        }

        removeExtension('EXT_draw_buffers', splitSource);
        removeExtension('EXT_frag_depth', splitSource);

        replaceInSourceString('texture2D', 'texture', splitSource);
        replaceInSourceString('texture3D', 'texture', splitSource);
        replaceInSourceString('textureCube', 'texture', splitSource);
        replaceInSourceString('gl_FragDepthEXT', 'gl_FragDepth', splitSource);

        if (isFragmentShader) {
            replaceInSourceString('varying', 'in', splitSource);
        } else {
            replaceInSourceString('attribute', 'in', splitSource);
            replaceInSourceString('varying', 'out', splitSource);
        }

        return compileSource(splitSource);
    }

    return modernizeShader;
});
<commit_msg>Replaces RegExp.exec with RegExp.test<commit_after>define([
        '../Core/defined',
        '../Core/DeveloperError',
    ], function(
        defined,
        DeveloperError) {
    'use strict';

    // Note that this fails if your string looks like
    // searchString[singleCharacter]searchString
    function replaceInSourceString(str, replacement, splitSource) {
        var regexStr = '(^|[^\\w])(' + str + ')($|[^\\w])';
        var regex = new RegExp(regexStr, 'g');

        for (var number = 0; number < splitSource.length; ++number) {
            var line = splitSource[number];
            splitSource[number] = line.replace(regex, '$1' + replacement + '$3');
        }
    }

    function replaceInSourceRegex(regex, replacement, splitSource) {
        for (var number = 0; number < splitSource.length; ++number) {
            var line = splitSource[number];
            splitSource[number] = line.replace(regex, replacement);
        }
    }

    function findInSource(str, splitSource) {
        var regexStr = '(^|[^\\w])(' + str + ')($|[^\\w])';
        var regex = new RegExp(regexStr, 'g');
        for (var number = 0; number < splitSource.length; ++number) {
            var line = splitSource[number];
            if (regex.test(line)) {
                return true;
            }
        }
        return false;
    }

    function compileSource(splitSource) {
        var wholeSource = '';
        for (var number = 0; number < splitSource.length; ++number) {
            wholeSource += splitSource[number] + '\n';
        }
        return wholeSource;
    }

    function setAdd(variable, set1) {
        if (set1.indexOf(variable) === -1) {
            set1.push(variable);
        }
    }

    function getVariablePreprocessorBranch(variablesThatWeCareAbout, splitSource) {
        var variableMap = {};

        var numVariablesWeCareAbout = variablesThatWeCareAbout.length;
        for (var a = 0; a < numVariablesWeCareAbout; ++a) {
            var variableThatWeCareAbout = variablesThatWeCareAbout[a];
            variableMap[variableThatWeCareAbout] = [null];
        }

        var stack = [];
        for (var i = 0; i < splitSource.length; ++i) {
            var line = splitSource[i];
            var hasIF = /(#ifdef|#if)/g.test(line);
            var hasELSE = /#else/g.test(line);
            var hasENDIF = /#endif/g.test(line);

            if (hasIF) {
                stack.push(line);
            } else if (hasELSE) {
                var top = stack[stack.length - 1];
                var op = top.replace('ifdef', 'ifndef');
                if (/if/g.test(op)) {
                    op = op.replace(/(#if\s+)(\S*)([^]*)/, '$1!($2)$3');
                }
                stack.pop();
                stack.push(op);
            } else if (hasENDIF) {
                stack.pop();
            } else if (!/layout/g.test(line)) {
                for (var varIndex = 0; varIndex < numVariablesWeCareAbout; ++varIndex) {
                    var varName = variablesThatWeCareAbout[varIndex];
                    if (line.indexOf(varName) !== -1) {
                        if (variableMap[varName].length === 1 && variableMap[varName][0] === null) {
                            variableMap[varName] = stack.slice();
                        } else {
                            variableMap[varName] = variableMap[varName].filter(function(x) {
                                return stack.indexOf(x) >= 0;
                            });
                        }
                    }
                }
            }
        }

        for (var care in variableMap) {
            if (variableMap.hasOwnProperty(care)) {
                if (variableMap.length === 1 && variableMap[0] === null) {
                    variableMap.splice(0, 1);
                }
            }
        }

        return variableMap;
    }

    function removeExtension(name, splitSource) {
        var regex = '#extension\\s+GL_' + name + '\\s+:\\s+[a-zA-Z0-9]+\\s*$';
        replaceInSourceRegex(new RegExp(regex, 'g'), '', splitSource);
    }

    /**
     * A function to port GLSL shaders from GLSL ES 1.00 to GLSL ES 3.00
     *
     * This function is nowhere near comprehensive or complete. It just
     * handles some common cases.
     *
     * Note that this function requires the presence of the
     * "#define OUTPUT_DECLARATION" line that is appended
     * by ShaderSource.
     *
     * @private
     */
    function modernizeShader(source, isFragmentShader) {
        var outputDeclarationRegex = /#define OUTPUT_DECLARATION/;
        var splitSource = source.split('\n');

        if (/#version 300 es/g.test(source)) {
            return source;
        }

        var outputDeclarationLine = -1;
        var number;
        for (number = 0; number < splitSource.length; ++number) {
            var line = splitSource[number];
            if (outputDeclarationRegex.exec(line)) {
                outputDeclarationLine = number;
                break;
            }
        }

        if (outputDeclarationLine === -1) {
            throw new DeveloperError('Could not find a #define OUTPUT_DECLARATION!');
        }

        var outputVariables = [];

        for (var i = 0; i < 10; i++) {
            var fragDataString = 'gl_FragData\\[' + i + '\\]';
            var newOutput = 'czm_out' + i;
            var regex = new RegExp(fragDataString, 'g');
            if (regex.test(source)) {
                setAdd(newOutput, outputVariables);
                replaceInSourceString(fragDataString, newOutput, splitSource);
                splitSource.splice(outputDeclarationLine, 0, 'layout(location = ' + i + ') out vec4 ' + newOutput + ';');
                outputDeclarationLine += 1;
            }
        }

        var czmFragColor = 'czm_fragColor';
        if (findInSource('gl_FragColor', splitSource)) {
            setAdd(czmFragColor, outputVariables);
            replaceInSourceString('gl_FragColor', czmFragColor, splitSource);
            splitSource.splice(outputDeclarationLine, 0, 'layout(location = 0) out vec4 czm_fragColor;');
            outputDeclarationLine += 1;
        }

        var variableMap = getVariablePreprocessorBranch(outputVariables, splitSource);
        var lineAdds = {};
        for (var c = 0; c < splitSource.length; c++) {
            var l = splitSource[c];
            for (var care in variableMap) {
                if (variableMap.hasOwnProperty(care)) {
                    var matchVar = new RegExp('(layout)[^]+(out)[^]+(' + care + ')[^]+', 'g');
                    if (matchVar.test(l)) {
                        lineAdds[l] = care;
                    }
                }
            }
        }

        for (var layoutDeclaration in lineAdds) {
            if (lineAdds.hasOwnProperty(layoutDeclaration)) {
                var variableName = lineAdds[layoutDeclaration];
                var lineNumber = splitSource.indexOf(layoutDeclaration);
                var entry = variableMap[variableName];
                var depth = entry.length;
                var d;
                for (d = 0; d < depth; d++) {
                    splitSource.splice(lineNumber, 0, entry[d]);
                }
                lineNumber += depth + 1;
                for (d = depth - 1; d >= 0; d--) {
                    splitSource.splice(lineNumber, 0, '#endif //' + entry[d]);
                }
            }
        }

        var versionThree = '#version 300 es';
        var foundVersion = false;
        for (number = 0; number < splitSource.length; number++) {
            if (/#version/.test(splitSource[number])) {
                splitSource[number] = versionThree;
                foundVersion = true;
            }
        }

        if (!foundVersion) {
            splitSource.splice(0, 0, versionThree);
        }

        removeExtension('EXT_draw_buffers', splitSource);
        removeExtension('EXT_frag_depth', splitSource);

        replaceInSourceString('texture2D', 'texture', splitSource);
        replaceInSourceString('texture3D', 'texture', splitSource);
        replaceInSourceString('textureCube', 'texture', splitSource);
        replaceInSourceString('gl_FragDepthEXT', 'gl_FragDepth', splitSource);

        if (isFragmentShader) {
            replaceInSourceString('varying', 'in', splitSource);
        } else {
            replaceInSourceString('attribute', 'in', splitSource);
            replaceInSourceString('varying', 'out', splitSource);
        }

        return compileSource(splitSource);
    }

    return modernizeShader;
});
<|endoftext|>


<commit_before>'use strict';

const defaultState = {
  types: [],
  selected: []
};

export default (state=defaultState, action) => {
  switch (action.type) {
  case 'DOCS_FETCH':
    return {
      ...state,
      types: [...new Set(action.docs.map(d => d.type))]
    };
  case 'DOC_INSERT':
    return {
      ...state,
      types: [...new Set([...state.types, action.doc.type])]
    };
  case 'TYPE_ADD':
    return {
      ...state,
      selected: [...state.selected, action.t]
    };
  case 'TYPE_REMOVE':
    return {
      ...state,
      selected: [...state.selected].filter(d => d !== action.t)
    };
  case 'TYPE_SET':
    return {
      ...state,
      selected: action.types
    };
  default:
    return state;
  }
};
<commit_msg>sorting the doc types before presentation<commit_after>'use strict';

const defaultState = {
  types: [],
  selected: []
};

export default (state=defaultState, action) => {
  switch (action.type) {
  case 'DOCS_FETCH':
    return {
      ...state,
      types: [...new Set(action.docs.map(d => d.type))].sort()
    };
  case 'DOC_INSERT':
    return {
      ...state,
      types: [...new Set([...state.types, action.doc.type])].sort()
    };
  case 'TYPE_ADD':
    return {
      ...state,
      selected: [...state.selected, action.t]
    };
  case 'TYPE_REMOVE':
    return {
      ...state,
      selected: [...state.selected].filter(d => d !== action.t)
    };
  case 'TYPE_SET':
    return {
      ...state,
      selected: action.types
    };
  default:
    return state;
  }
};
<|endoftext|>


<commit_before>// if you don't specify a html file, the sniper will generate a div
var app = require("biojs-vis-proteinfeaturesviewer");
var instance = new app({el: yourDiv, text: 'biojs', uniprotacc : 'P05067'});
instance.getDispatcher().on("ready", function() {
    console.log('ready');
});
instance.getDispatcher().on("featureSelected", function(obj) {
    console.log('feature selected');
    console.log(obj);
});
instance.getDispatcher().on("featureDeselected", function(obj) {
    console.log('feature deselected');
    console.log(obj);
});<commit_msg>Force jenkins refresh.<commit_after>// if you don't specify a html file, the sniper will generate a div
var app = require("biojs-vis-proteinfeaturesviewer");
var instance = new app({el: yourDiv, text: 'biojs', uniprotacc : 'P05067'});
instance.getDispatcher().on("ready", function() {
    console.log('ready');
});
instance.getDispatcher().on("featureSelected", function(obj) {
    console.log('Feature selected');
    console.log(obj);
});
instance.getDispatcher().on("featureDeselected", function(obj) {
    console.log('Feature deselected');
    console.log(obj);
});<|endoftext|>


<commit_before>/*
OpenFisca -- A versatile microsimulation software
By: OpenFisca Team <contact@openfisca.fr>

Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
https://github.com/openfisca

This file is part of OpenFisca.

OpenFisca is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

OpenFisca is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

// App config the for production environment.
// Do not require this directly. Use ./src/config instead.

export default {
  apiBaseUrl: "http://api-test.openfisca.fr",
  gitWebpageUrl: "https://git.framasoft.org/openfisca/legislation-explorer",
  websiteUrl: "http://www.openfisca.fr/",
};
<commit_msg>Update API URL<commit_after>/*
OpenFisca -- A versatile microsimulation software
By: OpenFisca Team <contact@openfisca.fr>

Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
https://github.com/openfisca

This file is part of OpenFisca.

OpenFisca is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

OpenFisca is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

// App config the for production environment.
// Do not require this directly. Use ./src/config instead.

export default {
  apiBaseUrl: "http://api.openfisca.fr",
  gitWebpageUrl: "https://git.framasoft.org/openfisca/legislation-explorer",
  websiteUrl: "http://www.openfisca.fr/",
};
<|endoftext|>