<commit_before>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var profile = require('../../../util/profile');
var utils = require('../../../util/utils');
var util = require('util');
var providerOperationConstants = require('./providerUtils').providerOperationConstants;
var Wildcard = utils.Wildcard;
var __ = require('underscore');
var $ = utils.getLocaleString;

exports.init = function (cli) {
  var log = cli.output;
  var withProgress = cli.interaction.withProgress.bind(cli.interaction);

  var provider = cli.category('provider');
  var providerOperations = provider.category('operations')
    .description($('Commands to get the operations or actions allowed by an Azure resource provider.'));

  providerOperations.command('show [operationSearchString]')
    .description($('Show operations for the requested provider action string. The command takes as input an action string (with possible wildcard (*) character(s)) which determines the action details to display.'))
    .usage('[options] <operationSearchString>')
    .option('-o --operationSearchString <operationSearchString>', $('The provider action string (with possible wildcard (*) characters). Example: "*" to get all actions for all providers, "Microsoft.Insights/*" to get actions for a particular provider, "*/virtualMachines/*" to get all actions that can be performed on virtual machines.'))
    .option('-s --subscription <subscription>', $('Subscription to show provider operations for'))
    .execute(function (operationSearchString, options, _) {
    var subscription = profile.current.getSubscription(options.subscription);
    var client = utils.createResourceClient(subscription);

    validateOperationString(operationSearchString);
    var flattenedProviderOperations = [];

    if (Wildcard.containWildcards(operationSearchString)) {
      // OperationSearchString has wildcard character
      flattenedProviderOperations = getProviderOperationsWithWildCard(client, operationSearchString, _);
    }
    else {
      flattenedProviderOperations = getProviderOperationsWithoutWildCard(client, operationSearchString, _);
    }

    cli.interaction.formatOutput(flattenedProviderOperations, function (data) {
      if (!data || data.length === 0) {
        log.info($('No operations available matching the input action string'));
      } else {
        data.forEach(function (operation) {
          displayAProviderOperation(operation);
        });
      }
    });
    });

  function validateOperationString(operationString) {
    if (__.contains(operationString, providerOperationConstants.UnsupportedWildCardCharacter)) {
      throw new Error($('Only (*) wildcard character is supported.'));
    }

    var components = operationString.split(providerOperationConstants.Separator);
    components.forEach(function (component) {
      if (__.contains(component, providerOperationConstants.WildCardCharacter) && component.length != 1) {
        throw new Error($('Individual parts in the search string should either be just a * or not contain *.'));
      }
    });

    if (components.length == 1 && components[0] != providerOperationConstants.WildCardCharacter) {
      throw new Error(util.format($('To get all operations under "%s", please specify the search string as "%s/*"'), operationString, operationString));
    }
  }

  function getProviderOperationsWithWildCard(client, actionString, _) {
    var operationsToDisplay = [];
    var providersData = [];
    var unflattenedOperationsForAllProviders;
    console.log("In get wildcard ", actionString);
    var providerFullName = getProviderFullNameOrDefault(actionString);
    console.log("providerFullName ", providerFullName);
    if (providerFullName === providerOperationConstants.WildCardCharacter) {
      // Get operations for all providers
      unflattenedOperationsForAllProviders = listAllProviderOperationsMetadata(client, _);
      providersData = providersData.concat(unflattenedOperationsForAllProviders);
    }
    else {
      var unflattenedOperationsForSpecificProvider = getProviderOperationsMetadata(client, providerFullName, _);
      providersData.push(unflattenedOperationsForSpecificProvider);
    }

    providersData.forEach(function (unflattenedProviderData) {
      var operations = getFlattenedOperationsFromProviderOperationsMetadata(unflattenedProviderData);

      operations.forEach(function (operation) {
        if (Wildcard.isMatchCaseInsensitive(operation.operation, actionString)) {
          operationsToDisplay.push(operation);
        }
      });
    });

    return operationsToDisplay;
  }

  function getProviderOperationsWithoutWildCard(client, actionString, _) {
    var operationsToDisplay = [];

    var providerFullName = getProviderFullNameOrDefault(actionString);

    if (!__.isEmpty(providerFullName)) {
      var unflattenedProviderOperations = getProviderOperationsMetadata(client, providerFullName, _);
      var operations = getFlattenedOperationsFromProviderOperationsMetadata(unflattenedProviderOperations);

      operationsToDisplay = operations.filter(function (operationObj) {
        return utils.ignoreCaseEquals(operationObj.operation, actionString.toLowerCase());
      });
    }
    return operationsToDisplay;
  }

  function getProviderFullNameOrDefault(actionString) {
    var index = actionString.indexOf(providerOperationConstants.Separator);
    var fullName = actionString;
    if (index > 0) {
      fullName = actionString.substring(0, index);
    }
    return fullName;
  }

  function displayAProviderOperation(resourceProviderOperation) {
    log.data($('Operation         : '), resourceProviderOperation.operation);
    log.data($('OperationName     : '), resourceProviderOperation.operationName);
    log.data($('ProviderNamespace : '), resourceProviderOperation.providerNamespace);
    log.data($('ResourceName      : '), resourceProviderOperation.resourceName);
    log.data($('Description       : '), resourceProviderOperation.description);
    log.data('');
  }

  function getProviderOperationsMetadata(client, providerFullName, _){
    return withProgress($('Getting providerOperations metadata'),
        function (log, _) {
      return client.providerOperationsMetadata.get(providerFullName, _).provider;
    }, _);
  }

  function listAllProviderOperationsMetadata(client, _) {
    return withProgress($('Getting providerOperations metadata'),
        function (log, _) {
      return client.providerOperationsMetadata.list(_).providers;
    }, _);
  }

  function getFlattenedOperationsFromProviderOperationsMetadata(provider) {
    var flattenedOperations = [];
    provider.operations.forEach(function (operation) {
      if (isUserOperation(operation)) {
        flattenedOperations.push(getFlattenedOperationObject(operation, provider.displayName));
      }
    });

    if (provider.resourceTypes) {
      provider.resourceTypes.forEach(function (rt) {
        rt.operations.forEach(function (operation) {
          if (isUserOperation(operation)) {
            flattenedOperations.push(getFlattenedOperationObject(operation, provider.displayName, rt.displayName));
          }
        });
      });
    }
    return flattenedOperations;
  }

  function isUserOperation(operation) {
    return (!operation.origin || operation.origin.indexOf('user') > -1);
  }

  function getFlattenedOperationObject(operation, providerDisplayName, resourceDisplayName) {

    var operationObject = {
      operation: operation.name,
      operationName: operation.displayName,
      description: operation.description,
      providerNamespace: providerDisplayName,
      resourceName: !resourceDisplayName ? '' : resourceDisplayName
    };

    return operationObject;
  }
};
<commit_msg>build fixes<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var profile = require('../../../util/profile');
var utils = require('../../../util/utils');
var util = require('util');
var providerOperationConstants = require('./providerUtils').providerOperationConstants;
var Wildcard = utils.Wildcard;
var __ = require('underscore');
var $ = utils.getLocaleString;

exports.init = function (cli) {
  var log = cli.output;
  var withProgress = cli.interaction.withProgress.bind(cli.interaction);

  var provider = cli.category('provider');
  var providerOperations = provider.category('operations')
    .description($('Commands to get the operations or actions allowed by an Azure resource provider.'));

  providerOperations.command('show [operationSearchString]')
    .description($('Show operations for the requested provider action string. The command takes as input an action string (with possible wildcard (*) character(s)) which determines the action details to display.'))
    .usage('[options] <operationSearchString>')
    .option('-o --operationSearchString <operationSearchString>', $('The provider action string (with possible wildcard (*) characters). Example: "*" to get all actions for all providers, "Microsoft.Insights/*" to get actions for a particular provider, "*/virtualMachines/*" to get all actions that can be performed on virtual machines.'))
    .option('-s --subscription <subscription>', $('Subscription to show provider operations for'))
    .execute(function (operationSearchString, options, _) {
    var subscription = profile.current.getSubscription(options.subscription);
    var client = utils.createResourceClient(subscription);

    validateOperationString(operationSearchString);
    var flattenedProviderOperations = [];

    if (Wildcard.containWildcards(operationSearchString)) {
      // OperationSearchString has wildcard character
      flattenedProviderOperations = getProviderOperationsWithWildCard(client, operationSearchString, _);
    }
    else {
      flattenedProviderOperations = getProviderOperationsWithoutWildCard(client, operationSearchString, _);
    }

    cli.interaction.formatOutput(flattenedProviderOperations, function (data) {
      if (!data || data.length === 0) {
        log.info($('No operations available matching the input action string'));
      } else {
        data.forEach(function (operation) {
          displayAProviderOperation(operation);
        });
      }
    });
    });

  function validateOperationString(operationString) {
    if (__.contains(operationString, providerOperationConstants.UnsupportedWildCardCharacter)) {
      throw new Error($('Only (*) wildcard character is supported.'));
    }

    var components = operationString.split(providerOperationConstants.Separator);
    components.forEach(function (component) {
      if (__.contains(component, providerOperationConstants.WildCardCharacter) && component.length != 1) {
        throw new Error($('Individual parts in the search string should either be just a * or not contain *.'));
      }
    });

    if (components.length == 1 && components[0] != providerOperationConstants.WildCardCharacter) {
      throw new Error(util.format($('To get all operations under "%s", please specify the search string as "%s/*"'), operationString, operationString));
    }
  }

  function getProviderOperationsWithWildCard(client, actionString, _) {
    var operationsToDisplay = [];
    var providersData = [];
    var unflattenedOperationsForAllProviders;
    var providerFullName = getProviderFullNameOrDefault(actionString);
    if (providerFullName === providerOperationConstants.WildCardCharacter) {
      // Get operations for all providers
      unflattenedOperationsForAllProviders = listAllProviderOperationsMetadata(client, _);
      providersData = providersData.concat(unflattenedOperationsForAllProviders);
    }
    else {
      var unflattenedOperationsForSpecificProvider = getProviderOperationsMetadata(client, providerFullName, _);
      providersData.push(unflattenedOperationsForSpecificProvider);
    }

    providersData.forEach(function (unflattenedProviderData) {
      var operations = getFlattenedOperationsFromProviderOperationsMetadata(unflattenedProviderData);

      operations.forEach(function (operation) {
        if (Wildcard.isMatchCaseInsensitive(operation.operation, actionString)) {
          operationsToDisplay.push(operation);
        }
      });
    });

    return operationsToDisplay;
  }

  function getProviderOperationsWithoutWildCard(client, actionString, _) {
    var operationsToDisplay = [];

    var providerFullName = getProviderFullNameOrDefault(actionString);

    if (!__.isEmpty(providerFullName)) {
      var unflattenedProviderOperations = getProviderOperationsMetadata(client, providerFullName, _);
      var operations = getFlattenedOperationsFromProviderOperationsMetadata(unflattenedProviderOperations);

      operationsToDisplay = operations.filter(function (operationObj) {
        return utils.ignoreCaseEquals(operationObj.operation, actionString.toLowerCase());
      });
    }
    return operationsToDisplay;
  }

  function getProviderFullNameOrDefault(actionString) {
    var index = actionString.indexOf(providerOperationConstants.Separator);
    var fullName = actionString;
    if (index > 0) {
      fullName = actionString.substring(0, index);
    }
    return fullName;
  }

  function displayAProviderOperation(resourceProviderOperation) {
    log.data($('Operation         : '), resourceProviderOperation.operation);
    log.data($('OperationName     : '), resourceProviderOperation.operationName);
    log.data($('ProviderNamespace : '), resourceProviderOperation.providerNamespace);
    log.data($('ResourceName      : '), resourceProviderOperation.resourceName);
    log.data($('Description       : '), resourceProviderOperation.description);
    log.data('');
  }

  function getProviderOperationsMetadata(client, providerFullName, _){
    return withProgress($('Getting providerOperations metadata'),
        function (log, _) {
      return client.providerOperationsMetadata.get(providerFullName, _).provider;
    }, _);
  }

  function listAllProviderOperationsMetadata(client, _) {
    return withProgress($('Getting providerOperations metadata'),
        function (log, _) {
      return client.providerOperationsMetadata.list(_).providers;
    }, _);
  }

  function getFlattenedOperationsFromProviderOperationsMetadata(provider) {
    var flattenedOperations = [];
    provider.operations.forEach(function (operation) {
      if (isUserOperation(operation)) {
        flattenedOperations.push(getFlattenedOperationObject(operation, provider.displayName));
      }
    });

    if (provider.resourceTypes) {
      provider.resourceTypes.forEach(function (rt) {
        rt.operations.forEach(function (operation) {
          if (isUserOperation(operation)) {
            flattenedOperations.push(getFlattenedOperationObject(operation, provider.displayName, rt.displayName));
          }
        });
      });
    }
    return flattenedOperations;
  }

  function isUserOperation(operation) {
    return (!operation.origin || operation.origin.indexOf('user') > -1);
  }

  function getFlattenedOperationObject(operation, providerDisplayName, resourceDisplayName) {

    var operationObject = {
      operation: operation.name,
      operationName: operation.displayName,
      description: operation.description,
      providerNamespace: providerDisplayName,
      resourceName: !resourceDisplayName ? '' : resourceDisplayName
    };

    return operationObject;
  }
};
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-24 00:13:21<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//=require jquery
//= require jquery.turbolinks
//=require materialize
//= require turbolinks
//= require materialize/extras/nouislider
//= require jquery_ujs
//= require_tree .
$(document).on('turbolinks:load', function() {
	console.log("Hi2")
    $('select').material_select();
  });
<commit_msg>MaterialSelect Bug<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery.turbolinks
//= require materialize
//= require turbolinks
//= require materialize/extras/nouislider
//= require jquery_ujs
//= require_tree .
$(document).on('turbolinks:load', function() {
	console.log("Hi2")
    $('select').material_select();
  });
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const config = require('./config');

const bot = new Discord.Client();

bot.on('ready', () => {
  console.log(bot.servers);
});

bot.login(config.discord.email, config.discord.password);
<commit_msg>Removed unwanted test.js<commit_after><|endoftext|>


<commit_before>var jasmine = require('jasmine-node');

jasmine.executeSpecsInFolder(
    __dirname + '/tests',
    function(runner, log) { },
    true,
    true,
    false,
    false,
    new RegExp("spec\\.(js|coffee)$", 'i'),
    {
        report: false,
        savePath : "./reports/",
        useDotNotation: true,
        consolidate: true
    }
);<commit_msg>forgot to remove that file!<commit_after><|endoftext|>


<commit_before>// Example images were taken from http://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html

var cv = require('opencv');

cv.readImage('./Template_Matching_Original_Image.jpg', function(err, im) {
	im.convertGrayscale();

	return cv.readImage('./Template_Matching_Template_Image.jpg', function(err, templ) {
		templ.convertGrayscale();

		// matching method (numbers) available: https://github.com/peterbraden/node-opencv/blob/13a1de4f9259b5e745021f3198a8339ac99edecd/src/Matrix.cc#L2262
		return im.matchTemplate(templ, 3, function(result){
			result.save('./result.jpg');
		});
	});
});
<commit_msg>working test with template matching<commit_after>// Example images were taken from http://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html

var cv = require('opencv');

cv.readImage('./Template_Matching_Original_Image.jpg', function(err, im) {
  if (err) return console.error('error loading image');

  var output = im.matchTemplate('./Template_Matching_Template_Image.jpg', 3);

  var matches = output.templateMatches(0.80, 1.0, 5, false);

  console.log(matches);
});
<|endoftext|>


<commit_before>const os = require('os');
const fs = require('fs');
const path = require('path');

const async = require('async');
const expect = require('chai').expect;

const env = process.env;

describe('v8flags', function () {

  afterEach(function () {
    delete require.cache[require.resolve('user-home')];
    var v8flags = require('./');
    try {
      [
        path.resolve(require('user-home'), v8flags.configfile),
        path.resolve(os.tmpdir(), v8flags.configfile)
      ].map(fs.unlinkSync);
    } catch (e) {}
    delete require.cache[require.resolve('user-home')];
  });

  it('should cache and call back with the v8 flags for the running process', function (done) {
    var v8flags = require('./');
    var configfile = path.resolve(require('user-home'), v8flags.configfile);
    v8flags(function (err, flags) {
      expect(flags).to.be.a('array');
      expect(fs.existsSync(configfile)).to.be.true;
      fs.unlinkSync(configfile);
      fs.writeFileSync(configfile, JSON.stringify({cached:true}));
      v8flags(function (cacheErr, cachedFlags) {
        expect(cachedFlags).to.deep.equal({cached:true});
        done();
      });
    });
  });

  it('should not append the file when multiple calls happen concurrently and the config file does not yet exist', function (done) {
    var v8flags = require('./');
    var configfile = path.resolve(require('user-home'), v8flags.configfile);
    async.parallel([v8flags, v8flags, v8flags], function (err, result) {
      v8flags(function (err2, res) {
        done();
      });
    });
  });

  it('should fall back to writing to a temp dir if user home can\'t be found', function (done) {
    delete env.HOME;
    delete env.USERPROFILE;
    delete env.HOMEDRIVE;
    delete env.HOMEPATH;
    delete env.LOGNAME;
    delete env.USER;
    delete env.LNAME;
    delete env.USERNAME;
    var v8flags = require('./');
    var configfile = path.resolve(os.tmpdir(), v8flags.configfile);
    v8flags(function (err, flags) {
      expect(fs.existsSync(configfile)).to.be.true;
      done();
    });
  });

});
<commit_msg>correct concurrency test<commit_after>const os = require('os');
const fs = require('fs');
const path = require('path');

const async = require('async');
const expect = require('chai').expect;

const env = process.env;

describe('v8flags', function () {

  afterEach(function () {
    delete require.cache[require.resolve('user-home')];
    var v8flags = require('./');
    try {
      [
        path.resolve(require('user-home'), v8flags.configfile),
        path.resolve(os.tmpdir(), v8flags.configfile)
      ].map(fs.unlinkSync);
    } catch (e) {}
    delete require.cache[require.resolve('user-home')];
  });

  it('should cache and call back with the v8 flags for the running process', function (done) {
    var v8flags = require('./');
    var configfile = path.resolve(require('user-home'), v8flags.configfile);
    v8flags(function (err, flags) {
      expect(flags).to.be.a('array');
      expect(fs.existsSync(configfile)).to.be.true;
      fs.unlinkSync(configfile);
      fs.writeFileSync(configfile, JSON.stringify({cached:true}));
      v8flags(function (cacheErr, cachedFlags) {
        expect(cachedFlags).to.deep.equal({cached:true});
        done();
      });
    });
  });

  it('should create config correctly when multiple concurrent calls happen and it does not exist yet', function (done) {
    var v8flags = require('./');
    var configfile = path.resolve(require('user-home'), v8flags.configfile);
    async.parallel([v8flags, v8flags], function (err, results) {
      v8flags(function (err, final) {
        expect(results[0]).to.deep.equal(final);
        expect(results[1]).to.deep.equal(final);
        done();
      });
    });
  });

  it('should fall back to writing to a temp dir if user home can\'t be found', function (done) {
    delete env.HOME;
    delete env.USERPROFILE;
    delete env.HOMEDRIVE;
    delete env.HOMEPATH;
    delete env.LOGNAME;
    delete env.USER;
    delete env.LNAME;
    delete env.USERNAME;
    var v8flags = require('./');
    var configfile = path.resolve(os.tmpdir(), v8flags.configfile);
    v8flags(function (err, flags) {
      expect(fs.existsSync(configfile)).to.be.true;
      done();
    });
  });

});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var ipaMetadataParser = require('./');

describe('should parse .ipa file', function(){
  it('should contain the correct data', function(done) {
    ipaMetadataParser('tests/fixtures/testApp.ipa', function(err, data) {
      assert.equal(err, void 0);

      assert.equal(data.metadata['CFBundleDisplayName'], 'Test App');
      assert.equal(data.metadata['CFBundleIdentifier'], 'io.mts.testapp');
      assert.equal(data.metadata['CFBundleName'], 'Test App');
      assert.equal(data.metadata['CFBundleShortVersionString'], '1.0.0');
      assert.equal(data.metadata['CFBundleVersion'], '1337');

      done();
    });
  });
});

describe('should parse .ipa files with binary .plist files', function(){
  it('should contain the correct data', function(done) {
    ipaMetadataParser('tests/fixtures/testApp-binaryPlist.ipa', function(err, data) {
      assert.equal(err, void 0);

      assert.equal(data.metadata['CFBundleDisplayName'], 'Test App');
      assert.equal(data.metadata['CFBundleIdentifier'], 'io.mts.testapp');
      assert.equal(data.metadata['CFBundleName'], 'Test App');
      assert.equal(data.metadata['CFBundleShortVersionString'], '1.0.0');
      assert.equal(data.metadata['CFBundleVersion'], '1337');

      done();
    });
  });
});
<commit_msg>Fix broken tests - because any error callback in async.parallel stops execution<commit_after>'use strict';

var assert = require('assert');
var ipaMetadataParser = require('./');

describe('should parse .ipa file', function(){
  it('should contain the correct data', function(done) {
    ipaMetadataParser('tests/fixtures/testApp.ipa', function(err, data) {
      assert.equal(data.metadata['CFBundleDisplayName'], 'Test App');
      assert.equal(data.metadata['CFBundleIdentifier'], 'io.mts.testapp');
      assert.equal(data.metadata['CFBundleName'], 'Test App');
      assert.equal(data.metadata['CFBundleShortVersionString'], '1.0.0');
      assert.equal(data.metadata['CFBundleVersion'], '1337');

      done();
    });
  });
});

describe('should parse .ipa files with binary .plist files', function(){
  it('should contain the correct data', function(done) {
    ipaMetadataParser('tests/fixtures/testApp-binaryPlist.ipa', function(err, data) {
      assert.equal(data.metadata['CFBundleDisplayName'], 'Test App');
      assert.equal(data.metadata['CFBundleIdentifier'], 'io.mts.testapp');
      assert.equal(data.metadata['CFBundleName'], 'Test App');
      assert.equal(data.metadata['CFBundleShortVersionString'], '1.0.0');
      assert.equal(data.metadata['CFBundleVersion'], '1337');

      done();
    });
  });
});
<|endoftext|>


<commit_before>var before = {
    setup: function () {
        cookies = document.cookie.split('; ')
        for (var i = 0, c; (c = (cookies)[i]) && (c = c.split('=')[0]); i++) {
            document.cookie = c + '=; expires=' + new Date(0).toUTCString();
        }
    }
};

module('read', before);

test('simple value', 1, function () {
    document.cookie = 'c=v';
    equal($.cookie('c'), 'v', 'should return value');
});

test('empty value', 1, function () {
    // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, which
    // resulted in a bug while reading such a cookie.
    $.cookie('c', '');
    equal($.cookie('c'), '', 'should return value');
});

test('not existing', 1, function () {
    equal($.cookie('whatever'), null, 'should return null');
});

test('decode', 1, function () {
    document.cookie = encodeURIComponent(' c') + '=' + encodeURIComponent(' v');
    equal($.cookie(' c'), ' v', 'should decode key and value');
});

test('raw: true', 1, function () {
    document.cookie = 'c=%20v';
    equal($.cookie('c', { raw: true }), '%20v', 'should not decode');
});
test('$.cookie.defaults.raw = true', 1, function () {
    document.cookie = 'c=%20v';
    $.cookie.defaults.raw = true;
    equal($.cookie('c'), '%20v', 'should not decode');
    $.cookie.defaults.raw = false;
});

test('embedded equals', 1, function() {
  $.cookie('c', 'foo=bar', { raw: true });
  equal($.cookie('c', { raw: true }), 'foo=bar', 'should include the entire value');
});

module('write', before);

test('String primitive', 1, function () {
    $.cookie('c', 'v');
    equal($.cookie('c'), 'v', 'should write value');
});

test('String object', 1, function () {
    $.cookie('c', new String('v'));
    equal($.cookie('c'), 'v', 'should write value');
});

test('value "[object Object]"', 1, function() {
    $.cookie('c', '[object Object]');
    equal($.cookie('c'), '[object Object]', 'should write value');
});

test('number', 1, function() {
    $.cookie('c', 1234);
    equal($.cookie('c'), '1234', 'should write value');
});

test('return value', 1, function () {
    equal($.cookie('c', 'v'), 'c=v', 'should return written cookie string');
});

test('raw: true', 1, function () {
    equal($.cookie('c', ' v', { raw: true }).split('=')[1],
        ' v', 'should not encode');
});

test('$.cookie.defaults.raw = true', 1, function () {
    $.cookie.defaults.raw = true;
    equal($.cookie('c', ' v').split('=')[1],
        ' v', 'should not encode');
    $.cookie.defaults.raw = false;
});

module('delete', before);

test('delete', 2, function () {
    document.cookie = 'c=v';
    $.cookie('c', null);
    equal(document.cookie, '', 'should delete with null as value');

    document.cookie = 'c=v';
    $.cookie('c', undefined);
    equal(document.cookie, '', 'should delete with undefined as value');
});
<commit_msg>Reviewed tests from pull request.<commit_after>var before = {
    setup: function () {
        cookies = document.cookie.split('; ')
        for (var i = 0, c; (c = (cookies)[i]) && (c = c.split('=')[0]); i++) {
            document.cookie = c + '=; expires=' + new Date(0).toUTCString();
        }

        $.cookie.defaults = {};
    }
};

module('read', before);

test('simple value', 1, function () {
    document.cookie = 'c=v';
    equal($.cookie('c'), 'v', 'should return value');
});

test('empty value', 1, function () {
    // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, which
    // resulted in a bug while reading such a cookie.
    $.cookie('c', '');
    equal($.cookie('c'), '', 'should return value');
});

test('not existing', 1, function () {
    equal($.cookie('whatever'), null, 'should return null');
});

test('decode', 1, function () {
    document.cookie = encodeURIComponent(' c') + '=' + encodeURIComponent(' v');
    equal($.cookie(' c'), ' v', 'should decode key and value');
});

test('raw: true', 1, function () {
    document.cookie = 'c=%20v';
    equal($.cookie('c', { raw: true }), '%20v', 'should not decode');
});

test('embedded equals', 1, function() {
  $.cookie('c', 'foo=bar', { raw: true });
  equal($.cookie('c', { raw: true }), 'foo=bar', 'should include the entire value');
});

test('defaults', 1, function () {
    document.cookie = 'c=%20v';
    $.cookie.defaults.raw = true;
    equal($.cookie('c'), '%20v', 'should use raw from defaults');
});

module('write', before);

test('String primitive', 1, function () {
    $.cookie('c', 'v');
    equal($.cookie('c'), 'v', 'should write value');
});

test('String object', 1, function () {
    $.cookie('c', new String('v'));
    equal($.cookie('c'), 'v', 'should write value');
});

test('value "[object Object]"', 1, function() {
    $.cookie('c', '[object Object]');
    equal($.cookie('c'), '[object Object]', 'should write value');
});

test('number', 1, function() {
    $.cookie('c', 1234);
    equal($.cookie('c'), '1234', 'should write value');
});

test('return value', 1, function () {
    equal($.cookie('c', 'v'), 'c=v', 'should return written cookie string');
});

test('raw: true', 1, function () {
    equal($.cookie('c', ' v', { raw: true }).split('=')[1],
        ' v', 'should not encode');
});

test('defaults', 1, function () {
    $.cookie.defaults.raw = true;
    equal($.cookie('c', ' v').split('=')[1], ' v', 'should use raw from defaults');
});

module('delete', before);

test('delete', 2, function () {
    document.cookie = 'c=v';
    $.cookie('c', null);
    equal(document.cookie, '', 'should delete with null as value');

    document.cookie = 'c=v';
    $.cookie('c', undefined);
    equal(document.cookie, '', 'should delete with undefined as value');
});
<|endoftext|>


<commit_before>var page        = require("webpage").create()

page.open("./index.html", function(status) {
  var result = page.evaluate(function() {
    var buildFailed = false
    var messages    = []
    var firstCell   = $(".cell").first()
    var lastCell    = $(".cell").last()

    firstCell.mousedown()
    test("Pen works", [
      [$(".cell[data-emoji=':star:']").length, 1, "One cell be star"],
      [firstCell.attr("data-emoji"), ":star:", "This cell be star"]
    ])

    $(".js-paint").focus()
    $("[alt=':100:']").parents(".js-emoji").click()
    lastCell.mousedown()
    test("Change emoji paint works", [
      [$(".js-paint").val(), ":100:", "Paint be 100"],
      [lastCell.attr('data-emoji'), ":100:", "This cell be 100"],
      [$(".cell[data-emoji=':100:']").length, 1, "One cell be 100"]
    ])

    firstCell.find(".js-sip").click()
    test("Sip works", [
      [$(".js-paint").val(), ":star:", "Paint be star"]
    ])

    firstCell.mousedown()
    test("Erasing works", [
      [$(".cell[data-emoji=':star:']").length, 0, "No cells be star"],
      [firstCell.attr("data-emoji"), ":white_large_square:", "This cell not star"]
    ])

    $('.js-bucketfy').click()
    firstCell.mousedown()
    test("Bucketfy works", [
      [$(".cell[data-emoji=':star:']").length, 143, "All cells but one be star"]
    ])

    function test(topic, expectations) {
      messages.push("# " + topic + "\n")
      expectations.forEach(function(arr) {
        var evaluation  = arr[0]
        var expectation = arr[1]
        var statement   = arr[2]

        if(evaluation != expectation) {
          buildFailed = true
          messages.push("– " + statement + "\n")
          messages.push("  Expected " + expectation + ", got " + evaluation + "\n\n")
        }
      })

      if(!buildFailed) {
        messages.push("YES!\n\n")
      }
    }

    return {buildFailed: buildFailed, messages: messages}
  })
  reveal(result)
})

function reveal(result) {
  console.log(result.messages.join(""))
  if(result.buildFailed) {
    console.log("😢  \x1B[91mNo good, something failed.\x1B[0m 💥\n")
    phantom.exit(result.buildFailed)
  } else {
    console.log("✨  \x1B[96mWho's awesome? You're awesome!\x1B[0m 👍\n")
    phantom.exit()
  }
}
<commit_msg>refactor tests<commit_after>var page = require("webpage").create()

page.open("./index.html", function(status) {
  var result = page.evaluate(function() {
    var buildFailed = false
    var messages    = []
    var firstCell   = $(".cell").first()
    var lastCell    = $(".cell").last()

    test("Pen works", function() {
      firstCell.mousedown()

      expectEqual($(".cell[data-emoji=':star:']").length, 1, "One cell be star")
      expectEqual(firstCell.attr("data-emoji"), ":star:", "This cell be star")
    })

    test("Change emoji paint works", function() {
      $(".js-paint").focus()
      $("[alt=':100:']").parents(".js-emoji").click()
      lastCell.mousedown()

      expectEqual($(".js-paint").val(), ":100:", "Paint be 100")
      expectEqual(lastCell.attr('data-emoji'), ":100:", "This cell be 100")
      expectEqual($(".cell[data-emoji=':100:']").length, 1, "One cell be 100")
    })

    test("Sip works", function() {
      firstCell.find(".js-sip").click()

      expectEqual($(".js-paint").val(), ":star:", "Paint be star")
    })

    test("Erasing works", function() {
      firstCell.mousedown()
      expectEqual($(".cell[data-emoji=':star:']").length, 0, "No cells be star")
      expectEqual(firstCell.attr("data-emoji"), ":white_large_square:", "This cell not star")
    })

    test("Bucketfy works", function() {
      $('.js-bucketfy').click()
      firstCell.mousedown()
      expectEqual($(".cell[data-emoji=':star:']").length, 143, "All cells but one be star")
    })

    function test(topic, testing) {
      messages.push("# " + topic + "\n")
      testing()

      if(!buildFailed) {
        messages.push("YES!\n\n")
      }
    }

    function expectEqual(evaluation, expectation, message) {
      if(evaluation != expectation) {
        buildFailed = true
        messages.push("– " + message + "\n")
        messages.push("  Expected " + expectation + ", got " + evaluation + "\n\n")
      }
    }

    return {buildFailed: buildFailed, messages: messages}
  })
  reveal(result)
})

function reveal(result) {
  console.log(result.messages.join(""))
  if(result.buildFailed) {
    console.log("😢  \x1B[91mNo good, something failed.\x1B[0m 💥\n")
    phantom.exit(result.buildFailed)
  } else {
    console.log("✨  \x1B[96mWho's awesome? You're awesome!\x1B[0m 👍\n")
    phantom.exit()
  }
}
<|endoftext|>


<commit_before>var TradeSocket = (function () {
    'use strict';

    var tradeSocket,
        socketUrl = "wss://www.devbin.io/websockets/contracts",
        bufferedSends = [];

    var status = function () {
        return tradeSocket && tradeSocket.readyState;
    };

    var isReady = function () {
        return tradeSocket && tradeSocket.readyState === 1;
    };

    var isClose = function () {
        return tradeSocket && tradeSocket.readyState === 3;
    };

    var sendBufferedSends = function () {
        while (bufferedSends.length > 0) {
            tradeSocket.send(JSON.stringify(bufferedSends.shift()));
        }
    };

    var init = function (token) {
        tradeSocket = new WebSocket(socketUrl);

        tradeSocket.onopen = function (token){
            sendBufferedSends();
        };

        tradeSocket.onmessage = function (msg){
            Message.process(msg);
        };

        tradeSocket.onclose = function (e) {
            console.log('socket closed', e);
        };

        tradeSocket.onerror = function (error) {
            console.log('socket error', error);
        };
    };

    var send = function(data) {
        if (isClose()) {
            bufferedSends.push(data);
            init();
        } else if (isReady()) {
            tradeSocket.send(JSON.stringify(data));
        } else {
            bufferedSends.push(data);
        }
    };

    var close = function () {
        if (tradeSocket) {
            tradeSocket.close();
        }
    };

    return {
        init: init,
        send: send,
        close: close,
        socket: function () { return tradeSocket; }
    };

})();
<commit_msg>check for socket close properly<commit_after>var TradeSocket = (function () {
    'use strict';

    var tradeSocket,
        socketUrl = "wss://www.devbin.io/websockets/contracts",
        bufferedSends = [];

    var status = function () {
        return tradeSocket && tradeSocket.readyState;
    };

    var isReady = function () {
        return tradeSocket && tradeSocket.readyState === 1;
    };

    var isClose = function () {
        return !tradeSocket || tradeSocket.readyState === 3;
    };

    var sendBufferedSends = function () {
        while (bufferedSends.length > 0) {
            tradeSocket.send(JSON.stringify(bufferedSends.shift()));
        }
    };

    var init = function (token) {
        tradeSocket = new WebSocket(socketUrl);

        tradeSocket.onopen = function (token){
            sendBufferedSends();
        };

        tradeSocket.onmessage = function (msg){
            Message.process(msg);
        };

        tradeSocket.onclose = function (e) {
            console.log('socket closed', e);
        };

        tradeSocket.onerror = function (error) {
            console.log('socket error', error);
        };
    };

    var send = function(data) {
        if (isClose()) {
            bufferedSends.push(data);
            init();
        } else if (isReady()) {
            tradeSocket.send(JSON.stringify(data));
        } else {
            bufferedSends.push(data);
        }
    };

    var close = function () {
        if (tradeSocket) {
            tradeSocket.close();
        }
    };

    return {
        init: init,
        send: send,
        close: close,
        socket: function () { return tradeSocket; }
    };

})();
<|endoftext|>


<commit_before>/*jshint laxbreak:true */

var assert = require('assert');
var metadata = require('./index');

describe('metadata.cmd()', function() {
  it('returns command without exif data', function() {
    var cmd = 'identify -format "name=%[name]\nsize=%[size]\nformat=%m\n'
            + 'colorspace=%[colorspace]\nheight=%[height]\nwidth=%[width]\n'
            + 'orientation=%[orientation]\n" /foo/bar/baz';

    assert.equal(metadata.cmd('/foo/bar/baz'), cmd);
  });

  it('returns command with exif data', function() {
    var cmd = 'identify -format "name=%[name]\nsize=%[size]\nformat=%m\n'
            + 'colorspace=%[colorspace]\nheight=%[height]\nwidth=%[width]\n'
            + 'orientation=%[orientation]\n%[exif:*]" /foo/bar/baz';

    assert.equal(metadata.cmd('/foo/bar/baz', {exif: true}), cmd);
  });
});

describe('metadata.parse()', function() {
  it('returns object for metadata string', function() {
    assert.deepEqual(metadata.parse('foo=bar\nbar=foo'), {
      foo: 'bar',
      bar: 'foo'
    });
  });

  it('skips empty lines', function() {
    assert.deepEqual(metadata.parse('foo=bar\n\nbar=foo\n\n'), {
      foo: 'bar',
      bar: 'foo'
    });
  });

  it('returns object for single value', function() {
    assert.deepEqual(metadata.parse('foo=bar'), {
      foo: 'bar'
    });
  });

  it('return correct size for bogus value', function() {
    assert.deepEqual(metadata.parse('size=4.296MBB'), {
      size: '4.296MB'
    });
  });

});

describe('metadata()', function() {
  it('returns metadata for image', function(done) {
    metadata('./image.jpg', { exif: true }, function(err, data) {
      assert.ifError(err);

      assert.equal(data.name, '');
      assert.equal(data.size, '4.296MB');
      assert.equal(data.format, 'JPEG');
      assert.equal(data.colorspace, 'sRGB');
      assert.equal(data.height, 3456);
      assert.equal(data.width, 5184);
      assert.equal(data.orientation, 'TopLeft');

      done();
    });
  });
});
<commit_msg>Sort test logically<commit_after>/*jshint laxbreak:true */

var assert = require('assert');
var metadata = require('./index');

describe('metadata.cmd()', function() {
  it('returns command without exif data', function() {
    var cmd = 'identify -format "name=%[name]\nsize=%[size]\nformat=%m\n'
            + 'colorspace=%[colorspace]\nheight=%[height]\nwidth=%[width]\n'
            + 'orientation=%[orientation]\n" /foo/bar/baz';

    assert.equal(metadata.cmd('/foo/bar/baz'), cmd);
  });

  it('returns command with exif data', function() {
    var cmd = 'identify -format "name=%[name]\nsize=%[size]\nformat=%m\n'
            + 'colorspace=%[colorspace]\nheight=%[height]\nwidth=%[width]\n'
            + 'orientation=%[orientation]\n%[exif:*]" /foo/bar/baz';

    assert.equal(metadata.cmd('/foo/bar/baz', {exif: true}), cmd);
  });
});

describe('metadata.parse()', function() {
  it('returns object for single value', function() {
    assert.deepEqual(metadata.parse('foo=bar'), {
      foo: 'bar'
    });
  });

  it('returns object for metadata string', function() {
    assert.deepEqual(metadata.parse('foo=bar\nbar=foo'), {
      foo: 'bar',
      bar: 'foo'
    });
  });

  it('skips empty lines', function() {
    assert.deepEqual(metadata.parse('foo=bar\n\nbar=foo\n\n'), {
      foo: 'bar',
      bar: 'foo'
    });
  });

  it('return correct size for bogus value', function() {
    assert.deepEqual(metadata.parse('size=4.296MBB'), {
      size: '4.296MB'
    });
  });

});

describe('metadata()', function() {
  it('returns metadata for image', function(done) {
    metadata('./image.jpg', { exif: true }, function(err, data) {
      assert.ifError(err);

      assert.equal(data.name, '');
      assert.equal(data.size, '4.296MB');
      assert.equal(data.format, 'JPEG');
      assert.equal(data.colorspace, 'sRGB');
      assert.equal(data.height, 3456);
      assert.equal(data.width, 5184);
      assert.equal(data.orientation, 'TopLeft');

      done();
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Image.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/*jshint smarttabs:true, undef:true, unused:true, latedef:true, curly:true, bitwise:false, scripturl:true, browser:true, laxcomma:true */
/*global define:true */

/**
@class moxie/runtime/html5/image/Image
@private
*/
define("moxie/runtime/html5/image/Image", [
	"moxie/runtime/html5/Runtime",
	"moxie/core/utils/Basic",
	"moxie/core/Exceptions",
	"moxie/core/utils/Encode",
	"moxie/file/Blob",
	"moxie/runtime/html5/image/ImageInfo",
	"moxie/runtime/html5/image/MegaPixel",
	"moxie/core/utils/Mime",
	"moxie/core/utils/Env"
], function(extensions, Basic, x, Encode, Blob, ImageInfo, MegaPixel, Mime, Env) {

	function HTML5Image() {
		var me = this
		, _img, _imgInfo, _canvas, _binStr, _srcBlob
		, _modified = false // is set true whenever image is modified
		, _preserveHeaders = true
		;

		Basic.extend(this, {
			loadFromBlob: function(blob) {
				var comp = this, I = comp.getRuntime()
				, asBinary = arguments.length > 1 ? arguments[1] : true
				;

				if (!I.can('access_binary')) {
					throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
				}

				if (blob.isDetached()) {
					_srcBlob = {
						name: blob.name,
						size: blob.size,
						type: blob.type
					};
					_loadFromBinaryString.call(this, blob.getSource());
					return;
				} else {
					_srcBlob = blob.getSource();

					if (asBinary) { // this will let us to hack the file internals
						_readAsBinaryString(_srcBlob, function(data) {
							_loadFromBinaryString.call(comp, data);
						});
					} else { // ... but this is faster
						_readAsDataUrl(_srcBlob, function(data) {
							_loadFromDataUrl.call(comp, data);
						});
					}
				}
			},

			loadFromImage: function(img, exact) {
				this.meta = img.meta;

				_srcBlob = {
					name: img.name,
					size: img.size,
					type: img.type
				};

				if (exact) {
					_loadFromBinaryString.call(this, img.getAsBinaryString());
				} else {
					_loadFromDataUrl.call(this, img.getAsDataURL());
				}
			},

			getInfo: function() {
				var I = this.getRuntime(), info;

				if (!_imgInfo && _binStr && I.can('access_image_binary')) {
					_imgInfo = new ImageInfo(_binStr);
				}

				info = {
					width: _getImg().width || 0,
					height: _getImg().height || 0,
					type: _srcBlob.type || Mime.getFileMime(_srcBlob.name),
					size: _binStr && _binStr.length || _srcBlob.size || 0,
					name: _srcBlob.name || '',
					meta: _imgInfo && _imgInfo.meta || this.meta || {}
				};

				return info;
			},

			resize: function() {
				_resize.apply(this, arguments);
			},

			getAsCanvas: function() {
				if (_canvas) {
					_canvas.id = this.uid + '_canvas';
				}
				return _canvas;
			},

			getAsBlob: function(type, quality) {
				if (type !== this.type) {
					// if different mime type requested prepare image for conversion
					_resize.call(this, this.width, this.height, false);
				}
				return new Blob(null, me.getAsDataURL.call(this, type, quality));
			},

			getAsDataURL: function(type) {
				var quality = arguments[1] || 90;

				// if image has not been modified, return the source right away
				if (!_modified) {
					return _img.src;
				}

				if ('image/jpeg' !== type) {
					return _canvas.toDataURL('image/png');
				} else {
					try {
						// older Geckos used to result in an exception on quality argument
						return _canvas.toDataURL('image/jpeg', quality/100);
					} catch (ex) {
						return _canvas.toDataURL('image/jpeg');
					}
				}
			},

			getAsBinaryString: function(type, quality) {
				// if image has not been modified, return the source right away
				if (!_modified) {
					// if image was not loaded from binary string
					if (!_binStr) {
						_binStr = _convertToBinary(me.getAsDataURL(type, quality));
					}
					return _binStr;
				}

				if ('image/jpeg' !== type) {
					_binStr = _convertToBinary(me.getAsDataURL(type, quality));
				} else {
					var dataUrl;

					// if jpeg
					if (!quality) {
						quality = 90;
					}

					try {
						// older Geckos used to result in an exception on quality argument
						dataUrl = _canvas.toDataURL('image/jpeg', quality/100);
					} catch (ex) {
						dataUrl = _canvas.toDataURL('image/jpeg');
					}

					_binStr = _convertToBinary(dataUrl);

					if (_imgInfo && _preserveHeaders) {
						// update dimensions info in exif
						if (_imgInfo.meta && _imgInfo.meta.exif) {
							_imgInfo.setExif({
								PixelXDimension: this.width,
								PixelYDimension: this.height
							});
						}

						// re-inject the headers
						_binStr = _imgInfo.writeHeaders(_binStr);

						// will be re-created from fresh on next getInfo call
						_imgInfo.purge();
						_imgInfo = null;
					}
				}

				_modified = false;

				return _binStr;
			},

			destroy: function() {
				me = null;
				_purge.call(this);
				this.getRuntime().getShim().removeInstance(this.uid);
			}
		});

		function _getImg() {
			if (!_canvas && !_img) {
				throw new x.ImageError(x.DOMException.INVALID_STATE_ERR);
			}
			return _canvas || _img;
		}

		function _convertToBinary(dataUrl) {
			return Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7));
		}

		function _loadFromBinaryString(binStr) {
			var comp = this;

			_purge.call(this);

			_img = new Image();
			_img.onerror = function() {
				_purge.call(this);
				throw new x.ImageError(x.ImageError.WRONG_FORMAT);
			};
			_img.onload = function() {
				_binStr = binStr;
				comp.trigger('load');
			};

			_img.src = 'data:' + (_srcBlob.type || '') + ';base64,' + Encode.btoa(binStr);
		}

		function _loadFromDataUrl(dataUrl) {
			var comp = this;

			_img = new Image();
			_img.onerror = function() {
				_purge.call(this);
				throw new x.ImageError(x.ImageError.WRONG_FORMAT);
			};
			_img.onload = function() {
				comp.trigger('load');
			};
			_img.src = dataUrl;
		}

		function _readAsBinaryString(file, callback) {
			var fr;

			// use FileReader if it's available
			if (window.FileReader) {
				if (FileReader.prototype.readAsBinaryString) { // readAsBinaryString is depricated in general and already dropped in IE10
					fr = new FileReader();
					fr.onload = function() {
						callback(this.result);
					};
					fr.readAsBinaryString(file);
				} else {
					_readAsDataUrl(file, function(result) {
						callback(_convertToBinary(result));
					});
				}
			} else {
				return callback(file.getAsBinary());
			}
		}

		function _readAsDataUrl(file, callback) {
			var fr;

			// use FileReader if it's available
			if (window.FileReader) {
				fr = new FileReader();
				fr.onload = function() {
					callback(this.result);
				};
				fr.readAsDataURL(file);
			} else {
				return callback(file.getAsDataURL());
			}
		}

		function _resize(width, height, crop, preserveHeaders) {
			var self = this, ctx, scale, mathFn, x, y, img, imgWidth, imgHeight, orientation;

			_preserveHeaders = preserveHeaders; // we will need to check this on export

			// take into account orientation tag
			orientation = (this.meta && this.meta.tiff && this.meta.tiff.Orientation) || 1;

			if (Basic.inArray(orientation, [5,6,7,8]) !== -1) { // values that require 90 degree rotation
				// swap dimensions
				var mem = width;
				width = height;
				height = mem;
			}

			img = _getImg();

			// unify dimensions
			mathFn = !crop ? Math.min : Math.max;
			scale = mathFn(width/img.width, height/img.height);

			// we only downsize here
			if (scale > 1 && (!crop || preserveHeaders)) { // when cropping one of dimensions may still exceed max, so process it anyway
				this.trigger('Resize');
				return;
			}

			imgWidth = Math.round(img.width * scale);
			imgHeight = Math.round(img.height * scale);

			// prepare canvas if necessary
			if (!_canvas) {
				_canvas = document.createElement("canvas");
			}

			ctx = _canvas.getContext('2d');

			// scale image and canvas
			if (crop) {
				_canvas.width = width;
				_canvas.height = height;
			} else {
				_canvas.width = imgWidth;
				_canvas.height = imgHeight;
			}

			// if dimensions of the resulting image still larger than canvas, center it
			x = imgWidth > _canvas.width ? Math.round((imgWidth - _canvas.width) / 2)  : 0;
			y = imgHeight > _canvas.height ? Math.round((imgHeight - _canvas.height) / 2) : 0;

			if (!_preserveHeaders) {
				_rotateToOrientaion(_canvas.width, _canvas.height, orientation);
			}

			_drawToCanvas.call(this, img, _canvas, -x, -y, imgWidth, imgHeight);

			this.width = _canvas.width;
			this.height = _canvas.height;

			_modified = true;
			self.trigger('Resize');
		}

		function _drawToCanvas(img, canvas, x, y, w, h) {
			if (Env.OS === 'iOS') {
				// avoid squish bug in iOS6
				MegaPixel.renderTo(img, canvas, { width: w, height: h, x: x, y: y });
			} else {
				var ctx = canvas.getContext('2d');
				ctx.drawImage(img, x, y, w, h);
			}
		}

		/**
		* Transform canvas coordination according to specified frame size and orientation
		* Orientation value is from EXIF tag
		* @author Shinichi Tomita <shinichi.tomita@gmail.com>
		*/
		function _rotateToOrientaion(width, height, orientation) {
			switch (orientation) {
				case 5:
				case 6:
				case 7:
				case 8:
					_canvas.width = height;
					_canvas.height = width;
					break;
				default:
					_canvas.width = width;
					_canvas.height = height;
			}

			/**
			1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
			2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
			3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
			4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
			5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
			6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
			7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
			8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
			*/

			var ctx = _canvas.getContext('2d');
			switch (orientation) {
				case 2:
					// horizontal flip
					ctx.translate(width, 0);
					ctx.scale(-1, 1);
					break;
				case 3:
					// 180 rotate left
					ctx.translate(width, height);
					ctx.rotate(Math.PI);
					break;
				case 4:
					// vertical flip
					ctx.translate(0, height);
					ctx.scale(1, -1);
					break;
				case 5:
					// vertical flip + 90 rotate right
					ctx.rotate(0.5 * Math.PI);
					ctx.scale(1, -1);
					break;
				case 6:
					// 90 rotate right
					ctx.rotate(0.5 * Math.PI);
					ctx.translate(0, -height);
					break;
				case 7:
					// horizontal flip + 90 rotate right
					ctx.rotate(0.5 * Math.PI);
					ctx.translate(width, -height);
					ctx.scale(-1, 1);
					break;
				case 8:
					// 90 rotate left
					ctx.rotate(-0.5 * Math.PI);
					ctx.translate(-width, 0);
					break;
			}
		}

		function _purge() {
			if (_imgInfo) {
				_imgInfo.purge();
				_imgInfo = null;
			}
			_binStr = _img = _canvas = null;
			_modified = false;
		}
	}

	return (extensions.Image = HTML5Image);
});
<commit_msg>Image, HTML5: FileReader.getAsBinaryString() is deprecated, get rid of it.<commit_after>/**
 * Image.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/*jshint smarttabs:true, undef:true, unused:true, latedef:true, curly:true, bitwise:false, scripturl:true, browser:true, laxcomma:true */
/*global define:true */

/**
@class moxie/runtime/html5/image/Image
@private
*/
define("moxie/runtime/html5/image/Image", [
	"moxie/runtime/html5/Runtime",
	"moxie/core/utils/Basic",
	"moxie/core/Exceptions",
	"moxie/core/utils/Encode",
	"moxie/file/Blob",
	"moxie/runtime/html5/image/ImageInfo",
	"moxie/runtime/html5/image/MegaPixel",
	"moxie/core/utils/Mime",
	"moxie/core/utils/Env"
], function(extensions, Basic, x, Encode, Blob, ImageInfo, MegaPixel, Mime, Env) {

	function HTML5Image() {
		var me = this
		, _img, _imgInfo, _canvas, _binStr, _srcBlob
		, _modified = false // is set true whenever image is modified
		, _preserveHeaders = true
		;

		Basic.extend(this, {
			loadFromBlob: function(blob) {
				var comp = this, I = comp.getRuntime()
				, asBinary = arguments.length > 1 ? arguments[1] : true
				;

				if (!I.can('access_binary')) {
					throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
				}

				if (blob.isDetached()) {
					_srcBlob = {
						name: blob.name,
						size: blob.size,
						type: blob.type
					};
					_binStr = blob.getSource();
					_preload.call(this, _binStr);
					return;
				} else {
					_srcBlob = blob.getSource();
					_readAsDataUrl(_srcBlob, function(dataUrl) {
						if (asBinary) {
							_binStr = _toBinary(dataUrl);
						}
						_preload.call(comp, dataUrl);
					});
				}
			},

			loadFromImage: function(img, exact) {
				this.meta = img.meta;

				_srcBlob = {
					name: img.name,
					size: img.size,
					type: img.type
				};

				_preload.call(this, exact ? (_binStr = img.getAsBinaryString()) : img.getAsDataURL());
			},

			getInfo: function() {
				var I = this.getRuntime(), info;

				if (!_imgInfo && _binStr && I.can('access_image_binary')) {
					_imgInfo = new ImageInfo(_binStr);
				}

				info = {
					width: _getImg().width || 0,
					height: _getImg().height || 0,
					type: _srcBlob.type || Mime.getFileMime(_srcBlob.name),
					size: _binStr && _binStr.length || _srcBlob.size || 0,
					name: _srcBlob.name || '',
					meta: _imgInfo && _imgInfo.meta || this.meta || {}
				};

				return info;
			},

			resize: function() {
				_resize.apply(this, arguments);
			},

			getAsCanvas: function() {
				if (_canvas) {
					_canvas.id = this.uid + '_canvas';
				}
				return _canvas;
			},

			getAsBlob: function(type, quality) {
				if (type !== this.type) {
					// if different mime type requested prepare image for conversion
					_resize.call(this, this.width, this.height, false);
				}
				return new Blob(null, me.getAsDataURL.call(this, type, quality));
			},

			getAsDataURL: function(type) {
				var quality = arguments[1] || 90;

				// if image has not been modified, return the source right away
				if (!_modified) {
					return _img.src;
				}

				if ('image/jpeg' !== type) {
					return _canvas.toDataURL('image/png');
				} else {
					try {
						// older Geckos used to result in an exception on quality argument
						return _canvas.toDataURL('image/jpeg', quality/100);
					} catch (ex) {
						return _canvas.toDataURL('image/jpeg');
					}
				}
			},

			getAsBinaryString: function(type, quality) {
				// if image has not been modified, return the source right away
				if (!_modified) {
					// if image was not loaded from binary string
					if (!_binStr) {
						_binStr = _toBinary(me.getAsDataURL(type, quality));
					}
					return _binStr;
				}

				if ('image/jpeg' !== type) {
					_binStr = _toBinary(me.getAsDataURL(type, quality));
				} else {
					var dataUrl;

					// if jpeg
					if (!quality) {
						quality = 90;
					}

					try {
						// older Geckos used to result in an exception on quality argument
						dataUrl = _canvas.toDataURL('image/jpeg', quality/100);
					} catch (ex) {
						dataUrl = _canvas.toDataURL('image/jpeg');
					}

					_binStr = _toBinary(dataUrl);

					if (_imgInfo && _preserveHeaders) {
						// update dimensions info in exif
						if (_imgInfo.meta && _imgInfo.meta.exif) {
							_imgInfo.setExif({
								PixelXDimension: this.width,
								PixelYDimension: this.height
							});
						}

						// re-inject the headers
						_binStr = _imgInfo.writeHeaders(_binStr);

						// will be re-created from fresh on next getInfo call
						_imgInfo.purge();
						_imgInfo = null;
					}
				}

				_modified = false;

				return _binStr;
			},

			destroy: function() {
				me = null;
				_purge.call(this);
				this.getRuntime().getShim().removeInstance(this.uid);
			}
		});

		function _getImg() {
			if (!_canvas && !_img) {
				throw new x.ImageError(x.DOMException.INVALID_STATE_ERR);
			}
			return _canvas || _img;
		}

		function _toBinary(str) {
			return Encode.atob(str.substring(str.indexOf('base64,') + 7));
		}

		function _toDataUrl(str, type) {
			return 'data:' + (type || '') + ';base64,' + Encode.btoa(str);
		}

		function _preload(str) {
			var comp = this;

			_img = new Image();
			_img.onerror = function() {
				_purge.call(this);
				throw new x.ImageError(x.ImageError.WRONG_FORMAT);
			};
			_img.onload = function() {
				comp.trigger('load');
			};

			_img.src = /^data:[^;]*;base64,/.test(str) ? str : _toDataUrl(str, _srcBlob.type);
		}

		function _readAsDataUrl(file, callback) {
			var fr;

			// use FileReader if it's available
			if (window.FileReader) {
				fr = new FileReader();
				fr.onload = function() {
					callback(this.result);
				};
				fr.readAsDataURL(file);
			} else {
				return callback(file.getAsDataURL());
			}
		}

		function _resize(width, height, crop, preserveHeaders) {
			var self = this, ctx, scale, mathFn, x, y, img, imgWidth, imgHeight, orientation;

			_preserveHeaders = preserveHeaders; // we will need to check this on export

			// take into account orientation tag
			orientation = (this.meta && this.meta.tiff && this.meta.tiff.Orientation) || 1;

			if (Basic.inArray(orientation, [5,6,7,8]) !== -1) { // values that require 90 degree rotation
				// swap dimensions
				var mem = width;
				width = height;
				height = mem;
			}

			img = _getImg();

			// unify dimensions
			mathFn = !crop ? Math.min : Math.max;
			scale = mathFn(width/img.width, height/img.height);

			// we only downsize here
			if (scale > 1 && (!crop || preserveHeaders)) { // when cropping one of dimensions may still exceed max, so process it anyway
				this.trigger('Resize');
				return;
			}

			imgWidth = Math.round(img.width * scale);
			imgHeight = Math.round(img.height * scale);

			// prepare canvas if necessary
			if (!_canvas) {
				_canvas = document.createElement("canvas");
			}

			ctx = _canvas.getContext('2d');

			// scale image and canvas
			if (crop) {
				_canvas.width = width;
				_canvas.height = height;
			} else {
				_canvas.width = imgWidth;
				_canvas.height = imgHeight;
			}

			// if dimensions of the resulting image still larger than canvas, center it
			x = imgWidth > _canvas.width ? Math.round((imgWidth - _canvas.width) / 2)  : 0;
			y = imgHeight > _canvas.height ? Math.round((imgHeight - _canvas.height) / 2) : 0;

			if (!_preserveHeaders) {
				_rotateToOrientaion(_canvas.width, _canvas.height, orientation);
			}

			_drawToCanvas.call(this, img, _canvas, -x, -y, imgWidth, imgHeight);

			this.width = _canvas.width;
			this.height = _canvas.height;

			_modified = true;
			self.trigger('Resize');
		}

		function _drawToCanvas(img, canvas, x, y, w, h) {
			if (Env.OS === 'iOS') {
				// avoid squish bug in iOS6
				MegaPixel.renderTo(img, canvas, { width: w, height: h, x: x, y: y });
			} else {
				var ctx = canvas.getContext('2d');
				ctx.drawImage(img, x, y, w, h);
			}
		}

		/**
		* Transform canvas coordination according to specified frame size and orientation
		* Orientation value is from EXIF tag
		* @author Shinichi Tomita <shinichi.tomita@gmail.com>
		*/
		function _rotateToOrientaion(width, height, orientation) {
			switch (orientation) {
				case 5:
				case 6:
				case 7:
				case 8:
					_canvas.width = height;
					_canvas.height = width;
					break;
				default:
					_canvas.width = width;
					_canvas.height = height;
			}

			/**
			1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
			2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
			3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
			4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
			5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
			6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
			7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
			8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
			*/

			var ctx = _canvas.getContext('2d');
			switch (orientation) {
				case 2:
					// horizontal flip
					ctx.translate(width, 0);
					ctx.scale(-1, 1);
					break;
				case 3:
					// 180 rotate left
					ctx.translate(width, height);
					ctx.rotate(Math.PI);
					break;
				case 4:
					// vertical flip
					ctx.translate(0, height);
					ctx.scale(1, -1);
					break;
				case 5:
					// vertical flip + 90 rotate right
					ctx.rotate(0.5 * Math.PI);
					ctx.scale(1, -1);
					break;
				case 6:
					// 90 rotate right
					ctx.rotate(0.5 * Math.PI);
					ctx.translate(0, -height);
					break;
				case 7:
					// horizontal flip + 90 rotate right
					ctx.rotate(0.5 * Math.PI);
					ctx.translate(width, -height);
					ctx.scale(-1, 1);
					break;
				case 8:
					// 90 rotate left
					ctx.rotate(-0.5 * Math.PI);
					ctx.translate(-width, 0);
					break;
			}
		}

		function _purge() {
			if (_imgInfo) {
				_imgInfo.purge();
				_imgInfo = null;
			}
			_binStr = _img = _canvas = null;
			_modified = false;
		}
	}

	return (extensions.Image = HTML5Image);
});
<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-enable no-unused-vars */
import FormUtil from '../../utils/FormUtil';

const Networking = {
  type: 'object',
  title: 'Network',
  description: 'Configure the networking for your service.',
  properties: {
    networkType: {
      fieldType: 'select',
      title: 'Network Type',
      options: [
        {html: 'Host (Default)', id: 'host'},
        {html: 'Bridge', id: 'bridge'}
      ],
      getter: function (service) {
        let ipAddress = service.getIpAddress();
        if (ipAddress) {

          return ipAddress.networkName;
        }

        let container = service.getContainerSettings();
        if (container && container.docker && container.docker.network) {

          return container.docker.network.toLowerCase();
        }

        return 'host';
      },
      filterProperties: function (currentValue, definition, model) {
        // Hide this definition when model values dictate
        if (model.containerSettings
          && model.containerSettings.image != null
          && model.containerSettings.image.length) {

          definition.formElementClass = '';
        } else {
          definition.formElementClass = 'hidden-form-element';
          model.networking.networkType = 'host';
        }
      }
    },
    ports: {
      title: 'Service Endpoints',
      description: (

          Configure the ports and endpoints you would like to use to talk to your service, or we can assign a random port for you. Learn more about ports.

      ),
      type: 'array',
      duplicable: true,
      addLabel: 'Add an endpoint',
      getter: function (service) {
        let container = service.getContainerSettings();
        let portMappings = null;
        if (container && container.docker && container.docker.portMappings) {
          portMappings = container.docker.portMappings;
        }

        if (portMappings == null) {
          portMappings = service.getPortDefinitions();

          if (portMappings == null) {
            return null;
          }
        }

        return portMappings.map(function (portMapping) {
          return {
            lbPort: portMapping.port || portMapping.containerPort,
            name: portMapping.name,
            protocol: portMapping.protocol,
            discovery: portMapping.labels &&
              Object.keys(portMapping.labels).length > 0,
            expose: portMapping.hostPort != null
          };
        });
      },
      filterProperties: function (service = {}, instanceDefinition, model) {
        let properties = Networking
          .properties
          .ports
          .itemShape
          .properties;

        instanceDefinition.forEach(function (definition) {
          let prop = definition.name;
          if (FormUtil.isFieldInstanceOfProp('ports', definition)) {
            prop = FormUtil.getPropKey(definition.name);
          }

          if (properties[prop].shouldShow) {
            definition.formElementClass = {
              'hidden-form-element': !properties[prop].shouldShow(
                service, model || {networking: {}})
            };
          }

          let disabledLBPortFieldValue = service.lbPort || 'Not Enabled';
          if (prop === 'lbPort' && model && model.networking) {
            if (model.networking.networkType !== 'host') {
              definition.showLabel = 'Container Port';
              if (definition.value === 'Not Enabled') {
                definition.value = null;
              }
            } else {
              definition.showLabel = 'LB Port';

              if (service.discovery) {
                // show as input
                if (definition.value === disabledLBPortFieldValue) {
                  definition.value = null;
                  definition.disabled = false;
                  definition.className = 'form-control';
                  definition.fieldType = 'number';
                }
              } else {
                // show as disabled
                definition.value = disabledLBPortFieldValue;
                definition.disabled = true;
                definition.fieldType = 'text';
                definition.className = 'form-control lb-port-input-field-disabled';
              }

            }
          }
        });
      },
      itemShape: {
        properties: {
          lbPort: {
            title: 'LB Port',
            type: 'number'
          },
          name: {
            title: 'Name',
            type: 'string'
          },
          protocol: {
            title: 'Protocol',
            type: 'string',
            fieldType: 'select',
            default: 'tcp',
            options: ['tcp', 'udp', 'udp,tcp']
          },
          discovery: {
            label: 'Discovery',
            showLabel: false,
            title: 'Discovery',
            type: 'boolean'
          }
        }
      }
    }
  }
};

module.exports = Networking;
<commit_msg>Fix reseting ports<commit_after>/* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-enable no-unused-vars */
import FormUtil from '../../utils/FormUtil';

const Networking = {
  type: 'object',
  title: 'Network',
  description: 'Configure the networking for your service.',
  properties: {
    networkType: {
      fieldType: 'select',
      title: 'Network Type',
      options: [
        {html: 'Host (Default)', id: 'host'},
        {html: 'Bridge', id: 'bridge'}
      ],
      getter: function (service) {
        let ipAddress = service.getIpAddress();
        if (ipAddress) {

          return ipAddress.networkName;
        }

        let container = service.getContainerSettings();
        if (container && container.docker && container.docker.network) {

          return container.docker.network.toLowerCase();
        }

        return 'host';
      },
      filterProperties: function (currentValue, definition, model) {
        // Hide this definition when model values dictate
        if (model.containerSettings
          && model.containerSettings.image != null
          && model.containerSettings.image.length) {

          definition.formElementClass = '';
        } else {
          definition.formElementClass = 'hidden-form-element';
          model.networking.networkType = 'host';
        }
      }
    },
    ports: {
      title: 'Service Endpoints',
      description: (

          Configure the ports and endpoints you would like to use to talk to your service, or we can assign a random port for you. Learn more about ports.

      ),
      type: 'array',
      duplicable: true,
      addLabel: 'Add an endpoint',
      getter: function (service) {
        let container = service.getContainerSettings();
        let portMappings = null;
        if (container && container.docker && container.docker.portMappings) {
          portMappings = container.docker.portMappings;
        }

        if (portMappings == null) {
          portMappings = service.getPortDefinitions();

          if (portMappings == null) {
            return null;
          }
        }

        return portMappings.map(function (portMapping) {
          return {
            lbPort: portMapping.port || portMapping.containerPort,
            name: portMapping.name,
            protocol: portMapping.protocol,
            discovery: portMapping.labels &&
              Object.keys(portMapping.labels).length > 0,
            expose: portMapping.hostPort != null
          };
        });
      },
      filterProperties: function (service = {}, instanceDefinition, model) {
        let properties = Networking
          .properties
          .ports
          .itemShape
          .properties;

        instanceDefinition.forEach(function (definition) {
          let prop = definition.name;
          if (FormUtil.isFieldInstanceOfProp('ports', definition)) {
            prop = FormUtil.getPropKey(definition.name);
          }

          if (properties[prop].shouldShow) {
            definition.formElementClass = {
              'hidden-form-element': !properties[prop].shouldShow(
                service, model || {networking: {}})
            };
          }

          let disabledLBPortFieldValue = service.lbPort || 'Not Enabled';
          if (prop === 'lbPort' && model && model.networking) {
            if (model.networking.networkType !== 'host') {
              definition.showLabel = 'Container Port';
              if (definition.value === 'Not Enabled') {
                definition.value = null;
              }
            } else {
              definition.showLabel = 'LB Port';

              if (service.discovery) {
                // show as input
                if (definition.value === 'Not Enabled') {
                  definition.value = null;
                  definition.disabled = false;
                  definition.className = 'form-control';
                  definition.fieldType = 'number';
                }
              } else {
                // show as disabled
                definition.value = disabledLBPortFieldValue;
                definition.disabled = true;
                definition.fieldType = 'text';
                definition.className = 'form-control lb-port-input-field-disabled';
              }

            }
          }
        });
      },
      itemShape: {
        properties: {
          lbPort: {
            title: 'LB Port',
            type: 'number'
          },
          name: {
            title: 'Name',
            type: 'string'
          },
          protocol: {
            title: 'Protocol',
            type: 'string',
            fieldType: 'select',
            default: 'tcp',
            options: ['tcp', 'udp', 'udp,tcp']
          },
          discovery: {
            label: 'Discovery',
            showLabel: false,
            title: 'Discovery',
            type: 'boolean'
          }
        }
      }
    }
  }
};

module.exports = Networking;
<|endoftext|>


<commit_before>const { Vector,sum,product } = require("./vecto");

// let v = Vector.zeroes([2]);
// console.log(v);

// let v2 = Vector.zeroes([2,3]);
// console.log(v2);
// console.log(v2.size);
// let v3 = new Vector([6]);
// v3.arrange();
// let sm = Vector.add(v2,v3);
// console.log(sm);

// let n2v = Vector.array([[4,2,1],[7,8,9]]);
// console.log(Vector.calc_shape(n2v.array));
// console.log(Vector.calc_size(n2v.shape));
// console.log(n2v);

// let tnv = new Vector([2,2,3,4]);
// tnv.arrange(4);
// console.log(tnv);
// tnv.reshape([6,8]);
// console.log(tnv);
// n2v.reshape([6]);
// console.log(`reshaped = `,n2v);
// n2v.resize([5,5]);
// console.log(`resized = `,n2v);

// let nv = new Vector([2,3]);
// nv.arrange(2);
// console.log(nv.array);
// let nv2 = new Vector([2,3]);
// nv2.arrange(4);
// console.log(nv2.array);
// console.log(Vector.add(nv,nv2));

// let nnv = new Vector([5,5]);
// nnv.arrange(5);
// console.log(nnv);

// console.log(product(nnv.array,n2v.array));

// let nvvn = new Vector([5,5]);
// nvvn.arrange(6);

// let nv22 = new Vector(nvvn.shape);
// nv22.arrange(5);

// console.log(product(nvvn.array,nv22.array));
// console.log(sum(nvvn.array,nv22.array));
// console.log(sum(nvvn.array));
// console.log(product(nvvn.array,[2,2,2,2,2]));
// console.log(product(nvvn.array,2));

let c = [[2,3,4],[5,6,7]];
let d = [[2,4,5],[8,9,10]];

console.log(product(c,d));<commit_msg>:hammer::hankey:<commit_after>const { Vector,sum,product } = require("./vecto");

let v = Vector.zeroes([2]);
console.log(v);

let v2 = Vector.zeroes([2,3]);
console.log(v2);
console.log(v2.size);
let v3 = new Vector([6]);
v3.arrange();
let sm = Vector.add(v2,v3);
console.log(sm);

let n2v = Vector.array([[4,2,1],[7,8,9]]);
console.log(Vector.calc_shape(n2v.array));
console.log(Vector.calc_size(n2v.shape));
console.log(n2v);

let tnv = new Vector([2,2,3,4]);
tnv.arrange(4);
console.log(tnv);
tnv.reshape([6,8]);
console.log(tnv);
n2v.reshape([6]);
console.log(`reshaped = `,n2v);
n2v.resize([5,5]);
console.log(`resized = `,n2v);

let nv = new Vector([2,3]);
nv.arrange(2);
console.log(nv.array);
let nv2 = new Vector([2,3]);
nv2.arrange(4);
console.log(nv2.array);
console.log(Vector.add(nv,nv2));

let nnv = new Vector([5,5]);
nnv.arrange(5);
console.log(nnv);

console.log(product(nnv.array,n2v.array));

let nvvn = new Vector([5,5]);
nvvn.arrange(6);

let nv22 = new Vector(nvvn.shape);
nv22.arrange(5);

console.log(product(nvvn.array,nv22.array));
console.log(sum(nvvn.array,nv22.array));
console.log(sum(nvvn.array));
console.log(product(nvvn.array,[2,2,2,2,2]));
console.log(product(nvvn.array,2));

let c = [[2,3,4],[5,6,7]];
let d = [[2,4,5],[8,9,10]];

console.log(product(c,d));<|endoftext|>


<commit_before>require('chai').should()
import postcss from 'postcss'
import fs from 'fs'
import path from 'path'

import plugin from './'

function run(done, input, output, opts = {}) {
  return postcss([plugin(opts)]).process(input)
    .then(result => {
      result.warnings().length.should.be.equal(0)
      result.css.should.be.equal(output)
      done()
    })
    .catch(done)
}

const options = {
  extract: {
    important: 'extracted.css',
  },
}

const fixturesDir = path.join(__dirname, 'fixtures')
fs.readdirSync(fixturesDir).forEach(caseName => {
  if (caseName.includes('[notest]')) return

  it(caseName, done => {
    const fixtureDir = path.join(fixturesDir, caseName)
    const input = fs.readFileSync(path.join(fixtureDir, 'input.css')).toString()
    const output = fs.readFileSync(path.join(fixtureDir, 'output.css')).toString()
    run(done, input, output, options)
  })
})
<commit_msg>Fix test .DS_Store<commit_after>require('chai').should()
import postcss from 'postcss'
import fs from 'fs'
import path from 'path'

import plugin from './'

function run(done, input, output, opts = {}) {
  return postcss([plugin(opts)]).process(input)
    .then(result => {
      result.warnings().length.should.be.equal(0)
      result.css.should.be.equal(output)
      done()
    })
    .catch(done)
}

const options = {
  extract: {
    important: 'extracted.css',
  },
}

const fixturesDir = path.join(__dirname, 'fixtures')
fs.readdirSync(fixturesDir).forEach(caseName => {
  if (caseName.includes('[notest]')) return

  const fixtureDir = path.join(fixturesDir, caseName)
  if (!fs.lstatSync(fixtureDir).isDirectory()) return
  it(caseName, done => {
    const input = fs.readFileSync(path.join(fixtureDir, 'input.css')).toString()
    const output = fs.readFileSync(path.join(fixtureDir, 'output.css')).toString()
    run(done, input, output, options)
  })
})
<|endoftext|>


<commit_before>function viewCollections(collectionId) {

    var result = {};
    var pageDataRequests = []; // list of promises - one for each ajax request.
    pageDataRequests.push(
        $.ajax({
            url: "/zebedee/collections",
            type: "get",
            success: function (data) {
                result.data = data;
            },
            error: function (jqxhr) {
                handleApiError(jqxhr);
            }
        })
    );
    pageDataRequests.push(
        getTeams(
            success = function (team) {
                result.team = team;
            },
            error = function (response) {
                handleApiError(response);
            }
        )
    );

    $.when.apply($, pageDataRequests).then(function () {

        var response = [], teams = [], date = "";

        $.each(result.data, function (i, collection) {
            var approvalStates = {inProgress: false, thrownError: false, completed: false, notStarted: false};

            if (collection.approvalStatus != "COMPLETE") {

                // Set publish date
                if (!collection.publishDate) {
                    date = '[manual collection]';
                } else if (collection.publishDate && collection.type === 'manual') {
                    date = StringUtils.formatIsoDateString(collection.publishDate) + ' [rolled back]';
                } else {
                    date = StringUtils.formatIsoDateString(collection.publishDate);
                }

                // Set approval state
                switch (collection.approvalStatus) {
                    case (undefined): {
                        break;
                    }
                    case ('NOT_STARTED'): {
                        approvalStates.notStarted = true;
                        break;
                    }
                    case ('IN_PROGRESS'): {
                        approvalStates.inProgress = true;
                        break;
                    }
                    case ('COMPLETE'): {
                        approvalStates.completed = true;
                        break;
                    }
                    case ('ERROR'): {
                        approvalStates.thrownError = true;
                        break;
                    }
                }

                response.push({id: collection.id, name: collection.name, date: date, approvalState: approvalStates});
            }
        });

        var isDataVis = false;
        if (Florence.Authentication.userType() === "DATA_VISUALISATION") {
            isDataVis = true;
        }
        var collectionsHtml = templates.collectionList({response: response, teams: result.team.teams, isDataVis: isDataVis});
        $('.section').html(collectionsHtml);

        if (collectionId) {
            viewCollectionDetails(collectionId, $('.js-selectable-table tr[data-id="' + collectionId + '"]'));
        }

        $('.js-selectable-table tbody tr').click(function () {
            var collectionId = $(this).attr('data-id');
            viewCollectionDetails(collectionId, $(this));
        });

        $("#team-tag").tagit({
            singleField: true,
            singleFieldNode: $('#team-input')
        });

        $('.ui-autocomplete-input').hide();

        $('select#team').change(function () {
            $('#team-tag').tagit('createTag', $("#team option:selected").text());
        });

        $('#team-input').change(function () {
            teams = $('#team-input').val().split(',');
            //After creating the array tagit leaves an empty string if all elements are removed
            if (teams.length === 1 && teams[0] === "") {
                teams = [];
            }
        });

        $('form input[type=radio]').click(function () {

            if ($(this).val() === 'manual') {
                $('#scheduledPublishOptions').hide();
            } else if ($(this).val() === 'scheduled') {
                $('#scheduledPublishOptions').show();
            } else if ($(this).val() === 'custom') {
                $('#customScheduleOptions').show();
                $('#releaseScheduleOptions').hide();
            } else if ($(this).val() === 'release') {
                $('#customScheduleOptions').hide();
                $('#releaseScheduleOptions').show();
            }
        });

        $(function () {
            var today = new Date();
            $('#date').datepicker({
                minDate: today,
                dateFormat: 'dd/mm/yy',
                constrainInput: true
            });
        });

        $('.btn-select-release').on("click", function (e) {
            e.preventDefault();
            viewReleaseSelector();
        });

        $('.form-create-collection').submit(function (e) {
            e.preventDefault();
            createCollection(teams);
        });
    });
}<commit_msg>Update viewCollections function to always redirect to new collections screen<commit_after>function viewCollections(collectionId) {

    if (collectionId) {
        location.href = location.origin + "/florence/collections/" + collectionId;
    } else {
        location.pathname = "/florence/collections";
    }

    // var result = {};
    // var pageDataRequests = []; // list of promises - one for each ajax request.
    // pageDataRequests.push(
    //     $.ajax({
    //         url: "/zebedee/collections",
    //         type: "get",
    //         success: function (data) {
    //             result.data = data;
    //         },
    //         error: function (jqxhr) {
    //             handleApiError(jqxhr);
    //         }
    //     })
    // );
    // pageDataRequests.push(
    //     getTeams(
    //         success = function (team) {
    //             result.team = team;
    //         },
    //         error = function (response) {
    //             handleApiError(response);
    //         }
    //     )
    // );

    // $.when.apply($, pageDataRequests).then(function () {

    //     var response = [], teams = [], date = "";

    //     $.each(result.data, function (i, collection) {
    //         var approvalStates = {inProgress: false, thrownError: false, completed: false, notStarted: false};

    //         if (collection.approvalStatus != "COMPLETE") {

    //             // Set publish date
    //             if (!collection.publishDate) {
    //                 date = '[manual collection]';
    //             } else if (collection.publishDate && collection.type === 'manual') {
    //                 date = StringUtils.formatIsoDateString(collection.publishDate) + ' [rolled back]';
    //             } else {
    //                 date = StringUtils.formatIsoDateString(collection.publishDate);
    //             }

    //             // Set approval state
    //             switch (collection.approvalStatus) {
    //                 case (undefined): {
    //                     break;
    //                 }
    //                 case ('NOT_STARTED'): {
    //                     approvalStates.notStarted = true;
    //                     break;
    //                 }
    //                 case ('IN_PROGRESS'): {
    //                     approvalStates.inProgress = true;
    //                     break;
    //                 }
    //                 case ('COMPLETE'): {
    //                     approvalStates.completed = true;
    //                     break;
    //                 }
    //                 case ('ERROR'): {
    //                     approvalStates.thrownError = true;
    //                     break;
    //                 }
    //             }

    //             response.push({id: collection.id, name: collection.name, date: date, approvalState: approvalStates});
    //         }
    //     });

    //     var isDataVis = false;
    //     if (Florence.Authentication.userType() === "DATA_VISUALISATION") {
    //         isDataVis = true;
    //     }
    //     var collectionsHtml = templates.collectionList({response: response, teams: result.team.teams, isDataVis: isDataVis});
    //     $('.section').html(collectionsHtml);

    //     if (collectionId) {
    //         viewCollectionDetails(collectionId, $('.js-selectable-table tr[data-id="' + collectionId + '"]'));
    //     }

    //     $('.js-selectable-table tbody tr').click(function () {
    //         var collectionId = $(this).attr('data-id');
    //         viewCollectionDetails(collectionId, $(this));
    //     });

    //     $("#team-tag").tagit({
    //         singleField: true,
    //         singleFieldNode: $('#team-input')
    //     });

    //     $('.ui-autocomplete-input').hide();

    //     $('select#team').change(function () {
    //         $('#team-tag').tagit('createTag', $("#team option:selected").text());
    //     });

    //     $('#team-input').change(function () {
    //         teams = $('#team-input').val().split(',');
    //         //After creating the array tagit leaves an empty string if all elements are removed
    //         if (teams.length === 1 && teams[0] === "") {
    //             teams = [];
    //         }
    //     });

    //     $('form input[type=radio]').click(function () {

    //         if ($(this).val() === 'manual') {
    //             $('#scheduledPublishOptions').hide();
    //         } else if ($(this).val() === 'scheduled') {
    //             $('#scheduledPublishOptions').show();
    //         } else if ($(this).val() === 'custom') {
    //             $('#customScheduleOptions').show();
    //             $('#releaseScheduleOptions').hide();
    //         } else if ($(this).val() === 'release') {
    //             $('#customScheduleOptions').hide();
    //             $('#releaseScheduleOptions').show();
    //         }
    //     });

    //     $(function () {
    //         var today = new Date();
    //         $('#date').datepicker({
    //             minDate: today,
    //             dateFormat: 'dd/mm/yy',
    //             constrainInput: true
    //         });
    //     });

    //     $('.btn-select-release').on("click", function (e) {
    //         e.preventDefault();
    //         viewReleaseSelector();
    //     });

    //     $('.form-create-collection').submit(function (e) {
    //         e.preventDefault();
    //         createCollection(teams);
    //     });
    // });
}<|endoftext|>