<commit_before>
import React, { Component } from "react";
import SPChannel from "./sp-channel";
import SPCamera from "./sp-camera";
import styled from "styled-components";
import {subscribe} from "./sp-binding";
import {FlexContainer} from "./shared.style";
import {UserBar} from "./channel-route.style";

/**
 * Hacky. Yuck. But it gets the title of the channel up there on the title bar, so I'm fine with
 * it.
 */
const TitleBar = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  pointer-events: none;
  margin-top: -42px;
  font-size: 2em;
  font-weight: 200;
  margin-left: 0.3em;
`;

const ChannelName = styled.strong`
  font-weight: 600;
  font-size: 0.7em;
  position: relative;
  top: -3px;
`;

export class ChannelRoute extends Component {
  static propTypes = {
    channels: React.PropTypes.array,
  };

  constructor() {
    super();
    this.state = {};
  }

  render () {
    const channel = this.props.channels[0] || {};
    return (
      <FlexContainer>
        <TitleBar>
          📹 <ChannelName>{channel.slug}</ChannelName>
        </TitleBar>
        <FlexContainer>
          <SPChannel width={1920} height={1080}>
            <SPCamera x={0} y={0} width={960} height={270} userId="8145ebde-cf2d-44e9-8462-92aac7fe0074"></SPCamera>
            <SPCamera x={960} y={0} width={960} height={1080} userId="12006157-fa7e-4262-8152-abda9acae2f6"></SPCamera>
            <SPCamera x={0} y={270} width={960} height={810} userId="8145ebde-cf2d-44e9-8462-92aac7fe0074"></SPCamera>
          </SPChannel>
          <UserBar />
        </FlexContainer>
      </FlexContainer>
    );
  }
}

export default subscribe(ChannelRoute, function(props, SP) {
  return {
    channels: SP.channels.watch({slug: props.match.params.slug}),
  };
});
<commit_msg>fix window overflow on windows<commit_after>
import React, { Component } from "react";
import SPCanvas from "./sp-canvas";
import SPCamera from "./sp-camera";
import styled from "styled-components";
import {subscribe} from "./sp-binding";
import {FlexContainer} from "./shared.style";
import {UserBar} from "./channel-route.style";

/**
 * Hacky. Yuck. But it gets the title of the channel up there on the title bar, so I'm fine with
 * it.
 */
const TitleBar = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  pointer-events: none;
  margin-top: -42px;
  font-size: 2em;
  font-weight: 200;
  padding-left: 0.3em;
`;

const ChannelName = styled.strong`
  font-weight: 600;
  font-size: 0.7em;
  position: relative;
  top: -3px;
`;

export class ChannelRoute extends Component {
  static propTypes = {
    channels: React.PropTypes.array,
  };

  constructor() {
    super();
    this.state = {};
  }

  render () {
    const channel = this.props.channels[0] || {};
    return (
      <FlexContainer>
        <TitleBar>
          📹 <ChannelName>{channel.slug}</ChannelName>
        </TitleBar>
        <FlexContainer>
          <SPCanvas width={1920} height={1080}>
            <SPCamera x={0} y={0} width={960} height={270} userId="8145ebde-cf2d-44e9-8462-92aac7fe0074"></SPCamera>
            <SPCamera x={960} y={0} width={960} height={1080} userId="12006157-fa7e-4262-8152-abda9acae2f6"></SPCamera>
            <SPCamera x={0} y={270} width={960} height={810} userId="8145ebde-cf2d-44e9-8462-92aac7fe0074"></SPCamera>
          </SPCanvas>
          <UserBar />
        </FlexContainer>
      </FlexContainer>
    );
  }
}

export default subscribe(ChannelRoute, function(props, SP) {
  return {
    channels: SP.channels.watch({slug: props.match.params.slug}),
  };
});
<|endoftext|>


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

  define([
      'app',
      'utils/chartHelpers',
      'utils/duration',
      'utils/escapeHtml',
      'utils/parseLinkHeader',
      'utils/sortBuildList',
      'modules/collection',
      'directives/radialProgressBar',
      'directives/timeSince'], function(app, chartHelpers, duration, escapeHtml, parseLinkHeader, sortBuildList) {
    app.controller('projectDetailsCtrl', [
        '$scope', '$rootScope', 'initialProject', 'initialBuildList', '$http', '$routeParams', 'stream', 'collection',
        function($scope, $rootScope, initialProject, initialBuildList, $http, $routeParams, Stream, Collection) {
      var stream,
          entrypoint = '/api/0/projects/' + $routeParams.project_id + '/builds/',
          chart_options = {
            tooltipFormatter: function(item) {
              var content = '';

              content += '
';
              content += escapeHtml(item.name);
              content += '
';
              content += escapeHtml(item.target);
              if (item.author) {
                content += ' — ' + item.author.name;
              }
              content += '';
              content += '
';
              if (item.status.id == 'finished') {
                content += '
Build ' + item.result.name;
                if (item.duration) {
                  content += ' in ' + duration(item.duration);
                }
                content += '
';
              } else {
                content += '
' + item.status.name + '
';
              }

              return content;
            }
          };

      $scope.getBuildStatus = function(build) {
        if (build.status.id == 'finished') {
          return build.result.name;
        } else {
          return build.status.name;
        }
      };

      function loadBuildList(url) {
        if (!url) {
          return;
        }
        $http.get(url)
          .success(function(data, status, headers){
            $scope.builds = new Collection($scope, data, {
              sortFunc: sortBuildList,
              limit: 100
            });
            $scope.pageLinks = parseLinkHeader(headers('Link'));
          });
      }

      $scope.loadPreviousPage = function() {
        $(document.body).scrollTop(0);
        loadBuildList($scope.pageLinks.previous);
      };

      $scope.loadNextPage = function() {
        $(document.body).scrollTop(0);
        loadBuildList($scope.pageLinks.next);
      };

      $scope.$watch("pageLinks", function(value) {
        $scope.nextPage = value.next || null;
        $scope.previousPage = value.previous || null;
      });

      $scope.pageLinks = parseLinkHeader(initialBuildList.headers('Link'));

      $scope.project = initialProject.data.project;
      $scope.builds = new Collection($scope, initialBuildList.data, {
        sortFunc: sortBuildList,
        limit: 100
      });
      $scope.chartData = chartHelpers.getChartData($scope.builds, null, chart_options);
      $scope.includePatches = false;
      $rootScope.activeProject = $scope.project;
      $rootScope.pageTitle = $scope.project.name + ' Builds';

      $scope.$watch("includePatches", function() {
        loadBuildList(entrypoint + '?include_patches=' + ($scope.includePatches ? '1' : '0'));
      });

      $scope.$watch("builds", function() {
        $scope.chartData = chartHelpers.getChartData($scope.builds, null, chart_options);
      });

      stream = new Stream($scope, entrypoint);
      stream.subscribe('build.update', function(data){
        if (data.patch && !$scope.includePatches) {
          return;
        }
        $scope.builds.updateItem(data);
      });
    }]);
  });
})();
<commit_msg>Fix patch check in project details<commit_after>(function(){
  'use strict';

  define([
      'app',
      'utils/chartHelpers',
      'utils/duration',
      'utils/escapeHtml',
      'utils/parseLinkHeader',
      'utils/sortBuildList',
      'modules/collection',
      'directives/radialProgressBar',
      'directives/timeSince'], function(app, chartHelpers, duration, escapeHtml, parseLinkHeader, sortBuildList) {
    app.controller('projectDetailsCtrl', [
        '$scope', '$rootScope', 'initialProject', 'initialBuildList', '$http', '$routeParams', 'stream', 'collection',
        function($scope, $rootScope, initialProject, initialBuildList, $http, $routeParams, Stream, Collection) {
      var stream,
          entrypoint = '/api/0/projects/' + $routeParams.project_id + '/builds/',
          chart_options = {
            tooltipFormatter: function(item) {
              var content = '';

              content += '
';
              content += escapeHtml(item.name);
              content += '
';
              content += escapeHtml(item.target);
              if (item.author) {
                content += ' — ' + item.author.name;
              }
              content += '';
              content += '
';
              if (item.status.id == 'finished') {
                content += '
Build ' + item.result.name;
                if (item.duration) {
                  content += ' in ' + duration(item.duration);
                }
                content += '
';
              } else {
                content += '
' + item.status.name + '
';
              }

              return content;
            }
          };

      $scope.getBuildStatus = function(build) {
        if (build.status.id == 'finished') {
          return build.result.name;
        } else {
          return build.status.name;
        }
      };

      function loadBuildList(url) {
        if (!url) {
          return;
        }
        $http.get(url)
          .success(function(data, status, headers){
            $scope.builds = new Collection($scope, data, {
              sortFunc: sortBuildList,
              limit: 100
            });
            $scope.pageLinks = parseLinkHeader(headers('Link'));
          });
      }

      $scope.loadPreviousPage = function() {
        $(document.body).scrollTop(0);
        loadBuildList($scope.pageLinks.previous);
      };

      $scope.loadNextPage = function() {
        $(document.body).scrollTop(0);
        loadBuildList($scope.pageLinks.next);
      };

      $scope.$watch("pageLinks", function(value) {
        $scope.nextPage = value.next || null;
        $scope.previousPage = value.previous || null;
      });

      $scope.pageLinks = parseLinkHeader(initialBuildList.headers('Link'));

      $scope.project = initialProject.data.project;
      $scope.builds = new Collection($scope, initialBuildList.data, {
        sortFunc: sortBuildList,
        limit: 100
      });
      $scope.chartData = chartHelpers.getChartData($scope.builds, null, chart_options);
      $scope.includePatches = false;
      $rootScope.activeProject = $scope.project;
      $rootScope.pageTitle = $scope.project.name + ' Builds';

      $scope.$watch("includePatches", function() {
        loadBuildList(entrypoint + '?include_patches=' + ($scope.includePatches ? '1' : '0'));
      });

      $scope.$watch("builds", function() {
        $scope.chartData = chartHelpers.getChartData($scope.builds, null, chart_options);
      });

      stream = new Stream($scope, entrypoint);
      stream.subscribe('build.update', function(data){
        if (data.source.patch && !$scope.includePatches) {
          return;
        }
        $scope.builds.updateItem(data);
      });
    }]);
  });
})();
<|endoftext|>


<commit_before>/*
 Inc v1.0.0
 (c) 2014 Clearwave Designs, LLC. http://clearwavedesigns.com
 License: Apache 2.0
*/

 function Inc(t){var e=t.elem,a="input"===e.nodeName.toLowerCase()?!0:!1,n=parseFloat(e.getAttribute("data-inc-value"))||0,i=parseInt(e.getAttribute("data-inc-duration"))||0,r=parseInt(e.getAttribute("data-inc-delay"))||0,d=(t.decimal>2?2:t.decimal)||0,l=t.currency||"",c=(t.speed<30?30:t.speed)||30,o=0,u=n/(i/c),s=null,p=/\B(?=(\d{3})+(?!\d))/g,g=function(){o+=u,n>o?a?e.value=l+o.toFixed(d).toString().replace(p,","):e.innerHTML=l+o.toFixed(d).toString().replace(p,","):(clearInterval(s),a?e.value=l+n.toFixed(d).toString().replace(p,","):e.innerHTML=l+n.toFixed(d).toString().replace(p,","))};setTimeout(function(){s=setInterval(g.bind(this),c)}.bind(this),r),this.reset=function(){clearInterval(s),n=parseFloat(e.getAttribute("data-inc-value"))||0,i=parseInt(e.getAttribute("data-inc-duration"))||0,u=n/(i/c),r=parseInt(e.getAttribute("data-inc-delay"))||0,o=0,s=setInterval(g,c)}.bind(this)}
<commit_msg>Updated license<commit_after>/*
 Inc v1.0.0
 (c) 2014 Clearwave Designs, LLC. http://clearwavedesigns.com
 License: MIT
*/

 function Inc(t){var e=t.elem,a="input"===e.nodeName.toLowerCase()?!0:!1,n=parseFloat(e.getAttribute("data-inc-value"))||0,i=parseInt(e.getAttribute("data-inc-duration"))||0,r=parseInt(e.getAttribute("data-inc-delay"))||0,d=(t.decimal>2?2:t.decimal)||0,l=t.currency||"",c=(t.speed<30?30:t.speed)||30,o=0,u=n/(i/c),s=null,p=/\B(?=(\d{3})+(?!\d))/g,g=function(){o+=u,n>o?a?e.value=l+o.toFixed(d).toString().replace(p,","):e.innerHTML=l+o.toFixed(d).toString().replace(p,","):(clearInterval(s),a?e.value=l+n.toFixed(d).toString().replace(p,","):e.innerHTML=l+n.toFixed(d).toString().replace(p,","))};setTimeout(function(){s=setInterval(g.bind(this),c)}.bind(this),r),this.reset=function(){clearInterval(s),n=parseFloat(e.getAttribute("data-inc-value"))||0,i=parseInt(e.getAttribute("data-inc-duration"))||0,u=n/(i/c),r=parseInt(e.getAttribute("data-inc-delay"))||0,o=0,s=setInterval(g,c)}.bind(this)}
<|endoftext|>


<commit_before>import StarWarsApp from './components/StarWarsApp';
import StarWarsAppHomeRoute from './routes/StarWarsAppHomeRoute';

export default {
    Component: StarWarsApp,
    route: new StarWarsAppHomeRoute({
        factionNames: ['empire', 'rebels']
    }),
};
<commit_msg>Remove an unused file<commit_after><|endoftext|>


<commit_before>!function(a){if("object"==typeof exports&&"object"==typeof module)module.exports=a();else{if("function"==typeof define&&define.amd)return define([],a);this.classList=a()}}(function(){"use strict";function f(a,b){if(a&&(a=a.match(d)),b=b?" "+b+" ":"")for(var c=0;e=a[c++];)b.indexOf(" "+e+" ")>-1&&(b=b.replace(" "+e+" "," "));return String.prototype.trim?b.trim():g(b)}function g(a){return a.replace(/^\s+/,"").replace(/\s+$/,"")}var e,a={},b=document,c="classList"in b.documentElement,d=/\S+/g;return a.addClass=function(a,b){if(a&&b&&"string"==typeof b){b=b.match(d);for(var e=b.length;e--;)b[e]&&!this.hasClass(a,b[e])&&(c?a.classList.add(b[e]):a.className?a.className+=" "+b[e]:a.className=b[e]);return this}},a.removeClass=function(a,b){if(a&&b&&"string"==typeof b){if(c){b=b.match(d);for(var e=b.length;e--;)b[e]&&this.hasClass(a,b[e])&&a.classList.remove(b[e])}else a.className=f(b,a.className);return this}},a.toggleClass=function(a,b){if(a&&b&&"string"==typeof b){b&&(b=b.match(d));for(var c=b.length;c--;)b[c]&&this.hasClass(a,b[c])?this.removeClass(a,b[c]):this.addClass(a,b[c])}},a.hasClass=function(a,b){return a&&b&&"string"==typeof b?c?a.classList.contains(b):new RegExp("\\b"+b+"\\b").test(a.className):void 0},a});<commit_msg>amd/cmd supports<commit_after>/*
*   Author: xiaoyuze
*   https://github.com/xiaoyuze88/classList
*/
!function(a){if("object"==typeof exports&&"object"==typeof module)module.exports=a();else{if("function"==typeof define&&define.amd)return define([],a);this.classList=a()}}(function(){"use strict";function f(a,b){if(a&&(a=a.match(d)),b=b?" "+b+" ":"")for(var c=0;e=a[c++];)b.indexOf(" "+e+" ")>-1&&(b=b.replace(" "+e+" "," "));return String.prototype.trim?b.trim():g(b)}function g(a){return a.replace(/^\s+/,"").replace(/\s+$/,"")}var e,a={},b=document,c="classList"in b.documentElement,d=/\S+/g;return a.addClass=function(a,b){if(a&&b&&"string"==typeof b){b=b.match(d);for(var e=b.length;e--;)b[e]&&!this.hasClass(a,b[e])&&(c?a.classList.add(b[e]):a.className?a.className+=" "+b[e]:a.className=b[e]);return this}},a.removeClass=function(a,b){if(a&&b&&"string"==typeof b){if(c){b=b.match(d);for(var e=b.length;e--;)b[e]&&this.hasClass(a,b[e])&&a.classList.remove(b[e])}else a.className=f(b,a.className);return this}},a.toggleClass=function(a,b){if(a&&b&&"string"==typeof b){b&&(b=b.match(d));for(var c=b.length;c--;)b[c]&&this.hasClass(a,b[c])?this.removeClass(a,b[c]):this.addClass(a,b[c])}},a.hasClass=function(a,b){return a&&b&&"string"==typeof b?c?a.classList.contains(b):new RegExp("\\b"+b+"\\b").test(a.className):void 0},a});<|endoftext|>


<commit_before>/**
 * CalcPad - Line Type Definitions
 * Copyright (C) 2014 Thomas Michael Wallace
 * Apache 2 Licensed
 */

// Line type definitions for CalcPad.

// This is not correctly modular at the moment, but it clears the dev.evelopment pad.
define(function (require) {
    "use strict";

    var blank =         require('lines/blank/blank'),
        image =         require('lines/image/image'),
        input =         require('lines/input/input'),
        paragraph =     require('lines/paragraph/paragraph'),
        sectiontitle =  require('lines/sectiontitle/sectiontitle'),
        title =         require('lines/title/title')
        ;

    var linetypes = {

        Blank:          blank,
        Image:          image,
        Input:          input,
        Paragraph:      paragraph,
        SectionTitle:   sectiontitle,
        Title:          title

    };

    return linetypes;
});<commit_msg>Added formula to linetypes.<commit_after>/**
 * CalcPad - Line Type Definitions
 * Copyright (C) 2014 Thomas Michael Wallace
 * Apache 2 Licensed
 */

// Line type definitions for CalcPad.

// This is not correctly modular at the moment, but it clears the dev.evelopment pad.
define(function (require) {
    "use strict";

    var blank =         require('lines/blank/blank'),
        image =         require('lines/image/image'),
        formula =       require('lines/formula/formula'),
        input =         require('lines/input/input'),
        paragraph =     require('lines/paragraph/paragraph'),
        sectiontitle =  require('lines/sectiontitle/sectiontitle'),
        title =         require('lines/title/title')
        ;

    var linetypes = {

        Blank:          blank,
        Image:          image,
        Formula:        formula,
        Input:          input,
        Paragraph:      paragraph,
        SectionTitle:   sectiontitle,
        Title:          title

    };

    return linetypes;
});<|endoftext|>


<commit_before>/**
 * 2017-9-21  sunzhiyue
 */
var _ = require('lodash');
_.chunk(['a', 's', 'd', 'f', 'g',2]);

_.chunk(['a', 'b', 'c', 'd', 'e', 'f',3]);

_.compact([2, 1, 0, false, '', 3]);

var array = [1];
var other  = _.concat(array, 2, [3], [[4]]);

console.log(other);

console.log(array);

console.log( _.difference([2, 1], [2, 2], [3, 2]));//选第一个不同的数显示出来
console.log( _.difference([2, 3, 4], [2, 3, 2]));
console.log(_.difference([2, 3, 4], [3, 4, 5]));
console.log(_.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor));//定一个条件选一个不同的数
console.log(_.differenceBy([{'x': 2}, {'x': 1}],[{'x': 1}], 'x'));

var ob  = [{'x': 1,'y': 2}, {'x': 2, 'y': 1}];
console.log(_.differenceWith(ob, [{'x': 1, 'y': 2}],_.isEqual))//比较上边的和下面的那个不一样输出这个数组
console.log(_.drop([1, 2, 3]));//删除数组里的第一个数；
console.log(_.drop([1, 2, 3, 4],3));//从第三个开始删
console.log(_.dropRight([1, 2, 4, 5]));//从倒数第一个删
console.log(_.dropRight([1, 2, 3, 4, 5, 6],2))//从倒数第2个删；

var users = [
    {'user': 'barney', 'active': true},
    {'user': 'fred', 'active': false},
    {'user': 'peddles', 'active': false}
];
console.log(_.dropRightWhile(users,function(o){
    return !o.active;
}), '------1------');
console.log(_.dropRightWhile(users,{
    'user': 'pebbles', 'active': false
}), '-------2-------');
console.log(_.dropRightWhile(users, ['active',false]), '-----3----');
console.log(_.dropRightWhile(users, 'active'), '----4----');

console.log(_.flatten([1, [2, [3, [4]],5]]),[1, [2, [3, [4]],5]]);
console.log(_.flattenDeep([1, [2, [3, [4]],5]]));

var array1 = [1, 2, 3];
console.log(_.fill(array1, 'a'),array1);
console.log(_.fill(Array(4),6));//Array(有几个)，值
console.log(_.fill([4, 5, 3, 6, 7], '*', 2, 3));

var user = [
    {'user': 'ba', 'active': false},
    {'user': 'fr', 'active': false},
    {'user': 'pe', 'active': true}
];
console.log(_.findIndex(user, function(o){return o.user == 'ba';}));
console.log(_.findIndex(user,{'user': 'fr', 'active': false}));

console.log(_.head([2, 3, 4, 5]))

console.log(_.fromPairs([['a', 1], ['b', 2]]));

console.log(_.indexOf([1, 2, 3, 4],2));
console.log(_.indexOf([1, 1, 1, 4, 5, 6], 6, 5));

console.log(_.initial([1, 2, 3, 4, 5, 6, 7]))//删除最后一个

console.log(_.intersection([2, 1], [2, 3]))//输出相同的

console.log(_.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor));
console.log(_.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }], [{ 'x': 1 }], 'x'));

var a = [{'x': 1, 'y': 2}, {'x': 2, 'y': 1}];
var b = [{'x':1, 'y': 1},{'x': 1, 'y': 2}];
console.log(_.intersectionWith(a, b, _.isEqual));
console.log(_.join(['a', 'b', 'c'], '~'));

var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
console.log(_.pullAll(arr, ['a', 'd']))
console.log(arr);
var arr2 = [1, 2, 3, 4]
var evrens = _.remove(arr2, function(n){
    return n % 2 == 0;
})
console.log(evrens)
module.exports = _;<commit_msg>lodash的方法练习<commit_after>/**
 * 2017-9-21  sunzhiyue
 */
var _ = require('lodash');
_.chunk(['a', 's', 'd', 'f', 'g',2]);

_.chunk(['a', 'b', 'c', 'd', 'e', 'f',3]);

_.compact([2, 1, 0, false, '', 3]);

var array = [1];
var other  = _.concat(array, 2, [3], [[4]]);

console.log(other);

console.log(array);

console.log( _.difference([2, 1], [2, 2], [3, 2]));//选第一个不同的数显示出来
console.log( _.difference([2, 3, 4], [2, 3, 2]));
console.log(_.difference([2, 3, 4], [3, 4, 5]));
console.log(_.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor));//定一个条件选一个不同的数
console.log(_.differenceBy([{'x': 2}, {'x': 1}],[{'x': 1}], 'x'));

var ob  = [{'x': 1,'y': 2}, {'x': 2, 'y': 1}];
console.log(_.differenceWith(ob, [{'x': 1, 'y': 2}],_.isEqual))//比较上边的和下面的那个不一样输出这个数组
console.log(_.drop([1, 2, 3]));//删除数组里的第一个数；
console.log(_.drop([1, 2, 3, 4],3));//从第三个开始删
console.log(_.dropRight([1, 2, 4, 5]));//从倒数第一个删
console.log(_.dropRight([1, 2, 3, 4, 5, 6],2))//从倒数第2个删；

var users = [
    {'user': 'barney', 'active': true},
    {'user': 'fred', 'active': false},
    {'user': 'peddles', 'active': false}
];
console.log(_.dropRightWhile(users,function(o){
    return !o.active;
}), '------1------');
console.log(_.dropRightWhile(users,{
    'user': 'pebbles', 'active': false
}), '-------2-------');
console.log(_.dropRightWhile(users, ['active',false]), '-----3----');
console.log(_.dropRightWhile(users, 'active'), '----4----');

console.log(_.flatten([1, [2, [3, [4]],5]]),[1, [2, [3, [4]],5]]);
console.log(_.flattenDeep([1, [2, [3, [4]],5]]));

var array1 = [1, 2, 3];
console.log(_.fill(array1, 'a'),array1);
console.log(_.fill(Array(4),6));//Array(有几个)，值
console.log(_.fill([4, 5, 3, 6, 7], '*', 2, 3));

var user = [
    {'user': 'ba', 'active': false},
    {'user': 'fr', 'active': false},
    {'user': 'pe', 'active': true}
];
console.log(_.findIndex(user, function(o){return o.user == 'ba';}));
console.log(_.findIndex(user,{'user': 'fr', 'active': false}));

console.log(_.head([2, 3, 4, 5]))

console.log(_.fromPairs([['a', 1], ['b', 2]]));

console.log(_.indexOf([1, 2, 3, 4],2));
console.log(_.indexOf([1, 1, 1, 4, 5, 6], 6, 5));

console.log(_.initial([1, 2, 3, 4, 5, 6, 7]))//删除最后一个

console.log(_.intersection([2, 1], [2, 3]))//输出相同的

console.log(_.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor));
console.log(_.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }], [{ 'x': 1 }], 'x'));

var a = [{'x': 1, 'y': 2}, {'x': 2, 'y': 1}];
var b = [{'x':1, 'y': 1},{'x': 1, 'y': 2}];
console.log(_.intersectionWith(a, b, _.isEqual));
console.log(_.join(['a', 'b', 'c'], '~'));

var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
console.log(_.pullAll(arr, ['a', 'd']))
console.log(arr);
var arr2 = [1, 2, 3, 4]
var evrens = _.remove(arr2, function(n){
    return n % 2 == 0;
})

console.log(_.sortedUniq([1, 1, 1, 3, 3, 1, 3, 4]))
console.log(_.without([ 3, 4, 3, 4, 1, 5 ], 3, 4))
console.log (_.sortedIndexOf([4, 5, 6, 4, 5, 6], 5))

console.log(_.xor([2, 1], [2, 2], [2, 3], [3, 2], [4, 3, 2]));
console.log(_.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor));
console.log(_.xorBy([{ 'x': 1}], [{ 'x' : 2}, {'x': 1}], 'x'));

console.log(_.zip(['a', 'b'], [1, 2], [true, false]));
console.log(_.zipObject(['a', 'b'], [1, 2], [3, 4]));

console.log(_.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]))
console.log(_.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c){
    return a * b + c;
}))

console.log(_.countBy[6.1, 4.2, 6.3], Math.floor);
console.log(_.countBy(['one', 'two', 'three', 'four', 'five'],'length'));<|endoftext|>


<commit_before>(function(global, undefined) {
"use strict";

var Mocha = global.Mocha;
var Suite = Mocha.Suite;
var Test = Mocha.Test;

var assertFns = {
  ok: function(val) {
    if (!val) {
      throw new Error("Expected " + val + " to be truthy");
    }
  },
  equal: function(val1, val2) {
    if (val1 != val2) {
      throw new Error("Expected " + val1 + " to equal " + val2);
    }
  },
  notStrictEqual: function(val1, val2) {
    if (val1 !== val2) {
      throw new Error("Expected " + val1 + " to strictly equal " + val2);
    }
  }
};

/**
 * QUnit-style interface:
 *
 *     module('Array');
 *
 *     test('#length', function() {
 *       var arr = [1,2,3];
 *       ok(arr.length == 3);
 *     });
 *
 *     test('#indexOf()', function() {
 *       var arr = [1,2,3];
 *       ok(arr.indexOf(1) == 0);
 *       ok(arr.indexOf(2) == 1);
 *       ok(arr.indexOf(3) == 2);
 *     });
 *
 *     suite('String');
 *
 *     test('#length', function() {
 *       ok('foo'.length == 3);
 *     });
 *
 */

var ui = function(suite) {
  var suites = [suite];

  var assertionCount = 0;
  var inModule = false;
  var expectedAssertions;
  var deferrals;
  var currentDoneFn;
  var checkingDeferrals;

  suite.on('pre-require', function(realContext) {

    /**
     * Execute before running tests.
     */
    var context = {};
    var assert = {};

    /**
     * Describe a "suite" with the given `title`.
     */

    context.module = function(title, opts) {
      if (suites.length > 1) suites.shift();
      var suite = Suite.create(suites[0], title);
      suites.unshift(suite);

      suite.beforeEach(function() {
        checkingDeferrals = false;
        deferrals = 0;
        inModule = true;
        assertionCount = 0;
      });
      if (opts) {
        suite.beforeEach(function() { for (var k in opts) this[k] = opts[k] });
        if (opts.setup) suite.beforeEach(opts.setup.bind(this, assert));
        if (opts.teardown) suite.afterEach(opts.teardown.bind(this, assert));
      }
      suite.afterEach(function(done) {
        done(checkAssertionCount());
      });
    };

    /**
    * Call this after each assertion to increment the assertion count
    * (for custom assertion types)
    */
    context.afterAssertion = function() {
      assertionCount++;
    };

    /** The number of assertions to expect in the current test case */
    context.expect = function(n) {
      if (!arguments.length) {
        return expectedAssertions;
      }
      expectedAssertions = n;
    };

    /** Define all of the QUnit Assertions based of their node.js equivalents */
    ["deepEqual", "equal", "notDeepEqual", "notEqual",
      "notStrictEqual","ok","strictEqual","throws"].forEach(function(k) {
      assert[k] = function() {
        assertionCount++;
        assertFns[k].apply(null, arguments);
      }
    });

    // Deprecated since QUnit v1.9.0, but still used, e.g. by Backbone.
    context.raises = context.throws

    /**
    * Checks to see if the assertion counts indicate a failure.
    * Returns an Error object if it did, null otherwise;
    */
    var checkAssertionCount = function() {
      if(expectedAssertions > 0 && expectedAssertions != assertionCount){
        return new Error("Expected "+ expectedAssertions + " assertions but saw " + assertionCount);
      };
      return null;
    };

    context.start = function() {
      deferrals--;
      if (deferrals === 0 && !checkingDeferrals) {
        checkingDeferrals = true;
        setTimeout(function() {
          checkingDeferrals = false;
          if (deferrals === 0 && currentDoneFn) {
            currentDoneFn();
          }
        }, 0);
      } else if (deferrals < 0) {
        throw new Error("cannot call start() when not stopped");
      }
    };

    context.stop = function() {
      deferrals++;
    };

    function normalizeTestArgs(fn) {
      return function(title, expect, test) {
        if (typeof expect == "function") {
          test = expect;
          expect = 0;
        }

        return fn.call(this, title, expect, test);
      };
    }

    function wrapTestFunction(test, wrapper) {
      var result = function(done) {
        return wrapper.call(this, test, done);
      };
      result.toString = test.toString.bind(test);
      return result;
    }

    function addTest(title, expect, test) {
      suites[0].addTest(new Test(title, wrapTestFunction(test, function(test, done) {
        deferrals = 0;
        checkingDeferrals = false;
        expectedAssertions = expect;
        assertionCount = 0;
        currentDoneFn = function() {
          done(checkAssertionCount());
          currentDoneFn = null;
        };
        context.stop();
        test.call(this, currentDoneFn);
        context.start();
      })));
    }

    /**
     * Describe a specification or test-case
     * with the given `title`, an optional number of assertions to expect,
     * callback `test` acting as a thunk.
     */
    context.test = normalizeTestArgs(function(title, expect, test) {
      addTest(title, expect, test.bind(this, assert));
    });

    context.asyncTest = normalizeTestArgs(function(title, expect, test) {
      addTest(title, expect, wrapTestFunction(test, function(test, done) {
        context.stop();
        test.call(this, assert);
      }));
    });

    context.assert = assert;
    realContext.QUnit = context;
    Object.keys(assert).forEach(function(attr) {
      context[attr] = assert[attr];
    });
    Object.keys(context).forEach(function(attr) {
      realContext[attr] = context[attr];
    });
  });
};

Mocha.interfaces.qunit = ui;
if (typeof module !== "undefined") {
  module.exports = ui;
}
}(this));
<commit_msg>Update `start` and `stop` to accept number values<commit_after>(function(global, undefined) {
"use strict";

var Mocha = global.Mocha;
var Suite = Mocha.Suite;
var Test = Mocha.Test;

var assertFns = {
  ok: function(val) {
    if (!val) {
      throw new Error("Expected " + val + " to be truthy");
    }
  },
  equal: function(val1, val2) {
    if (val1 != val2) {
      throw new Error("Expected " + val1 + " to equal " + val2);
    }
  },
  notStrictEqual: function(val1, val2) {
    if (val1 !== val2) {
      throw new Error("Expected " + val1 + " to strictly equal " + val2);
    }
  }
};

/**
 * QUnit-style interface:
 *
 *     module('Array');
 *
 *     test('#length', function() {
 *       var arr = [1,2,3];
 *       ok(arr.length == 3);
 *     });
 *
 *     test('#indexOf()', function() {
 *       var arr = [1,2,3];
 *       ok(arr.indexOf(1) == 0);
 *       ok(arr.indexOf(2) == 1);
 *       ok(arr.indexOf(3) == 2);
 *     });
 *
 *     suite('String');
 *
 *     test('#length', function() {
 *       ok('foo'.length == 3);
 *     });
 *
 */

var ui = function(suite) {
  var suites = [suite];

  var assertionCount = 0;
  var inModule = false;
  var expectedAssertions;
  var deferrals;
  var currentDoneFn;
  var checkingDeferrals;

  suite.on('pre-require', function(realContext) {

    /**
     * Execute before running tests.
     */
    var context = {};
    var assert = {};

    /**
     * Describe a "suite" with the given `title`.
     */

    context.module = function(title, opts) {
      if (suites.length > 1) suites.shift();
      var suite = Suite.create(suites[0], title);
      suites.unshift(suite);

      suite.beforeEach(function() {
        checkingDeferrals = false;
        deferrals = 0;
        inModule = true;
        assertionCount = 0;
      });
      if (opts) {
        suite.beforeEach(function() { for (var k in opts) this[k] = opts[k] });
        if (opts.setup) suite.beforeEach(opts.setup.bind(this, assert));
        if (opts.teardown) suite.afterEach(opts.teardown.bind(this, assert));
      }
      suite.afterEach(function(done) {
        done(checkAssertionCount());
      });
    };

    /**
    * Call this after each assertion to increment the assertion count
    * (for custom assertion types)
    */
    context.afterAssertion = function() {
      assertionCount++;
    };

    /** The number of assertions to expect in the current test case */
    context.expect = function(n) {
      if (!arguments.length) {
        return expectedAssertions;
      }
      expectedAssertions = n;
    };

    /** Define all of the QUnit Assertions based of their node.js equivalents */
    ["deepEqual", "equal", "notDeepEqual", "notEqual",
      "notStrictEqual","ok","strictEqual","throws"].forEach(function(k) {
      assert[k] = function() {
        assertionCount++;
        assertFns[k].apply(null, arguments);
      }
    });

    // Deprecated since QUnit v1.9.0, but still used, e.g. by Backbone.
    context.raises = context.throws

    /**
    * Checks to see if the assertion counts indicate a failure.
    * Returns an Error object if it did, null otherwise;
    */
    var checkAssertionCount = function() {
      if(expectedAssertions > 0 && expectedAssertions != assertionCount){
        return new Error("Expected "+ expectedAssertions + " assertions but saw " + assertionCount);
      };
      return null;
    };

    context.start = function(count) {
      count = count || 1;
      deferrals -= count;
      if (deferrals === 0 && !checkingDeferrals) {
        checkingDeferrals = true;
        setTimeout(function() {
          checkingDeferrals = false;
          if (deferrals === 0 && currentDoneFn) {
            currentDoneFn();
          }
        }, 0);
      } else if (deferrals < 0) {
        throw new Error("cannot call start() when not stopped");
      }
    };

    context.stop = function(count) {
      count = count || 1;
      deferrals += count;
    };

    function normalizeTestArgs(fn) {
      return function(title, expect, test) {
        if (typeof expect == "function") {
          test = expect;
          expect = 0;
        }

        return fn.call(this, title, expect, test);
      };
    }

    function wrapTestFunction(test, wrapper) {
      var result = function(done) {
        return wrapper.call(this, test, done);
      };
      result.toString = test.toString.bind(test);
      return result;
    }

    function addTest(title, expect, test) {
      suites[0].addTest(new Test(title, wrapTestFunction(test, function(test, done) {
        deferrals = 0;
        checkingDeferrals = false;
        expectedAssertions = expect;
        assertionCount = 0;
        currentDoneFn = function() {
          done(checkAssertionCount());
          currentDoneFn = null;
        };
        context.stop();
        test.call(this, currentDoneFn);
        context.start();
      })));
    }

    /**
     * Describe a specification or test-case
     * with the given `title`, an optional number of assertions to expect,
     * callback `test` acting as a thunk.
     */
    context.test = normalizeTestArgs(function(title, expect, test) {
      addTest(title, expect, test.bind(this, assert));
    });

    context.asyncTest = normalizeTestArgs(function(title, expect, test) {
      addTest(title, expect, wrapTestFunction(test, function(test, done) {
        context.stop();
        test.call(this, assert);
      }));
    });

    context.assert = assert;
    realContext.QUnit = context;
    Object.keys(assert).forEach(function(attr) {
      context[attr] = assert[attr];
    });
    Object.keys(context).forEach(function(attr) {
      realContext[attr] = context[attr];
    });
  });
};

Mocha.interfaces.qunit = ui;
if (typeof module !== "undefined") {
  module.exports = ui;
}
}(this));
<|endoftext|>


<commit_before>define(['js/data/Entity', 'sprd/entity/Offset', 'sprd/entity/PrintArea'], function (Entity, Offset, PrintArea) {
	return Entity.inherit('sprd.entity.ViewMap', {

        defaults: {
            transformations: ""
        },

        schema: {
            transformations: String,
            printArea: PrintArea,
            offset: Offset
        },

        getProductType: function() {
            return this.$parent;
        },

		getDefaultPrintArea : function() {

			var defaultViewId = this.$.id,
				printArea, i;

            var printAreas = this.printAreas();

            for (i = 0; i < printAreas.length; i++) {
                printArea = printAreas[i];
                if (printArea.id === defaultViewId) {
                    return printArea;
                }
            }

            return printAreas[0];

		},

        getViewMaps: function() {
            var ret = [];

            var productType = this.$parent;

            if (productType) {
                for (var i = 0; i < this.$.viewMaps.length; i++) {
                    var viewMap = this.$.viewMaps[i];

                    if (viewMap.id === this.$.id) {
                        var printArea = productType.getPrintAreaById(viewMap.printArea.id);
                        if (printArea) {
                            ret.push(printArea);
                        }
                    }
                }
            }

            return ret;
        },

        printAreas: function() {
            var ret = [];

            var productType = this.$parent;

            if (productType) {
                for (var i = 0; i < this.$.viewMaps.length; i++) {
                    var viewMap = this.$.viewMaps[i];

                    if (viewMap.id === this.$.id) {
                        var printArea = productType.getPrintAreaById(viewMap.printArea.id);
                        if (printArea) {
                            ret.push(printArea);
                        }
                    }
                }
            }

            return ret;
        }

	});
});
<commit_msg>fixed printAreas for ViewMap<commit_after>define(['js/data/Entity', 'sprd/entity/Offset', 'sprd/entity/PrintArea'], function (Entity, Offset, PrintArea) {
	return Entity.inherit('sprd.entity.ViewMap', {

        defaults: {
            transformations: ""
        },

        schema: {
            transformations: String,
            printArea: PrintArea,
            offset: Offset
        },

        getProductType: function() {
            return this.$parent;
        },

		getDefaultPrintArea : function() {

			var defaultViewId = this.$.id,
				printArea, i;

            var printAreas = this.printAreas();

            for (i = 0; i < printAreas.length; i++) {
                printArea = printAreas[i];
                if (printArea.id === defaultViewId) {
                    return printArea;
                }
            }

            return printAreas[0];

		},

        getViewMaps: function() {
            var ret = [];

            var productType = this.$parent;

            if (productType) {
                for (var i = 0; i < this.$.viewMaps.length; i++) {
                    var viewMap = this.$.viewMaps[i];

                    if (viewMap.id === this.$.id) {
                        var printArea = productType.getPrintAreaById(viewMap.printArea.id);
                        if (printArea) {
                            ret.push(printArea);
                        }
                    }
                }
            }

            return ret;
        },

        printAreas: function() {
            var ret = [];

            var productType = this.$parent;

            if (productType) {
                for (var i = 0; i < productType.$.viewMaps.$items.length; i++) {
                    var viewMap = productType.$.viewMaps.$items[i];

                    if (viewMap.id === this.$.id) {
                        ret.push(viewMap.$.printArea);
                    }
                }
            }

            return ret;
        }

	});
});
<|endoftext|>


<commit_before>var StatusError = require("./statuserror");
var Utils = require("./utils");

/*
  Handlers for events emitted by `send` / `call` etc.
 */
var handlers = {

  // ----------------------------------- Constants -------------------------------------------------

  maxConfirmations: 24,          // Maximum number of confirmation web3 emits
  defaultTimeoutBlocks: 50,      // Maximum number of blocks web3 will wait before abandoning tx
  timeoutMessage: '50 blocks',   // Substring of web3 timeout error.

  // -----------------------------------  Helpers --------------------------------------------------

  /**
   * Parses error message and determines if we should squash block timeout errors at user's request.
   * @param  {Object} context execution state
   * @param  {Object} error   error
   * @return {Boolean}
   */
  ignoreTimeoutError: function(context, error){
    var timedOut = error.message && error.message.includes(handlers.timeoutMessage);

    var shouldWait = context.contract &&
                     context.contract.timeoutBlocks &&
                     context.contract.timeoutBlocks > handlers.defaultTimeoutBlocks;

    return timedOut && shouldWait;
  },

  /**
   * Attaches Truffle specific handlers to all of the events emitted by a web3 method.
   * @param {Object}       context  execution state
   * @param {PromiEvent}   emitter  promiEvent returned by a web3 method call
   */
  setup: function(emitter, context){
    emitter.on('error',           handlers.error.bind(emitter, context))
    emitter.on('transactionHash', handlers.hash.bind(emitter, context))
    emitter.on('confirmation',    handlers.confirmation.bind(emitter, context))
    emitter.on('receipt',         handlers.receipt.bind(emitter, context));
  },

  // -----------------------------------  Handlers -------------------------------------------------
  /**
   * Error event handler. Emits error unless error is block timeout and user has
   * specified we should wait longer
   * @param  {Object} context   execution state
   * @param  {Object} error     error
   */
  error: function(context, error){
    if (!handlers.ignoreTimeoutError(context, error)){
      context.promiEvent.eventEmitter.emit('error', error);
      this.removeListener('error', handlers.error);
      context.promiEvent.reject(error); // This shouldn't be necessary!!!
    }
  },

  /**
   * Transaction hash event handler. Attaches the hash to the context object
   * so it can be attached to the contract instance after a deployment resolves.
   * @param  {Object} context   execution state
   * @param  {String} hash      transaction hash
   */
  hash: function(context, hash){
    context.transactionHash = hash;
    context.promiEvent.eventEmitter.emit('transactionHash', hash);
    this.removeListener('transactionHash', handlers.hash);
  },

  confirmation: function(context, number, receipt){
    context.promiEvent.eventEmitter.emit('confirmation', number, receipt)

    // Per web3: initial confirmation index is 0
    if (number === handlers.maxConfirmations + 1) {
      this.removeListener('confirmation', handlers.confirmation);
    }
  },

  /**
   * Receipt event handler. This handler decodes the event logs, re-emits the receipt,
   * and (for method calls only) resolves/rejects the promiEvent with the receipt.
   * @param  {Object} context   execution state
   * @param  {Object} receipt   transaction receipt
   */
  receipt: function(context, receipt){
    // Decode logs
    var logs;

    (receipt.logs)
      ? logs = Utils.decodeLogs.call(context.contract, receipt.logs)
      : logs = [];

    // Rewrite logs and emit receipt
    receipt.logs = logs;
    context.promiEvent.eventEmitter.emit('receipt', receipt)

    // .new(): Exit early. We need the promiEvent to resolve a contract instance.
    if(context.onlyEmitReceipt){
      context.receipt = receipt;
      return;
    }

    // .method(): resolve/reject receipt in handler
    if (parseInt(receipt.status) == 0 && !context.onlyEmitReceipt){
      var error = new StatusError(context.params, receipt.transactionHash, receipt);
      return context.promiEvent.reject(error)
    }

    // This object has some duplicate data but is backward compatible.
    context.promiEvent.resolve({
      tx: receipt.transactionHash,
      receipt: receipt,
      logs: logs
    });

    this.removeListener('receipt', handlers.receipt);
  },
}

module.exports = handlers;<commit_msg>Do not rewrite receipt logs<commit_after>var StatusError = require("./statuserror");
var Utils = require("./utils");

/*
  Handlers for events emitted by `send` / `call` etc.
 */
var handlers = {

  // ----------------------------------- Constants -------------------------------------------------

  maxConfirmations: 24,          // Maximum number of confirmation web3 emits
  defaultTimeoutBlocks: 50,      // Maximum number of blocks web3 will wait before abandoning tx
  timeoutMessage: '50 blocks',   // Substring of web3 timeout error.

  // -----------------------------------  Helpers --------------------------------------------------

  /**
   * Parses error message and determines if we should squash block timeout errors at user's request.
   * @param  {Object} context execution state
   * @param  {Object} error   error
   * @return {Boolean}
   */
  ignoreTimeoutError: function(context, error){
    var timedOut = error.message && error.message.includes(handlers.timeoutMessage);

    var shouldWait = context.contract &&
                     context.contract.timeoutBlocks &&
                     context.contract.timeoutBlocks > handlers.defaultTimeoutBlocks;

    return timedOut && shouldWait;
  },

  /**
   * Attaches Truffle specific handlers to all of the events emitted by a web3 method.
   * @param {Object}       context  execution state
   * @param {PromiEvent}   emitter  promiEvent returned by a web3 method call
   */
  setup: function(emitter, context){
    emitter.on('error',           handlers.error.bind(emitter, context))
    emitter.on('transactionHash', handlers.hash.bind(emitter, context))
    emitter.on('confirmation',    handlers.confirmation.bind(emitter, context))
    emitter.on('receipt',         handlers.receipt.bind(emitter, context));
  },

  // -----------------------------------  Handlers -------------------------------------------------
  /**
   * Error event handler. Emits error unless error is block timeout and user has
   * specified we should wait longer
   * @param  {Object} context   execution state
   * @param  {Object} error     error
   */
  error: function(context, error){
    if (!handlers.ignoreTimeoutError(context, error)){
      context.promiEvent.eventEmitter.emit('error', error);
      this.removeListener('error', handlers.error);
      context.promiEvent.reject(error); // This shouldn't be necessary!!!
    }
  },

  /**
   * Transaction hash event handler. Attaches the hash to the context object
   * so it can be attached to the contract instance after a deployment resolves.
   * @param  {Object} context   execution state
   * @param  {String} hash      transaction hash
   */
  hash: function(context, hash){
    context.transactionHash = hash;
    context.promiEvent.eventEmitter.emit('transactionHash', hash);
    this.removeListener('transactionHash', handlers.hash);
  },

  confirmation: function(context, number, receipt){
    context.promiEvent.eventEmitter.emit('confirmation', number, receipt)

    // Per web3: initial confirmation index is 0
    if (number === handlers.maxConfirmations + 1) {
      this.removeListener('confirmation', handlers.confirmation);
    }
  },

  /**
   * Receipt event handler. This handler decodes the event logs, re-emits the receipt,
   * and (for method calls only) resolves/rejects the promiEvent with the receipt.
   * @param  {Object} context   execution state
   * @param  {Object} receipt   transaction receipt
   */
  receipt: function(context, receipt){
    // Decode logs
    var logs;

    (receipt.logs)
      ? logs = Utils.decodeLogs.call(context.contract, receipt.logs)
      : logs = [];

    // Emit receipt
    context.promiEvent.eventEmitter.emit('receipt', receipt)

    // .new(): Exit early. We need the promiEvent to resolve a contract instance.
    if(context.onlyEmitReceipt){
      context.receipt = receipt;
      return;
    }

    // .method(): resolve/reject receipt in handler
    if (parseInt(receipt.status) == 0 && !context.onlyEmitReceipt){
      var error = new StatusError(context.params, receipt.transactionHash, receipt);
      return context.promiEvent.reject(error)
    }

    // This object has some duplicate data but is backward compatible.
    context.promiEvent.resolve({
      tx: receipt.transactionHash,
      receipt: receipt,
      logs: logs
    });

    this.removeListener('receipt', handlers.receipt);
  },
}

module.exports = handlers;<|endoftext|>


<commit_before>/******************************************
 * Websanova.com
 *
 * Resources for web entrepreneurs
 *
 * @author          Websanova
 * @copyright       Copyright (c) 2012 Websanova.
 * @license         This websanova JSNova jQuery plugin is dual licensed under the MIT and GPL licenses.
 * @link            http://www.websanova.com
 * @docs            http://www.websanova.com/plugins/websanova/jsnova
 * @version         Version 1.0
 *
 ******************************************/

<<<<<<>>>>>> master
(function($)
{
	$.fn.wJSNova = function(option, settings)
	{
		if(typeof option === 'object')
		{
			settings = option;
		}
		else if(typeof option === 'string')
		{
			var data = this.data('_wJSNova');

			if(data)
			{
				if(option == 'resize') { data.resize(); return true }
				else if($.fn.wJSNova.defaultSettings[option] !== undefined)
				{
					if(settings !== undefined){
						data.settings[option] = settings;
						return true;
					}
					else return data.settings[option];
				}
				else return false;
			}
			else return false;
		}

		settings = $.extend({}, $.fn.wJSNova.defaultSettings, settings || {});

		return this.each(function()
		{
			var $elem = $(this);

			var $settings = jQuery.extend(true, {}, settings);

			var jsn = new JSNova($settings);

			$elem.append(jsn.generate());
			jsn.resize();

			$elem.data('_wJSNova', jsn);
		});
	}

	$.fn.wJSNova.defaultSettings = {};

	function JSNova(settings)
	{
		this.jsn = null;
		this.settings = settings;

		this.menu = null;

		this.sidebar = null;
		this.jQueryVersion = null;
		this.jQueryUIVersion = null;
		this.jQueryUITheme = null;

		this.codeArea = null;
		this.boxHTML = null;
		this.boxQML = null;
		this.boxJS = null;
		this.boxResult = null;

		return this;
	}

	JSNova.prototype =
	{
		init: function()
		{
			this.resize();
		},

		generate: function()
		{
			var $this = this;

			if($this.jsn) return $this.jsn;

			/************************************************
			 * Menu
			 ************************************************/
			var menuButton_run = $('Run').click(function(){$this.run();});
			var menuButton_download = $('Download').click(function(){$this.download();});
			var menuButton_save = $('Suggest Demo').click(function(){$this.save();});
			var menuButton_reset = $('Reset').click(function(){$this.reset();});

			$this.menu =
			$('

')
			.append('

')
			.append(
				$('

')
				.append(menuButton_run)
				.append(menuButton_download)
				.append(menuButton_save)
				.append(menuButton_reset)
				.append('')
			);

			/************************************************
			 * Sidebar
			 ************************************************/
			var demos = [['Single Video','single'],['Playlist','playlist'],['Duplicate Video 2','duplicate2'],['Whirlwind','whirlwind'],['Multiscreen Demo','multiscreen'],['Duplicate Video','duplicate'],['Fullscreen Zoom','zoom'],['3D Rotate','rotate']];
			$this.Demoz = $("<select name='demos' onchange='location = \"http://jaruba.github.io/WebchimeraGUI/editor/?demo=\"+this.options[this.selectedIndex].value;' style='width: 100%'></select>");
<<<<<<>>>>>> master
			 for (var item = 0; item < demos.length; item++) {
				 if (demos[item][1] == hash) {
					$this.Demoz.append('<option value="' + demos[item][1] + '" selected>' + demos[item][0] + '</option>');
				 } else {
					$this.Demoz.append('<option value="' + demos[item][1] + '">' + demos[item][0] + '</option>');
				 }
			 }

			$this.WebchimeraJS = $('<select name="webchimerajs" class="_wJSNova_sidebarSelect"></select>');
			$this.WebchimeraJS.append('<option value="latest">Latest Webchimera.js</option>');
			$this.WebchimeraJS.append('<option value="none">none</option>');

			$this.jQueryVersion = $('<select name="jquery" class="_wJSNova_sidebarSelect"></select>');
			$this.jQueryVersion.append('<option value="none">none</option>');
			$.each(['2.1.1', '2.1.0', '2.0.3', '2.0.2', '2.0.1', '2.0.0', '1.11.1', '1.11.0'],
			function(index,version){ $this.jQueryVersion.append('<option value="https://ajax.googleapis.com/ajax/libs/jquery/' + version + '/jquery.min.js">jQuery ' + version + '</option>'); });

			$this.jQueryUIVersion = $('<select name="jqueryui" class="_wJSNova_sidebarSelect"></select>');
			$this.jQueryUIVersion.append('<option value="none">none</option>');
			$.each(['1.11.2', '1.11.1', '1.11.0', '1.10.4', '1.10.3', '1.10.2', '1.10.1', '1.10.0', '1.9.2', '1.9.1', '1.9.0'],
			function(index,version){ $this.jQueryUIVersion.append('<option value="https://ajax.googleapis.com/ajax/libs/jqueryui/' + version + '/jquery-ui.min.js">jQuery UI ' + version + '</option>'); });

//			$this.jQueryUITheme = $('<select class="_wJSNova_sidebarSelect"></seletct>');
//			$.each(['base', 'black-tie', 'blitzer', 'cupertino', 'dot-luv', 'excite-bike', 'hot-sneaks', 'humanity', 'mint-choc', 'redmond', 'smoothness', 'south-street', 'start', 'swanky-purse', 'trontastic', 'ui-darkness', 'ui-lightness', 'vader'],
//			function(index,version){ $this.jQueryUITheme.append('<option value="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/' + version + '/jquery-ui.css">' + version + '</option>'); });

			$this.sidebar =
			$('

')
			.append(
				$('

')
				.append('
Select Demo:
')
				.append($this.Demoz)
				.append('
Webchimera JS:
')
				.append($this.WebchimeraJS)
				.append('
jQuery Version:
')
				.append($this.jQueryVersion)
				.append('
jQuery UI Version:
')
				.append($this.jQueryUIVersion)
//				.append('
jQuery UI Theme:
')
//				.append($this.jQueryUITheme)
			);

			/************************************************
			 * Code Area
			 ************************************************/
			$this.boxHTML = $('<textarea name="html" class="_wJSNova_boxEdit" data-editor="html"></textarea>');
			$this.boxQML = $('<textarea name="qml" class="_wJSNova_boxEdit" data-editor="javascript"></textarea>');
			$this.boxJS = $('<textarea name="js" class="_wJSNova_boxEdit" data-editor="javascript"></textarea>');
			$this.boxResult = $('');

			$.each([$this.boxHTML, $this.boxQML, $this.boxJS, $this.boxResult], function(index, item)
			{
				item.hover(function(){ $(this).parent().children('._wJSNova_boxLabel').fadeOut(200); }, function() { if (!($(this).is(":focus"))) $(this).parent().children('._wJSNova_boxLabel').fadeIn(200); });
			});

			$this.codeArea =
			$('

')
			.append(
				$('

')
				.append(
					$('

')
					.append(
						$('	')
						.append(
							$('

')
							.append($this.boxHTML)
							.append('
HTML
')
							.hover(function() { $("#htmlbox").fadeOut(200); },function() { $("#htmlbox").fadeIn(200); })
						)
					)
					.append(
						$('	')
						.append(
							$('

')
							.append($this.boxJS)
							.append('
JavaScript
')
							.hover(function() { $("#jsbox").fadeOut(200); },function() { $("#jsbox").fadeIn(200); })
						)
					)
				)
				.append(
					$('

')
					.append(
						$('	')
						.append(
							$('

')
							.append($this.boxQML)
							.append('
QML
')
							.hover(function() { $("#qmlbox").fadeOut(200); },function() { $("#qmlbox").fadeIn(200); })
						)
					)
					.append(
						$('	')
						.append(
							$('

')
							.append($this.boxResult)
							.append('
Result
')
						)
					)
				)
			)

			$this.jsn =
			$('

')
			.append($this.menu)
			.append($this.sidebar)
			.append($this.codeArea);

			return $this.jsn;
		},

		run: function()
		{
			for (kl = 0; typeof textareas[kl] !== 'undefined'; kl++) textareas[kl].val(editors[kl].getSession().getValue());
			var html = this.boxHTML.val();
			var js = this.boxJS.val();
			var qml = this.boxQML.val();

			if (this.WebchimeraJS.val() != "none") {
				var WebchimeraScript = '';
			} else WebchimeraScript = '';

			if (this.jQueryVersion.val() != "none") {
				var jQuery = '';
			} else jQuery = '';

			if (this.jQueryUIVersion.val() != "none") {
				var jQueryUI = '';
			} else var jQueryUI = '';

//			var jQueryUITheme = '<link rel="stylesheet" type="text/css" href="' + this.jQueryUITheme.val() + '"/>'

			var result = '' + WebchimeraScript + jQuery + jQueryUI + '' + html + '<textarea id="qmlcode">' + qml + '</textarea>';

			this.writeResult(result);
		},

		reset: function()
		{
			location.reload();
		},

		download: function()
		{
			for (kl = 0; typeof textareas[kl] !== 'undefined'; kl++) textareas[kl].val(editors[kl].getSession().getValue());
			$("#editorform").submit();
		},

		save: function()
		{
			for (kl = 0; typeof textareas[kl] !== 'undefined'; kl++) textareas[kl].val(editors[kl].getSession().getValue());
			var data = $("#editorform").serializeArray();
			$.post("http://www.movault.net/webchimera/editor/generator/demos/custom-demo.php", data);
			$("#message").html("Demo sent successfully!").fadeIn(300).delay(2500).fadeOut(300);
		},

		writeResult: function(result)
		{
			var iframe = this.boxResult[0];

			if(iframe.contentDocument) doc = iframe.contentDocument;
			else if(iframe.contentWindow) doc = iframe.contentWindow.document;
			else doc = iframe.document;

			doc.open();
			doc.writeln(result);
			doc.close();
		},

		resize: function()
		{
			var menuHeight = this.menu.outerHeight(true);
			var jsnHeight = this.jsn.outerHeight(true) - menuHeight;

			var codeAreaWidth = this.jsn.outerWidth(true) - this.sidebar.outerWidth(true);

			this.sidebar.css({top: menuHeight, height: jsnHeight});
			this.codeArea.css({top: menuHeight, height: jsnHeight, width: codeAreaWidth});
		}
	}
})(jQuery);<commit_msg>Update wJSNova.1.0.js<commit_after>/******************************************
 * Websanova.com
 *
 * Resources for web entrepreneurs
 *
 * @author          Websanova
 * @copyright       Copyright (c) 2012 Websanova.
 * @license         This websanova JSNova jQuery plugin is dual licensed under the MIT and GPL licenses.
 * @link            http://www.websanova.com
 * @docs            http://www.websanova.com/plugins/websanova/jsnova
 * @version         Version 1.0
 *
 ******************************************/

function getUrlVar() {
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		if (key == "demo") return value;
	});
}

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

>>>>>>> master
(function($)
{
	$.fn.wJSNova = function(option, settings)
	{
		if(typeof option === 'object')
		{
			settings = option;
		}
		else if(typeof option === 'string')
		{
			var data = this.data('_wJSNova');

			if(data)
			{
				if(option == 'resize') { data.resize(); return true }
				else if($.fn.wJSNova.defaultSettings[option] !== undefined)
				{
					if(settings !== undefined){
						data.settings[option] = settings;
						return true;
					}
					else return data.settings[option];
				}
				else return false;
			}
			else return false;
		}

		settings = $.extend({}, $.fn.wJSNova.defaultSettings, settings || {});

		return this.each(function()
		{
			var $elem = $(this);

			var $settings = jQuery.extend(true, {}, settings);

			var jsn = new JSNova($settings);

			$elem.append(jsn.generate());
			jsn.resize();

			$elem.data('_wJSNova', jsn);
		});
	}

	$.fn.wJSNova.defaultSettings = {};

	function JSNova(settings)
	{
		this.jsn = null;
		this.settings = settings;

		this.menu = null;

		this.sidebar = null;
		this.jQueryVersion = null;
		this.jQueryUIVersion = null;
		this.jQueryUITheme = null;

		this.codeArea = null;
		this.boxHTML = null;
		this.boxQML = null;
		this.boxJS = null;
		this.boxResult = null;

		return this;
	}

	JSNova.prototype =
	{
		init: function()
		{
			this.resize();
		},

		generate: function()
		{
			var $this = this;

			if($this.jsn) return $this.jsn;

			/************************************************
			 * Menu
			 ************************************************/
			var menuButton_run = $('Run').click(function(){$this.run();});
			var menuButton_download = $('Download').click(function(){$this.download();});
			var menuButton_save = $('Suggest Demo').click(function(){$this.save();});
			var menuButton_reset = $('Reset').click(function(){$this.reset();});

			$this.menu =
			$('

')
			.append('

')
			.append(
				$('

')
				.append(menuButton_run)
				.append(menuButton_download)
				.append(menuButton_save)
				.append(menuButton_reset)
				.append('')
			);

			/************************************************
			 * Sidebar
			 ************************************************/
			var demos = [['Single Video','single'],['Playlist','playlist'],['Duplicate Video 2','duplicate2'],['Whirlwind','whirlwind'],['Multiscreen Demo','multiscreen'],['Duplicate Video','duplicate'],['Fullscreen Zoom','zoom'],['3D Rotate','rotate']];
			$this.Demoz = $("<select name='demos' onchange='location = \"http://jaruba.github.io/WebchimeraGUI/editor/?demo=\"+this.options[this.selectedIndex].value;' style='width: 100%'></select>");
<<<<<<>>>>>> master
			 for (var item = 0; item < demos.length; item++) {
				 if (demos[item][1] == hash) {
					$this.Demoz.append('<option value="' + demos[item][1] + '" selected>' + demos[item][0] + '</option>');
				 } else {
					$this.Demoz.append('<option value="' + demos[item][1] + '">' + demos[item][0] + '</option>');
				 }
			 }

			$this.WebchimeraJS = $('<select name="webchimerajs" class="_wJSNova_sidebarSelect"></select>');
			$this.WebchimeraJS.append('<option value="latest">Latest Webchimera.js</option>');
			$this.WebchimeraJS.append('<option value="none">none</option>');

			$this.jQueryVersion = $('<select name="jquery" class="_wJSNova_sidebarSelect"></select>');
			$this.jQueryVersion.append('<option value="none">none</option>');
			$.each(['2.1.1', '2.1.0', '2.0.3', '2.0.2', '2.0.1', '2.0.0', '1.11.1', '1.11.0'],
			function(index,version){ $this.jQueryVersion.append('<option value="https://ajax.googleapis.com/ajax/libs/jquery/' + version + '/jquery.min.js">jQuery ' + version + '</option>'); });

			$this.jQueryUIVersion = $('<select name="jqueryui" class="_wJSNova_sidebarSelect"></select>');
			$this.jQueryUIVersion.append('<option value="none">none</option>');
			$.each(['1.11.2', '1.11.1', '1.11.0', '1.10.4', '1.10.3', '1.10.2', '1.10.1', '1.10.0', '1.9.2', '1.9.1', '1.9.0'],
			function(index,version){ $this.jQueryUIVersion.append('<option value="https://ajax.googleapis.com/ajax/libs/jqueryui/' + version + '/jquery-ui.min.js">jQuery UI ' + version + '</option>'); });

//			$this.jQueryUITheme = $('<select class="_wJSNova_sidebarSelect"></seletct>');
//			$.each(['base', 'black-tie', 'blitzer', 'cupertino', 'dot-luv', 'excite-bike', 'hot-sneaks', 'humanity', 'mint-choc', 'redmond', 'smoothness', 'south-street', 'start', 'swanky-purse', 'trontastic', 'ui-darkness', 'ui-lightness', 'vader'],
//			function(index,version){ $this.jQueryUITheme.append('<option value="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/' + version + '/jquery-ui.css">' + version + '</option>'); });

			$this.sidebar =
			$('

')
			.append(
				$('

')
				.append('
Select Demo:
')
				.append($this.Demoz)
				.append('
Webchimera JS:
')
				.append($this.WebchimeraJS)
				.append('
jQuery Version:
')
				.append($this.jQueryVersion)
				.append('
jQuery UI Version:
')
				.append($this.jQueryUIVersion)
//				.append('
jQuery UI Theme:
')
//				.append($this.jQueryUITheme)
			);

			/************************************************
			 * Code Area
			 ************************************************/
			$this.boxHTML = $('<textarea name="html" class="_wJSNova_boxEdit" data-editor="html"></textarea>');
			$this.boxQML = $('<textarea name="qml" class="_wJSNova_boxEdit" data-editor="javascript"></textarea>');
			$this.boxJS = $('<textarea name="js" class="_wJSNova_boxEdit" data-editor="javascript"></textarea>');
			$this.boxResult = $('');

			$.each([$this.boxHTML, $this.boxQML, $this.boxJS, $this.boxResult], function(index, item)
			{
				item.hover(function(){ $(this).parent().children('._wJSNova_boxLabel').fadeOut(200); }, function() { if (!($(this).is(":focus"))) $(this).parent().children('._wJSNova_boxLabel').fadeIn(200); });
			});

			$this.codeArea =
			$('

')
			.append(
				$('

')
				.append(
					$('

')
					.append(
						$('	')
						.append(
							$('

')
							.append($this.boxHTML)
							.append('
HTML
')
							.hover(function() { $("#htmlbox").fadeOut(200); },function() { $("#htmlbox").fadeIn(200); })
						)
					)
					.append(
						$('	')
						.append(
							$('

')
							.append($this.boxJS)
							.append('
JavaScript
')
							.hover(function() { $("#jsbox").fadeOut(200); },function() { $("#jsbox").fadeIn(200); })
						)
					)
				)
				.append(
					$('

')
					.append(
						$('	')
						.append(
							$('

')
							.append($this.boxQML)
							.append('
QML
')
							.hover(function() { $("#qmlbox").fadeOut(200); },function() { $("#qmlbox").fadeIn(200); })
						)
					)
					.append(
						$('	')
						.append(
							$('

')
							.append($this.boxResult)
							.append('
Result
')
						)
					)
				)
			)

			$this.jsn =
			$('

')
			.append($this.menu)
			.append($this.sidebar)
			.append($this.codeArea);

			return $this.jsn;
		},

		run: function()
		{
			for (kl = 0; typeof textareas[kl] !== 'undefined'; kl++) textareas[kl].val(editors[kl].getSession().getValue());
			var html = this.boxHTML.val();
			var js = this.boxJS.val();
			var qml = this.boxQML.val();

			if (this.WebchimeraJS.val() != "none") {
				var WebchimeraScript = '';
			} else WebchimeraScript = '';

			if (this.jQueryVersion.val() != "none") {
				var jQuery = '';
			} else jQuery = '';

			if (this.jQueryUIVersion.val() != "none") {
				var jQueryUI = '';
			} else var jQueryUI = '';

//			var jQueryUITheme = '<link rel="stylesheet" type="text/css" href="' + this.jQueryUITheme.val() + '"/>'

			var result = '' + WebchimeraScript + jQuery + jQueryUI + '' + html + '<textarea id="qmlcode">' + qml + '</textarea>';

			this.writeResult(result);
		},

		reset: function()
		{
			location.reload();
		},

		download: function()
		{
			for (kl = 0; typeof textareas[kl] !== 'undefined'; kl++) textareas[kl].val(editors[kl].getSession().getValue());
			$("#editorform").submit();
		},

		save: function()
		{
			for (kl = 0; typeof textareas[kl] !== 'undefined'; kl++) textareas[kl].val(editors[kl].getSession().getValue());
			var data = $("#editorform").serializeArray();
			$.post("http://www.movault.net/webchimera/editor/generator/demos/custom-demo.php", data);
			$("#message").html("Demo sent successfully!").fadeIn(300).delay(2500).fadeOut(300);
		},

		writeResult: function(result)
		{
			var iframe = this.boxResult[0];

			if(iframe.contentDocument) doc = iframe.contentDocument;
			else if(iframe.contentWindow) doc = iframe.contentWindow.document;
			else doc = iframe.document;

			doc.open();
			doc.writeln(result);
			doc.close();
		},

		resize: function()
		{
			var menuHeight = this.menu.outerHeight(true);
			var jsnHeight = this.jsn.outerHeight(true) - menuHeight;

			var codeAreaWidth = this.jsn.outerWidth(true) - this.sidebar.outerWidth(true);

			this.sidebar.css({top: menuHeight, height: jsnHeight});
			this.codeArea.css({top: menuHeight, height: jsnHeight, width: codeAreaWidth});
		}
	}
})(jQuery);
<|endoftext|>


<commit_before>const regl = require('../regl')()
var seedrandom = require('seedrandom')

function cpuReduce (data, op) {
  var result = op(data[0], data[1])
  for (var i = 3; i < data.length; i++) {
    result = op(result, data[i])
  }
  return result
}

function gpuReduce (data, op) {
  var reducePass = regl({
    frag: `
    precision mediump float;
    uniform sampler2D tex;
    varying vec2 uv;
    uniform float rcpDim;

    float op(float a, float b) {
      return ${op};
    }

    void main () {
      float a = texture2D(tex, uv - vec2(0.0, 0.0) * rcpDim).x;
      float b = texture2D(tex, uv - vec2(1.0, 0.0) * rcpDim).x;
      float c = texture2D(tex, uv - vec2(0.0, 1.0) * rcpDim).x;
      float d = texture2D(tex, uv - vec2(1.0, 1.0) * rcpDim).x;

      float result = op(op(a, b), op(c, d));
      gl_FragColor = vec4(result);
    }`,

    vert: `
    precision mediump float;
    attribute vec2 position;
    varying vec2 uv;
    void main () {
      uv = position;
      gl_Position = vec4(1.0 - 2.0 * position, 0, 1);
    }`,

    attributes: {
      position: [-2, 0, 0, -2, 2, 2]
    },

    uniforms: {
      tex: regl.prop('inTex'),
      rcpDim: regl.prop('rcpDim')
    },

    framebuffer: regl.prop('outFbo'),

    count: 3
  })

  var textureData = []
  var i
  for (i = 0; i < data.length; i++) {
    var g = data[i]
    textureData.push(g, g, g, g)
  }

  // dimensions of the first texture is dimXdim.
  var DIM = Math.sqrt(data.length)
  var dim = DIM

  var firstTexture = regl.texture({
    width: dim,
    height: dim,
    data: textureData,
    format: 'rgba',
    type: 'uint8',
    mag: 'nearest',
    min: 'nearest'
  })

  var fbos = []

  do {
    dim >>= 1
    fbos.push(regl.framebuffer({
      colorFormat: 'rgba',
      colorType: 'uint8',
      width: dim,
      height: dim
    }))
  } while (dim > 1)

  // first pass.
  reducePass({inTex: firstTexture, outFbo: fbos[0], rcpDim: 1.0 / (fbos[0].width * 2)})

  // the rest of the passes.
  for (i = 0; i < fbos.length - 1; i++) {
    var inFbo = fbos[i + 0]
    var outFbo = fbos[i + 1]
/*
    regl({framebuffer: inFbo})(() => {
      console.log('done: ', regl.read())
    })*/

//    console.log('tex: ', inFbo.color[0])

    reducePass({inTex: inFbo.color[0], outFbo: outFbo, rcpDim: 1.0 / (outFbo.width * 2)})
  }

  var result
  regl({framebuffer: fbos[fbos.length - 1]})(() => {
    result = regl.read()[0]
  })
  return result
}

var seed = 'seed'

for (var j = 0; j < 100; j++) {
  seed += j

  var rng = seedrandom(seed)

  var data = []
  for (var i = 0; i < 512 * 512; i++) {
    data.push(Math.floor(rng() * 255))
  }

  var gpu = gpuReduce(data, 'max(a,b)')
  var cpu = cpuReduce(data, (a, b) => Math.max(a, b))

  if (cpu !== gpu) {
    console.log('FAILED')
    console.log('cpu: ', cpu)
    console.log('gpu: ', gpu)
    console.log('data: ', data)
    break
  }
  if (j % 10 === 0) {
    console.log('j: ', j)
  }
}
console.log('done')
<commit_msg> example/reduction.js: Add comments.<commit_after>/*

This example implements a parallell reduction algorithm on the GPU.

Given some elements x0, x1, x2,..., and a binary operator 'op', the parallell reduction
  becomes 'op(x0, op(x1, op(x2,...) ))'. For example, given the elements 4, 2, 4, 1, and the operator '+',
  the parallell reduction will be 11, which is just the sum of the elements.

 */

const regl = require('../regl')()
var seedrandom = require('seedrandom')

/*
  Reduction on the CPU
 */
function cpuReduce (data, op) {
  var result = op(data[0], data[1])
  for (var i = 3; i < data.length; i++) {
    result = op(result, data[i])
  }
  return result
}

/*
  Reduction on the GPU.

  We basically use the technique described in section 37.2 of this article:
  http://http.developer.nvidia.com/GPUGems/gpugems_ch37.html

  The algorithm: We basically start with a texture (A) of size
  (N)x(N). Then we create an FBO (B) of size (N/2)x(N/2). Then we render to FBO (B), and
  every fragment will sample four texels from (A). And by doing so, we will have performed
  a reduction of 2x2 sized blocks.

  Next, we create an FBO (C) of size (N/4)x(N/4), and, like above, we
  to render (C) to while sampling from (B), and so on. We keep going
  until we are left with an FBO of size 1x1. And that single pixel in
  that FBO contains our desired result.

  Note that we are using a texture of type RGBA8 in the below
  implementation. This means that we can't really use '+' as an
  operator for the reduction, since it will easily overflow. This can
  be solved by switching to a texture of type RGBA32F.
  But we are not using that, because it requires an extensions that is not always available.
  So to maximize compability, we use RGBA8 in this demo.
  So if you want to use the below reduce implementation in your own code, you will probably
  have to switch to RGBA32F.

  And to simplify things, we will be making the assumption that data.length will be one the numbers
  1x1, 2x2, 4x4, 8x8, 16x16,...
*/
function gpuReduce (data, op) {
  // a single reduce pass
  var reducePass = regl({
    frag: `
    precision mediump float;
    uniform sampler2D tex;
    varying vec2 uv;
    uniform float rcpDim;

    float op(float a, float b) {
      return ${op};
    }

    void main () {
      float a = texture2D(tex, uv - vec2(0.0, 0.0) * rcpDim).x;
      float b = texture2D(tex, uv - vec2(1.0, 0.0) * rcpDim).x;
      float c = texture2D(tex, uv - vec2(0.0, 1.0) * rcpDim).x;
      float d = texture2D(tex, uv - vec2(1.0, 1.0) * rcpDim).x;

      float result = op(op(a, b), op(c, d));
      gl_FragColor = vec4(result);
    }`,

    vert: `
    precision mediump float;
    attribute vec2 position;
    varying vec2 uv;
    void main () {
      uv = position;
      gl_Position = vec4(1.0 - 2.0 * position, 0, 1);
    }`,

    attributes: {
      position: [-2, 0, 0, -2, 2, 2]
    },

    uniforms: {
      tex: regl.prop('inTex'),
      rcpDim: regl.prop('rcpDim') // reciprocal texture dimensions.
    },

    framebuffer: regl.prop('outFbo'),

    count: 3
  })

  // We must use a texture format of type RGBA. Because you cannot create a single channel FBO of type
  // ALPHA in WebGL.
  var textureData = []
  var i
  for (i = 0; i < data.length; i++) {
    var g = data[i]
    textureData.push(g, g, g, g)
  }

  // dimensions of the first texture is (dim)X(dim).
  var DIM = Math.sqrt(data.length)
  var dim = DIM

  var firstTexture = regl.texture({
    width: dim,
    height: dim,
    data: textureData,
    format: 'rgba',
    type: 'uint8',
    mag: 'nearest',
    min: 'nearest'
  })

  var fbos = []
  do {
    dim >>= 1
    fbos.push(regl.framebuffer({
      colorFormat: 'rgba',
      colorType: 'uint8',
      width: dim,
      height: dim
    }))
  } while (dim > 1)

  // first pass.
  reducePass({inTex: firstTexture, outFbo: fbos[0], rcpDim: 1.0 / (fbos[0].width * 2)})

  // the rest of the passes.
  for (i = 0; i < fbos.length - 1; i++) {
    var inFbo = fbos[i + 0]
    var outFbo = fbos[i + 1]

    reducePass({inTex: inFbo.color[0], outFbo: outFbo, rcpDim: 1.0 / (outFbo.width * 2)})
  }

  // now retrieve the result from the GPU
  var result
  regl({framebuffer: fbos[fbos.length - 1]})(() => {
    result = regl.read()[0]
  })
  return result
}

var seed = 'seed'

for (var j = 0; j < 100; j++) {
  seed += j

  var rng = seedrandom(seed)

  var data = []
  for (var i = 0; i < 512 * 512; i++) {
    data.push(Math.floor(rng() * 255))
  }

  var gpu = gpuReduce(data, 'max(a,b)')
  var cpu = cpuReduce(data, (a, b) => Math.max(a, b))

  if (cpu !== gpu) {
    console.log('FAILED')
    console.log('cpu: ', cpu)
    console.log('gpu: ', gpu)
    console.log('data: ', data)
    break
  }
  if (j % 10 === 0) {
    console.log('j: ', j)
  }
}
console.log('done')
<|endoftext|>


<commit_before>;window.Plautocompleter.Login = (function($) {

  var redirectUri = 'http://localhost:8000/';
  var accessToken;
  var userId;

  var initialize = function() {
    $('#login').on('click', function() {
      window.Plautocompleter.Login.login();
    });
  };

  var login = function(){
    var params = {
      client_id: '1dfce943394b4650ba94e907d2856008',
      redirect_uri: redirectUri,
      scope: 'user-read-private playlist-read-private playlist-modify-public playlist-modify-private',
      response_type: 'token'
    };

    window.location = "https://accounts.spotify.com/authorize?" + toQueryString(params);
  }

  function toQueryString(obj) {
    var parts = [];
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
        }
    }
    return parts.join("&");
  }

  var getToken = function() {
    if (accessToken != undefined) {
      return  accessToken;
    }

    accessToken = window.location.hash.substring(1).split('&')[0].split('=')[1];
    return accessToken;
  }

  /* Export public interface */

  return {
    initialize: initialize,
    login: login,
    getToken: getToken,
    userId: userId
  };

})(jQuery);
<commit_msg>Hellooooooooo - made redirect url depend on current site location<commit_after>;window.Plautocompleter.Login = (function($) {

  var redirectUri = window.location.origin;
  var accessToken;
  var userId;

  var initialize = function() {
    $('#login').on('click', function() {
      window.Plautocompleter.Login.login();
    });
  };

  var login = function(){
    var params = {
      client_id: '1dfce943394b4650ba94e907d2856008',
      redirect_uri: redirectUri,
      scope: 'user-read-private playlist-read-private playlist-modify-public playlist-modify-private',
      response_type: 'token'
    };

    window.location = "https://accounts.spotify.com/authorize?" + toQueryString(params);
  }

  function toQueryString(obj) {
    var parts = [];
    for (var i in obj) {
      if (obj.hasOwnProperty(i)) {
        parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
      }
    }
    return parts.join("&");
  }

  var getToken = function() {
    if (accessToken != undefined) {
      return  accessToken;
    }

    accessToken = window.location.hash.substring(1).split('&')[0].split('=')[1];
    return accessToken;
  }

  /* Export public interface */

  return {
    initialize: initialize,
    login: login,
    getToken: getToken,
    userId: userId
  };

})(jQuery);
<|endoftext|>


<commit_before>'use strict';

class AbstractFactory {
    constructor() {
    }

    createProductA(product) {
    }

    createProductB(product) {
    }
}

class ConcreteFactory1 extends AbstractFactory {
    constructor() {
        super()
        console.log("ConcreteFactory1 class created");
    }

    createProductA(product) {
        console.log('ConcreteFactory1 createProductA')
        return new ProductA1()
    }

    createProductB(product) {
        console.log('ConcreteFactory1 createProductB')
        return new ProductB1()
    }
}

class ConcreteFactory2 extends AbstractFactory {
    constructor() {
        super()
        console.log("ConcreteFactory2 class created");
    }

    createProductA(product) {
        console.log('ConcreteFactory2 createProductA')
        return new ProductA2()
    }

    createProductB(product) {
        console.log('ConcreteFactory2 createProductB')
        return new ProductB2()
    }
}

class AbstractProductA {
    constructor() {
    }
}

class AbstractProductB {
    constructor() {
    }
}

class ProductA1 extends AbstractProductA {
    constructor() {
        super()
        console.log('ProductA1 created')
    }
}

class ProductA2 extends AbstractProductA {
    constructor() {
        super()
        console.log('ProductA2 created')
    }
}

class ProductB1 extends AbstractProductB {
    constructor() {
        super()
        console.log('ProductB1 created')
    }
}

class ProductB2 extends AbstractProductB {
    constructor() {
        super()
        console.log('ProductB2 created')
    }
}

var factory1 = new ConcreteFactory1()
var productB1 = factory1.createProductB()
var productA1 = factory1.createProductA()

var factory2 = new ConcreteFactory2()
var productA2 = factory2.createProductA()
var productB2 = factory2.createProductB()<commit_msg>update code format<commit_after>'use strict';

class AbstractFactory {
    constructor() {
        console.log("AbstractFactory class created");
    }

    createProductA(product) {
        console.log("AbstractFactory.createProductA created");
    }

    createProductB(product) {
        console.log("AbstractFactory.createProductB created");
    }
}

class ConcreteFactory1 extends AbstractFactory {
    constructor() {
        super();
        console.log("ConcreteFactory1 class created");
    }

    createProductA(product) {
        console.log('ConcreteFactory1 createProductA');
        return new ProductA1();
    }

    createProductB(product) {
        console.log('ConcreteFactory1 createProductB');
        return new ProductB1();
    }
}

class ConcreteFactory2 extends AbstractFactory {
    constructor() {
        super();
        console.log("ConcreteFactory2 class created");
    }

    createProductA(product) {
        console.log('ConcreteFactory2 createProductA');
        return new ProductA2();
    }

    createProductB(product) {
        console.log('ConcreteFactory2 createProductB');
        return new ProductB2();
    }
}

class AbstractProductA {
    constructor() {
        console.log('AbstractProductA created');
    }
}

class AbstractProductB {
    constructor() {
        console.log('AbstractProductB created');
    }
}

class ProductA1 extends AbstractProductA {
    constructor() {
        super();
        console.log('ProductA1 created');
    }
}

class ProductA2 extends AbstractProductA {
    constructor() {
        super();
        console.log('ProductA2 created');
    }
}

class ProductB1 extends AbstractProductB {
    constructor() {
        super();
        console.log('ProductB1 created');
    }
}

class ProductB2 extends AbstractProductB {
    constructor() {
        super();
        console.log('ProductB2 created');
    }
}

var factory1 = new ConcreteFactory1();
var productB1 = factory1.createProductB();
var productA1 = factory1.createProductA();

var factory2 = new ConcreteFactory2();
var productA2 = factory2.createProductA();
var productB2 = factory2.createProductB();<|endoftext|>


<commit_before>/**
 * Created by cbrownroberts on 9/13/16.
 */
function bookList() {

    "use strict";

    var myBookList = {

        settings: {},
        strings: {},
        bindUiActions: function () {
            myBookList.iterateUrls();
        },
        init: function () {
            myBookList.bindUiActions();

            var isotopeScript = "http://unpkg.com/isotope-layout@3.0.1/dist/isotope.pkgd.min.js";

            //get script
            $.getScript(isotopeScript, function(){
                $("head").append("<script src='" + isotopeScript + "'>");

                var $win = $(window);

                //set timeout to remove preloader
                setTimeout(function(){
                    $('#sorts').css('visibility', 'visible');
                    $('#new_books').css('visibility', 'visible');
                }, 1000);

                $win.on('load', function(){

                    // init Isotope
                    $('#new_books').isotope({
                        itemSelector: '.element-item',
                        layoutMode: 'fitRows',
                        fitRows: {
                            gutter: 0
                        },
                        getSortData: {
                            title: '[data-title]',
                            author: '[data-author]',
                            arrivaldate: '[data-arrivaldate]',
                            language: '[data-language]'
                        },
                       sortBy: 'arrivaldate',
                       sortAscending: 'false'
                    });

                    $('.books-loading').hide();

                });

                // sort items on button click
                $('#sorts').on( 'click', 'button', function() {
                    var sortByValue = $(this).attr('data-sort-value');
                    $('#new_books').isotope({ sortBy: sortByValue});
                    console.log('click');
                    $('#sorts button').removeClass('active-sort');
                     $(this).addClass('active-sort');
                });

                //flip
                $('.flip-btn').on( 'click', function() {
                    var flipCard = $(this).parent();
                    $(flipCard).toggleClass('hover');
                });

            }); //end .getScript

        },

        iterateUrls: function () {
            var elements = document.querySelectorAll('[property="url"]');

            $('.item-title a').each(function(i) {
                var url = $(this).attr('href');
                var grandFather = $(this).parent().parent();
                var split = url.split(",");
                var almaId = split[split.length - 1];
                var newUrl = 'http://sp.library.miami.edu/external_scripts/newitems/pnx.php?alma_id=' + almaId;

                $.get(newUrl, function(data) {

                    var isbn = $.parseJSON(data).search.isbn;
                    if( Array.isArray(isbn)) {
                        for (var j = 0; j < isbn.length; j++){
                            if (isbn[j].length === 13){
                                isbn = isbn [j];
                                break;
                            }
                        }
                    }

                    var bookCoverUrl = "http://sp.library.miami.edu/external_scripts/newitems/bookcover.php?syndetics_client_code=miamih&image_size=LC&isbn=" + isbn;

                    $.get(bookCoverUrl, function(data) {
                        var imgCover = document.createElement('img');
                        imgCover.setAttribute('src', data);
                        imgCover.setAttribute('class', 'webservice-cover');
                        grandFather.find(".item-image").prepend(imgCover);
                        $("#new_books_container .item-image").addClass("remove-placeholder-cover");

                    });
                });

            });

        }
    };
    return myBookList;
}

var bookList = bookList();
bookList.init();<commit_msg>fall back for alt image<commit_after>/**
 * Created by cbrownroberts on 9/13/16.
 */
function bookList() {

    "use strict";

    var myBookList = {

        settings: {},
        strings: {},
        bindUiActions: function () {
            myBookList.iterateUrls();
        },
        init: function () {
            myBookList.bindUiActions();

            var isotopeScript = "http://unpkg.com/isotope-layout@3.0.1/dist/isotope.pkgd.min.js";

            //get script
            $.getScript(isotopeScript, function(){
                $("head").append("<script src='" + isotopeScript + "'>");

                var $win = $(window);

                //set timeout to remove preloader
                setTimeout(function(){
                    $('#sorts').css('visibility', 'visible');
                    $('#new_books').css('visibility', 'visible');
                }, 1000);

                $win.on('load', function(){

                    // init Isotope
                    $('#new_books').isotope({
                        itemSelector: '.element-item',
                        layoutMode: 'fitRows',
                        fitRows: {
                            gutter: 0
                        },
                        getSortData: {
                            title: '[data-title]',
                            author: '[data-author]',
                            arrivaldate: '[data-arrivaldate]',
                            language: '[data-language]'
                        },
                       sortBy: 'arrivaldate',
                       sortAscending: 'false'
                    });

                    $('.books-loading').hide();

                });

                // sort items on button click
                $('#sorts').on( 'click', 'button', function() {
                    var sortByValue = $(this).attr('data-sort-value');
                    $('#new_books').isotope({ sortBy: sortByValue});
                    console.log('click');
                    $('#sorts button').removeClass('active-sort');
                     $(this).addClass('active-sort');
                });

                //flip
                $('.flip-btn').on( 'click', function() {
                    var flipCard = $(this).parent();
                    $(flipCard).toggleClass('hover');
                });

            }); //end .getScript

        },

        iterateUrls: function () {
            var elements = document.querySelectorAll('[property="url"]');

            $('.item-title a').each(function(i) {
                var url = $(this).attr('href');
                var grandFather = $(this).parent().parent();
                var split = url.split(",");
                var almaId = split[split.length - 1];
                var newUrl = 'http://sp.library.miami.edu/external_scripts/newitems/pnx.php?alma_id=' + almaId;

                $.get(newUrl, function(data) {

                    var isbn = $.parseJSON(data).search.isbn;
                    if( Array.isArray(isbn)) {
                        for (var j = 0; j < isbn.length; j++){
                            if (isbn[j].length === 13){
                                isbn = isbn [j];
                                break;
                            }
                        }
                    }

                    var bookCoverUrl = "http://sp.library.miami.edu/external_scripts/newitems/bookcover.php?syndetics_client_code=miamih&image_size=LC&isbn=" + isbn;

                    $.get(bookCoverUrl, function(data) {
                        var imgCover = document.createElement('img');
                        imgCover.setAttribute('src', data);
                        imgCover.setAttribute('class', 'webservice-cover');
                        grandFather.find(".item-image").prepend(imgCover);
                        $("#new_books_container .item-image").addClass("remove-placeholder-cover");

                    });
                });

            });

        }
    };
    return myBookList;
}

var bookList = bookList();
bookList.init();

$( document ).ready(function() {
   //set fallback image
   var cover = $(".item-image img");
   var altCover = "http://lorempixel.com/200/215";

   $('.item-image img').each(function() {

       if($(this).attr('src') == "") {
           console.log("no cover");
           $(this).attr("src", altCover);
       } else {
           console.log("cover found");
       }

   });
});<|endoftext|>


<commit_before>import DS from 'ember-data';
import RelationshipTracker from "ember-data-relationship-tracker";
import { inject as service } from '@ember/service';
import { computed, defineProperty, get } from '@ember/object';
import { readOnly, or } from '@ember/object/computed';
import { capitalize } from '@ember/string';
import { uniq } from 'lodash-es';

export default DS.Model.extend(RelationshipTracker, {
  resourceMetadata: service(),

  init() {
    this._super();
    let ownedRelationships = {};
    this._relationshipsByName().forEach((relation) => {
      let { kind, meta } = relation;
      if (meta) {
        let { owned } = meta.options;
        if (owned) {
          ownedRelationships[meta.name] = kind;
        }
      }
    });

    if (Object.keys(ownedRelationships).length > 0) {
      this._createDirtyTrackingCPs(ownedRelationships);
    }
    this.set('ownedRelationships', ownedRelationships);
  },

  relationshipTrackerVersion: computed(function() {
    let meta = this.get('resourceMetadata').read(this);
    return meta && meta.version;
  }),

  async save() {
    // this._super is not safe to use asynchronously
    // see https://github.com/ember-cli/ember-cli/issues/6282
    let modelSave = this._super.bind(this);

    if (Object.keys(this.ownedRelationships).length > 0) {
      await this.saveRelated();
    }

    await modelSave(...arguments);
  },

  async saveRelated() {
    let relatedSaves = Object.keys(this.ownedRelationships).map(async (relationName) => {
      let isRelationDirty = this.dirtyTrackingRelationNames[relationName];
      if (isRelationDirty) {
        let relatedRecords = relatedRecordsFor(this, relationName);
        let dirtyRecords = relatedRecords.filter(record => record.hasDirtyFields);
        return Promise.all(dirtyRecords.map(record => record.save()));
      }
    });
    return Promise.all(flatten(relatedSaves));
  },

  relatedOwnedRecords() {
    return uniq(relatedOwnedRecords([ this ]));
  },

  _createDirtyTrackingCPs(ownedRelationships) {
    let dirtyTrackingProperties = {};
    for (let relationshipName in ownedRelationships) {
      let kind = ownedRelationships[relationshipName];
      let propertyName = createHasDirtyForRelationship(this, relationshipName, kind);
      dirtyTrackingProperties[relationshipName] = propertyName;
    }
    createHasDirtyOwned(this, Object.values(dirtyTrackingProperties));
    this.set('dirtyTrackingRelationNames', dirtyTrackingProperties);
  },

  _relationshipsByName() {
    return get(this.constructor, 'relationshipsByName');
  }
});

function relatedOwnedRecords(models, records=[]) {
  if (models.length === 0) {
    return records;
  }
  let [ model, ...remainingModels ] = models;
  Object.keys(model.ownedRelationships).map((relationName) => {
    let relatedRecords = relatedRecordsFor(model, relationName);
    records = records.concat(relatedRecords);
    remainingModels = remainingModels.concat(relatedRecords);
  });
  return relatedOwnedRecords(remainingModels, records);
}

function relatedRecordsFor(model, relationName) {
  let kind = model.ownedRelationships[relationName];
  let related = model.get(relationName);
  return (kind === 'hasMany' ? related.toArray() : [ related ]).filter(Boolean);
}

function createHasDirtyForRelationship(model, name, kind) {
  let propertyName = `hasDirty${capitalize(name)}`;
  if (kind === 'hasMany') {
    defineProperty(model, propertyName, computed(`${name}.@each.hasDirtyAttributes`, function() {
      return model.get(name).toArray().some((related) => related.hasDirtyAttributes);
    }));
  } else {
    defineProperty(model, propertyName, readOnly(`${name}.hasDirtyAttributes`));
  }
  return propertyName;
}

function createHasDirtyOwned(model, properties) {
  defineProperty(model, 'hasDirtyOwned', or(properties.join(',')));
}

function flatten(arrays) {
  return arrays.reduce((flattened, array) => {
    return flattened.concat(array);
  }, []);
}
<commit_msg>Improve hasDirty* CP definitions<commit_after>import DS from 'ember-data';
import RelationshipTracker from "ember-data-relationship-tracker";
import { inject as service } from '@ember/service';
import { computed, defineProperty, get } from '@ember/object';
import { readOnly, or } from '@ember/object/computed';
import { capitalize } from '@ember/string';
import { uniq } from 'lodash-es';

export default DS.Model.extend(RelationshipTracker, {
  resourceMetadata: service(),

  init() {
    this._super();
    let ownedRelationships = {};
    this._relationshipsByName().forEach((relation) => {
      let { kind, meta } = relation;
      if (meta) {
        let { owned } = meta.options;
        if (owned) {
          ownedRelationships[meta.name] = kind;
        }
      }
    });

    if (Object.keys(ownedRelationships).length > 0) {
      this._createDirtyTrackingCPs(ownedRelationships);
    }
    this.set('ownedRelationships', ownedRelationships);
  },

  relationshipTrackerVersion: computed(function() {
    let meta = this.get('resourceMetadata').read(this);
    return meta && meta.version;
  }),

  async save() {
    // this._super is not safe to use asynchronously
    // see https://github.com/ember-cli/ember-cli/issues/6282
    let modelSave = this._super.bind(this);

    if (Object.keys(this.ownedRelationships).length > 0) {
      await this.saveRelated();
    }

    await modelSave(...arguments);
  },

  async saveRelated() {
    let relatedSaves = Object.keys(this.ownedRelationships).map(async (relationName) => {
      let isRelationDirty = this.dirtyTrackingRelationNames[relationName];
      if (isRelationDirty) {
        let relatedRecords = relatedRecordsFor(this, relationName);
        let dirtyRecords = relatedRecords.filter(record => record.hasDirtyFields);
        return Promise.all(dirtyRecords.map(record => record.save()));
      }
    });
    return Promise.all(flatten(relatedSaves));
  },

  relatedOwnedRecords() {
    return uniq(relatedOwnedRecords([ this ]));
  },

  _createDirtyTrackingCPs(ownedRelationships) {
    let dirtyTrackingProperties = {};
    for (let relationshipName in ownedRelationships) {
      let kind = ownedRelationships[relationshipName];
      let propertyName = createHasDirtyForRelationship(this, relationshipName, kind);
      dirtyTrackingProperties[relationshipName] = propertyName;
    }
    createHasDirtyOwned(this, ownedRelationships, Object.values(dirtyTrackingProperties));
    this.set('dirtyTrackingRelationNames', dirtyTrackingProperties);
  },

  _relationshipsByName() {
    return get(this.constructor, 'relationshipsByName');
  }
});

function relatedOwnedRecords(models, records=[]) {
  if (models.length === 0) {
    return records;
  }
  let [ model, ...remainingModels ] = models;
  Object.keys(model.ownedRelationships).map((relationName) => {
    let relatedRecords = relatedRecordsFor(model, relationName);
    records = records.concat(relatedRecords);
    remainingModels = remainingModels.concat(relatedRecords);
  });
  return relatedOwnedRecords(remainingModels, records);
}

function relatedRecordsFor(model, relationName) {
  let kind = model.ownedRelationships[relationName];
  let related = model.get(relationName);
  return (kind === 'hasMany' ? related.toArray() : [ related ]).filter(Boolean);
}

function createHasDirtyForRelationship(model, name, kind) {
  let propertyName = `hasDirty${capitalize(name)}`;
  if (kind === 'hasMany') {
    defineProperty(model, propertyName, computed(`${name}.@each.hasDirtyFields`, function() {
      return model.get(name).toArray().some((related) => related.hasDirtyFields);
    }));
  } else {
    defineProperty(model, propertyName, readOnly(`${name}.hasDirtyFields`));
  }
  return propertyName;
}

function createHasDirtyOwned(model, ownedRelationships, properties) {
  defineProperty(model, 'hasDirtyOwnedRelationships', or(properties.join(',')));

  let dependentKeys = Object.keys(ownedRelationships).reduce((dependentKeys, relationName) => {
    let kind = ownedRelationships[relationName];
    if (kind === 'belongsTo') {
      dependentKeys.push(`'${relationName}.hasDirtyOwned'`);
    } else {
      dependentKeys.push(`'${relationName}.@each.hasDirtyOwned'`);
    }
    return dependentKeys;
  }, []).join(',');

  defineProperty(model, 'hasDirtyOwned', computed('hasDirtyOwnedRelationships', dependentKeys, function() {
    if (model.hasDirtyOwnedRelationships) {
      return true;
    }
    return Object.keys(ownedRelationships).some((relationName) => {
      let relatedRecords = relatedRecordsFor(model, relationName);
      return relatedRecords.some((records) => records.hasDirtyOwned);
    });
  }));
}

function flatten(arrays) {
  return arrays.reduce((flattened, array) => {
    return flattened.concat(array);
  }, []);
}
<|endoftext|>