<commit_before>async function(args) {
/*
created_timestamp(-1)
base_component_id("app_editor_3")
is_app(true)
display_name("Editor App V3")
description("This will return the editor app V3")
logo_url("https://2.bp.blogspot.com/-6Hdixw3dFxk/WfSQOnB9lDI/AAAAAAAAFFc/84DRGgcwOpYBOgknkHQ-qmgxvFv1D-iHACLcBGAs/s1600/BracketsDarks.PNG")
load_once_from_file(true)
*/

    var argBaseComponentId = null
    var cardId = null
    await load("appEmbed")

    if (args) {
        argBaseComponentId = args.base_component_id
        cardId = args.card_id
    }
    Vue.component("app_editor_3",
    {
      props: ['app_id', 'card_index'],
      template: `

{{app_component_name?"" + app_component_name.substring(0,30):""}}{{(app_component_name && ((app_component_name.length > 30))?"...":"")}}

                            <select v-if='false' class="custom-select" v-model="selected_app" v-bind:onchange='load_new_app(selected_app)'>
                              <option value='' selected>Select an application to edit</option>
                              <option v-for='app in apps'
                                      v-bind:value="app.base_component_id"
                                      >{{app.display_name}}</option>
                            </select>
                            <button  type=button class='btn btn-primary'      v-on:click='chooseApp()'  >App</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='chooseCode()' >Code</button>
                            <button  type=button class=' btn btn-info'        v-on:click='chooseBoth()' >Both</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='copyAppMethod(base_component_id)' >Copy app</button>
                            <button  type=button class=' btn btn-info'        v-on:click='embedApp(base_component_id)' >Embed app</button>

                        <appEmbed v-bind:base_component_id_arg='base_component_id'></appEmbed>

                          <component  v-bind:is="editor_component" v-if="editor_loaded" ref="editorComponentRef">
                                          <button v-if='!read_only'
                                                  v-bind:style="'visibility: ' + ((app_shown && code_shown)?'':'hidden')"
                                                  slot-scope="editor_component"
                                                  v-on:click='save(base_component_id, code_id, editor_component.text2)'
                                                  type="button" class="btn btn-primary">

                                                      Update App
                                         </button>
                          </component>

                          <component  v-bind:is="app_component_name" v-if="app_loaded">
                            APP HERE
                          </component>

       `
       ,
       data: function() {
           return {
               editor_loaded:       false,
               selected_app:        '',
               editor_component:    null,
               app_loaded:          false,
               apps:               [],
               app_component_name:  null,
               base_component_id:   null,
               code_id:            "...",
               version: 0,
               card_id: null,
               app_width:           "33%",
               code_width:          "63%",
               app_shown:           true,
               code_shown:          true,
               read_only:           false,
               mode:                "edit"
           }
       }
       ,

       methods: {
            // ---------------------------------------------------------------
            //                         chooseApp
            //
            // This is called when the end user selects an app from the menu
            // ---------------------------------------------------------------
            chooseApp: function() {
                var mm = this
                this.code_width = "0%"
                this.code_shown = false

                this.app_width = "95%"
                this.app_shown = true

                var text = this.$refs.editorComponentRef.getText()

                //
                // there may be a problem here - we have to make sure that we saved
                // the correct code_id which is supposed to be the parent code id, so we
                // have to make sure that we save it every time we save code
                //
                this.save( this.base_component_id, this.code_id, text )
                //alert(1)
            },

            chooseCode: function() {
                var mm = this
                this.code_width = "95%"
                this.code_shown = true

                this.app_width = "0%"
                this.app_shown = false

                mm.load_app( this.base_component_id )
            },

            chooseBoth: function() {
                var mm = this
                this.code_width = "63%"
                this.code_shown = true

                this.app_width = "33%"
                this.app_shown = true
            },

            embedApp: function(x) {
                var mm = this
                this.mode = "embed"
            }
            ,

            copyAppMethod: async function( appId ) {
                var mm = this
                callDriverMethod( {driver_name: "copyApp",
                                   method_name: "copyAppshareApp"}
                                  ,{
                                      base_component_id:    appId
                                   }
                            ,
                            function(result) {
                                mm.load_new_app( result.value.base_component_id )
                                mm.$root.$emit('message', {
                                                                type:               "insert_app_at",
                                                                base_component_id:   result.value.base_component_id,
                                                                card_index:          mm.card_index
                                                            })

                            })
            }
            ,

           // ---------------------------------------------------------------
           //                           save
           //
           // This is called to save the currently edited code
           // ---------------------------------------------------------------
           save: async function( base_component_id, code_id, text ) {
               var mm = this
               //alert("Saving " + code_id)
               //alert("Saving " + text)
               //alert(base_component_id)
               var results = await callApp(
               {
                   driver_name:     "appEditorV2SaveCode",
                   method_name:     "saveCode"
               },
                   {
                        base_component_id:      base_component_id,
                        code_id:                code_id,
                        code:                   text
                   })
               //alert("Saved " + text)

               //alert("Reloading 2: " + JSON.stringify(results,null,2))
               //alert("Reloading 2: " + JSON.stringify(mm.base_component_id,null,2))
               mm.load_app( mm.base_component_id )
           },

           load_new_app: async function ( baseComponentId ) {
               var mm = this
               if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
               }
               this.editor_loaded = false
               this.load_app(baseComponentId)
           }
           ,

           // ---------------------------------------------------------------
           //                           load_app
           //
           // This loads the latest version of the code stream marked with
           // 'baseComponentId'
           // ---------------------------------------------------------------
           load_app: async function ( baseComponentId ) {
               var mm = this
               if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
               }
                mm.selected_app = ""

               //
               // set up vars
               //
               mm.app_loaded            = false
               mm.base_component_id     = baseComponentId
               mm.app_component_name    = null
               mm.card_id               = cardId

               //
               // read the code for the component that we are editing
               //
               var sql =    "select  id, cast(code as text)  as  code, editors  from  system_code  where " +
                            "        component_type = 'app' and base_component_id = '" + baseComponentId + "'" +
                            "        and code_tag = 'LATEST' "

               var results = await callApp(
                   {
                        driver_name:    "systemFunctions2",
                        method_name:    "sql"
                   }
                   ,
                   {
                       sql: sql
                   })

               if (results) {
                   //alert(JSON.stringify(results,null,2))
                   if (results.length > 0) {
                       var editors2 = results[0].editors
                       var newEditor = null
                       if (editors2) {
                            var edd = eval("(" + editors2 + ")")
                            newEditor = edd[0]
                       }
                       var code = results[0].code
                       var codeId = results[0].id
                       //alert(code)
                       if (mm.editor_loaded && (mm.code != code)) {
                            //alert("changed: " + code)
                            this.$refs.editorComponentRef.setText(code)
                       }
                       mm.code = code
                       mm.code_id = codeId
                       //alert(JSON.stringify(1,null,2))

                       if (!mm.editor_loaded) {
                            var editorName = "editor_component"
                            if (newEditor) {
                                 editorName = newEditor
                            }

                            await load(editorName,{text: code})
                            mm.editor_loaded = true
                            mm.editor_component = editorName
                       }

                       this.read_only = saveHelper.getValueOfCodeString(code, "read_only")

                   }

                   setTimeout(async function() {
                       var results = await callApp( {code_id:    codeId },{})
                       mm.app_loaded = true
                       mm.baseComponentId = baseComponentId
                       mm.app_component_name = baseComponentId
                       //alert(results.name + " loaded")
                   },200)
               }

               }

       },

       mounted: async function () {
           var mm = this
           //alert(argBaseComponentId)
           //alert(this.app_id)
            if (this.app_id) {
                //alert(this.app_id)
                //this.base_component_id = app_id
                this.load_app(this.app_id)
            }
           else if (argBaseComponentId) {
                this.load_app(argBaseComponentId)
            } else {
                var result = await callApp( {
                                        driver_name:  "systemFunctions",
                                        method_name:  "get_apps_list"  } ,{})

                mm.apps = result
            }
       }
       })
       return {name: "app_editor"}

}
<commit_msg>Trying to make "rename" in the app editor<commit_after>async function(args) {
/*
created_timestamp(-1)
base_component_id("app_editor_3")
is_app(true)
display_name("Editor App V3")
description("This will return the editor app V3")
logo_url("https://2.bp.blogspot.com/-6Hdixw3dFxk/WfSQOnB9lDI/AAAAAAAAFFc/84DRGgcwOpYBOgknkHQ-qmgxvFv1D-iHACLcBGAs/s1600/BracketsDarks.PNG")
load_once_from_file(true)
*/

    var argBaseComponentId = null
    var cardId = null
    await load("appEmbed")

    if (args) {
        argBaseComponentId = args.base_component_id
        cardId = args.card_id
    }
    Vue.component("app_editor_3",
    {
      props: ['app_id', 'card_index'],
      template: `

{{app_component_name?"" + app_component_name.substring(0,30):""}}{{(app_component_name && ((app_component_name.length > 30))?"...":"")}}

                        <input  class='caption' style='display: inline-block;' v-if='edit_name' v-model='new_name'></input>
                        <button type=button class='btn btn-primary' style='margin-left: 10px' v-if='edit_name' v-on:click='rename(new_name)'>Save new name</button>

                            <select v-if='false' class="custom-select" v-model="selected_app" v-bind:onchange='load_new_app(selected_app)'>
                              <option value='' selected>Select an application to edit</option>
                              <option v-for='app in apps'
                                      v-bind:value="app.base_component_id"
                                      >{{app.display_name}}</option>
                            </select>
                            <button  type=button class='btn btn-primary'      v-on:click='chooseApp()'  >App</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='chooseCode()' >Code</button>
                            <button  type=button class=' btn btn-info'        v-on:click='chooseBoth()' >Both</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='copyAppMethod(base_component_id)' >Copy app</button>
                            <button  type=button class=' btn btn-info'        v-on:click='embedApp(base_component_id)' >Embed app</button>

                        <appEmbed v-bind:base_component_id_arg='base_component_id'></appEmbed>

                          <component  v-bind:is="editor_component" v-if="editor_loaded" ref="editorComponentRef">
                                          <button v-if='!read_only'
                                                  v-bind:style="'visibility: ' + ((app_shown && code_shown)?'':'hidden')"
                                                  slot-scope="editor_component"
                                                  v-on:click='save(base_component_id, code_id, editor_component.text2)'
                                                  type="button" class="btn btn-primary">

                                                      Update App
                                         </button>
                          </component>

                          <component  v-bind:is="app_component_name" v-if="app_loaded">
                            APP HERE
                          </component>

       `
       ,
       data: function() {
           return {
               editor_loaded:       false,
               selected_app:        '',
               editor_component:    null,
               app_loaded:          false,
               apps:               [],
               app_component_name:  null,
               base_component_id:   null,
               code_id:            "...",
               version: 0,
               card_id: null,
               app_width:           "33%",
               code_width:          "63%",
               app_shown:           true,
               code_shown:          true,
               read_only:           false,
               mode:                "edit",
               show_name:           true,
               edit_name:           false,
               new_name:            ""
           }
       }
       ,

       methods: {
            // ---------------------------------------------------------------
            //                         chooseApp
            //
            // This is called when the end user selects an app from the menu
            // ---------------------------------------------------------------
            chooseApp: function() {
                var mm = this
                this.code_width = "0%"
                this.code_shown = false

                this.app_width = "95%"
                this.app_shown = true

                var text = this.$refs.editorComponentRef.getText()

                //
                // there may be a problem here - we have to make sure that we saved
                // the correct code_id which is supposed to be the parent code id, so we
                // have to make sure that we save it every time we save code
                //
                this.save( this.base_component_id, this.code_id, text )
                //alert(1)
            },

            chooseCode: function() {
                var mm = this
                this.code_width = "95%"
                this.code_shown = true

                this.app_width = "0%"
                this.app_shown = false

                mm.load_app( this.base_component_id )
            },

            chooseBoth: function() {
                var mm = this
                this.code_width = "63%"
                this.code_shown = true

                this.app_width = "33%"
                this.app_shown = true
            },

            rename: function(nn) {
            //zzz
                var text = this.$refs.editorComponentRef.getText()
                text = saveHelper.deleteCodeString(text, "base_component_id")
                text = saveHelper.insertCodeString(text, "base_component_id", nn)

                //
                // there may be a problem here - we have to make sure that we saved
                // the correct code_id which is supposed to be the parent code id, so we
                // have to make sure that we save it every time we save code
                //
                this.save( nn, this.code_id, text )
                this.edit_name = false
                this.show_name = true
            },

            embedApp: function(x) {
                var mm = this
                this.mode = "embed"
            }
            ,

            copyAppMethod: async function( appId ) {
                var mm = this
                callDriverMethod( {driver_name: "copyApp",
                                   method_name: "copyAppshareApp"}
                                  ,{
                                      base_component_id:    appId
                                   }
                            ,
                            function(result) {
                                mm.load_new_app( result.value.base_component_id )
                                mm.$root.$emit('message', {
                                                                type:               "insert_app_at",
                                                                base_component_id:   result.value.base_component_id,
                                                                card_index:          mm.card_index
                                                            })

                            })
            }
            ,

           // ---------------------------------------------------------------
           //                           save
           //
           // This is called to save the currently edited code
           // ---------------------------------------------------------------
           save: async function( base_component_id, code_id, text ) {
               var mm = this
               //alert("Saving " + code_id)
               //alert("Saving " + text)
               //alert(base_component_id)
               var results = await callApp(
               {
                   driver_name:     "appEditorV2SaveCode",
                   method_name:     "saveCode"
               },
                   {
                        base_component_id:      base_component_id,
                        code_id:                code_id,
                        code:                   text
                   })
               //alert("Saved " + text)

               //alert("Reloading 2: " + JSON.stringify(results,null,2))
               //alert("Reloading 2: " + JSON.stringify(mm.base_component_id,null,2))
               mm.load_app( mm.base_component_id )
           },

           load_new_app: async function ( baseComponentId ) {
               var mm = this
               if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
               }
               this.editor_loaded = false
               this.load_app(baseComponentId)
           }
           ,

           // ---------------------------------------------------------------
           //                           load_app
           //
           // This loads the latest version of the code stream marked with
           // 'baseComponentId'
           // ---------------------------------------------------------------
           load_app: async function ( baseComponentId ) {
               var mm = this
               if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
               }
                mm.selected_app = ""

               //
               // set up vars
               //
               mm.app_loaded            = false
               mm.base_component_id     = baseComponentId
               mm.app_component_name    = null
               mm.card_id               = cardId

               //
               // read the code for the component that we are editing
               //
               var sql =    "select  id, cast(code as text)  as  code, editors  from  system_code  where " +
                            "        component_type = 'app' and base_component_id = '" + baseComponentId + "'" +
                            "        and code_tag = 'LATEST' "

               var results = await callApp(
                   {
                        driver_name:    "systemFunctions2",
                        method_name:    "sql"
                   }
                   ,
                   {
                       sql: sql
                   })

               if (results) {
                   //alert(JSON.stringify(results,null,2))
                   if (results.length > 0) {
                       var editors2 = results[0].editors
                       var newEditor = null
                       if (editors2) {
                            var edd = eval("(" + editors2 + ")")
                            newEditor = edd[0]
                       }
                       var code = results[0].code
                       var codeId = results[0].id
                       //alert(code)
                       if (mm.editor_loaded && (mm.code != code)) {
                            //alert("changed: " + code)
                            this.$refs.editorComponentRef.setText(code)
                       }
                       mm.code = code
                       mm.code_id = codeId
                       //alert(JSON.stringify(1,null,2))

                       if (!mm.editor_loaded) {
                            var editorName = "editor_component"
                            if (newEditor) {
                                 editorName = newEditor
                            }

                            await load(editorName,{text: code})
                            mm.editor_loaded = true
                            mm.editor_component = editorName
                       }

                       this.read_only = saveHelper.getValueOfCodeString(code, "read_only")

                   }

                   setTimeout(async function() {
                       var results = await callApp( {code_id:    codeId },{})
                       mm.app_loaded = true
                       mm.baseComponentId = baseComponentId
                       mm.app_component_name = baseComponentId
                       //alert(results.name + " loaded")
                   },200)
               }

               }

       },

       mounted: async function () {
           var mm = this
           //alert(argBaseComponentId)
           //alert(this.app_id)
            if (this.app_id) {
                //alert(this.app_id)
                //this.base_component_id = app_id
                this.load_app(this.app_id)
            }
           else if (argBaseComponentId) {
                this.load_app(argBaseComponentId)
            } else {
                var result = await callApp( {
                                        driver_name:  "systemFunctions",
                                        method_name:  "get_apps_list"  } ,{})

                mm.apps = result
            }
       }
       })
       return {name: "app_editor"}

}
<|endoftext|>


<commit_before><commit_msg>remove extra file<commit_after><|endoftext|>


<commit_before>'use strict';
var assert = require('assert');
var connect = require('./rest_template').connect;

var utils = require('./suites/utils');
var getParameters = utils.getParameters;
var patchParameters = utils.patchParameters;
var generateDependencies = utils.generateDependencies;

var createClientAndUser = require('./test_invoice_db').createClientAndUser;

describe('Invoice REST API', function() {
  var urlRoot = 'http://localhost';
  var port = 3456;
  var resourceName = 'invoice';

  connect(urlRoot, port, resourceName);

  it('should fail with an empty invoice POST', function(done) {
    this.resource.post().then(function() {
      assert(false, 'Posted ' + resourceName + ' even though shouldn\'t');
    }).catch(function(res) {
      var data = res.data;

      assert(true, 'Failed to post ' + resourceName + ' as expected');

      assert.equal(res.status, 422);
      assert(data.message, 'Error message exists');
      assert(data.errors, 'Errors exist');
      assert(data.warnings, 'Warnings exist');
    }).finally(done);
  });

  it('should be able to POST an invoice', function(done) {
    var resource = this.resource;
    var postSchema = resource.post.parameters[0].schema;

    createClientAndUser(function(client, user) {
      // generate proper receiver/sender ids
      generateDependencies(this.client, this.schema, postSchema).then(function(d) {
        d.push({
          field: 'receiver',
          value: client.id
        });
        d.push({
          field: 'sender',
          value: user.id
        });
        d.push({
          field: 'due',
          value: new Date()
        });

        resource.post(
          patchParameters(getParameters(postSchema), d)
        ).then(function() {
          assert(true, 'Posted ' + resourceName + ' as expected');

          done();
        }).catch(done);
      }).catch(done);
    }.bind(this));
  });

  it('should be able to GET an invoice', function(done) {
    // TODO
    done();
  });

  it('should be able to PUT an invoice', function(done) {
    // TODO
    done();
  });

  it('should be able to approve an invoice', function(done) {
    // TODO
    done();
  });

  it('should be able to mark an invoice as paid', function(done) {
    // TODO
    done();
  });
});
<commit_msg>Add dummy test for GET<commit_after>'use strict';
var assert = require('assert');
var connect = require('./rest_template').connect;

var utils = require('./suites/utils');
var getParameters = utils.getParameters;
var patchParameters = utils.patchParameters;
var generateDependencies = utils.generateDependencies;

var createClientAndUser = require('./test_invoice_db').createClientAndUser;

describe('Invoice REST API', function() {
  var urlRoot = 'http://localhost';
  var port = 3456;
  var resourceName = 'invoice';

  connect(urlRoot, port, resourceName);

  it('should fail with an empty invoice POST', function(done) {
    this.resource.post().then(function() {
      assert(false, 'Posted ' + resourceName + ' even though shouldn\'t');
    }).catch(function(res) {
      var data = res.data;

      assert(true, 'Failed to post ' + resourceName + ' as expected');

      assert.equal(res.status, 422);
      assert(data.message, 'Error message exists');
      assert(data.errors, 'Errors exist');
      assert(data.warnings, 'Warnings exist');
    }).finally(done);
  });

  it('should be able to POST an invoice', function(done) {
    var resource = this.resource;
    var postSchema = resource.post.parameters[0].schema;

    createClientAndUser(function(client, user) {
      // generate proper receiver/sender ids
      generateDependencies(this.client, this.schema, postSchema).then(function(d) {
        d.push({
          field: 'receiver',
          value: client.id
        });
        d.push({
          field: 'sender',
          value: user.id
        });
        d.push({
          field: 'due',
          value: new Date()
        });

        resource.post(
          patchParameters(getParameters(postSchema), d)
        ).then(function() {
          assert(true, 'Posted ' + resourceName + ' as expected');

          done();
        }).catch(done);
      }).catch(done);
    }.bind(this));
  });

  it('should be able to GET an invoice', function(done) {
    this.resource.get().then(function(res) {
      assert(res.data.length === 0, 'Failed to get ' + resourceName + 's as expected');

      done();
    }).catch(done);
  });

  it('should be able to PUT an invoice', function(done) {
    // TODO
    done();
  });

  it('should be able to approve an invoice', function(done) {
    // TODO
    done();
  });

  it('should be able to mark an invoice as paid', function(done) {
    // TODO
    done();
  });
});
<|endoftext|>


<commit_before>/*
 * $Id: test.js,v 0.1 2016/01/04 09:17:08 dankogai Exp dankogai $
 *
 * use mocha to test me
 * http://visionmedia.github.com/mocha/
 */
var assert, G;
if (this['window'] !== this) {
    assert = require("assert");
    G = require('../hexfloat.js');
} else {
    G = this;
}
var is = function (a, e, m) {
    return function () {
        assert.equal(a, e, m)
    }
};

var dead_beef = 57005.7458343505859375;

describe('Hexadecimal Float', function () {
    it('Math.PI == 0x1.921fb54442d18p+1',
       is(G.parseHexFloat('0x1.921fb54442d18p+1'), Math.PI));
    it('-Math.PI == -0xc.90fdaa22168c235p-2',
       is(G.parseHexFloat('-0xc.90fdaa22168c235p-2'), -Math.PI));
    it('parseHexFloat(Math.PI.toHexString()) == Math.PI',
       is(G.parseHexFloat(Math.PI.toHexString()), Math.PI));
    it('Math.E == 0x1.5bf0a8b145769p+1',
       is(G.parseHexFloat('0x1.5bf0a8b145769p+1'), Math.E));
    it('-Math.E == -0xa.df85458a2bb4a9bp-2',
       is(G.parseHexFloat('-0xa.df85458a2bb4a9bp-2'), -Math.E));
    it('parseHexFloat(Math.E.toHexString()) == Math.E',
       is(G.parseHexFloat(Math.E.toHexString()), Math.E));
    it('0xdead.beefp0 == '+dead_beef,
       is(G.parseHexFloat('0xdead.beefp0'), dead_beef));
    it('dead_beef == 0xdead.beefp0',
       is((dead_beef).toHexString(), '0xdead.beefp0'));
    it('('+dead_beef+').toHexString(true) == 0x1.bd5b7ddep+15',
       is((dead_beef).toHexString(true), '0x1.bd5b7ddep+15'));
    it('(1/'+dead_beef+')toHexString(true) == 0x1.264eb565bf921p-16',
       is((1/dead_beef).toHexString(true), '0x1.264eb565bf921p-16'));
    it('0xdead.beefp0 == 0x1.bd5b7ddep+15',
       is(G.parseHexFloat('0xdead.beefp0'),
          G.parseHexFloat('0x1.bd5b7ddep+15')));
    it('-0x1p-42 == -Math.pow(2, -42)',
        is(G.parseHexFloat('-0x1p-42'), -Math.pow(2, -42)));
    it('isNaN(parseHexFloat("nonsense"))',
       is(isNaN(G.parseHexFloat('nonsense')), true));
});
<commit_msg>update test/test.js<commit_after>/*
 * $Id: test.js,v 0.1 2016/01/04 09:17:08 dankogai Exp dankogai $
 *
 * use mocha to test me
 * http://visionmedia.github.com/mocha/
 */
var assert, G;
if (this['window'] !== this) {
    assert = require("assert");
    parseHexFloat = require('../hexfloat.js').parseHexFloat;
}
var is = function (a, e, m) {
    return function () {
        assert.equal(a, e, m)
    }
};

var dead_beef = 57005.7458343505859375;

describe('Hexadecimal Float', function () {
    it('Math.PI == 0x1.921fb54442d18p+1',
       is(parseHexFloat('0x1.921fb54442d18p+1'), Math.PI));
    it('-Math.PI == -0xc.90fdaa22168c235p-2',
       is(parseHexFloat('-0xc.90fdaa22168c235p-2'), -Math.PI));
    it('parseHexFloat(Math.PI.toHexString()) == Math.PI',
       is(parseHexFloat(Math.PI.toHexString()), Math.PI));
    it('Math.E == 0x1.5bf0a8b145769p+1',
       is(parseHexFloat('0x1.5bf0a8b145769p+1'), Math.E));
    it('-Math.E == -0xa.df85458a2bb4a9bp-2',
       is(parseHexFloat('-0xa.df85458a2bb4a9bp-2'), -Math.E));
    it('parseHexFloat(Math.E.toHexString()) == Math.E',
       is(parseHexFloat(Math.E.toHexString()), Math.E));
    it('0xdead.beefp0 == '+dead_beef,
       is(parseHexFloat('0xdead.beefp0'), dead_beef));
    it('dead_beef == 0xdead.beefp0',
       is((dead_beef).toHexString(), '0xdead.beefp0'));
    it('('+dead_beef+').toHexString(true) == 0x1.bd5b7ddep+15',
       is((dead_beef).toHexString(true), '0x1.bd5b7ddep+15'));
    it('(1/'+dead_beef+')toHexString(true) == 0x1.264eb565bf921p-16',
       is((1/dead_beef).toHexString(true), '0x1.264eb565bf921p-16'));
    it('0xdead.beefp0 == 0x1.bd5b7ddep+15',
       is(parseHexFloat('0xdead.beefp0'), parseHexFloat('0x1.bd5b7ddep+15')));
    it('-0x1p-42 == -Math.pow(2, -42)',
        is(parseHexFloat('-0x1p-42'), -Math.pow(2, -42)));
    it('isNaN(parseHexFloat("nonsense"))',
       is(isNaN(parseHexFloat('nonsense')), true));
});
<|endoftext|>


<commit_before>define( [
    "backbone",
    "../datum/Datum",
    "recording/Recording",
    "recordings/Recordings"
//    "../user/User"
], function(
    Backbone,
    Datum,
    Recording,
    Recordings
//    User
    ) {
  var Exercise = Datum.extend(
   {
    /**
     * @class An Exercise is a type of Datum. It has the same information as a Datum plus extra,
     * but we want some info (e.g. recordings) to be kept confidential.
     *
     * @property {String} timesListened This is number of times the whole AudioVideo has been listened to by a specific user
     *
     * @property {Date} lastListened This is the date of the last time the student listened to this Exercise
     *
     * @property {RecordArray} recordings This is the array of all the recordings made by the student
     * each recording will have an accuracyRating (a percentage saying how close to the student's recording is compared to the Datum's sound)
     * each recording will have privacy settings to be determined by the student
     * each recording will say who recorded it
     * each recording will say what date it was recorded
     * the RecordArray will tell us how many recordings it has in it.
     *
     * @property {User} To be replaced by either student or teacher, but for the moment we just use User to get its ID.
	 * maybe we don't need User because it'd be in Session, which is in Datum.
	 * ? @property {String} student This is the ID of the student whose progress we're tracking
     *
     * @extends Backbone.Model
     *
     * @constructs
     *
     */
    initialize : function() {
      Exercise.__super__.initialize.call(this,);

//      this.set("user", "");
      this.set("lastListened", new Date(JSON.parse(t)));
      this.set("timesListened", "");
      //make the array of recordings

    },

    internalModels : {
      // recordAudio  :  RecordAudio
      // compareAudio  :  CompareAudio
    },
    saveAndInterConnectInApp : function(callback){

      if(typeof callback == "function"){
        callback();
      }
    }
  });

  return Exercise;
});

<commit_msg>found a small bug in a dead file<commit_after>define( [
    "backbone",
    "../datum/Datum",
    "recording/Recording",
    "recordings/Recordings"
//    "../user/User"
], function(
    Backbone,
    Datum,
    Recording,
    Recordings
//    User
    ) {
  var Exercise = Datum.extend(
   {
    /**
     * @class An Exercise is a type of Datum. It has the same information as a Datum plus extra,
     * but we want some info (e.g. recordings) to be kept confidential.
     *
     * @property {String} timesListened This is number of times the whole AudioVideo has been listened to by a specific user
     *
     * @property {Date} lastListened This is the date of the last time the student listened to this Exercise
     *
     * @property {RecordArray} recordings This is the array of all the recordings made by the student
     * each recording will have an accuracyRating (a percentage saying how close to the student's recording is compared to the Datum's sound)
     * each recording will have privacy settings to be determined by the student
     * each recording will say who recorded it
     * each recording will say what date it was recorded
     * the RecordArray will tell us how many recordings it has in it.
     *
     * @property {User} To be replaced by either student or teacher, but for the moment we just use User to get its ID.
	 * maybe we don't need User because it'd be in Session, which is in Datum.
	 * ? @property {String} student This is the ID of the student whose progress we're tracking
     *
     * @extends Backbone.Model
     *
     * @constructs
     *
     */
    initialize : function() {
//      Exercise.__super__.initialize.call(this,);

//      this.set("user", "");
      this.set("lastListened", new Date(JSON.parse(t)));
      this.set("timesListened", "");
      //make the array of recordings

    },

    internalModels : {
      // recordAudio  :  RecordAudio
      // compareAudio  :  CompareAudio
    },
    saveAndInterConnectInApp : function(callback){

      if(typeof callback == "function"){
        callback();
      }
    }
  });

  return Exercise;
});

<|endoftext|>


<commit_before>const parser = require("@babel/parser")
const traverse = require("@babel/traverse").default
const t = require("@babel/types")
const generate = require("@babel/generator").default

const code = `
import { render, h } from 'omis'

const Index = (props, store) => {
  return (
    <view>
      <text> {store.item.index}}: {store.item.msg} </text>
      <text> Time: {store.item.time} </text>
    </view>
  )
}

Index.store = _ => {
  return {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
    }
  }
}

render(<Index />, 'body')`;

const ast = parser.parse(code, {
  sourceType: 'module',
  plugins: [
    // enable jsx and flow syntax
    "jsx"
  ]
});

console.log(ast)
traverse(ast, {
  enter(path) {
    if (path.isIdentifier({ name: "n" })) {
      path.node.name = "x";
    }
  },
  JSXElement(p) {
    //p.stop();
    p.node.openingElement.attributes.push(t.jsxAttribute(t.JSXIdentifier('a'), t.StringLiteral('1')))
    console.log(p)
  }
})

console.log(generate(ast).code)

//输出
// import { render, h } from 'omis';

// const Index = (props, store) => {
//   return <view a="1" a="1">
//       <text a="1"> {store.item.index}}: {store.item.msg} </text>
//       <text a="1"> Time: {store.item.time} </text>
//     </view>;
// };

// Index.store = _ => {
//   return {
//     item: {
//       index: 0,
//       msg: 'this is a template',
//       time: '2016-09-15'
//     }
//   };
// };

// render(<Index a="1" />, 'body');<commit_msg>omip-new - generate testing<commit_after>const parser = require("@babel/parser")
const traverse = require("@babel/traverse").default
const t = require("@babel/types")
const generate = require("@babel/generator").default

const code = `
import { render, h } from 'omis'

const Index = (props, store) => {
  const abc =

  return (
    <view>
      <text> {store.item.index}: {store.item.msg} </text>
      <text> Time: {store.item.time} </text>
    </view>
  )
}

Index.store = _ => {
  return {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
    }
  }
}

render(<Index />, 'body')`;

const ast = parser.parse(code, {
  sourceType: 'module',
  plugins: [
    // enable jsx and flow syntax
    "jsx"
  ]
});

console.log(ast)
var jsxList =[]
traverse(ast, {
  enter(path) {
    if (path.isIdentifier({ name: "n" })) {
      path.node.name = "x";
    }
  },
  JSXElement(p) {
    //p.stop();
    //change attributes
    p.node.openingElement.attributes.push(t.jsxAttribute(t.JSXIdentifier('a'), t.StringLiteral('1')))
    console.log(p)
    jsxList.push(p)
  }
})

//change tag name
jsxList[0].node.openingElement.name.name = 'view'
jsxList[0].node.closingElement.name.name = 'view'
console.log(generate(jsxList[0].node).code)

<|endoftext|>


<commit_before>import Vue from 'vue'
import { warn } from 'core/util/debug'

describe('Global config', () => {
  it('should warn replacing config object', () => {
    const originalConfig = Vue.config
    Vue.config = {}
    expect(Vue.config).toBe(originalConfig)
    expect('Do not replace the Vue.config object').toHaveBeenWarned()
  })

  describe('silent', () => {
    it('should be false by default', () => {
      warn('foo')
      expect('foo').toHaveBeenWarned()
    })

    it('should work when set to true', () => {
      Vue.config.silent = true
      warn('foo')
      expect('foo').not.toHaveBeenWarned()
      Vue.config.silent = false
    })
  })

  describe('optionMergeStrategies', () => {
    it('should allow defining custom option merging strategies', () => {
      const spy = jasmine.createSpy('option merging')
      Vue.config.optionMergeStrategies.__test__ = (parent, child, vm) => {
        spy(parent, child, vm)
        return child + 1
      }
      const Test = Vue.extend({
        __test__: 1
      })
      expect(spy.calls.count()).toBe(1)
      expect(spy).toHaveBeenCalledWith(undefined, 1, undefined)
      expect(Test.options.__test__).toBe(2)
      const test = new Test({
        __test__: 2
      })
      expect(spy.calls.count()).toBe(2)
      expect(spy).toHaveBeenCalledWith(2, 2, test)
      expect(test.$options.__test__).toBe(3)
    })
  })
})
<commit_msg>test: add test for ignoredElements<commit_after>import Vue from 'vue'
import { warn } from 'core/util/debug'

describe('Global config', () => {
  it('should warn replacing config object', () => {
    const originalConfig = Vue.config
    Vue.config = {}
    expect(Vue.config).toBe(originalConfig)
    expect('Do not replace the Vue.config object').toHaveBeenWarned()
  })

  describe('silent', () => {
    it('should be false by default', () => {
      warn('foo')
      expect('foo').toHaveBeenWarned()
    })

    it('should work when set to true', () => {
      Vue.config.silent = true
      warn('foo')
      expect('foo').not.toHaveBeenWarned()
      Vue.config.silent = false
    })
  })

  describe('optionMergeStrategies', () => {
    it('should allow defining custom option merging strategies', () => {
      const spy = jasmine.createSpy('option merging')
      Vue.config.optionMergeStrategies.__test__ = (parent, child, vm) => {
        spy(parent, child, vm)
        return child + 1
      }
      const Test = Vue.extend({
        __test__: 1
      })
      expect(spy.calls.count()).toBe(1)
      expect(spy).toHaveBeenCalledWith(undefined, 1, undefined)
      expect(Test.options.__test__).toBe(2)
      const test = new Test({
        __test__: 2
      })
      expect(spy.calls.count()).toBe(2)
      expect(spy).toHaveBeenCalledWith(2, 2, test)
      expect(test.$options.__test__).toBe(3)
    })
  })

  describe('ignoredElements', () => {
    it('should work', () => {
      Vue.config.ignoredElements = ['foo', /^ion-/]
      new Vue({
        template: `<div><foo/><ion-foo/><ion-bar/></div>`
      }).$mount()
      expect('Unknown custom element').not.toHaveBeenWarned()
      Vue.config.ignoredElements = []
    })
  })
})
<|endoftext|>


<commit_before>angular.module('app.services').factory('youtube',function () {

  var youtubeImage = 'http://img.youtube.com/vi/';

  return {
    parseId: function (url) {
      //noinspection JSUnresolvedFunction
      return (/(&|\?)v=(.+?)(&|$)/.exec((url || '').trimRight()) || [undefined, undefined, null])[2];
    },

    generatePreviewLink: function (id, previewId) {
      return !id ? null : youtubeImage + id + '/' + (previewId || 0) + '.jpg';
    }
  };

}).factory('formUtils', function () {
  return {
    getErrorFields: function (form) {
      var props = [];
      _(form.$error).each(function (fields) {
        if (fields) {
          _(fields).each(function (field) {
            if (!_.contains(props, field)) {
              props.push(field);
            }
          });
        }
      });
      return props;
    }
  };
}).factory('errorFormMessage',function (defaultsFormErrors) {

  return function (form, errors) {
    var result = [], unknownError = false;
    errors = _.defaults(errors || {}, defaultsFormErrors);

    _(form.$error).each(function (fields, errorKey) {
      if (fields) {
        if (errors[errorKey]) {
          result.push(errors[errorKey]);
        } else {
          unknownError = true;
        }
      }
    });

    if (!result.length || unknownError) {
      result.push(errors.defaultError);
    }

    return result;
  };

}).factory('getFormData',function () {

  function defaultTransform(value) {
    return _.isObject(value) ? _.clone(value) : value;
  }

  function getDataKey(transformer, originalKey) {
    if (_.isString(transformer)) {
      return transformer;
    } else if (_.isArray(transformer)) {
      return transformer[0];
    }
    return originalKey;
  }

  function getDataTransformer(transformer) {
    if (_.isFunction(transformer)) {
      return transformer;
    } else if (_.isArray(transformer)) {
      return transformer[1];
    }
    return defaultTransform;
  }

  return function (form, transformers) {
    transformers = transformers || {};
    var data = {};
    _(form).each(function (value, key) {
      if (_.isObject(value) && value.$name === key) {
        var dataKey = getDataKey(transformers[key], key);
        var dataTransformer = getDataTransformer(transformers[key]);
        data[dataKey] = dataTransformer(value.$modelValue);
      }
    });
    return data;
  };

}).factory('camelcase2underscore',function () {
  return function (string) {
    return string.replace(/([A-Z])/g, function ($1) {
      return '_' + $1.toLowerCase();
    });
  };
}).factory('formatOptions',function () {

  var colors = ['#54c5ff', '#ba3830', '#4fb0f3', '#dbfa08', '#08fac4'];

  return function (options) {
    var code = 65;
    var maxOption = _(options).max(function (option) {
      return option.votes_count;
    });

    var votes = _(options).reduce(function (memo, option) {
      return memo + option.votes_count;
    }, 0);

    var colorId = 0;
    _(options).each(function (option) {
      option.title = String.fromCharCode(code++);
      option.color = colors[colorId++];

      if (!colors[colorId]) {
        colorId = 0;
      }

      if (maxOption.votes_count) {
        option.width = option.votes_count * 100 / maxOption.votes_count;
        option.percent = option.votes_count * 100 / votes;
      } else {
        option.percent = 0;
      }
      if (!option.width) {
        option.width = 1;
      }
    });

    return votes;
  };
}).factory('iParse',function () {

  var hashTagsRegExp = /(\s|^)(#[\w-]+)/g;

  return {
    getTimeString: function (value) {
      return String(value).match(/\s(\d{1,2}:\d{1,2})/)[1];
    },
    wrapHashTags: function(value) {
      return String(value).replace(hashTagsRegExp, '$1<hash-tag>$2</hash-tag>');
    },
    wrapLinks: function(value) {
      return Autolinker.link(value);
    },
    htmlEscape: function(value) {
      return _.escape(value);
    }
  };
}).value('defaultsFormErrors', {
  required: 'Fill all required fields.',
  defaultError: 'Invalid data.',
  date: 'Invalid date.',
  email: 'Invalid email.',
  url: 'Invalid URL.'
}).value('stateAbbreviations', {
  US: {
    'Alabama': 'AL',
    'Alaska': 'AK',
    'Arizona': 'AZ',
    'Arkansas': 'AR',
    'California': 'CA',
    'Colorado': 'CO',
    'Connecticut': 'CT',
    'Delaware': 'DE',
    'Florida': 'FL',
    'Georgia': 'GA',
    'Hawaii': 'HI',
    'Idaho': 'ID',
    'Illinois': 'IL',
    'Indiana': 'IN',
    'Iowa': 'IA',
    'Kansas': 'KS',
    'Kentucky': 'KY',
    'Louisiana': 'LA',
    'Maine': 'ME',
    'Maryland': 'MD',
    'Massachusetts': 'MA',
    'Michigan': 'MI',
    'Minnesota': 'MN',
    'Mississippi': 'MS',
    'Missouri': 'MO',
    'Montana': 'MT',
    'Nebraska': 'NE',
    'Nevada': 'NV',
    'New Hampshire': 'NH',
    'New Jersey': 'NJ',
    'New Mexico': 'NM',
    'New York': 'NY',
    'North Carolina': 'NC',
    'North Dakota': 'ND',
    'Ohio': 'OH',
    'Oklahoma': 'OK',
    'Oregon': 'OR',
    'Pennsylvania': 'PA',
    'Rhode Island': 'RI',
    'South Carolina': 'SC',
    'South Dakota': 'SD',
    'Tennessee': 'TN',
    'Texas': 'TX',
    'Utah': 'UT',
    'Vermont': 'VT',
    'Virginia': 'VA',
    'Washington': 'WA',
    'West Virginia': 'WV',
    'Wisconsin': 'WI',
    'Wyoming': 'WY',
    'District of Columbia': 'DC'
  }
}).factory('Sha1',function () {
    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
  /*  SHA-1 implementation in JavaScript                  (c) Chris Veness 2002-2014 / MIT Licence  */
  /*                                                                                */
  /*  - see http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html                              */
  /*        http://csrc.nist.gov/groups/ST/toolkit/examples.html                                    */
  /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

  /* jshint node:true *//* global define, escape, unescape */
  'use strict';

  /**
   * SHA-1 hash function reference implementation.
   *
   * @namespace
   */
  var Sha1 = {};

  /**
   * Generates SHA-1 hash of string.
   *
   * @param   {string} msg - (Unicode) string to be hashed.
   * @returns {string} Hash of msg as hex character string.
   */
  Sha1.hash = function(msg) {
      // convert string to UTF-8, as SHA only deals with byte-streams
      msg = msg.utf8Encode();

      // constants [§4.2.1]
      var K = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6 ];

      // PREPROCESSING

      msg += String.fromCharCode(0x80);  // add trailing '1' bit (+ 0's padding) to string [§5.1.1]

      // convert string msg into 512-bit/16-integer blocks arrays of ints [§5.2.1]
      var l = msg.length/4 + 2; // length (in 32-bit integers) of msg + ‘1’ + appended length
      var N = Math.ceil(l/16);  // number of 16-integer-blocks required to hold 'l' ints
      var M = new Array(N);

      for (var i=0; i<N; i++) {
          M[i] = new Array(16);
          for (var j=0; j<16; j++) {  // encode 4 chars per integer, big-endian encoding
              M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) |
                  (msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
          } // note running off the end of msg is ok 'cos bitwise ops on NaN return 0
      }
      // add length (in bits) into final pair of 32-bit integers (big-endian) [§5.1.1]
      // note: most significant word would be (len-1)*8 >>> 32, but since JS converts
      // bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
      M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14]);
      M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;

      // set initial hash value [§5.3.1]
      var H0 = 0x67452301;
      var H1 = 0xefcdab89;
      var H2 = 0x98badcfe;
      var H3 = 0x10325476;
      var H4 = 0xc3d2e1f0;

      // HASH COMPUTATION [§6.1.2]

      var W = new Array(80); var a, b, c, d, e;
      for (var i=0; i<N; i++) {

          // 1 - prepare message schedule 'W'
          for (var t=0;  t<16; t++) W[t] = M[i][t];
          for (var t=16; t<80; t++) W[t] = Sha1.ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);

          // 2 - initialise five working variables a, b, c, d, e with previous hash value
          a = H0; b = H1; c = H2; d = H3; e = H4;

          // 3 - main loop
          for (var t=0; t<80; t++) {
              var s = Math.floor(t/20); // seq for blocks of 'f' functions and 'K' constants
              var T = (Sha1.ROTL(a,5) + Sha1.f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
              e = d;
              d = c;
              c = Sha1.ROTL(b, 30);
              b = a;
              a = T;
          }

          // 4 - compute the new intermediate hash value (note 'addition modulo 2^32')
          H0 = (H0+a) & 0xffffffff;
          H1 = (H1+b) & 0xffffffff;
          H2 = (H2+c) & 0xffffffff;
          H3 = (H3+d) & 0xffffffff;
          H4 = (H4+e) & 0xffffffff;
      }

      return Sha1.toHexStr(H0) + Sha1.toHexStr(H1) + Sha1.toHexStr(H2) +
            Sha1.toHexStr(H3) + Sha1.toHexStr(H4);
  };

  /**
   * Function 'f' [§4.1.1].
   * @private
   */
  Sha1.f = function(s, x, y, z)  {
      switch (s) {
          case 0: return (x & y) ^ (~x & z);           // Ch()
          case 1: return  x ^ y  ^  z;                 // Parity()
          case 2: return (x & y) ^ (x & z) ^ (y & z);  // Maj()
          case 3: return  x ^ y  ^  z;                 // Parity()
      }
  };

  /**
   * Rotates left (circular left shift) value x by n positions [§3.2.5].
   * @private
   */
  Sha1.ROTL = function(x, n) {
      return (x<<n) | (x>>>(32-n));
  };

  /**
   * Hexadecimal representation of a number.
   * @private
   */
  Sha1.toHexStr = function(n) {
      // note can't use toString(16) as it is implementation-dependant,
      // and in IE returns signed numbers when used on full words
      var s="", v;
      for (var i=7; i>=0; i--) { v = (n>>>(i*4)) & 0xf; s += v.toString(16); }
      return s;
  };

  /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

  /** Extend String object with method to encode multi-byte string to utf8
   *  - monsur.hossa.in/2012/07/20/utf-8-in-javascript.html */
  if (typeof String.prototype.utf8Encode == 'undefined') {
      String.prototype.utf8Encode = function() {
          return unescape( encodeURIComponent( this ) );
      };
  }

  /** Extend String object with method to decode utf8 string to multi-byte */
  if (typeof String.prototype.utf8Decode == 'undefined') {
      String.prototype.utf8Decode = function() {
          try {
              return decodeURIComponent( escape( this ) );
          } catch (e) {
              return this; // invalid UTF-8? return as-is
          }
      };
  }

  /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
  if (typeof module != 'undefined' && module.exports) module.exports = Sha1; // CommonJs export
  if (typeof define == 'function' && define.amd) define([], function() { return Sha1; }); // AMD

  return Sha1
})
<commit_msg>#436: make youtube videos working also with youtube.be url<commit_after>angular.module('app.services').factory('youtube',function () {

  var youtubeImage = 'http://img.youtube.com/vi/';

  return {
    parseId: function (url) {
      var yid = null
      //noinspection JSUnresolvedFunction
      if(url.indexOf('youtu.be') >= 0){ // https://youtu.be/iOmgD_aCSPM
        yid =  _.last(url.split('/'))
      } else // https://www.youtube.com/watch?v=iOmgD_aCSPM
        yid =  (/(&|\?)v=(.+?)(&|$)/.exec((url || '').trimRight()) || [undefined, undefined, null])[2];
      return yid
    },

    generatePreviewLink: function (id, previewId) {
      return !id ? null : youtubeImage + id + '/' + (previewId || 0) + '.jpg';
    }
  };

}).factory('formUtils', function () {
  return {
    getErrorFields: function (form) {
      var props = [];
      _(form.$error).each(function (fields) {
        if (fields) {
          _(fields).each(function (field) {
            if (!_.contains(props, field)) {
              props.push(field);
            }
          });
        }
      });
      return props;
    }
  };
}).factory('errorFormMessage',function (defaultsFormErrors) {

  return function (form, errors) {
    var result = [], unknownError = false;
    errors = _.defaults(errors || {}, defaultsFormErrors);

    _(form.$error).each(function (fields, errorKey) {
      if (fields) {
        if (errors[errorKey]) {
          result.push(errors[errorKey]);
        } else {
          unknownError = true;
        }
      }
    });

    if (!result.length || unknownError) {
      result.push(errors.defaultError);
    }

    return result;
  };

}).factory('getFormData',function () {

  function defaultTransform(value) {
    return _.isObject(value) ? _.clone(value) : value;
  }

  function getDataKey(transformer, originalKey) {
    if (_.isString(transformer)) {
      return transformer;
    } else if (_.isArray(transformer)) {
      return transformer[0];
    }
    return originalKey;
  }

  function getDataTransformer(transformer) {
    if (_.isFunction(transformer)) {
      return transformer;
    } else if (_.isArray(transformer)) {
      return transformer[1];
    }
    return defaultTransform;
  }

  return function (form, transformers) {
    transformers = transformers || {};
    var data = {};
    _(form).each(function (value, key) {
      if (_.isObject(value) && value.$name === key) {
        var dataKey = getDataKey(transformers[key], key);
        var dataTransformer = getDataTransformer(transformers[key]);
        data[dataKey] = dataTransformer(value.$modelValue);
      }
    });
    return data;
  };

}).factory('camelcase2underscore',function () {
  return function (string) {
    return string.replace(/([A-Z])/g, function ($1) {
      return '_' + $1.toLowerCase();
    });
  };
}).factory('formatOptions',function () {

  var colors = ['#54c5ff', '#ba3830', '#4fb0f3', '#dbfa08', '#08fac4'];

  return function (options) {
    var code = 65;
    var maxOption = _(options).max(function (option) {
      return option.votes_count;
    });

    var votes = _(options).reduce(function (memo, option) {
      return memo + option.votes_count;
    }, 0);

    var colorId = 0;
    _(options).each(function (option) {
      option.title = String.fromCharCode(code++);
      option.color = colors[colorId++];

      if (!colors[colorId]) {
        colorId = 0;
      }

      if (maxOption.votes_count) {
        option.width = option.votes_count * 100 / maxOption.votes_count;
        option.percent = option.votes_count * 100 / votes;
      } else {
        option.percent = 0;
      }
      if (!option.width) {
        option.width = 1;
      }
    });

    return votes;
  };
}).factory('iParse',function () {

  var hashTagsRegExp = /(\s|^)(#[\w-]+)/g;

  return {
    getTimeString: function (value) {
      return String(value).match(/\s(\d{1,2}:\d{1,2})/)[1];
    },
    wrapHashTags: function(value) {
      return String(value).replace(hashTagsRegExp, '$1<hash-tag>$2</hash-tag>');
    },
    wrapLinks: function(value) {
      return Autolinker.link(value);
    },
    htmlEscape: function(value) {
      return _.escape(value);
    }
  };
}).value('defaultsFormErrors', {
  required: 'Fill all required fields.',
  defaultError: 'Invalid data.',
  date: 'Invalid date.',
  email: 'Invalid email.',
  url: 'Invalid URL.'
}).value('stateAbbreviations', {
  US: {
    'Alabama': 'AL',
    'Alaska': 'AK',
    'Arizona': 'AZ',
    'Arkansas': 'AR',
    'California': 'CA',
    'Colorado': 'CO',
    'Connecticut': 'CT',
    'Delaware': 'DE',
    'Florida': 'FL',
    'Georgia': 'GA',
    'Hawaii': 'HI',
    'Idaho': 'ID',
    'Illinois': 'IL',
    'Indiana': 'IN',
    'Iowa': 'IA',
    'Kansas': 'KS',
    'Kentucky': 'KY',
    'Louisiana': 'LA',
    'Maine': 'ME',
    'Maryland': 'MD',
    'Massachusetts': 'MA',
    'Michigan': 'MI',
    'Minnesota': 'MN',
    'Mississippi': 'MS',
    'Missouri': 'MO',
    'Montana': 'MT',
    'Nebraska': 'NE',
    'Nevada': 'NV',
    'New Hampshire': 'NH',
    'New Jersey': 'NJ',
    'New Mexico': 'NM',
    'New York': 'NY',
    'North Carolina': 'NC',
    'North Dakota': 'ND',
    'Ohio': 'OH',
    'Oklahoma': 'OK',
    'Oregon': 'OR',
    'Pennsylvania': 'PA',
    'Rhode Island': 'RI',
    'South Carolina': 'SC',
    'South Dakota': 'SD',
    'Tennessee': 'TN',
    'Texas': 'TX',
    'Utah': 'UT',
    'Vermont': 'VT',
    'Virginia': 'VA',
    'Washington': 'WA',
    'West Virginia': 'WV',
    'Wisconsin': 'WI',
    'Wyoming': 'WY',
    'District of Columbia': 'DC'
  }
}).factory('Sha1',function () {
    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
  /*  SHA-1 implementation in JavaScript                  (c) Chris Veness 2002-2014 / MIT Licence  */
  /*                                                                                */
  /*  - see http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html                              */
  /*        http://csrc.nist.gov/groups/ST/toolkit/examples.html                                    */
  /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

  /* jshint node:true *//* global define, escape, unescape */
  'use strict';

  /**
   * SHA-1 hash function reference implementation.
   *
   * @namespace
   */
  var Sha1 = {};

  /**
   * Generates SHA-1 hash of string.
   *
   * @param   {string} msg - (Unicode) string to be hashed.
   * @returns {string} Hash of msg as hex character string.
   */
  Sha1.hash = function(msg) {
      // convert string to UTF-8, as SHA only deals with byte-streams
      msg = msg.utf8Encode();

      // constants [§4.2.1]
      var K = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6 ];

      // PREPROCESSING

      msg += String.fromCharCode(0x80);  // add trailing '1' bit (+ 0's padding) to string [§5.1.1]

      // convert string msg into 512-bit/16-integer blocks arrays of ints [§5.2.1]
      var l = msg.length/4 + 2; // length (in 32-bit integers) of msg + ‘1’ + appended length
      var N = Math.ceil(l/16);  // number of 16-integer-blocks required to hold 'l' ints
      var M = new Array(N);

      for (var i=0; i<N; i++) {
          M[i] = new Array(16);
          for (var j=0; j<16; j++) {  // encode 4 chars per integer, big-endian encoding
              M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) |
                  (msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
          } // note running off the end of msg is ok 'cos bitwise ops on NaN return 0
      }
      // add length (in bits) into final pair of 32-bit integers (big-endian) [§5.1.1]
      // note: most significant word would be (len-1)*8 >>> 32, but since JS converts
      // bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
      M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14]);
      M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;

      // set initial hash value [§5.3.1]
      var H0 = 0x67452301;
      var H1 = 0xefcdab89;
      var H2 = 0x98badcfe;
      var H3 = 0x10325476;
      var H4 = 0xc3d2e1f0;

      // HASH COMPUTATION [§6.1.2]

      var W = new Array(80); var a, b, c, d, e;
      for (var i=0; i<N; i++) {

          // 1 - prepare message schedule 'W'
          for (var t=0;  t<16; t++) W[t] = M[i][t];
          for (var t=16; t<80; t++) W[t] = Sha1.ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);

          // 2 - initialise five working variables a, b, c, d, e with previous hash value
          a = H0; b = H1; c = H2; d = H3; e = H4;

          // 3 - main loop
          for (var t=0; t<80; t++) {
              var s = Math.floor(t/20); // seq for blocks of 'f' functions and 'K' constants
              var T = (Sha1.ROTL(a,5) + Sha1.f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
              e = d;
              d = c;
              c = Sha1.ROTL(b, 30);
              b = a;
              a = T;
          }

          // 4 - compute the new intermediate hash value (note 'addition modulo 2^32')
          H0 = (H0+a) & 0xffffffff;
          H1 = (H1+b) & 0xffffffff;
          H2 = (H2+c) & 0xffffffff;
          H3 = (H3+d) & 0xffffffff;
          H4 = (H4+e) & 0xffffffff;
      }

      return Sha1.toHexStr(H0) + Sha1.toHexStr(H1) + Sha1.toHexStr(H2) +
            Sha1.toHexStr(H3) + Sha1.toHexStr(H4);
  };

  /**
   * Function 'f' [§4.1.1].
   * @private
   */
  Sha1.f = function(s, x, y, z)  {
      switch (s) {
          case 0: return (x & y) ^ (~x & z);           // Ch()
          case 1: return  x ^ y  ^  z;                 // Parity()
          case 2: return (x & y) ^ (x & z) ^ (y & z);  // Maj()
          case 3: return  x ^ y  ^  z;                 // Parity()
      }
  };

  /**
   * Rotates left (circular left shift) value x by n positions [§3.2.5].
   * @private
   */
  Sha1.ROTL = function(x, n) {
      return (x<<n) | (x>>>(32-n));
  };

  /**
   * Hexadecimal representation of a number.
   * @private
   */
  Sha1.toHexStr = function(n) {
      // note can't use toString(16) as it is implementation-dependant,
      // and in IE returns signed numbers when used on full words
      var s="", v;
      for (var i=7; i>=0; i--) { v = (n>>>(i*4)) & 0xf; s += v.toString(16); }
      return s;
  };

  /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

  /** Extend String object with method to encode multi-byte string to utf8
   *  - monsur.hossa.in/2012/07/20/utf-8-in-javascript.html */
  if (typeof String.prototype.utf8Encode == 'undefined') {
      String.prototype.utf8Encode = function() {
          return unescape( encodeURIComponent( this ) );
      };
  }

  /** Extend String object with method to decode utf8 string to multi-byte */
  if (typeof String.prototype.utf8Decode == 'undefined') {
      String.prototype.utf8Decode = function() {
          try {
              return decodeURIComponent( escape( this ) );
          } catch (e) {
              return this; // invalid UTF-8? return as-is
          }
      };
  }

  /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
  if (typeof module != 'undefined' && module.exports) module.exports = Sha1; // CommonJs export
  if (typeof define == 'function' && define.amd) define([], function() { return Sha1; }); // AMD

  return Sha1
})
<|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("REST API call control")
description("This will return the REST APIn call control")
base_component_id("rest_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "text",
            name:       "Dev text",
            default:    "REST API Call",
            type:       "String"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    140,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    40,
            type:       "Number"
        }
        ,
        {
            id:             "callDefaultRestApi",
            pre_snippet:    `await `,
            snippet:        `callDefaultRestApi()`,
            name:           "Execute Command",
            type:           "Action"
        }
        ,
        {
            id:         "callRestApi",
            pre_snippet:    `await `,
            snippet:    `callRestApi("http://INSERT_URL_HERE")`,
            name:       "Execute Command",
            type:       "Action"
        }
        ,
        {
            id:         "URL",
            name:       "URL",
            default:    "https://raw.githubusercontent.com/typicode/demo/master/db.json",
            type:       "String"
        }

    ]
)//properties
logo_url("/driver_icons/rest.png")
*/

    Vue.component("rest_control",{

        props: ["meta", "args","design_mode","refresh"]

        ,

        template:

`

        {{args.text}}

            <slot v-bind:refresh='refresh'>
            </slot>

`

        ,

        data: function() {
            return {
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

        }
        ,

        methods: {
            callRestApiInternal: async function() {
                var mm = this

                var result = await callFunction(
                {
                    driver_name: "rest_call_service",
                    method_name: "rest_call_service"
                }
                ,
                {
                    URL:    mm.args.URL
                })

                if (result) {
                    return result
                }
                return null
            }
            ,

            callDefaultRestApi: async function() {

                var qwe = await this.callRestApiInternal()
                return qwe
            }
            ,

            callRestApi: async function(urlToCall) {

                var mm = this
                if (urlToCall) {
                    mm.args.URL = urlToCall
                }
                var qwe = await this.callRestApiInternal()
                return qwe
            }

        }

    })
}
<commit_msg>Show more details for the REST control in the default design mode<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("REST API call control")
description("This will return the REST APIn call control")
base_component_id("rest_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "text",
            name:       "Dev text",
            default:    "REST API Call",
            type:       "String"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    180,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    70,
            type:       "Number"
        }
        ,
        {
            id:             "callDefaultRestApi",
            pre_snippet:    `await `,
            snippet:        `callDefaultRestApi()`,
            name:           "Execute Command",
            type:           "Action"
        }
        ,
        {
            id:         "callRestApi",
            pre_snippet:    `await `,
            snippet:    `callRestApi("http://INSERT_URL_HERE")`,
            name:       "Execute Command",
            type:       "Action"
        }
        ,
        {
            id:         "URL",
            name:       "URL",
            default:    "https://raw.githubusercontent.com/typicode/demo/master/db.json",
            type:       "String"
        }

    ]
)//properties
logo_url("/driver_icons/rest.png")
*/

    Vue.component("rest_control",{

        props: ["meta", "args","design_mode","refresh"]

        ,

        template:

`

        {{args.text}}

           {{args.text}}

           {{args.URL}}

            <slot v-bind:refresh='refresh'>
            </slot>

`

        ,

        data: function() {
            return {
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

        }
        ,

        methods: {
            callRestApiInternal: async function() {
                var mm = this

                var result = await callFunction(
                {
                    driver_name: "rest_call_service",
                    method_name: "rest_call_service"
                }
                ,
                {
                    URL:    mm.args.URL
                })

                if (result) {
                    return result
                }
                return null
            }
            ,

            callDefaultRestApi: async function() {

                var qwe = await this.callRestApiInternal()
                return qwe
            }
            ,

            callRestApi: async function(urlToCall) {

                var mm = this
                if (urlToCall) {
                    mm.args.URL = urlToCall
                }
                var qwe = await this.callRestApiInternal()
                return qwe
            }

        }

    })
}
<|endoftext|>


<commit_before>/**
 * @class  Router
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 * Routing system for the apps, used to manage flow from notifications, startups, direct routing.
 */

/**
 * * **trackWithGA**: Auto track the dispatched and resolved routes with GA
 * @type {Object}
 */
var config = _.extend({
	trackWithGA: false
}, Alloy.CFG.T.router);
exports.config = config;

var __Routes = [];
var XCallbackURL = require('T/ext/xcallbackurl');

/**
 * Register a route with defined callbacks
 *
 * @param  {String|RegExp|Function}   	key 			The route name.
 * It can be:
 * * `String`: (exact route match)
 * * `RegExp`: is evaluated with the argument and the matches are passed to the callback
 * * `Function`: must return a `non-undefined` value to be executed. That value is passed to the callback
 *
 * @param  {Function}	callback  		The callback
 */
function on(key, callback) {
	__Routes.push({ key: key, callback: callback });
}
exports.on = on;

/**
 * Dispatch the router
 * @param  {String} 	link 		The route
 */
function dispatch(link) {
	var run = false;
	var matches = null;

	var X = XCallbackURL.parse(link);
	var path = X.path();

	for (var i in __Routes) {
		var routeDefinition = __Routes[i];

		if (_.isString(routeDefinition.key)) {

			// Regular string equals
			run = (routeDefinition.key===path);

		} else if (_.isRegExp(routeDefinition.key)) {

			// Regular expression complex match
			matches = path.match(routeDefinition.key);
			run = !!(matches);
			if (matches) matches.shift();

		} else if (_.isFunction(routeDefinition.key)) {

			// Function match
			matches = routeDefinition.key(path);
			run = (matches!==undefined);

		}

		if (run) {
			Ti.API.debug("Router: Match found ("+routeDefinition.key.toString()+", "+JSON.stringify(matches)+")");
			if (config.trackWithGA) require('T/ga').trackScreen(link);

			routeDefinition.callback.apply(X, matches);

			return; // IS VERY IMPORTANT TO EXIT
		}
	}

	Ti.API.warn("Router: no matches for the selected route ("+link+")");
}
exports.dispatch = dispatch;

/**
 * @method go
 * @inheritDoc #dispatch
 * Alias for {@link #dispatch}
 */
exports.go = dispatch;
<commit_msg>Router explain doc<commit_after>/**
 * @class  Router
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 * Routing system for the apps, used to manage flow from notifications, startups, direct routing.
 */

/**
 * * **trackWithGA**: Auto track the dispatched and resolved routes with GA
 * @type {Object}
 */
var config = _.extend({
	trackWithGA: false
}, Alloy.CFG.T.router);
exports.config = config;

var __Routes = [];
var XCallbackURL = require('T/ext/xcallbackurl');

/**
 * Register a route with defined callbacks
 *
 * @param  {String|RegExp|Function}   	key 			The route name.
 * It can be:
 * * `String`: (exact route match)
 * * `RegExp`: is evaluated with the argument and the matches are passed to the callback
 * * `Function`: must return a `non-undefined` value to be executed. That value is passed to the callback
 *
 * @param  {Function}	callback  		The callback
 */
function on(key, callback) {
	__Routes.push({ key: key, callback: callback });
}
exports.on = on;

/**
 * Dispatch the router
 *
 * This function call the defined function with `Router.on`
 *
 * The param `this` represents an XCallback-URL Object for selected route.
 *
 * See {@link https://github.com/FokkeZB/UTiL/blob/master/XCallbackURL/XCallbackURL.js} for more details.
 *
 * The arguments passed are the matches for your regex definition (if present)
 *
 * @param  {String} 	link 		The route
 */
function dispatch(link) {
	var run = false;
	var matches = null;

	var X = XCallbackURL.parse(link);
	var path = X.path();

	for (var i in __Routes) {
		var routeDefinition = __Routes[i];

		if (_.isString(routeDefinition.key)) {

			// Regular string equals
			run = (routeDefinition.key===path);

		} else if (_.isRegExp(routeDefinition.key)) {

			// Regular expression complex match
			matches = path.match(routeDefinition.key);
			run = !!(matches);
			if (matches) matches.shift();

		} else if (_.isFunction(routeDefinition.key)) {

			// Function match
			matches = routeDefinition.key(path);
			run = (matches!==undefined);

		}

		if (run) {
			Ti.API.debug("Router: Match found ("+routeDefinition.key.toString()+", "+JSON.stringify(matches)+")");
			if (config.trackWithGA) require('T/ga').trackScreen(link);

			routeDefinition.callback.apply(X, matches);

			return; // IS VERY IMPORTANT TO EXIT
		}
	}

	Ti.API.warn("Router: no matches for the selected route ("+link+")");
}
exports.dispatch = dispatch;

/**
 * @method go
 * @inheritDoc #dispatch
 * Alias for {@link #dispatch}
 */
exports.go = dispatch;
<|endoftext|>


<commit_before>'use strict';

/**
 * lei-promise tests
 *
 * @author Zongmin Lei <leizongmin@gmail.com>
 */

const assert = require('assert');
const me = require('../');

describe('promisify', function () {

  it('passed 1 argument and callback 1 argument', function (done) {

    function sleep(ms, callback) {
      console.log(`sleep(${ms})`);
      setTimeout(function () {
        console.log(`sleep(${ms}) callback`);
        callback(null, ms);
      }, ms);
    }

    let sleep2 = me.promisify(sleep);

    sleep2(100).then(([ms]) => {
      console.log(ms);
      assert.equal(ms, 100);
      done();
    }).catch(err => {
      throw err;
    });

  });

  it('passed 2 argument and callback 2 argument', function (done) {

    function sleep(ms, msg, callback) {
      console.log(`sleep(${ms})`);
      setTimeout(function () {
        console.log(`sleep(${ms}) callback`);
        callback(null, msg, ms);
      }, ms);
    }

    let sleep2 = me.promisify(sleep);

    sleep2(100, 'ok').then(([msg, ms]) => {
      console.log(msg, ms);
      assert.equal(msg, 'ok');
      assert.equal(ms, 100);
      done();
    }).catch(err => {
      throw err;
    });

  });

  it('callback error', function (done) {

    function sleep(ms, callback) {
      console.log(`sleep(${ms})`);
      setTimeout(function () {
        console.log(`sleep(${ms}) callback`);
        let err = new Error('just test');
        err.code = 'just_test';
        callback(err);
      }, ms);
    }

    let sleep2 = me.promisify(sleep);

    sleep2(100).then(_ => {
      throw new Error('should catch error');
    }).catch(err => {
      assert.equal(err.code, 'just_test');
      done();
    });

  });

  it('after promisify still callback', function (done) {

    function sleep(ms, callback) {
      console.log(`sleep(${ms})`);
      setTimeout(function () {
        console.log(`sleep(${ms}) callback`);
        callback(null, ms);
      }, ms);
    }

    let sleep2 = me.promisify(sleep);

    sleep2(100, function (err, ms) {
      console.log(err, ms);
      assert.equal(err, null);
      assert.equal(ms, 100);
      done();
    });

  });

});

describe('callbackify', function () {

  it('passed 1 argument', function (done) {

    function sleep(ms) {
      console.log(`sleep(${ms})`);
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          console.log(`sleep(${ms}) resolve`);
          resolve(ms);
        }, ms);
      });
    }

    let sleep2 = me.callbackify(sleep);

    sleep2(100, function (err, ms) {
      console.log(err, ms);
      assert.equal(err, null);
      assert.equal(ms, 100);
      done();
    });

  });

  it('passed 2 argument', function (done) {

    function sleep(ms, msg) {
      console.log(`sleep(${ms})`);
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          console.log(`sleep(${ms}) resolve`);
          resolve([ms, msg]);
        }, ms);
      });
    }

    let sleep2 = me.callbackify(sleep);

    sleep2(100, 'ok', function (err, [ms, msg]) {
      console.log(err, ms, msg);
      assert.equal(err, null);
      assert.equal(ms, 100);
      assert.equal(msg, 'ok');
      done();
    });

  });

  it('reject', function (done) {

    function sleep(ms) {
      console.log(`sleep(${ms})`);
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          console.log(`sleep(${ms}) resolve`);
          var err = new Error('just test');
          err.code = 'just_test';
          reject(err);
        }, ms);
      });
    }

    let sleep2 = me.callbackify(sleep);

    sleep2(100, function (err) {
      console.log(err);
      assert.ok(err instanceof Error);
      assert.equal(err.code, 'just_test');
      done();
    });

  });

  it('after callbackify still callback', function (done) {

    function sleep(ms) {
      console.log(`sleep(${ms})`);
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          console.log(`sleep(${ms}) resolve`);
          resolve(ms);
        }, ms);
      });
    }

    let sleep2 = me.callbackify(sleep);

    sleep2(100).then(ms => {
      console.log(ms);
      assert.equal(ms, 100);
      done();
    }).catch(err => {
      throw err;
    });

  });

});
<commit_msg>test promisifyRequire()<commit_after>'use strict';

/**
 * lei-promise tests
 *
 * @author Zongmin Lei <leizongmin@gmail.com>
 */

const assert = require('assert');
const me = require('../');

describe('promisify', function () {

  it('passed 1 argument and callback 1 argument', function (done) {

    function sleep(ms, callback) {
      console.log(`sleep(${ms})`);
      setTimeout(function () {
        console.log(`sleep(${ms}) callback`);
        callback(null, ms);
      }, ms);
    }

    let sleep2 = me.promisify(sleep);

    sleep2(100).then(([ms]) => {
      console.log(ms);
      assert.equal(ms, 100);
      done();
    }).catch(err => {
      throw err;
    });

  });

  it('passed 2 argument and callback 2 argument', function (done) {

    function sleep(ms, msg, callback) {
      console.log(`sleep(${ms})`);
      setTimeout(function () {
        console.log(`sleep(${ms}) callback`);
        callback(null, msg, ms);
      }, ms);
    }

    let sleep2 = me.promisify(sleep);

    sleep2(100, 'ok').then(([msg, ms]) => {
      console.log(msg, ms);
      assert.equal(msg, 'ok');
      assert.equal(ms, 100);
      done();
    }).catch(err => {
      throw err;
    });

  });

  it('callback error', function (done) {

    function sleep(ms, callback) {
      console.log(`sleep(${ms})`);
      setTimeout(function () {
        console.log(`sleep(${ms}) callback`);
        let err = new Error('just test');
        err.code = 'just_test';
        callback(err);
      }, ms);
    }

    let sleep2 = me.promisify(sleep);

    sleep2(100).then(_ => {
      throw new Error('should catch error');
    }).catch(err => {
      assert.equal(err.code, 'just_test');
      done();
    });

  });

  it('after promisify still callback', function (done) {

    function sleep(ms, callback) {
      console.log(`sleep(${ms})`);
      setTimeout(function () {
        console.log(`sleep(${ms}) callback`);
        callback(null, ms);
      }, ms);
    }

    let sleep2 = me.promisify(sleep);

    sleep2(100, function (err, ms) {
      console.log(err, ms);
      assert.equal(err, null);
      assert.equal(ms, 100);
      done();
    });

  });

});

describe('callbackify', function () {

  it('passed 1 argument', function (done) {

    function sleep(ms) {
      console.log(`sleep(${ms})`);
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          console.log(`sleep(${ms}) resolve`);
          resolve(ms);
        }, ms);
      });
    }

    let sleep2 = me.callbackify(sleep);

    sleep2(100, function (err, ms) {
      console.log(err, ms);
      assert.equal(err, null);
      assert.equal(ms, 100);
      done();
    });

  });

  it('passed 2 argument', function (done) {

    function sleep(ms, msg) {
      console.log(`sleep(${ms})`);
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          console.log(`sleep(${ms}) resolve`);
          resolve([ms, msg]);
        }, ms);
      });
    }

    let sleep2 = me.callbackify(sleep);

    sleep2(100, 'ok', function (err, [ms, msg]) {
      console.log(err, ms, msg);
      assert.equal(err, null);
      assert.equal(ms, 100);
      assert.equal(msg, 'ok');
      done();
    });

  });

  it('reject', function (done) {

    function sleep(ms) {
      console.log(`sleep(${ms})`);
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          console.log(`sleep(${ms}) resolve`);
          var err = new Error('just test');
          err.code = 'just_test';
          reject(err);
        }, ms);
      });
    }

    let sleep2 = me.callbackify(sleep);

    sleep2(100, function (err) {
      console.log(err);
      assert.ok(err instanceof Error);
      assert.equal(err.code, 'just_test');
      done();
    });

  });

  it('after callbackify still callback', function (done) {

    function sleep(ms) {
      console.log(`sleep(${ms})`);
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          console.log(`sleep(${ms}) resolve`);
          resolve(ms);
        }, ms);
      });
    }

    let sleep2 = me.callbackify(sleep);

    sleep2(100).then(ms => {
      console.log(ms);
      assert.equal(ms, 100);
      done();
    }).catch(err => {
      throw err;
    });

  });

});

describe('promisifyRequire', function () {

  const fs = me.promisifyRequire('fs');
  const path = me.promisifyRequire('path');

  it('fs.readdir promise', function (done) {

    fs.readdir(__dirname).then(([list]) => {
      console.log(list);
      assert.ok(Array.isArray(list));
      assert.ok(list.length > 0);
      done();
    }).catch(err => {
      throw err;
    });

  });

  it('fs.readdir callback', function (done) {

    fs.readdir(__dirname, (err, list) => {
      console.log(err, list);
      assert.equal(err, null);
      assert.ok(Array.isArray(list));
      assert.ok(list.length > 0);
      done();
    });

  });

  it('fs.readdirSync', function () {

    let list = fs.readdirSync(__dirname);
    console.log(list);
    assert.ok(Array.isArray(list));
    assert.ok(list.length > 0);

  });

});
<|endoftext|>


<commit_before>'use strict';

const { describe, it } = require('../helpers/mocha');
const { expect } = require('../helpers/chai');
const sinon = require('sinon');
const path = require('path');
const _getStartAndEndCommands = require('../../src/get-start-and-end-commands');
const utils = require('../../src/utils');

const projectName = 'my-custom-app';
const startVersion = '0.0.1';
const endVersion = '0.0.2';
const packageRoot = '/test/package/root';
const packageVersion = startVersion;
const cwd = '/test/cwd';
const packageName = 'ember-cli';
const commandName = 'ember';
const blueprint = 'test-blueprint';
const blueprintPath = '/path/to/blueprint';
const projectPath = path.normalize(`${cwd}/${projectName}`);

describe(_getStartAndEndCommands, function() {
  let sandbox;
  let npxStub;
  let spawnStub;

  beforeEach(function() {
    sandbox = sinon.createSandbox();

    npxStub = sandbox.stub(utils, 'npx').resolves();
    spawnStub = sandbox.stub(utils, 'spawn').resolves();
  });

  afterEach(function() {
    sandbox.restore();
  });

  function getStartAndEndCommands(options) {
    return _getStartAndEndCommands(Object.assign({
      packageJson: { name: projectName },
      projectOptions: ['app'],
      startVersion,
      endVersion,
      startBlueprint: { name: 'ember-cli' },
      endBlueprint: { name: 'ember-cli' }
    }, options));
  }

  it('returns an options object', function() {
    let options = getStartAndEndCommands();

    expect(options.createProjectFromCache).to.be.a('function');
    expect(options.createProjectFromRemote).to.be.a('function');

    delete options.createProjectFromCache;
    delete options.createProjectFromRemote;

    expect(options).to.deep.equal({
      projectName,
      projectOptions: ['app'],
      packageName,
      commandName,
      startOptions: {
        packageVersion: startVersion,
        blueprint: { name: 'ember-cli' }
      },
      endOptions: {
        packageVersion: endVersion,
        blueprint: { name: 'ember-cli' }
      }
    });
  });

  it('can create a project from cache', async function() {
    let { createProjectFromCache } = getStartAndEndCommands();

    let createProject = createProjectFromCache({
      packageRoot,
      options: {
        projectName
      }
    });

    expect(await createProject(cwd)).to.equal(projectPath);

    expect(spawnStub.args).to.deep.equal([[
      'node',
      [
        path.normalize(`${packageRoot}/bin/ember`),
        'new',
        projectName,
        '-sn',
        '-sg',
        '--no-welcome'
      ],
      {
        cwd
      }
    ]]);
  });

  it('can create a project from remote', async function() {
    let { createProjectFromRemote } = getStartAndEndCommands();

    let createProject = createProjectFromRemote({
      options: {
        projectName,
        packageVersion,
        blueprint: { name: 'ember-cli' }
      }
    });

    expect(await createProject(cwd)).to.equal(projectPath);

    expect(npxStub.args).to.deep.equal([[
      `-p ${packageName}@${packageVersion} ${commandName} new ${projectName} -sn -sg --no-welcome`,
      {
        cwd
      }
    ]]);
  });

  describe('custom blueprint', function() {
    it('returns an options object', async function() {
      let options = getStartAndEndCommands({
        projectOptions: ['blueprint']
      });

      expect(options.createProjectFromRemote).to.be.a('function');

      delete options.createProjectFromRemote;

      expect(options).to.deep.equal({
        projectName,
        projectOptions: ['blueprint'],
        startOptions: {
          packageVersion: startVersion,
          blueprint: { name: 'ember-cli' }
        },
        endOptions: {
          packageVersion: endVersion,
          blueprint: { name: 'ember-cli' }
        }
      });
    });

    it('can create a project from remote', async function() {
      let { createProjectFromRemote } = getStartAndEndCommands();

      let createProject = createProjectFromRemote({
        options: {
          projectName,
          packageVersion,
          blueprint: {
            name: blueprint,
            path: blueprintPath
          }
        }
      });

      expect(await createProject(cwd)).to.equal(projectPath);

      expect(npxStub.args).to.deep.equal([[
        `${packageName} new ${projectName} -sn -sg --no-welcome -b ${blueprintPath}`,
        {
          cwd
        }
      ]]);
    });
  });

  describe('options', function() {
    async function processOptions(projectOptions) {
      let options = getStartAndEndCommands({
        projectOptions
      });

      expect(options.projectOptions).to.deep.equal(projectOptions);

      let createProject = options.createProjectFromCache({
        packageRoot,
        options: {
          projectName
        }
      });

      await createProject(cwd);

      return spawnStub.args[0][1];
    }

    it('can create an app', async function() {
      expect(await processOptions(['app'])).to.include('new');
    });

    it('can create an addon', async function() {
      expect(await processOptions(['addon'])).to.include('addon');
    });

    it('cannot create a glimmer app', async function() {
      await expect(processOptions(['glimmer']))
        .to.eventually.be.rejectedWith('cannot checkout older versions of glimmer blueprint');
    });

    it('can create an app with the --no-welcome option', async function() {
      expect(await processOptions(['app'])).to.include('--no-welcome');
    });

    it('can create an app without the --no-welcome option', async function() {
      expect(await processOptions(['app', 'welcome'])).to.not.include('--no-welcome');
    });

    it('can create an app without the yarn option', async function() {
      expect(await processOptions(['app'])).to.not.include('--yarn');
    });

    it('can create an app with the yarn option', async function() {
      expect(await processOptions(['app', 'yarn'])).to.include('--yarn');
    });
  });
});
<commit_msg>fix options assertion<commit_after>'use strict';

const { describe, it } = require('../helpers/mocha');
const { expect } = require('../helpers/chai');
const sinon = require('sinon');
const path = require('path');
const _getStartAndEndCommands = require('../../src/get-start-and-end-commands');
const utils = require('../../src/utils');

const projectName = 'my-custom-app';
const startVersion = '0.0.1';
const endVersion = '0.0.2';
const packageRoot = '/test/package/root';
const packageVersion = startVersion;
const cwd = '/test/cwd';
const packageName = 'ember-cli';
const commandName = 'ember';
const blueprint = 'test-blueprint';
const blueprintPath = '/path/to/blueprint';
const projectPath = path.normalize(`${cwd}/${projectName}`);

describe(_getStartAndEndCommands, function() {
  let sandbox;
  let npxStub;
  let spawnStub;

  beforeEach(function() {
    sandbox = sinon.createSandbox();

    npxStub = sandbox.stub(utils, 'npx').resolves();
    spawnStub = sandbox.stub(utils, 'spawn').resolves();
  });

  afterEach(function() {
    sandbox.restore();
  });

  function getStartAndEndCommands(options) {
    return _getStartAndEndCommands(Object.assign({
      packageJson: { name: projectName },
      projectOptions: ['app'],
      startVersion,
      endVersion,
      startBlueprint: { name: 'ember-cli' },
      endBlueprint: { name: 'ember-cli' }
    }, options));
  }

  it('returns an options object', function() {
    let options = getStartAndEndCommands();

    expect(options.createProjectFromCache).to.be.a('function');
    expect(options.createProjectFromRemote).to.be.a('function');

    delete options.createProjectFromCache;
    delete options.createProjectFromRemote;

    expect(options).to.deep.equal({
      projectName,
      projectOptions: ['app'],
      packageName,
      commandName,
      startOptions: {
        packageVersion: startVersion,
        blueprint: { name: 'ember-cli' }
      },
      endOptions: {
        packageVersion: endVersion,
        blueprint: { name: 'ember-cli' }
      }
    });
  });

  it('can create a project from cache', async function() {
    let { createProjectFromCache } = getStartAndEndCommands();

    let createProject = createProjectFromCache({
      packageRoot,
      options: {
        projectName
      }
    });

    expect(await createProject(cwd)).to.equal(projectPath);

    expect(spawnStub.args).to.deep.equal([[
      'node',
      [
        path.normalize(`${packageRoot}/bin/ember`),
        'new',
        projectName,
        '-sn',
        '-sg',
        '--no-welcome'
      ],
      {
        cwd
      }
    ]]);
  });

  it('can create a project from remote', async function() {
    let { createProjectFromRemote } = getStartAndEndCommands();

    let createProject = createProjectFromRemote({
      options: {
        projectName,
        packageVersion,
        blueprint: { name: 'ember-cli' }
      }
    });

    expect(await createProject(cwd)).to.equal(projectPath);

    expect(npxStub.args).to.deep.equal([[
      `-p ${packageName}@${packageVersion} ${commandName} new ${projectName} -sn -sg --no-welcome`,
      {
        cwd
      }
    ]]);
  });

  describe('custom blueprint', function() {
    it('returns an options object', async function() {
      let options = getStartAndEndCommands({
        projectOptions: ['blueprint'],
        startBlueprint: { name: blueprint },
        endBlueprint: { name: blueprint }
      });

      expect(options.createProjectFromRemote).to.be.a('function');

      delete options.createProjectFromRemote;

      expect(options).to.deep.equal({
        projectName,
        projectOptions: ['blueprint'],
        startOptions: {
          packageVersion: startVersion,
          blueprint: { name: blueprint }
        },
        endOptions: {
          packageVersion: endVersion,
          blueprint: { name: blueprint }
        }
      });
    });

    it('can create a project from remote', async function() {
      let { createProjectFromRemote } = getStartAndEndCommands();

      let createProject = createProjectFromRemote({
        options: {
          projectName,
          packageVersion,
          blueprint: {
            name: blueprint,
            path: blueprintPath
          }
        }
      });

      expect(await createProject(cwd)).to.equal(projectPath);

      expect(npxStub.args).to.deep.equal([[
        `${packageName} new ${projectName} -sn -sg --no-welcome -b ${blueprintPath}`,
        {
          cwd
        }
      ]]);
    });
  });

  describe('options', function() {
    async function processOptions(projectOptions) {
      let options = getStartAndEndCommands({
        projectOptions
      });

      expect(options.projectOptions).to.deep.equal(projectOptions);

      let createProject = options.createProjectFromCache({
        packageRoot,
        options: {
          projectName
        }
      });

      await createProject(cwd);

      return spawnStub.args[0][1];
    }

    it('can create an app', async function() {
      expect(await processOptions(['app'])).to.include('new');
    });

    it('can create an addon', async function() {
      expect(await processOptions(['addon'])).to.include('addon');
    });

    it('cannot create a glimmer app', async function() {
      await expect(processOptions(['glimmer']))
        .to.eventually.be.rejectedWith('cannot checkout older versions of glimmer blueprint');
    });

    it('can create an app with the --no-welcome option', async function() {
      expect(await processOptions(['app'])).to.include('--no-welcome');
    });

    it('can create an app without the --no-welcome option', async function() {
      expect(await processOptions(['app', 'welcome'])).to.not.include('--no-welcome');
    });

    it('can create an app without the yarn option', async function() {
      expect(await processOptions(['app'])).to.not.include('--yarn');
    });

    it('can create an app with the yarn option', async function() {
      expect(await processOptions(['app', 'yarn'])).to.include('--yarn');
    });
  });
});
<|endoftext|>